Skip to content

fix(ollama): preserve reasoning and tool-call context - #6605

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/ollama-reasoning-content
Aug 10, 2026
Merged

Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
seefs001:fix/ollama-reasoning-content

Conversation

@seefs001

@seefs001 seefs001 commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

对OpenAI chat completions -> ollama chat 缺失的部分进行补全

reasoning_content/reasoning 转 ollama thinking
reasoning_effort/reasoning.effort -> think( none -> think=none)
json_object -> json
stream 显式处理
tool_call_id 补全

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

Summary by CodeRabbit

  • New Features

    • Improved compatibility with tool calls by preserving call IDs across requests and streamed responses.
    • Added support for assistant reasoning content and tool names in Ollama interactions.
    • Improved handling of response formats and JSON schemas.
  • Bug Fixes

    • Ensured chat and generation requests consistently include stream settings.
    • Added clearer errors when response-format schemas cannot be parsed.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Ollama request conversion now preserves assistant reasoning, response formats, tool-call identifiers, and tool names. Chat and generate requests always serialize stream settings. Stream tests validate upstream and generated tool-call IDs.

Changes

Ollama conversion updates

Layer / File(s) Summary
Request contracts and response formats
relay/channel/ollama/dto.go, relay/channel/ollama/relay-ollama.go
Ollama DTOs now include tool-call IDs and always serialize stream flags. Chat and generate conversions share response-format handling and return schema parsing errors.
Message and tool-call conversion
relay/channel/ollama/relay-ollama.go
Assistant reasoning maps to Ollama thinking data. Tool messages retain call IDs and resolve tool names. Tool arguments and stop lists use shared helpers.
Stream identifier preservation
relay/channel/ollama/stream.go, relay/channel/ollama/stream_test.go
Streamed tool calls preserve upstream IDs and generate indexed fallback IDs. Tests assert both behaviors.
Shared decoding
relay/channel/ollama/relay-ollama.go
Version-response decoding uses common.Unmarshal.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

Possibly related PRs

  • QuantumNous/new-api#6604 — Modifies the same Ollama conversion path to preserve assistant reasoning and tool-call data.

Suggested reviewers: calcium-ion

Poem

