fix(ollama): apply DeepSeek reasoning/max_tokens adapter on CC bridge paths

This commit is contained in:
alfadb committed 2026-09-13 10:38:55 +08:00
1 parent 8321c57bd6
commit 35d05f3d25
5 files changed
+332 -10

No files matched your search

@@ -254,10 +254,13 @@ type ccStreamScanState struct {
// scanCCStream 驱动两条 CC 回退路径共享的 SSE 读循环:提取 data 行、在 [DONE]
// 哨兵处停止、保留最新 usage、记录首 token 时延,并把每个解析成功的 chunk 交给
// emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后
// 记入 Warn 日志。
// 记入 Warn 日志。account 与 upstreamModel 用于在解析成 chunk 之前对原始 SSE 行
// 做 Ollama Cloud DeepSeek reasoning 归一化(未命中时字节级透传,语义等同不挂)。
func (s *OpenAIGatewayService) scanCCStream(
c *gin.Context,
resp *http.Response,
account *Account,
upstreamModel string,
logPrefix string,
requestID string,
startTime time.Time,
@@ -268,6 +271,9 @@ func (s *OpenAIGatewayService) scanCCStream(
scanner := s.newUpstreamSSEScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
// Ollama Cloud DeepSeek 出站:在解析成 chunk 之前把 reasoning/thinking 归一化
// 成 reasoning_content,让协议转换器看到与官方 DeepSeek 完全一致的形态。
line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line)
payload, ok := extractOpenAISSEDataLine(line)
if !ok {
continue
@@ -326,10 +332,14 @@ func logCCStreamMissingDoneSentinel(logPrefix, requestID string) {
}
// readCCUpstreamJSONResponse 读取并解析 CC 非流式 JSON 响应,失败时以调用方
// 端点格式回写错误;成功时顺带提取 usage。
// 端点格式回写错误;成功时顺带提取 usage。account 与 upstreamModel 用于在解析
// 成结构体之前对原始响应体做 Ollama Cloud DeepSeek reasoning 归一化(未命中时
// 字节级透传,语义等同不挂)。
func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
c *gin.Context,
resp *http.Response,
account *Account,
upstreamModel string,
writeError compatErrorWriter,
) (*apicompat.ChatCompletionsResponse, OpenAIUsage, error) {
respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError)
@@ -340,6 +350,11 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
return nil, OpenAIUsage{}, fmt.Errorf("read upstream body: %w", err)
}
// Ollama Cloud DeepSeek 出站:在解析成结构体之前把 message/delta 里的
// reasoning/thinking 归一化成 reasoning_content,让协议转换器看到与官方
// DeepSeek 完全一致的形态。
respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody)
var ccResp apicompat.ChatCompletionsResponse
if err := json.Unmarshal(respBody, &ccResp); err != nil {
writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response")
@@ -100,6 +100,13 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
// so the converted Chat Completions body never contains one and the policy
// would always be a no-op on this path.
// Ollama Cloud → DeepSeek 出站(chatReq.Model 已是模型映射后的 upstreamModel):
// 与 raw 路径同序——先归一化 request(历史 assistant 消息
// reasoning_content → reasoning)、再 clamp max_tokens(>65535 → 65535)。
// 官方 DeepSeek/glm 等未命中时字节级透传。
chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody)
chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody)
logger.L().Debug("openai messages: forwarding via raw chat completions",
zap.Int64("account_id", account.ID),
zap.String("original_model", originalModel),
@@ -132,14 +139,15 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
// 5. Convert response
if clientStream {
return s.streamChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
return s.streamChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
}
return s.bufferChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
return s.bufferChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
}
func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
c *gin.Context,
resp *http.Response,
account *Account,
originalModel string,
billingModel string,
upstreamModel string,
@@ -148,7 +156,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
startTime time.Time,
) (*OpenAIForwardResult, error) {
requestID := resp.Header.Get("x-request-id")
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeAnthropicError)
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeAnthropicError)
if err != nil {
return nil, err
}
@@ -177,6 +185,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic(
c *gin.Context,
resp *http.Response,
account *Account,
originalModel string,
billingModel string,
upstreamModel string,
@@ -214,7 +223,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic(
}
}
scan := s.scanCCStream(c, resp, "openai messages chat fallback", requestID, startTime, emitChunk)
scan := s.scanCCStream(c, resp, account, upstreamModel, "openai messages chat fallback", requestID, startTime, emitChunk)
usage := scan.Usage
if scan.Err != nil {
@@ -0,0 +1,145 @@
//go:build unit
package service
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// runOllamaMessagesChatFallback 直接走 /v1/messages → raw CC 降级桥
// forwardAnthropicViaRawChatCompletions(与 messages 桥既有测试同风格,直接调桥函数)。
func runOllamaMessagesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) {
t.Helper()
gin.SetMode(gin.TestMode)
contentType := "application/json"
if stream {
contentType = "text/event-stream"
}
upstreamResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Content-Type": []string{contentType},
"x-request-id": []string{"rid_ollama_messages_fallback"},
},
Body: io.NopCloser(strings.NewReader(upstreamBody)),
}
upstream := &httpUpstreamRecorder{resp: upstreamResp}
svc := &OpenAIGatewayService{
cfg: rawChatCompletionsTestConfig(),
httpUpstream: upstream,
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
result, err := svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, body, "")
require.NoError(t, err)
require.NotNil(t, result)
return rec, upstream
}
func TestMessagesChatFallback_OllamaDeepSeek_ClampMaxTokens(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 701)
t.Run("256000 clamps to 65535", func(t *testing.T) {
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
_, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String())
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
})
t.Run("1000 stays 1000", func(t *testing.T) {
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
_, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
})
}
// TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧
// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content
// 在归一化之后产出完全相同的 thinking 输出(同一转换路径跑多个输入对比)。
func TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 702)
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":true}`)
run := func(reasoningField string) string {
upstreamBody := strings.Join([]string{
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`,
"",
"data: [DONE]",
"",
}, "\n")
rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamBody, true)
return rec.Body.String()
}
baseline := run(`"reasoning_content":"abc"`)
for _, tc := range []struct {
name string
field string
}{
{name: "delta.reasoning alias", field: `"reasoning":"abc"`},
{name: "delta.thinking alias", field: `"thinking":"abc"`},
} {
t.Run(tc.name, func(t *testing.T) {
out := run(tc.field)
require.Equal(t, baseline, out, "归一化后输出必须与 reasoning_content 基线完全一致")
require.Contains(t, out, "event: content_block_start")
require.Contains(t, out, `"type":"thinking"`)
require.Contains(t, out, `"thinking":"abc"`)
require.Contains(t, out, `"type":"text"`)
require.Contains(t, out, `"text":"final answer"`)
})
}
}
func TestMessagesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 703)
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, "thinking", gjson.Get(rec.Body.String(), "content.0.type").String())
require.Equal(t, "abc", gjson.Get(rec.Body.String(), "content.0.thinking").String())
require.Equal(t, "text", gjson.Get(rec.Body.String(), "content.1.type").String())
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.1.text").String())
}
func TestMessagesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) {
official := officialDeepSeekTestAccount(704)
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
// thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃,
// 输出不出现 thinking 块(与不挂钩子的原始路径行为一致)。
upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, upstream := runOllamaMessagesChatFallback(t, official, body, upstreamJSON, false)
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
require.NotContains(t, rec.Body.String(), `"type":"thinking"`)
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String())
}
func TestMessagesChatFallback_OllamaGLM_Untouched(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 705)
body := []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
require.NotContains(t, rec.Body.String(), `"type":"thinking"`)
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String())
}
@@ -89,6 +89,9 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions(
}
// /v1/responses 降级到 raw CC 的出站与 forwardAsRawChatCompletions 共用同一个
// 独立 Ollama Cloud token 钩子;chatReq.Model 已是模型映射后的 upstreamModel。
// reasoning 归一化与 raw 路径同序:先归一化 request(历史 assistant 消息的
// reasoning_content → reasoning)再 clamp max_tokens。
chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody)
chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody)
// Keep the final outbound tier for usage-time reconciliation. A policy
// filter that removes the field therefore leaves this nil.
@@ -123,14 +126,15 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions(
}
if clientStream {
return s.streamChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
return s.streamChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
}
return s.bufferChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
return s.bufferChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
}
func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
c *gin.Context,
resp *http.Response,
account *Account,
originalModel string,
customTools map[string]bool,
functionTools map[string]bool,
@@ -143,7 +147,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
startTime time.Time,
) (*OpenAIForwardResult, error) {
requestID := resp.Header.Get("x-request-id")
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeOpenAIResponsesFallbackError)
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeOpenAIResponsesFallbackError)
if err != nil {
return nil, err
}
@@ -173,6 +177,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
func (s *OpenAIGatewayService) streamChatCompletionsAsResponses(
c *gin.Context,
resp *http.Response,
account *Account,
originalModel string,
customTools map[string]bool,
functionTools map[string]bool,
@@ -220,7 +225,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses(
c.Writer.Flush()
}
scan := s.scanCCStream(c, resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) {
scan := s.scanCCStream(c, resp, account, upstreamModel, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) {
events := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, state)
s.cacheReasoningItemsFromEvents(events)
writeEvents(events)
@@ -0,0 +1,148 @@
//go:build unit
package service
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// runOllamaResponsesChatFallback 直接走 /v1/responses → raw CC 降级桥
// forwardResponsesViaRawChatCompletions(与 raw 路径测试同风格,直接调桥函数)。
func runOllamaResponsesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) {
t.Helper()
gin.SetMode(gin.TestMode)
contentType := "application/json"
if stream {
contentType = "text/event-stream"
}
upstreamResp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Content-Type": []string{contentType},
"x-request-id": []string{"rid_ollama_responses_fallback"},
},
Body: io.NopCloser(strings.NewReader(upstreamBody)),
}
upstream := &httpUpstreamRecorder{resp: upstreamResp}
svc := &OpenAIGatewayService{
cfg: rawChatCompletionsTestConfig(),
httpUpstream: upstream,
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
result, err := svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, body)
require.NoError(t, err)
require.NotNil(t, result)
return rec, upstream
}
func TestResponsesChatFallback_OllamaDeepSeek_ClampMaxOutputTokens(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 601)
t.Run("256000 clamps to 65535", func(t *testing.T) {
body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
_, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String())
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
})
t.Run("1000 stays 1000", func(t *testing.T) {
body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
_, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
})
}
// TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧
// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content
// 在归一化之后产出完全相同的 reasoning 输出(同一转换路径跑多个输入对比)。
// normalizeStreamIDs 抹平响应里每次运行随机生成的 item id 与 created_at 时间戳,
// 使两条输入路径的 SSE 输出可做语义级字节比较。
var normalizeStreamIDs = regexp.MustCompile(`("item_[0-9a-f]+"|"created_at":[0-9]+)`)
func TestResponsesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 602)
body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":true}`)
run := func(reasoningField string) string {
upstreamBody := strings.Join([]string{
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`,
"",
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`,
"",
"data: [DONE]",
"",
}, "\n")
rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamBody, true)
return normalizeStreamIDs.ReplaceAllString(rec.Body.String(), `"item_x"`)
}
baseline := run(`"reasoning_content":"abc"`)
require.Contains(t, baseline, "response.reasoning_summary_text.delta")
require.Contains(t, baseline, `"delta":"abc"`)
require.Contains(t, baseline, `"delta":"final answer"`)
for _, tc := range []struct {
name string
field string
}{
{name: "delta.reasoning alias", field: `"reasoning":"abc"`},
{name: "delta.thinking alias", field: `"thinking":"abc"`},
} {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, baseline, run(tc.field), "归一化后输出必须与 reasoning_content 基线完全一致")
})
}
}
func TestResponsesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 603)
body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":1000,"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, _ := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, "reasoning", gjson.Get(rec.Body.String(), "output.0.type").String())
require.Equal(t, "abc", gjson.Get(rec.Body.String(), "output.0.summary.0.text").String())
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.1.content.0.text").String())
}
func TestResponsesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) {
official := officialDeepSeekTestAccount(604)
body := []byte(`{"model":"deepseek-v4-flash","input":"hello","max_output_tokens":256000,"stream":false}`)
// thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃,
// 输出不出现 reasoning item(与不挂钩子的原始路径行为一致)。
upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, upstream := runOllamaResponsesChatFallback(t, official, body, upstreamJSON, false)
// 请求侧不被 clamp:max_completion_tokens 保持 256000。
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
// 响应侧不归一化:输出只有 message item,没有 reasoning item。
require.NotContains(t, rec.Body.String(), `"type":"reasoning"`)
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String())
}
func TestResponsesChatFallback_OllamaGLM_Untouched(t *testing.T) {
account := ollamaUpstreamTestAccount(PlatformDeepseek, 605)
body := []byte(`{"model":"glm-5.3-flash","input":"hello","max_output_tokens":256000,"stream":false}`)
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
rec, upstream := runOllamaResponsesChatFallback(t, account, body, upstreamJSON, false)
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
require.NotContains(t, rec.Body.String(), `"type":"reasoning"`)
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "output.0.content.0.text").String())
}