Compare commits

...
10 Commits
Author SHA1 Message Date
super 6320967c2b docs(readme): 更新中英文 NovaLink 功能介绍 2026-12-05 15:16:57 +08:00
super 98df62db7d merge: 同步 new-api 上游至 080997bf2 2026-12-05 14:25:19 +08:00
Calcium-Ion 080997bf23 fix(relay): Claude 流开始输出后不再换渠道重试,上游 error 转给客户端 (#8550)
上游在流中途发来 error 事件(如 overloaded_error)时,HandleStreamResponseData
返回 500。重试判断不知道这次尝试已经给客户端写过事件,换渠道重来,新流接在
半截旧流后面,客户端看到两个 message_start;全部失败时还会再补一个 error。

- 还没有事件写给客户端:照旧可以重试。
- 已写出事件但没有输出:不重试,由 relay 在同一条流里发 error 并退款。
- 已有输出:不重试,error 事件转给客户端(保留上游 type 和 message),
  已送达的输出按上游报告的 usage 计费,没报告则按估算。
- Claude 转 Responses:发出 response.failed 后同样只为已送达的输出计费,
  没有输出不收费,流状态记为失败。

controller 的 writeRelayStreamError 移到 helper.StreamErrorData,供 Claude
处理器复用。
2026-12-03 18:34:34 +08:00
Seefs 5911c8cca8 fix(middleware): abort canceled Redis rate-limit checks with 499 (#8512)
Treat Redis rate-limit failures as client-closed (HTTP 499, no error log) only when both the Redis error and request context report context.Canceled, while keeping deadline timeouts and Redis failures fail-closed with HTTP 500.

Closes #8462
2026-12-02 19:06:23 +08:00
Seefs 5f56c685d4 fix(gemini): emit stream finish_reason only in dedicated terminal chunk (#8522)
Stop setting finish_reason=tool_calls unconditionally on every Gemini stream chunk containing a functionCall, omit empty content strings on non-text chunks, and strip upstream finish reasons from payload chunks so GeminiChatStreamHandler and GeminiToChatStreamState emit finish_reason once in an empty-delta terminal chunk.
2026-12-02 19:03:33 +08:00
Seefs 16369071a1 fix(relay): normalize /pg/ playground path for route matching (#8534)
Playground sends chat completions to /pg/chat/completions while GenRelayInfo maps info.RequestURLPath to /v1/chat/completions. Distributor path filters, per-route pass-through lookup in InitChannelMeta, and route resolution in the advanced custom and provider plugin adaptors still read raw c.Request.URL.Path, rejecting advanced custom, vLLM/SGLang preset, and provider plugin channels in Playground.

Add common.NormalizeRelayPath to map /pg/... paths onto /v1/... at the route matching and provider plugin hook boundaries while keeping c.Request.URL.Path unchanged for Playground detection, group selection, and request logs.

Closes #5966
2026-12-02 15:42:41 +08:00
Seefs 1c0b4d6471 fix(billing): cap subscription usage at settlement instead of rejecting overrun (#8523)
* fix(billing): cap subscription usage at settlement instead of rejecting overrun

When a post-request settlement delta exceeds the remaining subscription quota,
PostConsumeUserSubscriptionDelta rejects the whole update and leaves
amount_used below amount_total. Subsequent requests with small pre-consume
estimates keep passing admission and become free, and secondary subscriptions
are never selected.

Add model.SettleUserSubscriptionDelta to cap positive settlement charges at
AmountTotal (or math.MaxInt64 for unlimited plans), log the uncovered
remainder, and return the applied delta. Route SubscriptionFunding.Settle and
async task settlement to it while keeping PostConsumeUserSubscriptionDelta
strict for reservations and Realtime in-session metering, and without changing
the FundingSource interface signature.

* test(billing): add regression coverage for capped subscription settlement

Consolidate regression cases in service/subscription_settle_test.go covering SettleUserSubscriptionDelta finite capping, unlimited MaxInt64 saturation, refund zero-flooring, BillingSession dual-subscription exhaustion and switching, strict PostConsumeQuota rejection for Realtime in-session metering, and async RecalculateTaskQuota overrun capping.
2026-12-02 15:11:32 +08:00
Hao Wang 0d0d396f48 fix(task): find unfinished tasks through the status index (#8529)
HasUnfinishedSyncTasks, GetAllUnFinishSyncTasks and GetTimedOutUnfinishedTasks
exclude the two terminal statuses with "status != ?" or "NOT IN". PostgreSQL
and SQLite cannot use idx_tasks_status for that filter, so every check reads
all finished tasks. The async_task_poll scheduler runs the existence check
every 15 seconds. On a PostgreSQL table with 1.4 million finished tasks, one
check took about 27 seconds, and the database kept scanning the table even
when no task was unfinished.

Write the filter as the key ranges around FAILURE and SUCCESS. It matches the
same rows, and all three databases answer it from the status index.

Closes #8528
2026-12-02 14:45:40 +08:00
coderwhq b697786325 fix(openai): record first response time on first non-empty stream output (#8531) 2026-12-02 14:05:07 +08:00
Seefs f0c94957fd fix(channels): enable VolcEngine upstream model discovery (#8306) 2026-12-02 13:52:23 +08:00
35 changed files with 1216 additions and 143 deletions

No files matched your search

+91
View File
@@ -1,3 +1,94 @@
# NovaLink New API
NovaLink builds on [QuantumNous/new-api](https://github.com/QuantumNous/new-api) and adds upstream cost analysis, user operations, referral payouts, site documentation, and support tickets for gateway operators.
[Live gateway](https://newapi.it120.cloud) · [NovaLink releases](https://github.com/zsz2018/NovaLink-new-api/releases) · [Report an issue](https://github.com/zsz2018/NovaLink-new-api/issues) · [简体中文](./README.md)
[Upstream monitoring](#novalink-monitor) · [User operations](#novalink-operations) · [Referral commissions](#novalink-referrals) · [Site documentation](#novalink-docs) · [Support tickets](#novalink-support) · [Client integrations](#novalink-extras) · [Console locations](#novalink-entries) · [Deployment](#novalink-deployment) · [Upstream project](#upstream-reference)
<a id="novalink-monitor"></a>
### Upstream monitoring and margin comparison
- Manage upstream sites and accounts, currencies, exchange rates, and top-up conversion settings. The server encrypts stored credentials. Administrators can check whether paired browsers are online and revoke device access.
- Pair the separate NovaLink Browser Bridge extension to record browser steps, map response fields, and preview the results. Run collections manually or on an account schedule, resume after manual verification, and review diagnostics and historical snapshots.
- Collect account identity, balances, groups, and multipliers from authorized upstream browser sessions, with optional model prices and top-up records. Use the New API or Sub2API adapter, or configure field mappings for other sites with optional AI assistance. The extension sends structured results and keeps raw responses in memory for the duration of the task.
- Configure one backup address per site. If the primary becomes unavailable during a task, collection can switch once and authenticate again at the backup. The operator confirms before the task repeats actions other than login or requests that are not read-only. Snapshots record the address used for collection.
- Map local models and groups to upstream procurement channels and compare selling prices with procurement costs for the same usage scenario. The comparison supports token, per-request, tiered, and supported native pricing expressions. Administrators can opt in to reviewed reference prices when procurement quotes are missing.
> Upstream monitoring and the browser extension are still in development. Collection requires a matching extension, `UPSTREAM_MONITOR_KEY`, and device pairing by a root administrator.
<a id="novalink-operations"></a>
### User operations and contribution levels
- Track activity, registration conversion, first and repeat purchases, wallet balances, debt, and usage and invitation rankings. Reports show verified payments by provider, payment method, and original currency. Day 1, 7, and 30 usage retention includes users whose measurement dates have ended and have complete usage records.
- Annual contribution levels count 100% of a user's verified net external wallet top-ups and 50% of the equivalent top-ups made by their direct referrals. Contributions count for 365 days from credit. Automatic levels are reviewed on January 1 in Beijing time, and users can earn upgrades during the year.
- Configure separate rewards for first purchases and first subscriptions. Wallet top-ups and eligible redemption codes share one lifetime first-purchase reward. Registration and invitation rewards are issued immediately, with separate amounts for the inviter and invitee.
- Root administrators can manage contribution levels and earnings holds, and pause, resume, cancel, or retry rewards that have yet to be issued. Administrators can search users and usage logs by exact user ID and bulk-enable, disable, or add quota to users. The margin comparison can also show an operating net profit estimate based on the last 30 complete Beijing calendar days.
<a id="novalink-referrals"></a>
### Referral commissions and withdrawals
- Choose between pausing new commissions, earning commission on eligible direct referrals' wallet purchases, or earning commission as direct referrals spend eligible verified wallet credits.
- Each eligible wallet credit retains its referral relationship, policy, level, commission rate, and release delay at the time of credit. Users can view pending, available, and held earnings, as well as commission and withdrawal history.
- When switching from consumption to purchase commissions, a root administrator can preview and confirm settlement of the remaining eligible credits under their original terms. The buyer keeps those credits available in their wallet.
- Users can move available earnings to their spending wallet or request a withdrawal. A withdrawal holds the required balance and locks the CNY quote. A root administrator claims the request, makes the manual payout, and records its payment reference.
> Weighted contribution levels require a root administrator to publish an enabled multi-level policy. New commissions, first-purchase rewards, first-subscription rewards, and withdrawals are off by default.
<a id="novalink-docs"></a>
### Site documentation
- Visitors can browse published Markdown articles at `/docs`, search by title or group, and switch articles in the same reader. The reader includes a mobile table of contents, heading navigation, and controls to copy section links and code snippets.
- Root administrators can manage document groups and ordering, preview edits, save drafts, publish articles, and unpublish them. Readers see the last published version while drafts are being edited. Article URLs stay fixed after first publication.
<a id="novalink-support"></a>
### Support tickets and reports
- Signed-in users can open tickets about API errors, accounts, payments, feature requests, and reports. API error tickets can link to a request record. Users can track progress and reply within an open ticket.
- Administrators can filter by category or status, reply, mark tickets complete, close them, and reopen them. Sidebar badges show tickets waiting for a reply and notify users when their tickets are completed.
<a id="novalink-extras"></a>
### Client integrations and maintenance
- Pin up to three chat presets as API key import shortcuts. The full preset list remains available in the menu, and administrators can edit presets visually or in JSON.
- Import an API key configuration into CC Switch for clients such as Claude Code, Codex, and Gemini CLI. Choose the app, name the configuration, and select a model if needed. Confirm the import in CC Switch v4.0.47 or later.
- Fetch the upstream model list when creating or editing a VolcEngine channel, then choose which models to enable.
- Read full multiline API key group descriptions in the picker and after selecting a group. Administrators can check the current NovaLink version and open the release notes from the console header.
<a id="novalink-entries"></a>
### Console locations
| Task | Location | Access |
| --- | --- | --- |
| Configure upstream collection and compare margins | Upstream Monitoring · `/upstream-monitor` | Root administrator |
| Review user operations and manage rewards or withdrawals | User Management → Operations Overview · `/users` | Administrators with access. Configuration and payouts require a root administrator |
| Review contribution levels, commissions, and withdrawals | Wallet → Referral Program · `/wallet` | Signed-in users |
| Search and read published documentation | Site Documentation · `/docs` | Visitors and signed-in users |
| Edit and publish documentation | Site & Branding → Site Documentation · `/system-settings/site/docs` | Root administrator |
| Submit tickets and view replies | My Tickets · `/support-tickets` | Signed-in users |
| Review and handle tickets | Ticket Management · `/admin/support-tickets` | Administrator |
| Configure API key import shortcuts | System Settings → Content → Chat Presets · `/system-settings/content/chat` | Root administrator |
| Import into CC Switch or use chat presets | API Keys · `/keys` | Signed-in users |
<a id="novalink-deployment"></a>
### Deploy NovaLink
Download the Windows x64 package from [NovaLink releases](https://github.com/zsz2018/NovaLink-new-api/releases), or build from this repository. For Docker, run `docker build -t novalink-new-api:local .` in the repository root, then set the `new-api` service's image in the [Compose configuration](./docker-compose.yml) to `novalink-new-api:local`.
The [NovaLink deployment guide in Chinese](./README.md#novalink-deployment) covers configuration to preserve across upgrades, the shared payment credential key, and Alipay AI Pay setup and migration.
---
<a id="upstream-reference"></a>
<div align="center">
![new-api](/web/public/logo.png)
+16 -4
View File
@@ -13,7 +13,7 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
[本仓库](https://github.com/zsz2018/NovaLink-new-api) · [NovaLink 版本发布](https://github.com/zsz2018/NovaLink-new-api/releases) · [问题反馈](https://github.com/zsz2018/NovaLink-new-api/issues) · [English](./README.en.md)
[上游监控与利润比较](#novalink-monitor) · [用户运营](#novalink-operations) · [返佣与提现](#novalink-referrals) · [站内文档](#novalink-docs) · [其他改进](#novalink-extras) · [使用入口](#novalink-entries) · [部署](#novalink-deployment) · [上游资料](#upstream-reference)
[上游监控与利润比较](#novalink-monitor) · [用户运营](#novalink-operations) · [返佣与提现](#novalink-referrals) · [站内文档](#novalink-docs) · [客服工单](#novalink-support) · [其他改进](#novalink-extras) · [使用入口](#novalink-entries) · [部署](#novalink-deployment) · [上游资料](#upstream-reference)
</div>
@@ -28,6 +28,7 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
- **集中管理上游站点和账号**,维护币种、汇率及充值折算参数。服务端加密保存登录凭据,控制台可查看浏览器在线状态并撤销设备授权。
- **录制并执行浏览器采集流程**。配对独立的 NovaLink Browser Bridge 扩展后,在侧栏录制页面操作、配置字段映射并预览结果。控制台支持手动采集、按账号定时采集、人工验证后继续、取消、重试,以及查看任务诊断和历史快照。
- **从已授权登录的上游页面采集数据**,包括账号身份、余额、分组和倍率,以及可选的模型价格与充值记录。提供 New API、Sub2API 专用适配器及普通站点字段映射,支持分页、跨响应取值和嵌套分组模型列表。扩展向本站回传结构化结果,原始响应仅在当次任务的扩展内存中使用。
- **采集主备切换**。站点可配置一个备用地址。主站不可用时,正在执行的任务可切换一次,在备用站点重新认证并采集。重做已发出的非登录操作或非只读请求前,需管理员确认。采集快照会记录实际使用的站点。
- **按需使用 AI 辅助配置**普通站点的字段映射。管理员预览验证并确认保存后,后续采集直接执行已保存的规则。
- **从本地分组快捷绑定采购渠道**,可选择上游账号及分组、查看已采集的分组倍率、批量绑定本地模型或指定单个模型的对应关系。
- **在同一用量场景中比较售价和采购成本**,可调整输入、输出、缓存读写 Token 和请求次数。支持按 Token、按次、阶梯价格及受支持的原生计费表达式,纳入汇率、分组倍率、充值折算及双方费率设置。可筛选亏损线路,查看毛利、毛利率、成本数据覆盖率,以及按阶梯和计费项拆分的明细。
@@ -66,15 +67,24 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
### 站内文档中心
- **公开阅读**。访客可从站点导航进入 `/docs`,按分组浏览已发布的 Markdown 文章。阅读页支持移动端目录、正文标题导航、复制章节链接及代码片段。
- **公开阅读与搜索**。访客可从站点导航进入 `/docs`,按分组浏览已发布的 Markdown 文章,也可按标题或分组搜索并直接打开结果。可在同一阅读页切换文章。阅读页支持移动端目录、正文标题导航、复制章节链接及代码片段。
- **目录与文章管理**。在站点与品牌设置中维护文档分组、文章归属和展示顺序。编辑工作区提供实时预览、全页预览、保存草稿、发布和下架。
- **草稿与发布快照分别保存**。保存草稿后,读者仍可访问上次发布的版本。首次发布后文章地址固定,目录调整可以单独保存。
<a id="novalink-support"></a>
### 客服工单与举报
- **我的工单**支持提交 API 错误、账号、支付、功能建议和举报等问题。提交 API 错误时可关联请求记录。用户可在工单内查看进度并继续回复。
- **工单管理**支持按分类和状态筛选、回复、标记完成、关闭和重新打开。侧栏提醒显示待回复工单,用户也会收到工单完成提醒。
<a id="novalink-extras"></a>
### 客户端接入与维护改进
- **API 密钥导入快捷按钮**支持从聊天预设中设置图标并勾选最多 3 项,按预设顺序直接显示在密钥列表。其余预设仍可从菜单打开。设置支持可视化编辑和 JSON 编辑。
- **一键导入 CC Switch**。从 API 密钥列表选择 Claude Code、Codex、Gemini CLI 等应用,填写配置名称并按需选择模型,再打开 CC Switch 确认导入。需要 CC Switch v4.0.47 或更新版本。
- **火山引擎模型获取**。新建或编辑火山引擎渠道时,可从上游获取模型列表并选择要启用的模型。
- **API 密钥分组描述**在候选列表和选中后均可完整显示,保留多行说明并自动换行。
- **NovaLink 版本检查**让管理员从控制台顶部查看当前版本、检查本分支发布并打开发布说明。普通登录用户在此位置可打开本分支仓库,错误页面也提供本分支的问题反馈入口。
- **NovaLink 图标**应用于 Web 标志、浏览器标签和 Electron 桌面应用与托盘。
@@ -90,10 +100,12 @@ NovaLink 基于 [QuantumNous/new-api](https://github.com/QuantumNous/new-api)
| 上游采集、配置与利润对比 | 上游监控 · `/upstream-monitor` | 超级管理员 |
| 用户运营、奖励记录与提现处理 | 用户管理 → 运营概览 · `/users` | 管理员查看获授权的数据,超级管理员可配置和处理提现 |
| 等级进度、推广佣金和提现申请 | 钱包 → 推荐计划 · `/wallet` | 登录用户 |
| 阅读已发布的文档 | 站点文档 · `/docs` | 访客与登录用户 |
| 搜索和阅读已发布的文档 | 站点文档 · `/docs` | 访客与登录用户 |
| 编辑和发布文档 | 站点与品牌 → 站点文档 · `/system-settings/site/docs` | 超级管理员 |
| 提交工单或举报、查看回复 | 我的工单 · `/support-tickets` | 登录用户 |
| 筛选和处理工单 | 工单管理 · `/admin/support-tickets` | 管理员 |
| 配置密钥导入快捷按钮 | 系统设置 → 内容 → 聊天预设 · `/system-settings/content/chat` | 超级管理员 |
| 使用密钥导入快捷按钮 | API 密钥 · `/keys` | 登录用户 |
| 导入 CC Switch 或使用聊天预设 | API 密钥 · `/keys` | 登录用户 |
<a id="novalink-deployment"></a>
+9
View File
@@ -62,6 +62,15 @@ func IsRequestBodyTooLargeError(err error) bool {
return errors.As(err, &mbe)
}
// NormalizeRelayPath maps Playground relay paths (/pg/...) onto their canonical
// API path (/v1/...) for route matching while leaving other paths unchanged.
func NormalizeRelayPath(path string) string {
if rest, ok := strings.CutPrefix(path, "/pg/"); ok {
return "/v1/" + rest
}
return path
}
func GetRequestBody(c *gin.Context) (io.Seeker, error) {
// 首先检查是否有 BodyStorage 缓存
if storage, exists := c.Get(KeyBodyStorage); exists && storage != nil {
+1
View File
@@ -743,6 +743,7 @@
"stream scanner data: %s": "收到流数据: %s",
"streaming timeout seconds: %d": "流式超时: %d 秒",
"stripe topup": "Stripe 充值",
"subscription %d exhausted at settlement, %d quota of the final delta uncovered": "订阅 %d 在结算时已用尽,最终差额中有 %d 额度未扣除",
"subscription balance purchase": "余额购买订阅",
"subscription expiration": "订阅到期",
"subscription expire task failed: %v": "处理过期订阅失败: %v",
+3 -21
View File
@@ -25,7 +25,6 @@ import (
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/relay/requestplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
@@ -109,7 +108,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
upstreamURLs := common.UpstreamAddresses(c)
if relayFormat != types.RelayFormatOpenAIRealtime && c.Writer.Written() &&
strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") {
writeRelayStreamError(c, relayFormat, newAPIError)
helper.StreamErrorData(c, relayFormat, newAPIError)
return
}
if relayFormat != types.RelayFormatOpenAIRealtime {
@@ -195,7 +194,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
RequestPath: common.NormalizeRelayPath(c.Request.URL.Path),
Retry: common.GetPointer(0),
}
relayInfo.RetryIndex = 0
@@ -270,23 +269,6 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
}
func writeRelayStreamError(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
// 心跳提交响应头后,最终错误继续通过同一个流返回。
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = helper.ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = helper.ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
helper.Done(c)
}
// CountClaudeTokens implements Anthropic's token-counting utility endpoint.
// It deliberately skips upstream generation and billing; callers use this
// endpoint to size prompts before creating a Message.
@@ -661,7 +643,7 @@ func executeTaskSubmissionWith(
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
RequestPath: common.NormalizeRelayPath(c.Request.URL.Path),
Retry: common.GetPointer(0),
}
+1 -1
View File
@@ -283,7 +283,7 @@ func TestRelayStreamErrorAfterKeepAlive(t *testing.T) {
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, "https://provider.example")
common.SetContextKey(c, constant.ContextKeyUpstreamRequestOrigin, "https://provider.example")
apiError := types.NewErrorWithStatusCode(errors.New("upstream rejected input at https://provider.example/v1/messages"), types.ErrorCodeBadResponseStatusCode, http.StatusBadRequest)
writeRelayStreamError(c, format, apiError)
helper.StreamErrorData(c, format, apiError)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, "text/event-stream", recorder.Header().Get("Content-Type"))
require.Contains(t, recorder.Body.String(), "upstream rejected input")
+3 -2
View File
@@ -39,10 +39,11 @@ func Distribute() func(c *gin.Context) {
service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("request rejected"), types.ErrorCodeInvalidRequest, c.Writer.Status(), types.ErrOptionWithSkipRetry()))
}
}()
requestPath := common.NormalizeRelayPath(c.Request.URL.Path)
constraints := service.GetChannelConstraints(c)
constraints.AddFilter(taskdto.ChannelFilter{
Kind: taskdto.FilterRequestPath,
RequestPath: c.Request.URL.Path,
RequestPath: requestPath,
})
service.AppendTaskPluginIdentityFilter(c, c.GetString("expected_task_plugin_key"))
modelRequest, shouldSelectChannel, err := getModelRequest(c)
@@ -112,7 +113,7 @@ func Distribute() func(c *gin.Context) {
Ctx: c,
ModelName: modelRequest.Model,
TokenGroup: usingGroup,
RequestPath: c.Request.URL.Path,
RequestPath: requestPath,
Retry: common.GetPointer(0),
})
}
+20
View File
@@ -36,8 +36,20 @@ end
return {1, count, ttl}
`
// statusClientClosedRequest is the nginx convention for a request the client
// abandoned before the server responded. It is never seen by the client and
// only keeps access logs from counting the abort as a server error.
const statusClientClosedRequest = 499
var inMemoryRateLimiter common.InMemoryRateLimiter
// requestCanceledByClient reports whether a Redis rate limit failure was caused
// by the client closing its request. A deadline or any other Redis failure is
// still a server error, so the limiter keeps failing closed for those.
func requestCanceledByClient(c *gin.Context, err error) bool {
return errors.Is(err, context.Canceled) && errors.Is(c.Request.Context().Err(), context.Canceled)
}
var defNext = func(c *gin.Context) {
c.Next()
}
@@ -115,6 +127,10 @@ func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark st
duration,
)
if err != nil {
if requestCanceledByClient(c, err) {
c.AbortWithStatus(statusClientClosedRequest)
return
}
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (mark=%s): %v", mark, err))
c.Status(http.StatusInternalServerError)
c.Abort()
@@ -250,6 +266,10 @@ func userRateLimitFactory(maxRequestNum int, duration int64, mark string) func(c
func userRedisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, key string) {
allowed, _, ttlSeconds, err := redisFixedWindowTake(c.Request.Context(), key, maxRequestNum, duration)
if err != nil {
if requestCanceledByClient(c, err) {
c.AbortWithStatus(statusClientClosedRequest)
return
}
logger.LogError(c.Request.Context(), common.LogText("rate limit check failed (key=%s): %v", key, err))
c.Status(http.StatusInternalServerError)
c.Abort()
+66
View File
@@ -1,11 +1,13 @@
package middleware
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -227,6 +229,70 @@ func TestRedisFailurePolicies(t *testing.T) {
assert.Equal(t, http.StatusNoContent, performRateLimitRequest(router, "/email", "192.0.2.62:12345").Code)
}
func TestRedisRateLimiterRequestContextErrors(t *testing.T) {
useRateLimitMiniRedis(t)
canceledContext := func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
}
expiredContext := func() context.Context {
ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0))
cancel()
return ctx
}
tests := []struct {
name string
path string
requestCtx func() context.Context
wantStatus int
wantLogged bool
}{
{name: "IP limiter client canceled", path: "/ip", requestCtx: canceledContext, wantStatus: 499},
{name: "user limiter client canceled", path: "/user", requestCtx: canceledContext, wantStatus: 499},
{name: "IP limiter deadline exceeded", path: "/ip", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
{name: "user limiter deadline exceeded", path: "/user", requestCtx: expiredContext, wantStatus: http.StatusInternalServerError, wantLogged: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var logs bytes.Buffer
common.LogWriterMu.Lock()
previousErrorWriter := gin.DefaultErrorWriter
gin.DefaultErrorWriter = &logs
common.LogWriterMu.Unlock()
restoreErrorWriter := func() {
common.LogWriterMu.Lock()
gin.DefaultErrorWriter = previousErrorWriter
common.LogWriterMu.Unlock()
}
t.Cleanup(restoreErrorWriter)
downstreamCalled := false
downstream := func(c *gin.Context) {
downstreamCalled = true
c.Status(http.StatusNoContent)
}
router := gin.New()
require.NoError(t, router.SetTrustedProxies(nil))
router.GET("/ip", rateLimitFactory(1, 30, "CTX-IP"), downstream)
router.GET("/user", func(c *gin.Context) { c.Set("id", 9) }, userRateLimitFactory(1, 30, "CTX-USER"), downstream)
recorder := httptest.NewRecorder()
request := httptest.NewRequestWithContext(tt.requestCtx(), http.MethodGet, tt.path, nil)
request.RemoteAddr = "192.0.2.63:12345"
router.ServeHTTP(recorder, request)
restoreErrorWriter()
assert.Equal(t, tt.wantStatus, recorder.Code)
assert.Empty(t, recorder.Body.String())
assert.False(t, downstreamCalled)
assert.Equal(t, tt.wantLogged, strings.Contains(logs.String(), "rate limit check failed"), logs.String())
})
}
}
func TestGlobalWebRateLimitCountsFrontendFilesInStaticBucket(t *testing.T) {
gin.SetMode(gin.TestMode)
previousWebEnable, previousWebNum, previousWebDuration := common.GlobalWebRateLimitEnable, common.GlobalWebRateLimitNum, common.GlobalWebRateLimitDuration
+43
View File
@@ -3,6 +3,7 @@ package model
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"sync"
@@ -1603,3 +1604,45 @@ func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error
return tx.Save(&sub).Error
})
}
// SettleUserSubscriptionDelta applies a post-request settlement delta and
// returns the amount actually applied to AmountUsed. Unlike
// PostConsumeUserSubscriptionDelta, which refuses overruns during reservation,
// a positive delta that exceeds the remaining allowance fills the subscription
// to AmountTotal and logs the uncovered part so subsequent requests do not keep
// passing small pre-consumes on an unexhausted plan.
func SettleUserSubscriptionDelta(userSubscriptionId int, delta int64) (applied int64, err error) {
if userSubscriptionId <= 0 {
return 0, errors.New("invalid userSubscriptionId")
}
if delta == 0 {
return 0, nil
}
err = DB.Transaction(func(tx *gorm.DB) error {
var sub UserSubscription
if err := lockForUpdate(tx).
Where("id = ?", userSubscriptionId).
First(&sub).Error; err != nil {
return err
}
charge := delta
if charge > 0 {
limit := int64(math.MaxInt64)
if sub.AmountTotal > 0 {
limit = sub.AmountTotal
}
charge = min(charge, max(limit-max(sub.AmountUsed, 0), 0))
}
newUsed := max(sub.AmountUsed+charge, 0)
applied = newUsed - sub.AmountUsed
sub.AmountUsed = newUsed
return tx.Save(&sub).Error
})
if err != nil {
return 0, err
}
if delta > 0 && applied < delta {
common.SysLog(common.LogText("subscription %d exhausted at settlement, %d quota of the final delta uncovered", userSubscriptionId, delta-applied))
}
return applied, nil
}
+17 -6
View File
@@ -420,10 +420,19 @@ func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*
return tasks
}
// unfinishedTasks keeps tasks whose status is neither FAILURE nor SUCCESS.
// It writes the condition as the ranges around the two terminal statuses
// (FAILURE sorts before SUCCESS), so the database reads only unfinished rows
// from the status index instead of scanning every finished task.
func unfinishedTasks(tx *gorm.DB) *gorm.DB {
return tx.Where("status < ? OR (status > ? AND status < ?) OR status > ?",
TaskStatusFailure, TaskStatusFailure, TaskStatusSuccess, TaskStatusSuccess)
}
func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
var tasks []*Task
err := DB.Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess, TaskStatusBillingPending}).
Where("submit_time < ?", cutoffUnix).
err := DB.Scopes(unfinishedTasks).
Where("status <> ? AND submit_time < ?", TaskStatusBillingPending, cutoffUnix).
Order("submit_time").
Limit(limit).
Find(&tasks).Error
@@ -435,9 +444,12 @@ func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
func GetAllUnFinishSyncTasks(limit int) []*Task {
var tasks []*Task
var err error
// Upstream progress can reach 100% before the task enters a terminal state.
err = DB.Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess, TaskStatusBillingPending}).Limit(limit).Order("id").Find(&tasks).Error
err := DB.Scopes(unfinishedTasks).
Where("status <> ?", TaskStatusBillingPending).
Limit(limit).
Order("id").
Find(&tasks).Error
if err != nil {
return nil
}
@@ -473,8 +485,7 @@ func HasPendingWalletTaskSettlements() bool {
func HasUnfinishedSyncTasks() bool {
var id int64
err := DB.Model(&Task{}).
Where("status != ?", TaskStatusFailure).
Where("status != ?", TaskStatusSuccess).
Scopes(unfinishedTasks).
Limit(1).
Pluck("id", &id).Error
return err == nil && id != 0
+3 -2
View File
@@ -178,7 +178,7 @@ func TestUnfinishedTaskQueriesDatabaseMatrix(t *testing.T) {
assert.False(t, HasUnfinishedSyncTasks())
const cutoff int64 = 1_800_000_000
for _, status := range []TaskStatus{TaskStatusNotStart, TaskStatusSubmitted, TaskStatusQueued, TaskStatusInProgress, TaskStatusSuccess, TaskStatusFailure} {
for _, status := range []TaskStatus{"", TaskStatusNotStart, TaskStatusSubmitted, TaskStatusQueued, TaskStatusInProgress, TaskStatusUnknown, TaskStatusSuccess, TaskStatusFailure, TaskStatusBillingPending} {
for _, progress := range []string{"99%", "100%"} {
t.Run(string(status)+"/"+progress, func(t *testing.T) {
task := &Task{TaskID: "query_candidate", Status: status, Progress: progress, SubmitTime: cutoff - 1}
@@ -186,7 +186,8 @@ func TestUnfinishedTaskQueriesDatabaseMatrix(t *testing.T) {
t.Cleanup(func() { assert.NoError(t, db.Delete(task).Error) })
unfinished := status != TaskStatusSuccess && status != TaskStatusFailure
assert.Equal(t, unfinished, HasUnfinishedSyncTasks())
if unfinished {
assert.Equal(t, status == TaskStatusBillingPending, HasPendingWalletTaskSettlements())
if unfinished && status != TaskStatusBillingPending {
require.Len(t, GetAllUnFinishSyncTasks(1), 1)
assert.Equal(t, task.ID, GetAllUnFinishSyncTasks(1)[0].ID)
require.Len(t, GetTimedOutUnfinishedTasks(cutoff, 1), 1)
+4 -2
View File
@@ -8,6 +8,7 @@ import (
"net/url"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/relay/channel"
"github.com/QuantumNous/new-api/relay/channel/claude"
@@ -423,12 +424,13 @@ func (a *Adaptor) resolve(c *gin.Context, info *relaycommon.RelayInfo) error {
func incomingRequestPath(c *gin.Context, info *relaycommon.RelayInfo) string {
if c != nil && c.Request != nil && c.Request.URL != nil {
return c.Request.URL.Path
return common.NormalizeRelayPath(c.Request.URL.Path)
}
if info == nil {
return ""
}
return strings.Split(info.RequestURLPath, "?")[0]
path, _, _ := strings.Cut(info.RequestURLPath, "?")
return common.NormalizeRelayPath(path)
}
func (a *Adaptor) routeURL(info *relaycommon.RelayInfo) (string, error) {
+4 -1
View File
@@ -284,6 +284,7 @@ func awsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (
}
events := stream.Events()
started := false
streamLoop:
for {
select {
@@ -302,8 +303,10 @@ streamLoop:
info.SetFirstResponseTime()
respErr := claude.HandleStreamResponseData(c, info, claudeInfo, string(v.Value.Bytes))
if respErr != nil {
return respErr, nil
usage, err := claude.HandleStartedStreamError(c, info, claudeInfo, started, respErr)
return err, usage
}
started = true
case *bedrockruntimeTypes.UnknownUnionMember:
fmt.Println(common.LogText("unknown tag: %v", v.Tag))
return types.NewError(errors.New("unknown response type"), types.ErrorCodeInvalidRequest), nil
+57 -29
View File
@@ -273,34 +273,7 @@ func recordClaudeServerToolUse(info *relaycommon.RelayInfo, serverToolUse *dto.C
}
func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
completeClaudeStreamUsage(c, info, claudeInfo)
if info.RelayFormat == types.RelayFormatClaude {
//
@@ -331,6 +304,58 @@ func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, clau
}
}
// HandleStartedStreamError settles a stream that fails after events have
// reached the client. A retry would splice a second message into the same
// response, so the failure ends this stream without one: with output
// delivered, the client gets the error event here and the output is billed;
// with none, the error goes back to the relay, which sends it and refunds.
func HandleStartedStreamError(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, started bool, streamErr *types.NewAPIError) (*dto.Usage, *types.NewAPIError) {
if !started {
return nil, streamErr
}
if claudeInfo.ResponseText.Len() == 0 {
types.ErrOptionWithSkipRetry()(streamErr)
return nil, streamErr
}
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
helper.StreamErrorData(c, info.RelayFormat, streamErr)
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
// completeClaudeStreamUsage fills the usage a stream left unreported from the
// streamed content and finalizes its billing usage.
func completeClaudeStreamUsage(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
}
func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
claudeInfo := &ClaudeResponseInfo{
ResponseId: helper.GetResponseID(c),
@@ -340,15 +365,18 @@ func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
Usage: &dto.Usage{},
}
var err *types.NewAPIError
started := false
helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
err = HandleStreamResponseData(c, info, claudeInfo, data)
if err != nil {
sr.Stop(err)
return
}
started = true
})
info.StreamStatus.RequireTerminal()
if err != nil {
return nil, err
return HandleStartedStreamError(c, info, claudeInfo, started, err)
}
HandleStreamFinalResponse(c, info, claudeInfo)
+69
View File
@@ -2,6 +2,7 @@ package claude
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -65,6 +66,74 @@ func TestClaudeStreamFinalUsageEstimatesOnlyUncountedUsage(t *testing.T) {
}
}
func TestClaudeStreamErrorRetriesOnlyBeforeTheClientGotEvents(t *testing.T) {
gin.SetMode(gin.TestMode)
previousTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = previousTimeout })
start := `{"type":"message_start","message":{"id":"msg_1","model":"claude-opus-4-8","usage":{"input_tokens":1000,"output_tokens":1}}}`
thinking := `{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hello"}}`
overloaded := `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`
for _, tc := range []struct {
name string
format types.RelayFormat
events []string
wantErr bool
wantRetry bool
wantInput int
wantOutput int
wantBody []string
}{
{name: "error before any event may retry", format: types.RelayFormatClaude, events: []string{overloaded}, wantErr: true, wantRetry: true},
{name: "error after message_start ends the stream unbilled", format: types.RelayFormatClaude, events: []string{start, overloaded}, wantErr: true},
{name: "error after output reaches the client and bills it", format: types.RelayFormatClaude, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: error\n", `"type":"overloaded_error"`}},
{name: "converted chat stream gets the error and bills the output", format: types.RelayFormatOpenAI, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{`"error":`, `"overloaded_error"`, "data: [DONE]"}},
{name: "converted responses stream bills the output before response.failed", format: types.RelayFormatOpenAIResponses, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: response.failed\n"}},
{name: "converted responses stream failing before output is free", format: types.RelayFormatOpenAIResponses, events: []string{start, overloaded}, wantBody: []string{"event: response.failed\n"}},
} {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
info := &relaycommon.RelayInfo{RelayFormat: tc.format, IsStream: true, ChannelMeta: &relaycommon.ChannelMeta{UpstreamModelName: "claude-opus-4-8"}}
info.SetEstimatePromptTokens(1200)
var body strings.Builder
for _, event := range tc.events {
body.WriteString("data: " + event + "\n\n")
}
resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body.String()))}
handler := ClaudeStreamHandler
if tc.format == types.RelayFormatOpenAIResponses {
handler = ClaudeResponsesStreamHandler
}
usage, apiErr := handler(c, resp, info)
if tc.wantErr {
require.NotNil(t, apiErr)
assert.Nil(t, usage, "a failure without output is refunded")
assert.Equal(t, tc.wantRetry, !types.IsSkipRetryError(apiErr))
assert.NotContains(t, recorder.Body.String(), "Overloaded", "the relay sends the error once")
return
}
require.Nil(t, apiErr)
for _, want := range tc.wantBody {
assert.Contains(t, recorder.Body.String(), want)
}
assert.Equal(t, 1, strings.Count(recorder.Body.String(), tc.wantBody[0]), "the failure is sent once")
assert.True(t, info.StreamStatus.ResponseFailed())
assert.Equal(t, tc.wantInput, usage.PromptTokens)
assert.Equal(t, tc.wantOutput, usage.CompletionTokens)
if tc.wantOutput == 0 {
return
}
canonical, ok := usage.BillingUsage.CanonicalUsage()
require.True(t, ok)
assert.Equal(t, tc.wantOutput, canonical.CompletionTokens, "settlement must bill the delivered output")
})
}
}
func TestResponseOpenAI2ClaudeToolUseInputIsObject(t *testing.T) {
tests := []struct {
name string
+9
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
@@ -78,6 +79,8 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return true
}
}
info.StreamStatus.MarkFailed("server_error", "", 0)
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
streamFailed = true
return true
}
@@ -162,6 +165,12 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return nil, streamErr
}
if streamFailed {
// The client received response.failed: output it got before the failure
// is billed, and a failure before any output is free.
if claudeInfo.ResponseText.Len() == 0 {
return &dto.Usage{}, nil
}
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
+44 -21
View File
@@ -420,6 +420,8 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
id := helper.GetResponseID(c)
createAt := common.GetTimestamp()
finishReason := constant.FinishReasonStop
sawToolCall := false
finishEmitted := false
toolCallIndexByChoice := make(map[int]map[string]int)
nextToolCallIndexByChoice := make(map[int]int)
@@ -429,18 +431,25 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
response.Id = id
response.Created = createAt
response.Model = info.UpstreamModelName
if response.IsToolCall() {
finishReason = constant.FinishReasonToolCalls
if info.RelayFormat == types.RelayFormatClaude {
for choiceIdx := range response.Choices {
response.Choices[choiceIdx].FinishReason = nil
}
}
}
hasUpstreamFinish := isStop
upstreamNonStopReason := ""
hasDelta := false
for choiceIdx := range response.Choices {
choiceKey := response.Choices[choiceIdx].Index
for toolIdx := range response.Choices[choiceIdx].Delta.ToolCalls {
tool := &response.Choices[choiceIdx].Delta.ToolCalls[toolIdx]
choice := &response.Choices[choiceIdx]
if choice.FinishReason != nil && *choice.FinishReason != "" {
hasUpstreamFinish = true
if upstreamNonStopReason == "" {
upstreamNonStopReason = *choice.FinishReason
}
choice.FinishReason = nil
}
choiceKey := choice.Index
if len(choice.Delta.ToolCalls) > 0 {
sawToolCall = true
}
for toolIdx := range choice.Delta.ToolCalls {
tool := &choice.Delta.ToolCalls[toolIdx]
if tool.ID == "" {
continue
}
@@ -458,10 +467,22 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
m[tool.ID] = idx
tool.SetIndex(idx)
}
if choice.Delta.GetContentString() != "" ||
choice.Delta.GetReasoningContent() != "" ||
len(choice.Delta.ToolCalls) > 0 ||
len(choice.Delta.Annotations) > 0 {
hasDelta = true
}
}
if upstreamNonStopReason != "" {
finishReason = upstreamNonStopReason
} else if sawToolCall && finishReason == constant.FinishReasonStop {
finishReason = constant.FinishReasonToolCalls
}
logger.LogDebug(c, "info.SendResponseCount = %d", info.SendResponseCount)
if info.SendResponseCount == 0 {
if info.SendResponseCount == 0 && (hasDelta || hasUpstreamFinish) {
// send first response
emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil)
// Claude message_start is emitted from this first OpenAI chunk.
@@ -477,16 +498,11 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
}
emptyResponse.Choices[0].Delta.ToolCalls = copiedToolCalls
}
finishReason = constant.FinishReasonToolCalls
err := handleStream(c, info, emptyResponse)
if err != nil {
logger.LogError(c, err.Error())
}
response.ClearToolCalls()
if response.IsFinished() {
response.Choices[0].FinishReason = nil
}
} else {
err := handleStream(c, info, emptyResponse)
if err != nil {
@@ -495,13 +511,16 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
}
}
err := handleStream(c, info, response)
if err != nil {
logger.LogError(c, err.Error())
if hasDelta && !finishEmitted {
err := handleStream(c, info, response)
if err != nil {
logger.LogError(c, err.Error())
}
}
if isStop {
if hasUpstreamFinish && !finishEmitted {
if info.RelayFormat != types.RelayFormatClaude {
_ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
finishEmitted = true
}
}
return true
@@ -511,6 +530,10 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
return usage, err
}
if info.RelayFormat != types.RelayFormatClaude && info.SendResponseCount > 0 && !finishEmitted && !isGeminiDownstreamStop(c, info) {
_ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
}
response := helper.GenerateFinalUsageResponse(id, createAt, info.UpstreamModelName, *usage)
if info.RelayFormat == types.RelayFormatClaude && info.ClaudeConvertInfo != nil && !info.ClaudeConvertInfo.Done {
response = helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason)
+57
View File
@@ -1,6 +1,8 @@
package openai
import (
"bytes"
"encoding/json"
"fmt"
"strings"
@@ -19,6 +21,61 @@ import (
"github.com/gin-gonic/gin"
)
type openAIStreamOutputProbe struct {
Choices []struct {
Text json.RawMessage `json:"text"`
Delta struct {
Content json.RawMessage `json:"content"`
ReasoningContent json.RawMessage `json:"reasoning_content"`
Reasoning json.RawMessage `json:"reasoning"`
ReasoningDetails json.RawMessage `json:"reasoning_details"`
Refusal json.RawMessage `json:"refusal"`
ToolCalls json.RawMessage `json:"tool_calls"`
FunctionCall json.RawMessage `json:"function_call"`
Audio json.RawMessage `json:"audio"`
Annotations json.RawMessage `json:"annotations"`
Images json.RawMessage `json:"images"`
} `json:"delta"`
} `json:"choices"`
}
func hasNonEmptyJSONValue(raw json.RawMessage) bool {
b := bytes.TrimSpace(raw)
if len(b) == 0 || bytes.Equal(b, []byte("null")) || bytes.Equal(b, []byte(`""`)) {
return false
}
if len(b) >= 2 && ((b[0] == '[' && b[len(b)-1] == ']') || (b[0] == '{' && b[len(b)-1] == '}')) {
return len(bytes.TrimSpace(b[1:len(b)-1])) > 0
}
return true
}
// hasOpenAIStreamOutput reports whether an OpenAI Chat Completions or
// Completions SSE data payload carries generated output rather than role-only,
// empty-content, keepalive, or usage-only metadata.
func hasOpenAIStreamOutput(data string) bool {
var chunk openAIStreamOutputProbe
if err := common.UnmarshalJsonStr(data, &chunk); err != nil {
return false
}
for _, choice := range chunk.Choices {
if hasNonEmptyJSONValue(choice.Text) ||
hasNonEmptyJSONValue(choice.Delta.Content) ||
hasNonEmptyJSONValue(choice.Delta.ReasoningContent) ||
hasNonEmptyJSONValue(choice.Delta.Reasoning) ||
hasNonEmptyJSONValue(choice.Delta.ReasoningDetails) ||
hasNonEmptyJSONValue(choice.Delta.Refusal) ||
hasNonEmptyJSONValue(choice.Delta.ToolCalls) ||
hasNonEmptyJSONValue(choice.Delta.FunctionCall) ||
hasNonEmptyJSONValue(choice.Delta.Audio) ||
hasNonEmptyJSONValue(choice.Delta.Annotations) ||
hasNonEmptyJSONValue(choice.Delta.Images) {
return true
}
}
return false
}
// 辅助函数
func HandleStreamFormat(c *gin.Context, info *relaycommon.RelayInfo, data string, forceFormat bool, thinkToContent bool) error {
switch info.RelayFormat {
+1 -1
View File
@@ -142,7 +142,7 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
sr.Error(err)
}
}
})
}, helper.WithFirstResponsePredicate(hasOpenAIStreamOutput))
info.StreamStatus.RequireTerminal()
+1 -1
View File
@@ -179,7 +179,7 @@ func OaiChatToResponsesStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
return
}
}
})
}, helper.WithFirstResponsePredicate(hasOpenAIStreamOutput))
if streamErr != nil {
return nil, streamErr
@@ -0,0 +1,203 @@
package openai
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/QuantumNous/new-api/constant"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHasOpenAIStreamOutput(t *testing.T) {
t.Parallel()
tests := []struct {
name string
data string
want bool
}{
{
name: "role and empty content keepalive chunk",
data: `{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1700000005,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`,
want: false,
},
{
name: "role only chunk",
data: `{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1700000000,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant"}}]}`,
want: false,
},
{
name: "null content and empty tool calls",
data: `{"choices":[{"index":0,"delta":{"role":"assistant","content":null,"reasoning_content":null,"tool_calls":[]},"finish_reason":null}]}`,
want: false,
},
{
name: "usage only chunk with empty choices",
data: `{"id":"chatcmpl-1","choices":[],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
want: false,
},
{
name: "zero output content filter terminal chunk",
data: `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"content_filter"}],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
want: false,
},
{
name: "legacy completions empty text",
data: `{"choices":[{"index":0,"text":"","finish_reason":null}]}`,
want: false,
},
{
name: "inline error object",
data: `{"error":{"message":"upstream failed","type":"server_error"}}`,
want: false,
},
{
name: "non-json payload",
data: `not-json`,
want: false,
},
{
name: "text content token",
data: `{"choices":[{"index":0,"delta":{"content":"Hello"}}]}`,
want: true,
},
{
name: "whitespace content token",
data: `{"choices":[{"index":0,"delta":{"content":" "}}]}`,
want: true,
},
{
name: "reasoning_content token",
data: `{"choices":[{"index":0,"delta":{"reasoning_content":"The"}}]}`,
want: true,
},
{
name: "reasoning alias token",
data: `{"choices":[{"index":0,"delta":{"reasoning":"Step 1"}}]}`,
want: true,
},
{
name: "reasoning_details array",
data: `{"choices":[{"index":0,"delta":{"reasoning_details":[{"type":"reasoning.text","text":"step"}]}}]}`,
want: true,
},
{
name: "refusal token",
data: `{"choices":[{"index":0,"delta":{"refusal":"I cannot help with that."}}]}`,
want: true,
},
{
name: "tool_calls chunk",
data: `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}`,
want: true,
},
{
name: "legacy function_call chunk",
data: `{"choices":[{"index":0,"delta":{"function_call":{"name":"get_weather","arguments":""}}}]}`,
want: true,
},
{
name: "audio chunk",
data: `{"choices":[{"index":0,"delta":{"audio":{"id":"audio_1","data":"//uQ"}}}]}`,
want: true,
},
{
name: "annotations chunk",
data: `{"choices":[{"index":0,"delta":{"annotations":[{"type":"url_citation"}]}}]}`,
want: true,
},
{
name: "multimodal content array",
data: `{"choices":[{"index":0,"delta":{"content":[{"type":"text","text":"Hi"}]}}]}`,
want: true,
},
{
name: "legacy completions non-empty text",
data: `{"choices":[{"index":0,"text":"Hello"}]}`,
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, hasOpenAIStreamOutput(tt.data))
})
}
}
func TestOaiStreamHandler_FirstResponseTimeSkipsEmptyChunks(t *testing.T) {
oldTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
pr, pw := io.Pipe()
go func() {
defer pw.Close()
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000005,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"\"},\"finish_reason\":null}]}\n\n")
time.Sleep(80 * time.Millisecond)
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"reasoning_content\":\"Think\"},\"finish_reason\":null}]}\n\n")
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"},\"finish_reason\":null}]}\n\n")
_, _ = fmt.Fprint(pw, "data: {\"id\":\"chatcmpl-1\",\"object\":\"chat.completion.chunk\",\"created\":1700000000,\"model\":\"gpt-4o\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":10,\"total_tokens\":110}}\n\n")
_, _ = fmt.Fprint(pw, "data: [DONE]\n\n")
}()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o", Stream: &stream}, nil)
require.NoError(t, err)
info.ChannelMeta = &relaycommon.ChannelMeta{UpstreamModelName: "gpt-4o"}
info.DisablePing = true
usage, apiErr := OaiStreamHandler(c, info, &http.Response{Body: pr})
require.Nil(t, apiErr)
require.NotNil(t, usage)
assert.Equal(t, 100, usage.PromptTokens)
assert.Equal(t, 10, usage.CompletionTokens)
assert.True(t, info.HasSendResponse())
assert.GreaterOrEqual(t, info.FirstResponseTime.Sub(info.StartTime), 70*time.Millisecond)
assert.Contains(t, recorder.Body.String(), `"reasoning_content":"Think"`)
assert.Contains(t, recorder.Body.String(), `"content":"Hello"`)
}
func TestOaiStreamHandler_ZeroOutputDoesNotSetFirstResponseTime(t *testing.T) {
oldTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
body := strings.Join([]string{
`data: {"id":"chatcmpl-2","object":"chat.completion.chunk","created":1700000005,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`,
`data: {"id":"chatcmpl-2","object":"chat.completion.chunk","created":1700000000,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":""},"finish_reason":"content_filter"}],"usage":{"prompt_tokens":100,"completion_tokens":0,"total_tokens":100}}`,
`data: [DONE]`,
``,
}, "\n\n")
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o-mini", Stream: &stream}, nil)
require.NoError(t, err)
info.ChannelMeta = &relaycommon.ChannelMeta{UpstreamModelName: "gpt-4o-mini"}
info.DisablePing = true
usage, apiErr := OaiStreamHandler(c, info, &http.Response{Body: io.NopCloser(strings.NewReader(body))})
require.Nil(t, apiErr)
require.NotNil(t, usage)
assert.Equal(t, 0, usage.CompletionTokens)
assert.False(t, info.HasSendResponse())
}
+6 -4
View File
@@ -207,7 +207,7 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}
ctx := c.Request.Context()
input := jsplugin.ConvertInput{Path: c.Request.URL.Path, Model: info.UpstreamModelName, Stream: info.IsStream}
input := jsplugin.ConvertInput{Path: common.NormalizeRelayPath(c.Request.URL.Path), Model: info.UpstreamModelName, Stream: info.IsStream}
// files are the client's uploaded files by reference, nil for a JSON
// request.
var files map[string]*multipart.FileHeader
@@ -526,7 +526,9 @@ func (a *Adaptor) bind(c *gin.Context, info *relaycommon.RelayInfo) error {
if c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}
route, ok := a.plugin.Meta.ChannelRelayRoute(info.ChannelOtherSettings.PluginRoutes, strings.Split(path, "?")[0], info.OriginModelName)
path, _, _ = strings.Cut(path, "?")
path = common.NormalizeRelayPath(path)
route, ok := a.plugin.Meta.ChannelRelayRoute(info.ChannelOtherSettings.PluginRoutes, path, info.OriginModelName)
if !ok {
return fmt.Errorf("plugin %s has no relay route for %s and model %s", a.plugin.Meta.Key, path, info.OriginModelName)
}
@@ -594,7 +596,7 @@ func (a *Adaptor) credentialContext(info *relaycommon.RelayInfo) jsplugin.Creden
func (a *Adaptor) hookContext(c *gin.Context, info *relaycommon.RelayInfo) jsplugin.HookContext {
hookCtx := jsplugin.HookContext{BaseURL: info.ChannelBaseUrl, Config: a.config, Token: a.token}
if c != nil && c.Request != nil && c.Request.URL != nil {
hookCtx.Path = c.Request.URL.Path
hookCtx.Path = common.NormalizeRelayPath(c.Request.URL.Path)
}
return hookCtx
}
@@ -706,7 +708,7 @@ func (a *Adaptor) prepare(c *gin.Context, info *relaycommon.RelayInfo, body []by
}
}
prepared, err := a.plugin.CallPrepareRequest(c.Request.Context(), a.hookContext(c, info), jsplugin.PrepareInput{
Path: c.Request.URL.Path,
Path: common.NormalizeRelayPath(c.Request.URL.Path),
UpstreamPath: upstreamPath,
Model: info.UpstreamModelName,
Stream: info.IsStream,
+5 -1
View File
@@ -350,7 +350,7 @@ func (info *RelayInfo) InitChannelMeta(c *gin.Context) {
if (channelType == constant.ChannelTypeAdvancedCustom || providerPlugin) &&
!channelMeta.ChannelSetting.PassThroughBodyEnabled &&
c.Request != nil && c.Request.URL != nil {
route, matched := channelMeta.ChannelOtherSettings.AdvancedCustom.MatchPathForModel(c.Request.URL.Path, info.OriginModelName)
route, matched := channelMeta.ChannelOtherSettings.AdvancedCustom.MatchPathForModel(common.NormalizeRelayPath(c.Request.URL.Path), info.OriginModelName)
if matched && route.PassThroughBodyEnabled {
channelMeta.ChannelSetting.PassThroughBodyEnabled = true
}
@@ -1030,6 +1030,10 @@ func (info *RelayInfo) ConvOptions() *convmeta.Options {
return options
}
func (info *RelayInfo) IsFirstResponsePending() bool {
return info != nil && info.isFirstResponse
}
func (info *RelayInfo) SetFirstResponseTime() {
if info.isFirstResponse {
info.FirstResponseTime = time.Now()
+21
View File
@@ -9,7 +9,9 @@ import (
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
@@ -296,6 +298,25 @@ func Done(c *gin.Context) {
_ = StringData(c, "[DONE]")
}
// StreamErrorData ends a stream whose response has already started with an
// error event in the client's protocol, and records the failure on the
// response stream status.
func StreamErrorData(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
Done(c)
}
func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
if ws == nil {
logger.LogError(c, common.LogText("websocket connection is nil"))
+27 -2
View File
@@ -117,12 +117,35 @@ func (w *streamResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string, sr *StreamResult)) {
// StreamScannerOption customizes StreamScannerHandler behavior.
type StreamScannerOption func(*streamScannerConfig)
type streamScannerConfig struct {
isFirstResponse func(data string) bool
}
// WithFirstResponsePredicate delays info.SetFirstResponseTime until a
// non-[DONE] SSE data frame satisfies pred. A nil predicate preserves the
// default behavior of recording the first non-[DONE] data frame.
func WithFirstResponsePredicate(pred func(data string) bool) StreamScannerOption {
return func(cfg *streamScannerConfig) {
cfg.isFirstResponse = pred
}
}
func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string, sr *StreamResult), opts ...StreamScannerOption) {
if resp == nil || dataHandler == nil {
return
}
var cfg streamScannerConfig
for _, opt := range opts {
if opt != nil {
opt(&cfg)
}
}
// Finish the request keepalive before changing headers. The scanner owns
// subsequent ping and data writes through its shared write mutex.
if writer := keepAliveWriter(c); writer != nil {
@@ -307,7 +330,9 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
continue
}
if data != "[DONE]" {
info.SetFirstResponseTime()
if info.IsFirstResponsePending() && (cfg.isFirstResponse == nil || cfg.isFirstResponse(data)) {
info.SetFirstResponseTime()
}
info.ReceivedResponseCount++
select {
+64
View File
@@ -15,6 +15,8 @@ import (
"github.com/QuantumNous/new-api/constant"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
@@ -724,3 +726,65 @@ func TestSetEventStreamHeadersBoundsStreamWritesByBudget(t *testing.T) {
assert.False(t, recorder.deadlines[0].Before(before.Add(streamWriteTimeout+450*time.Second)))
assert.Contains(t, recorder.Body.String(), "data: AAAA")
}
func TestStreamScannerHandler_WithFirstResponsePredicate(t *testing.T) {
t.Parallel()
newPendingInfo := func(t *testing.T, c *gin.Context) *relaycommon.RelayInfo {
t.Helper()
stream := true
info, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, &dto.GeneralOpenAIRequest{Model: "gpt-4o", Stream: &stream}, nil)
require.NoError(t, err)
return info
}
t.Run("delays first response until predicate matches and stops evaluating after latch", func(t *testing.T) {
t.Parallel()
pr, pw := io.Pipe()
go func() {
defer pw.Close()
_, _ = fmt.Fprint(pw, "data: empty-1\n\n")
time.Sleep(80 * time.Millisecond)
_, _ = fmt.Fprint(pw, "data: token-1\n\n")
_, _ = fmt.Fprint(pw, "data: token-2\n\n")
_, _ = fmt.Fprint(pw, "data: [DONE]\n\n")
}()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
info := newPendingInfo(t, c)
resp := &http.Response{Body: pr}
var predCalls atomic.Int64
var received []string
StreamScannerHandler(c, resp, info, func(data string, _ *StreamResult) {
received = append(received, data)
}, WithFirstResponsePredicate(func(data string) bool {
predCalls.Add(1)
return strings.HasPrefix(data, "token-")
}))
assert.Equal(t, []string{"empty-1", "token-1", "token-2"}, received)
assert.Equal(t, int64(2), predCalls.Load(), "predicate should not be called after latching")
assert.True(t, info.HasSendResponse())
assert.GreaterOrEqual(t, info.FirstResponseTime.Sub(info.StartTime), 70*time.Millisecond)
})
t.Run("leaves first response unset when no chunk matches", func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
info := newPendingInfo(t, c)
resp := &http.Response{Body: io.NopCloser(strings.NewReader("data: empty-1\n\ndata: empty-2\n\ndata: [DONE]\n\n"))}
StreamScannerHandler(c, resp, info, func(string, *StreamResult) {}, WithFirstResponsePredicate(func(string) bool {
return false
}))
assert.False(t, info.HasSendResponse())
assert.True(t, info.IsFirstResponsePending())
assert.Equal(t, 2, info.ReceivedResponseCount)
})
}
@@ -227,9 +227,8 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
appended++
lastWasText = text
}
isTools := false
isThought := false
if candidate.FinishReason != nil {
if candidate.FinishReason != nil && *candidate.FinishReason != "" && *candidate.FinishReason != "FINISH_REASON_UNSPECIFIED" {
switch *candidate.FinishReason {
case "STOP":
choice.FinishReason = &types.FinishReasonStop
@@ -254,7 +253,6 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
content.WriteByte(')')
}
} else if part.FunctionCall != nil {
isTools = true
if call := geminiResponseToolCall(&part); call != nil {
call.SetIndex(len(choice.Delta.ToolCalls))
choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
@@ -285,14 +283,13 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
}
var emittedParts []renderedGeminiPart
if isThought {
choice.Delta.SetReasoningContent(content.String())
} else {
if content.Len() > 0 {
choice.Delta.SetReasoningContent(content.String())
}
} else if content.Len() > 0 {
choice.Delta.SetContentString(content.String())
emittedParts = textParts
}
if isTools {
choice.FinishReason = &types.FinishReasonToolCalls
}
choice.Delta.Annotations = groundingAnnotationsToChat(candidate.GroundingMetadata, textParts, content.String())
choices = append(choices, choice)
contentParts = append(contentParts, emittedParts)
@@ -382,13 +379,6 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
if err != nil {
return nil, err
}
hasNonStopFinish := false
for _, candidate := range geminiResponse.Candidates {
if candidate.FinishReason != nil && *candidate.FinishReason != "" && *candidate.FinishReason != "STOP" {
hasNonStopFinish = true
break
}
}
response, isStop, contentParts := streamResponseGeminiChat2OpenAI(geminiResponse)
if response == nil {
return nil, nil
@@ -397,12 +387,23 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
response.Created = s.created
response.Model = model
response.Usage = usage
nonStopFinishReason := ""
hasPayload := len(response.Choices) == 0 && usage != nil
for index := range geminiResponse.Candidates {
if index >= len(response.Choices) {
break
}
candidate := &geminiResponse.Candidates[index]
choice := &response.Choices[index]
if choice.FinishReason != nil && *choice.FinishReason != "" {
if nonStopFinishReason == "" {
nonStopFinishReason = *choice.FinishReason
}
choice.FinishReason = nil
}
if len(choice.Delta.ToolCalls) > 0 {
s.sawToolCall = true
}
for toolIndex := range choice.Delta.ToolCalls {
callID := strings.TrimSpace(choice.Delta.ToolCalls[toolIndex].ID)
indexesByID := s.toolIndexByCandidateID[candidate.Index]
@@ -431,31 +432,24 @@ func (s *GeminiToChatStreamState) ConvertChunk(geminiResponse *dto.GeminiChatRes
candidate.Index,
s.sentGroundingAnnotations,
)
}
if response.IsToolCall() {
s.sawToolCall = true
if !hasNonStopFinish {
for i := range response.Choices {
if response.Choices[i].FinishReason != nil && *response.Choices[i].FinishReason == types.FinishReasonToolCalls {
response.Choices[i].FinishReason = nil
}
}
if choice.Delta.GetContentString() != "" ||
choice.Delta.GetReasoningContent() != "" ||
len(choice.Delta.ToolCalls) > 0 ||
len(choice.Delta.Annotations) > 0 {
hasPayload = true
}
}
if usage != nil {
s.latestUsage = usage
}
for _, choice := range response.Choices {
if choice.FinishReason != nil && *choice.FinishReason != "" {
s.finishEmitted = true
break
}
}
responses := []*dto.ChatCompletionsStreamResponse{response}
if isStop && !s.finishEmitted {
responses = append(responses, s.terminalChunk(model))
responses := make([]*dto.ChatCompletionsStreamResponse, 0, 2)
if hasPayload && (!s.finishEmitted || len(response.Choices) == 0) {
responses = append(responses, response)
}
if (isStop || nonStopFinishReason != "") && !s.finishEmitted {
responses = append(responses, s.terminalChunk(model, nonStopFinishReason))
}
return responses, nil
}
@@ -479,7 +473,7 @@ func (s *GeminiToChatStreamState) Finalize(model string) ([]*dto.ChatCompletions
if s.finishEmitted {
return nil, nil
}
return []*dto.ChatCompletionsStreamResponse{s.terminalChunk(model)}, nil
return []*dto.ChatCompletionsStreamResponse{s.terminalChunk(model, "")}, nil
}
func (s *GeminiToChatStreamState) Usage() *dto.Usage {
@@ -717,10 +711,12 @@ func setGeminiPartialArgValue(current any, path []geminiPartialArgPathSegment, v
return object, nil
}
func (s *GeminiToChatStreamState) terminalChunk(model string) *dto.ChatCompletionsStreamResponse {
finishReason := types.FinishReasonStop
if s.sawToolCall {
finishReason = types.FinishReasonToolCalls
func (s *GeminiToChatStreamState) terminalChunk(model string, finishReason string) *dto.ChatCompletionsStreamResponse {
if finishReason == "" {
finishReason = types.FinishReasonStop
if s.sawToolCall {
finishReason = types.FinishReasonToolCalls
}
}
s.finishEmitted = true
return &dto.ChatCompletionsStreamResponse{
+3 -3
View File
@@ -107,9 +107,9 @@ func (s *BillingSession) Settle(actualQuota int) error {
s.relayInfo.UserId, s.relayInfo.TokenId, delta, tokenErr.Error()))
}
}
// 3) 更新 relayInfo 上的订阅 PostDelta(用于日志)
if s.funding.Source() == BillingSourceSubscription {
s.relayInfo.SubscriptionPostDelta += int64(delta)
// 3) 更新 relayInfo 上的订阅 PostDelta(用于日志),按实际生效的差额计
if sub, ok := s.funding.(*SubscriptionFunding); ok {
s.relayInfo.SubscriptionPostDelta += sub.settledDelta
}
s.settled, s.actualQuota, s.settlementErr = true, actualQuota, tokenErr
return tokenErr
+1 -1
View File
@@ -41,7 +41,7 @@ func AppendTaskPluginIdentityFilter(c *gin.Context, pluginKey string) {
}
if c.Request != nil && c.Request.URL != nil {
// An ordinary request may run on a plugin channel whose relay routes serve its path.
filter.RequestPath = c.Request.URL.Path
filter.RequestPath = common.NormalizeRelayPath(c.Request.URL.Path)
}
GetChannelConstraints(c).AddFilter(filter)
}
+8 -1
View File
@@ -140,6 +140,7 @@ type SubscriptionFunding struct {
amount int64 // 预扣的订阅额度(subConsume)
subscriptionId int
preConsumed int64
settledDelta int64
// 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用
AmountTotal int64
AmountUsedAfter int64
@@ -169,9 +170,15 @@ func (s *SubscriptionFunding) PreConsume(_ int) error {
func (s *SubscriptionFunding) Settle(delta int) error {
if delta == 0 {
s.settledDelta = 0
return nil
}
return model.PostConsumeUserSubscriptionDelta(s.subscriptionId, int64(delta))
applied, err := model.SettleUserSubscriptionDelta(s.subscriptionId, int64(delta))
if err != nil {
return err
}
s.settledDelta = applied
return nil
}
func (s *SubscriptionFunding) Refund() error {
+272
View File
@@ -0,0 +1,272 @@
package service
import (
"context"
"fmt"
"math"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupSubscriptionSettleTables(t *testing.T) {
t.Helper()
truncate(t)
require.NoError(t, model.DB.AutoMigrate(&model.SubscriptionPlan{}, &model.SubscriptionPreConsumeRecord{}))
t.Cleanup(func() {
model.DB.Exec("DELETE FROM subscription_pre_consume_records")
model.DB.Exec("DELETE FROM subscription_plans")
_ = model.PurgeSubscriptionPlanCache()
})
}
func seedSubscriptionPlanAndInstance(t *testing.T, userID int, total int64, used int64, allowWalletOverflow bool, endOffset time.Duration) *model.UserSubscription {
t.Helper()
plan := &model.SubscriptionPlan{
Title: fmt.Sprintf("Plan-%d", total),
DurationUnit: model.SubscriptionDurationDay,
DurationValue: 1,
TotalAmount: total,
QuotaResetPeriod: model.SubscriptionResetNever,
AllowWalletOverflow: common.GetPointer(allowWalletOverflow),
Enabled: true,
}
require.NoError(t, model.DB.Create(plan).Error)
now := model.GetDBTimestamp()
sub := &model.UserSubscription{
UserId: userID,
PlanId: plan.Id,
AmountTotal: total,
AmountUsed: used,
StartTime: now,
EndTime: now + int64(endOffset.Seconds()),
Status: "active",
AllowWalletOverflow: allowWalletOverflow,
}
require.NoError(t, model.DB.Create(sub).Error)
return sub
}
func newBillingTestContext(t *testing.T) *gin.Context {
t.Helper()
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
return c
}
func TestSettleUserSubscriptionDelta(t *testing.T) {
setupSubscriptionSettleTables(t)
const userID = 901
seedUser(t, userID, 0)
t.Run("finite plan caps overrun and floors refund", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 0, false, time.Hour)
steps := []struct {
name string
delta int64
wantApplied int64
wantUsed int64
}{
{name: "normal charge", delta: 40, wantApplied: 40, wantUsed: 40},
{name: "overrun capped at total", delta: 75, wantApplied: 60, wantUsed: 100},
{name: "full plan avoids int64 overflow", delta: math.MaxInt64, wantApplied: 0, wantUsed: 100},
{name: "refund clamped at zero", delta: -500, wantApplied: -100, wantUsed: 0},
{name: "zero delta is no-op", delta: 0, wantApplied: 0, wantUsed: 0},
}
for _, tc := range steps {
applied, err := model.SettleUserSubscriptionDelta(sub.Id, tc.delta)
require.NoError(t, err, tc.name)
assert.Equal(t, tc.wantApplied, applied, tc.name)
assert.Equal(t, tc.wantUsed, getSubscriptionUsed(t, sub.Id), tc.name)
}
})
t.Run("unlimited plan saturates at MaxInt64 without overflow", func(t *testing.T) {
sub := seedSubscriptionPlanAndInstance(t, userID, 0, math.MaxInt64-10, false, time.Hour)
applied, err := model.SettleUserSubscriptionDelta(sub.Id, 100)
require.NoError(t, err)
assert.Equal(t, int64(10), applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
applied, err = model.SettleUserSubscriptionDelta(sub.Id, 1)
require.NoError(t, err)
assert.Zero(t, applied)
assert.Equal(t, int64(math.MaxInt64), getSubscriptionUsed(t, sub.Id))
})
t.Run("invalid subscription id returns error", func(t *testing.T) {
for _, id := range []int{0, -1} {
applied, err := model.SettleUserSubscriptionDelta(id, 10)
require.Error(t, err)
assert.Zero(t, applied)
}
})
}
func TestBillingSessionSubscriptionSettleOverrunSwitchesPlanAndRejects(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 902
tokenID = 902
tokenInitialQuota = 40_000_000
planTotal = int64(15_000_000)
preConsume = 5_000
actualQuota = 2_250_375
fullDelta = int64(actualQuota - preConsume)
requestsPerPlan = 7
lastAppliedDelta = planTotal - int64(requestsPerPlan-1)*int64(actualQuota) - int64(preConsume)
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-overrun-switch", tokenInitialQuota)
subA := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, time.Hour)
subB := seedSubscriptionPlanAndInstance(t, userID, planTotal, 0, false, 2*time.Hour)
runRequest := func(seq int) (*relaycommon.RelayInfo, *types.NewAPIError) {
c := newBillingTestContext(t)
info := &relaycommon.RelayInfo{
RequestId: fmt.Sprintf("req-sub-overrun-%d", seq),
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-overrun-switch",
OriginModelName: "test-model",
UserSetting: dto.UserSetting{
BillingPreference: "subscription_first",
QuotaWarningEnabled: common.GetPointer(false),
},
}
if apiErr := PreConsumeBilling(c, preConsume, info); apiErr != nil {
return info, apiErr
}
require.NoError(t, SettleBilling(c, info, actualQuota))
return info, nil
}
// Requests 1..7 exhaust subscription A; request 7 caps at planTotal.
for i := range requestsPerPlan {
info, apiErr := runRequest(i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub A", i+1)
assert.Equal(t, subA.Id, info.SubscriptionId)
if i < requestsPerPlan-1 {
assert.Equal(t, fullDelta, info.SubscriptionPostDelta)
} else {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
require.NoError(t, info.Billing.Settle(actualQuota), "repeated settle must be idempotent")
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
other := model.NewLogOther()
appendBillingInfo(info, other)
snap := other.Snapshot()
assert.Equal(t, int64(preConsume)+lastAppliedDelta, snap["subscription_consumed"])
assert.Equal(t, int64(0), snap["subscription_remain"])
assert.Equal(t, planTotal, snap["subscription_used"])
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subA.Id))
assert.Zero(t, getSubscriptionUsed(t, subB.Id))
// Requests 8..14 automatically switch to subscription B and exhaust it.
for i := range requestsPerPlan {
info, apiErr := runRequest(requestsPerPlan + i + 1)
require.Nil(t, apiErr, "request %d should succeed on sub B", requestsPerPlan+i+1)
assert.Equal(t, subB.Id, info.SubscriptionId)
if i == requestsPerPlan-1 {
assert.Equal(t, lastAppliedDelta, info.SubscriptionPostDelta)
}
}
assert.Equal(t, planTotal, getSubscriptionUsed(t, subB.Id))
// Request 15 is rejected at pre-consume because both plans are full and wallet overflow is disabled.
_, apiErr := runRequest(2*requestsPerPlan + 1)
require.NotNil(t, apiErr)
assert.Equal(t, http.StatusForbidden, apiErr.StatusCode)
assert.Equal(t, types.ErrorCodeInsufficientUserQuota, apiErr.GetErrorCode())
// Token quota still accounts for the full actual cost of all 14 completed requests.
assert.Equal(t, tokenInitialQuota-2*requestsPerPlan*actualQuota, getTokenRemainQuota(t, tokenID))
}
func TestPostConsumeQuotaRejectsSubscriptionOverrun(t *testing.T) {
setupSubscriptionSettleTables(t)
const (
userID = 903
tokenID = 903
tokenRemain = 10_000
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-strict-post", tokenRemain)
sub := seedSubscriptionPlanAndInstance(t, userID, 100, 90, false, time.Hour)
info := &relaycommon.RelayInfo{
UserId: userID,
TokenId: tokenID,
TokenKey: "sk-sub-strict-post",
BillingSource: BillingSourceSubscription,
SubscriptionId: sub.Id,
}
// PostConsumeQuota backs Realtime PreWssConsumeQuota and must stay strict.
err := PostConsumeQuota(info, 25, 0, false)
require.Error(t, err)
assert.Contains(t, err.Error(), "subscription used exceeds total")
assert.Equal(t, int64(90), getSubscriptionUsed(t, sub.Id))
assert.Zero(t, info.SubscriptionPostDelta)
assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
}
func TestRecalculateTaskQuota_SubscriptionOverrunCapsPlan(t *testing.T) {
setupSubscriptionSettleTables(t)
ctx := context.Background()
const (
userID = 904
tokenID = 904
channelID = 904
preConsumed = 50
actualQuota = 200
tokenRemain = 500
)
seedUser(t, userID, 0)
seedToken(t, tokenID, userID, "sk-sub-task-overrun", tokenRemain)
seedChannel(t, channelID)
sub := seedSubscriptionPlanAndInstance(t, userID, 1000, 950, false, time.Hour)
seedChargedAccounting(t, userID, channelID, tokenID, preConsumed, 1)
task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceSubscription, sub.Id)
require.NoError(t, model.DB.Create(task).Error)
RecalculateTaskQuota(ctx, task, actualQuota, common.NewMessage("subscription overrun settle"))
assert.Equal(t, int64(1000), getSubscriptionUsed(t, sub.Id))
assert.Equal(t, actualQuota, task.Quota)
assert.Equal(t, actualQuota, getTaskQuota(t, task.ID))
assert.Equal(t, tokenRemain-(actualQuota-preConsumed), getTokenRemainQuota(t, tokenID))
usedQuota, requestCount := getUserUsageAccounting(t, userID)
assert.Equal(t, actualQuota, usedQuota)
assert.Equal(t, 1, requestCount)
assert.Equal(t, int64(actualQuota), getChannelUsedQuota(t, channelID))
log := getLastLog(t)
require.NotNil(t, log)
assert.Equal(t, model.LogTypeConsume, log.Type)
assert.Equal(t, actualQuota-preConsumed, log.Quota)
}
+2 -1
View File
@@ -126,7 +126,8 @@ func taskAdjustFunding(task *model.Task, delta int) error {
return fmt.Errorf("durable wallet task requires a terminal settlement intent")
}
if taskIsSubscription(task) {
return model.PostConsumeUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
_, err := model.SettleUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
return err
}
if delta > 0 {
return model.DecreaseUserQuota(task.UserId, delta, false)
@@ -1103,6 +1103,55 @@ test('a failed creation keeps its draft and prevents duplicate submission while
expect(screen.getByLabelText('Name *')).toHaveValue('Video A')
})
test.each(['create', 'edit'] as const)(
'VolcEngine %s exposes upstream discovery and lets users select fetched models',
async (mode) => {
editingChannel.type = 45
const post = vi.spyOn(api, 'post').mockResolvedValue({
data: { success: true, data: ['upstream-model'] },
})
const user = userEvent.setup()
render(
<ConfigurationHarness
currentRow={mode === 'edit' ? editingChannel : undefined}
/>
)
if (mode === 'create') {
await user.click(screen.getByRole('option', { name: /^VolcEngine / }))
fireEvent.change(screen.getByLabelText('API Key *'), {
target: { value: 'test-key' },
})
} else {
await screen.findByDisplayValue('Existing channel')
}
const fetch = screen.getByRole('button', { name: 'Fetch from Upstream' })
expect(fetch).toBeEnabled()
await user.click(fetch)
await user.click(
await screen.findByRole('checkbox', { name: 'upstream-model' })
)
expect(screen.getByRole('button', { name: 'upstream-model' })).toBeVisible()
if (mode === 'create') {
expect(post).toHaveBeenCalledWith(
'/api/channel/fetch_models',
expect.objectContaining({
type: 45,
key: 'test-key',
base_url: 'https://ark.cn-beijing.volces.com',
}),
expect.anything()
)
} else {
expect(api.get).toHaveBeenCalledWith(
'/api/channel/fetch_models/42',
expect.anything()
)
expect(post).not.toHaveBeenCalled()
}
}
)
test('model discovery discards a response for old credentials and retains manually selected models', async () => {
const oldReply = deferredResponse<{
data: { success: boolean; data: string[] }
+1
View File
@@ -519,6 +519,7 @@ export const MODEL_FETCHABLE_TYPES = new Set([
40,
42,
43,
45,
47,
48,
57,