A rabbit watched the tool calls hop,
And kept each ID from frame to frame.
It carried thoughts through Ollama’s stream,
While false flags stayed in the JSON scheme.
“No lost reasoning,” whispered the hare.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR also changes response-format conversion, stream serialization, tool-call IDs, and decoding behavior, which are not required by [#6603]. Split unrelated response-format, streaming, tool-call ID, and decoding changes into separate pull requests or link them to explicit issues.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the Ollama fix and the preservation of reasoning and tool-call context.
Linked Issues check ✅ Passed The changes map assistant reasoning content to Ollama Thinking as required by [#6603].
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@relay/channel/ollama/relay-ollama.go`:
- Around line 183-198: In the tool-call parsing loop around common.Unmarshal,
stop discarding JSON unmarshal errors and log the error with sufficient context,
including the affected tool call or function name. Preserve the existing
fallback behavior for nil arguments while ensuring malformed
tc.Function.Arguments produces a visible diagnostic.
- Around line 42-69: Update the effort switch in openAIChatToOllamaChat to map
OpenAI’s “minimal” value to Ollama’s “low” and “xhigh” to “max”; remove the
converter-level error for other unsupported values so they pass through for
Ollama to validate, while preserving existing mappings and error handling for
reasoning unmarshalling and think marshaling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2da144aa-6702-4142-b767-651328fb300b

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab0202 and 8ac5908.

📒 Files selected for processing (4)
  • relay/channel/ollama/dto.go
  • relay/channel/ollama/relay-ollama.go
  • relay/channel/ollama/stream.go
  • relay/channel/ollama/stream_test.go

Comment on lines 42 to +69
func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*OllamaChatRequest, error) {
think := r.Think
if len(think) == 0 {
effort := r.ReasoningEffort
if len(r.Reasoning) > 0 {
var reasoning dto.Reasoning
if err := common.Unmarshal(r.Reasoning, &reasoning); err != nil {
return nil, fmt.Errorf("invalid ollama reasoning: %w", err)
}
effort = lo.CoalesceOrEmpty(reasoning.Effort, effort)
}
if effort != "" {
var thinkValue any
switch effort {
case "none":
thinkValue = false
case "low", "medium", "high", "max":
thinkValue = effort
default:
return nil, fmt.Errorf("unsupported ollama reasoning effort %q", effort)
}
var err error
think, err = common.Marshal(thinkValue)
if err != nil {
return nil, fmt.Errorf("marshal ollama think: %w", err)
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

What values does Ollama's think API parameter currently accept, and what reasoning_effort values does OpenAI currently support across models?

💡 Result:

Ollama's think API parameter accepts boolean values (true/false) and reasoning level strings: "low", "medium", "high", and "max" [1][2]. While these values are supported at the top level for most models, the "max" level is sometimes specifically designated for use within the options object (e.g., options: {"think": "max"}) depending on the specific model and API implementation [3]. Some models, such as GPT-OSS, strictly require one of the reasoning levels ("low", "medium", or "high") and do not accept boolean values [1][4][5]. OpenAI supports several reasoning_effort values across its reasoning-capable models: "none", "minimal", "low", "medium", "high", "xhigh", and "max" [6][7][8]. The availability of these values is model-dependent [6][7]. For instance, certain models may default to "medium" and not support "none", while others might support "xhigh" or "max" only on specific advanced versions [8][9]. Users should consult model-specific documentation to verify which effort levels are compatible with a chosen model [6][7].

Citations:


🌐 Web query:

site:developers.openai.com/api/docs/guides/reasoning reasoning_effort minimal xhigh

💡 Result:

The reasoning_effort parameter is a configuration setting in OpenAI's reasoning models (such as the o-series) that controls the amount of computational processing, or thinking, the model performs before generating a final response [1]. By adjusting this parameter, you can influence the trade-off between latency, cost, and output quality [1]. The available settings typically range from minimal to max, with higher settings instructing the model to spend more time planning, analyzing, and reasoning through complex problems [1]. Key characteristics of these effort levels include: minimal: Prioritizes speed and lower token usage, making it suitable for simpler tasks where immediate, direct answers are preferred [1]. xhigh and max: Direct the model to engage in deeper, more comprehensive reasoning, which is recommended for complex debugging, long-horizon research, high-stakes decision-making, and other intellectually demanding workflows where accuracy and quality are more critical than low latency [1]. In practice, the models are designed to be adaptive, meaning that even with a specific effort setting, they may use fewer tokens for simple tasks and "think harder" only when the complexity of the input requires it [1]. The default effort setting, such as medium, is generally considered the best starting point for balancing performance, quality, and reliability [1].

Citations:


🌐 Web query:

site:docs.ollama.com/capabilities/thinking Ollama think low medium high max false true

💡 Result:

In Ollama, the think parameter is used to control the reasoning trace for supported models [1]. Users can specify the level of reasoning or toggle the feature on and off using the following options: Boolean values: - true: Enables the thinking process (default for supported models) [1]. - false: Disables the reasoning trace [1]. Thinking levels: - low, medium, high: These levels allow users to tune the length and depth of the model's reasoning trace [1]. - max: This option requests the highest level of thinking available for the model [1]. Note that some specific models, such as GPT-OSS, only accept the levels (low, medium, or high) rather than boolean values [1]. In addition to the API parameters, users can manage thinking in the CLI using commands like /set think, /set nothink, or the --hidethinking flag to perform reasoning without displaying the trace in the final output [1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the converter and nearby stream/channel support without executing repository code.
wc -l relay/channel/ollama/relay-ollama.go
sed -n '1,140p' relay/channel/ollama/relay-ollama.go
printf '\n--- streamSupportedChannels references ---\n'
rg -n "streamSupportedChannels|OpenAIChatToOllamaChat|openAIChatToOllamaChat" relay/channel/ollama relay -g '*.go' || true

Repository: QuantumNous/new-api

Length of output: 4646


Allow unsupported OpenAI reasoning-effort values to pass through.

OpenAI accepts minimal and xhigh, but this converter only maps none, low, medium, high, and max. Those values hit default, return an error, and abort the Ollama request conversion. Map minimal to low and xhigh to max, and let Ollama reject any other think value it does not support.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/ollama/relay-ollama.go` around lines 42 - 69, Update the effort
switch in openAIChatToOllamaChat to map OpenAI’s “minimal” value to Ollama’s
“low” and “xhigh” to “max”; remove the converter-level error for other
unsupported values so they pass through for Ollama to validate, while preserving
existing mappings and error handling for reasoning unmarshalling and think
marshaling.

Comment on lines 183 to 198
for _, tc := range parsed {
var args interface{}
if tc.Function.Arguments != "" {
_ = json.Unmarshal([]byte(tc.Function.Arguments), &args)
_ = common.Unmarshal([]byte(tc.Function.Arguments), &args)
}
if args == nil {
args = map[string]any{}
}
oc := OllamaToolCall{}
oc := OllamaToolCall{ID: tc.ID}
oc.Function.Name = tc.Function.Name
oc.Function.Arguments = args
calls = append(calls, oc)
if tc.ID != "" {
toolNamesByCallID[tc.ID] = tc.Function.Name
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Malformed tool-call arguments fail silently instead of surfacing an error.

common.Unmarshal errors on line 186 are discarded with _ =. If tc.Function.Arguments is malformed JSON, args silently falls back to map[string]any{}, and the tool call is forwarded to Ollama with empty arguments instead of the original (possibly still partially useful) payload or a visible error. This can silently drop tool-call context in multi-turn flows, which is the exact failure mode this PR aims to fix for reasoning content.

Log the unmarshal error so malformed payloads are diagnosable, instead of dropping them without a trace.

🐛 Proposed fix to surface unmarshal failures
 					var args interface{}
 					if tc.Function.Arguments != "" {
-						_ = common.Unmarshal([]byte(tc.Function.Arguments), &args)
+						if err := common.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
+							logger.LogError(c, "ollama tool call arguments decode error: "+err.Error())
+						}
 					}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for _, tc := range parsed {
var args interface{}
if tc.Function.Arguments != "" {
_ = json.Unmarshal([]byte(tc.Function.Arguments), &args)
_ = common.Unmarshal([]byte(tc.Function.Arguments), &args)
}
if args == nil {
args = map[string]any{}
}
oc := OllamaToolCall{}
oc := OllamaToolCall{ID: tc.ID}
oc.Function.Name = tc.Function.Name
oc.Function.Arguments = args
calls = append(calls, oc)
if tc.ID != "" {
toolNamesByCallID[tc.ID] = tc.Function.Name
}
}
for _, tc := range parsed {
var args interface{}
if tc.Function.Arguments != "" {
if err := common.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
logger.LogError(c, "ollama tool call arguments decode error: "+err.Error())
}
}
if args == nil {
args = map[string]any{}
}
oc := OllamaToolCall{ID: tc.ID}
oc.Function.Name = tc.Function.Name
oc.Function.Arguments = args
calls = append(calls, oc)
if tc.ID != "" {
toolNamesByCallID[tc.ID] = tc.Function.Name
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/ollama/relay-ollama.go` around lines 183 - 198, In the
tool-call parsing loop around common.Unmarshal, stop discarding JSON unmarshal
errors and log the error with sufficient context, including the affected tool
call or function name. Preserve the existing fallback behavior for nil arguments
while ensuring malformed tc.Function.Arguments produces a visible diagnostic.

@Calcium-Ion
Calcium-Ion merged commit 8ad159a into QuantumNous:main Aug 10, 2026
2 of 3 checks passed
latioswang added a commit to trycortexai/new-api that referenced this pull request Aug 10, 2026
* fix(relay): set Request.GetBody so the HTTP/2 transport can transparently retry after an upstream stream reset (QuantumNous#6249)

* fix(relay): set Request.GetBody so the HTTP/2 transport can transparently retry after an upstream stream reset

The outbound request body is a type-erased io.Reader over BodyStorage, so
net/http cannot derive Request.GetBody (it only does so for *bytes.Reader,
*bytes.Buffer and *strings.Reader). With GetBody nil, the HTTP/2 transport
cannot transparently retry a request once the body has been written and the
upstream resets the stream with a retryable error (REFUSED_STREAM, or a
connection-level GOAWAY); the relay request then fails with:

    http2: Transport: cannot retry err [...] after Request.Body was written;
    define Request.GetBody to avoid this error

This affects every relay path that goes through DoApiRequest (chat, claude,
gemini, responses, embedding, image, rerank).

BodyStorage (memory and disk) already implements io.Seeker, so replay support
only needed wiring:

- NewOutboundJSONBody additionally returns a getBody that rewinds the storage
  and hands out a fresh non-closing reader. The transport only calls GetBody
  after the previous attempt's body has been abandoned, so the rewind cannot
  race an in-flight read.
- RelayInfo carries it in the new UpstreamRequestGetBody field, set alongside
  UpstreamRequestBodySize by the handlers that build storage-backed bodies.
- applyUpstreamGetBody (symmetric with applyUpstreamContentLength) wires it
  into DoApiRequest/DoFormRequest/DoTaskApiRequest, only when req.GetBody is
  still nil.

Also remove the hand-rolled GetBody override in DoTaskApiRequest: it returned
the same already-consumed reader, so any transport-level replay would have
silently sent an empty body, and it clobbered the correct snapshot-based
GetBody that net/http derives from the *bytes.Reader bodies the task adaptors
pass in. For non-replayable bodies GetBody now stays nil, so a retry fails
loudly instead of corrupting the request.

Covered by unit tests plus an end-to-end raw-frame HTTP/2 test that resets
the first stream with REFUSED_STREAM after the body is written and asserts
the transport transparently retries with the complete body.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(relay): hand out independent readers from GetBody (address review)

Per the http.Request.GetBody contract ("returns a new copy of Body"),
each call must yield a reader with its own cursor. The previous
implementation rewound and reused the shared BodyStorage, so two
consecutive GetBody readers would interfere with each other, and a
replay could disturb the primary body's offset under extreme transport
timing (e.g. attempt N's body write not yet fully abandoned when the
transport builds attempt N+1).

Instead of snapshotting the payload (an extra copy), add
BodyStorage.NewReader, which returns an independent zero-copy reader:

- memory mode: a fresh bytes.Reader over the same immutable backing
  array;
- disk mode: a separate file descriptor over the cache file, so the
  transport closing a replayed body only closes that descriptor.

NewOutboundJSONBody's getBody now simply hands out storage.NewReader,
and once the handler releases the storage, GetBody fails with
ErrStorageClosed instead of replaying stale data.

Tests: interleaved reads across two replay readers and the primary
body each observe exactly their own byte stream, for both the memory
and the disk-backed storage; the existing GetBody and HTTP/2 retry
suites still pass (h2 e2e tests flake-free with -count=20).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(relay): bind replayable metadata on pass-through requests

* fix(relay): reset upstream body metadata between channels

* test(relay): cover replay across retries and channel attempts

* fix(relay): stop following upstream redirects

---------

Co-authored-by: Claude Fable 5 <[email protected]>

* refactor(relay): move replay metadata onto request bodies

* Merge commit from fork

* feat(channels): refine fetched model categorization (QuantumNous#6632)

* feat(channels): refine fetched model categorization

* fix: channel category

* fix: hy3 category

* fix: test Claude/Gemini endpoints with native request format (QuantumNous#6698)

* feat(rate-limit): add user critical rate limit middleware for access token and aff transfer routes

* fix: 修复兑换码额度精度损失 (QuantumNous#6685)

* fix: 修复兑换码额度精度损失(QuantumNous#6680)

* fix(redemption): guard update data integrity

* CI: enhance release synchronization workflow with optional file syncing

* fix(ali): stop injecting top_p into requests that omit it (QuantumNous#6674)

* fix(channels): classify Qwen TTS models correctly (QuantumNous#6711)

* feat(channels): add auto-disable-only channel test mode (QuantumNous#6728)

* perf(web): debounce server and large-list searches (QuantumNous#6727)

* fix: record reasoning effort consistently in usage logs (QuantumNous#6641)

* feat(relay): expose user and group context to parameter overrides (QuantumNous#6534)

* fix(ollama): preserve reasoning and tool-call context (QuantumNous#6605)

* fix: backend length validation (QuantumNous#5548)

* feat(billing): highlight matched conditional multipliers in logs (QuantumNous#6561)

* feat(billing): highlight matched conditional multipliers in usage logs

* fix(billing): make request rule tracing stable and type-safe

* fix(web): require confirmation before rotating access token (QuantumNous#6749)

---------

Co-authored-by: Lucas <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: CaIon <[email protected]>
Co-authored-by: RedwindA <[email protected]>
Co-authored-by: Seefs <[email protected]>
Co-authored-by: lihu-001 <[email protected]>
Co-authored-by: ENCHIGO <[email protected]>
0401lucky pushed a commit to 0401lucky/new-api that referenced this pull request Aug 16, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Aug 17, 2026
DayFliggy pushed a commit to DayFliggy/Ren2Hub that referenced this pull request Aug 17, 2026
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
biubiubiu125 pushed a commit to biubiubiu125/newapi that referenced this pull request Aug 29, 2026
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
MAakber pushed a commit to MAakber/new-api that referenced this pull request Sep 11, 2026
dofastted pushed a commit to dofastted/new-api that referenced this pull request Sep 16, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
piexian added a commit to piexian/new-api that referenced this pull request Oct 4, 2026
…s 77-80 (#16)

* fix: purge authentication data on hard user deletion (QuantumNous#6168)

* fix: purge authentication data on hard user deletion

* fix: fail closed when 2FA status lookup fails

* fix: reject stale Telegram login callbacks

* fix(twofa): prevent concurrent backup code and lockout bypasses

* fix(auth): harden user deletion and Telegram verification

(cherry picked from commit b6b97a6)

* fix: infer MiniMax vendor for MiniMax models (QuantumNous#6164)

* fix: infer MiniMax vendor for MiniMax models

* Delete model/pricing_default_test.go

---------

Co-authored-by: duanxufu <[email protected]>
(cherry picked from commit a63364d)

* fix(data-table): update table body immediately when toggling columns (QuantumNous#6253)

DataTableRow's React.memo did not depend on columnVisibility.
TanStack row references stay stable when visible columns change, so the
table body did not refresh after View -> Toggle columns until another
action rebuilt the column definitions.

Capture a visible column id signature (visibleColumnIds) outside the
memo and compare it, matching the existing isSelected snapshot pattern.
All tables that use DataTableRow pick up the fix.

(cherry picked from commit dc9aeab)

* fix: prevent duplicate tool calls in Responses-to-Chat streaming (QuantumNous#6225)

When a function call was already registered under its output_index key
via response.output_item.added, the synthetic events built from the
terminal response.completed output carry no output_index and resolve to
a different item-based key. ensureToolForEvent then created a second
tool index and resent the full arguments, so Chat Completions clients
received the same tool call twice.

Reuse the tool registered under itemIDToKey/callIDToKey before creating
a new one, and alias the new key to the existing tool.

Co-authored-by: Claude Fable 5 <[email protected]>
(cherry picked from commit 1086038)

* fix: drop realtime beta header for ga models and register new ones (QuantumNous#6032)

(cherry picked from commit 16bfae1)

* fix: prevent duplicate suno task refunds via cas status update (QuantumNous#6074)

* fix: prevent duplicate suno task refunds via cas status update

* fix: reconcile failed task refunds

---------

Co-authored-by: CaIon <[email protected]>
(cherry picked from commit e0d5156)

* fix: log response body when parsed upstream error message is empty

When an upstream error response parses as valid JSON but yields no usable
error message (e.g. an aggregator gateway returning {"error":{"message":""}}),
RelayErrorHandler previously produced a bare "bad response status code N"
error with no trace of the original body, making the failure undiagnosable.
Log the body preview in that case, mirroring the existing behavior for
unparseable bodies.

(cherry picked from commit 84a79b6)

* feat: add gemini-3-pro-image and gemini-3.1-flash-image GA models (QuantumNous#6371)

(cherry picked from commit 8b41def)

* fix: 慢查询/错误 SQL 日志参数化 (QuantumNous#6493)

* fix: parameterize slow/error SQL logs to avoid leaking credentials

* fix: validate SQL_SLOW_THRESHOLD_MS range

* fix: sanitize database driver error messages in SQL logs

* refactor: sanitize at gorm log writer seam to keep caller attribution

(cherry picked from commit c3db414)

* feat: support zstd request decompression (QuantumNous#6545)

(cherry picked from commit 0f9f668)

* fix(aws): cancel Bedrock requests on client disconnect (QuantumNous#6589)

* fix(aws): cancel Bedrock requests on client disconnect

* fix(billing): log effective usage billing path

(cherry picked from commit bd585d7)

* feat(rate-limit): add user critical rate limit middleware for access token and aff transfer routes

(cherry picked from commit 1da23d6)

* fix(ali): stop injecting top_p into requests that omit it (QuantumNous#6674)

(cherry picked from commit 2399de9)

* fix(ollama): preserve reasoning and tool-call context (QuantumNous#6605)

(cherry picked from commit 8ad159a)

* fix: backend length validation (QuantumNous#5548)

(cherry picked from commit d49160f)

* fix: 修复 Gemini 风格 /v1/models 列表请求 (QuantumNous#6199)

* fix: support Gemini model listing on v1 route

* test: cover Gemini query key model listing

(cherry picked from commit 3d5dc36)

* fix(topup): settle recharge orders atomically

(cherry picked from commit 50e5377)

* fix(billing): 异步任务退款时同步减少 used_quota (QuantumNous#6795)

* fix(billing): 异步任务退款时同步减少 used_quota
退款时仅恢复了 quota(剩余额度),但未同步减少 used_quota(已用额度),
导致"总额度"(quota + used_quota)随退款次数持续虚增,超出用户实际充值金额。

修复三处退款路径:
- RefundTaskQuota:任务失败完整退款
- RecalculateTaskQuota:差额结算退款分支
- controller/midjourney.go:Midjourney 任务失败退款

新增 model.UpdateUserUsedQuota 公开函数,仅调整 used_quota 不影响 request_count。

* fix(billing): 任务退款时同步扣减渠道 used_quota

* fix(billing): complete async task refund accounting

* style(model): group internal Midjourney fields

---------

Co-authored-by: CaIon <[email protected]>
(cherry picked from commit 58d4e9b)

* fix(ali): 修复阿里图片模型映射后仍使用原始模型名判断协议的问题 (QuantumNous#6772)

* feat(ali): support Qwen Image 3 requests

* refactor(ali): narrow Qwen Image 3 support

* fix(ali): focus image model mapping fix

(cherry picked from commit 93d2df8)

* fix(topup): reject uncreditable orders before payment (QuantumNous#6845)

* fix(topup): reject uncreditable orders before payment

* fix(topup): align zero-ratio Stripe validation

* fix(topup): mirror settlement conversions in validation

(cherry picked from commit 2a0ce34)

* fix: settle Responses cached token usage (QuantumNous#6892)

(cherry picked from commit f116414)

* fix(billing): 修复时间规则恒真表达式导致倍率全天生效 (QuantumNous#6934)

(cherry picked from commit ac381ac)

* fix(relay): 请求参数校验错误返回 HTTP 400 (QuantumNous#6774)

* fix(relay): return 400 for invalid request parameters

(cherry picked from commit 0f2a207)

* fix(ali): honor image response format (QuantumNous#5513) (QuantumNous#7048)

(cherry picked from commit 0bee5d4)

* fix(sqlite): enable WAL + working busy timeout + _txlock=immediate to stop concurrent write lockouts (QuantumNous#7030)

* fix(sqlite): enable WAL + working busy timeout + _txlock=immediate to stop concurrent write lockouts

(cherry picked from commit 1751f43)

* fix(relay): bound the wait for upstream response headers (fixes unbounded heap growth → OOM) (QuantumNous#6949)

* fix(relay): bound the wait for upstream response headers (fixes unbounded heap growth)

The relay transport sets a dial timeout, a TLS handshake timeout and an expect-continue
timeout, but nothing bounds how long it waits for the upstream *response headers* after
the request has been written. An upstream that accepts the connection and then never
answers -- without sending FIN/RST, which is what happens when a NAT/firewall silently
drops the flow or the provider hangs -- parks the goroutine in
net/http.(*persistConn).roundTrip forever.

That goroutine keeps the whole request alive, which in practice means three copies of the
request body stay reachable for the lifetime of the process: the raw bytes from
io.ReadAll in CreateBodyStorageFromReader, the decoded messages held as json.RawMessage,
and the re-marshalled upstream body from common.Marshal. BodyStorageCleanup cannot help
here: it runs after c.Next() returns, and for these requests c.Next() never returns.

Measured on v1.0.0-rc.23 in production (see QuantumNous#6947 for the full evidence):

  - 23 goroutines stuck in persistConn.roundTrip on a single 40h-old instance,
    blocked between 353 and 1894 minutes (5.9h to 31.5h)
  - 96.9% of the live heap, sampled after a forced GC, attributable to those three
    body copies (HeapAlloc 892 MiB surviving three GC cycles; HeapObjects dropping
    30x while bytes dropped only 25%)
  - the live floor grows with uptime: 33.7 MiB at 0.1h, 89.2 at 13.8h, 510.0 at 40.1h,
    955.2 at 146.8h, OOMKilled at 172.9h -- same image, same config, same load

Doubling the memory limit and adding GOMEMLIMIT only moved the OOM from 132h to 172.9h.

RELAY_TIMEOUT (http.Client.Timeout) cannot be used for this: it covers the whole response
read and would cut legitimate long streaming calls, which is why it defaults to 0.
ResponseHeaderTimeout only bounds the wait for the headers; streaming after they arrive is
unaffected.

The default is deliberately generous. Non-streaming upstreams usually send the response
headers only once generation has finished, so the value has to leave room for a long
completion. 1800s is 12x shorter than the shortest hang observed here while leaving
several times the headroom a normal non-streaming request needs; 0 restores the previous
unbounded behaviour.

The assignment goes next to the other transport.* lines rather than inside the else
branch: newRelayHTTPTransport() normally takes the http.DefaultTransport.Clone() path,
and DefaultTransport does not set ResponseHeaderTimeout either.

This repo already sets ResponseHeaderTimeout on its other outbound transports
(controller/model_sync.go, controller/ratio_sync.go); the relay path appears to have
been missed.

Refs QuantumNous#6947. Likely also the root cause of QuantumNous#6731, which reported the same symptom
(production OOM on /v1/responses after ~64h) but was closed for template reasons.

* review: clamp overflowing timeout values and switch the test to testify

Addresses the two CodeRabbit findings on this PR.

Overflow (common/init.go:113): a RELAY_RESPONSE_HEADER_TIMEOUT beyond ~9.2e9 seconds
overflows time.Duration and can wrap into a *tiny positive* timeout, which would cut
every relay request instead of only the stuck ones. The value is now clamped before the
conversion, with regression tests for both the negative and the overflowing input.

I did not add fail-on-startup validation for negative values, for two reasons: the
existing `if seconds > 0` guard already treats them as "disabled", and the neighbouring
env-driven timeouts in this file are less strict still -- RelayIdleConnTimeout is
converted with no guard at all. Failing startup on a bad value would be a behaviour
change out of step with the rest of the file; happy to add it if you'd prefer that
direction repo-wide.

Test style: switched to testify (require.Equal / require.Zero / require.Positive), which
is what every other test under service/ uses.

go build, go vet and go test ./common/... ./service/... pass.
(`go build ./...` fails on the `web/dist` embed both with and without this change -- the
frontend bundle is not checked in.)

(cherry picked from commit b518d00)

* fix: adapt relaykit hosttypes to types and add missing errors import

* fix(log): preserve quota in usage statistics (QuantumNous#7108)

* fix(log): preserve quota in usage statistics

(cherry picked from commit 8c8c415)

* fix(model): do not treat no-op system task state writes as lock loss (QuantumNous#7135)

(cherry picked from commit b7017c2)

* perf(common): 批量复制 RawMessage,优化请求深拷贝 (QuantumNous#7221)

* perf(relay): bulk-copy Responses raw JSON fields

* perf(common): share RawMessage deep-copy optimization

---------

Co-authored-by: CaIon <[email protected]>
(cherry picked from commit 2cf177a)

* fix(audio): normalize file extension case in GetAudioDuration (QuantumNous#7321)

Uppercase or mixed-case extensions (e.g. .MP3, .WAV) fell through to the
default branch and returned "unsupported audio format", so audio token
usage could not be measured. Lowercase the extension before the switch.

Closes QuantumNous#7319

(cherry picked from commit 76f7daf)

* fix(ollama): preserve tool calls from final stream frame | 保留流式末尾帧的 tool calls (QuantumNous#7376)

(cherry picked from commit 8e5e091)

* fix(gemini): reject :countTokens as an unknown route instead of relaying it as generateContent (QuantumNous#7388)

(cherry picked from commit 81336fc)

* fix(relay): request stream usage on every cross-protocol conversion to OpenAI chat (QuantumNous#7389)

(cherry picked from commit 610334d)

* fix(billing): count upstream images by payload instead of data length

OpenaiImageHandler and the JSON-to-SSE fallback billed the gjson data.#
element count. An object-shaped data yielded 0 and kept the requested n
while the SSE fallback dropped the image and sent only [DONE]; one image
split into a url entry and a b64_json entry billed twice; entries carrying
only revised_prompt billed as images.

Count images by payload: an object with url or b64_json is one image and
arrays bill max(url entries, b64_json entries). The SSE fallback forwards
one completed event per image payload for both shapes. xAI inherits the
fix through OpenaiImageHandler.

(cherry picked from commit 07578fa)

* fix(relay): map Images output_tokens_details into img_o billing (QuantumNous#7410)

(cherry picked from commit e2bb05f)

* fix(task): accept any 2xx upstream status on task submission (QuantumNous#7478)

(cherry picked from commit d61d6be)

* fix(auth): reject non-standard roles when creating a user (QuantumNous#7531)

(cherry picked from commit 2506e1b)

* fix: isolate TLS configs across HTTP transports (QuantumNous#7627)

(cherry picked from commit feefe09)

* fix(model): migrate database constraints, options primary key, and avoid redundant migrations

* feat(channel): add Sub2API, NewAPI, vLLM, and SGLang channels (77-80) and Tencent TokenHub

---------

Co-authored-by: Seefs <[email protected]>
Co-authored-by: fuxdev <[email protected]>
Co-authored-by: duanxufu <[email protected]>
Co-authored-by: DawnMoon1542 <[email protected]>
Co-authored-by: Niku <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: feitianbubu <[email protected]>
Co-authored-by: CaIon <[email protected]>
Co-authored-by: bigsong <[email protected]>
Co-authored-by: ENCHIGO <[email protected]>
Co-authored-by: zhibisora <[email protected]>
Co-authored-by: wans10 <[email protected]>
Co-authored-by: Scott <[email protected]>
Co-authored-by: Shawn Wang <[email protected]>
Co-authored-by: Qi <[email protected]>
Co-authored-by: zcxads666 <[email protected]>
Co-authored-by: Alex Xiang <[email protected]>
Co-authored-by: PuppetKL <[email protected]>
Co-authored-by: Xayinn <[email protected]>
Co-authored-by: txgo <[email protected]>
Co-authored-by: jimmyleocn <[email protected]>
Co-authored-by: mingisrookie <[email protected]>
Co-authored-by: Vladimir Babin <[email protected]>
Co-authored-by: sxhstc <[email protected]>
timwenx pushed a commit to timwenx/new-api that referenced this pull request Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: Ollama 渠道请求侧不回放 assistant 推理(reasoning_content → Thinking 未映射)

2 participants