diff --git a/README.ja.md b/README.ja.md
index 426af9c1e0..2b35bdfe9b 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -7,33 +7,38 @@
🍥 **次世代大規模モデルゲートウェイとAI資産管理システム**
@@ -49,10 +54,7 @@
## 📝 プロジェクト説明
-> [!NOTE]
-> 本プロジェクトは、[One API](https://github.com/songquanpeng/one-api)をベースに二次開発されたオープンソースプロジェクトです
-
-> [!IMPORTANT]
+> [!IMPORTANT]
> - 本プロジェクトは個人学習用のみであり、安定性の保証や技術サポートは提供しません。
> - ユーザーは、OpenAIの[利用規約](https://openai.com/policies/terms-of-use)および**法律法規**を遵守する必要があり、違法な目的で使用してはいけません。
> - [《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm)の要求に従い、中国地域の公衆に未登録の生成式AI サービスを提供しないでください。
@@ -68,17 +70,20 @@
@@ -179,7 +184,7 @@ docker run --name new-api -d --restart always \
| 機能 | 説明 |
|------|------|
| 🎨 新しいUI | モダンなユーザーインターフェースデザイン |
-| 🌍 多言語 | 中国語、英語、フランス語、日本語をサポート |
+| 🌍 多言語 | 簡体字中国語、繁体字中国語、英語、フランス語、日本語をサポート |
| 🔄 データ互換性 | オリジナルのOne APIデータベースと完全に互換性あり |
| 📈 データダッシュボード | ビジュアルコンソールと統計分析 |
| 🔒 権限管理 | トークングループ化、モデル制限、ユーザー管理 |
@@ -193,9 +198,11 @@ docker run --name new-api -d --restart always \
### 🔐 認証とセキュリティ
+- 😈 Discord認証ログイン
- 🤖 LinuxDO認証ログイン
- 📱 Telegram認証ログイン
- 🔑 OIDC統一認証
+- 🔍 Key使用量クォータ照会([neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool)と併用)
@@ -206,10 +213,6 @@ docker run --name new-api -d --restart always \
- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/ja/docs/api/ai-model/realtime/create-realtime-session)(Azureを含む)
- ⚡ [Claude Messages](https://docs.newapi.pro/ja/docs/api/ai-model/chat/create-message)
- ⚡ [Google Gemini](https://doc.newapi.pro/ja/api/google-gemini-chat)
-- 🔄 [Rerankモデル](https://docs.newapi.pro/ja/docs/api/ai-model/rerank/create-rerank)
-- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/ja/docs/api/ai-model/realtime/create-realtime-session)
-- ⚡ [Claude Messages](https://docs.newapi.pro/ja/docs/api/ai-model/chat/create-message)
-- ⚡ [Google Gemini](https://doc.newapi.pro/ja/api/google-gemini-chat)
- 🔄 [Rerankモデル](https://docs.newapi.pro/ja/docs/api/ai-model/rerank/create-rerank)(Cohere、Jina)
**インテリジェントルーティング:**
@@ -257,12 +260,13 @@ docker run --name new-api -d --restart always \
| モデルタイプ | 説明 | ドキュメント |
|---------|------|------|
-| 🤖 OpenAI GPTs | gpt-4-gizmo-* シリーズ | - |
-| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [ドキュメント](https://doc.newapi.pro/ja/api/midjourney-proxy-image) |
-| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [ドキュメント](https://doc.newapi.pro/ja/api/suno-music) |
-| 🔄 Rerank | Cohere、Jina | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/rerank/create-rerank) |
-| 💬 Claude | Messagesフォーマット | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/chat/create-message) |
-| 🌐 Gemini | Google Geminiフォーマット | [ドキュメント](https://doc.newapi.pro/ja/api/google-gemini-chat) |
+| 🤖 OpenAI-Compatible | OpenAI互換モデル | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/chat/openai/createchatcompletion) |
+| 🤖 OpenAI Responses | OpenAI Responsesフォーマット | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/chat/openai/createresponse) |
+| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [ドキュメント](https://doc.newapi.pro/api/midjourney-proxy-image) |
+| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [ドキュメント](https://doc.newapi.pro/api/suno-music) |
+| 🔄 Rerank | Cohere、Jina | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/rerank/creatererank) |
+| 💬 Claude | Messagesフォーマット | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/chat/createmessage) |
+| 🌐 Gemini | Google Geminiフォーマット | [ドキュメント](https://docs.newapi.pro/ja/docs/api/ai-model/chat/gemini/geminirelayv1beta) |
| 🔧 Dify | ChatFlowモード | - |
| 🎯 カスタム | 完全な呼び出しアドレスの入力をサポート | - |
@@ -271,16 +275,16 @@ docker run --name new-api -d --restart always \
@@ -368,7 +372,7 @@ docker run --name new-api -d --restart always \
calciumion/new-api:latest
```
-> **💡 パス説明:**
+> **💡 パス説明:**
> - `./data:/data` - 相対パス、データは現在のディレクトリのdataフォルダに保存されます
> - 絶対パスを使用することもできます:`/your/custom/path:/data`
@@ -439,6 +443,16 @@ docker run --name new-api -d --restart always \
---
+## 📜 ライセンス
+
+このプロジェクトは [GNU Affero General Public License v3.0 (AGPLv3)](./LICENSE) の下でライセンスされています。
+
+本プロジェクトは、[One API](https://github.com/songquanpeng/one-api)(MITライセンス)をベースに開発されたオープンソースプロジェクトです。
+
+お客様の組織のポリシーがAGPLv3ライセンスのソフトウェアの使用を許可していない場合、またはAGPLv3のオープンソース義務を回避したい場合は、こちらまでお問い合わせください:[support@quantumnous.com](mailto:support@quantumnous.com)
+
+---
+
## 🌟 スター履歴
-## 📝 项目说明
+## 📝 Project Description
-> [!NOTE]
-> 本项目为开源项目,在 [One API](https://github.com/songquanpeng/one-api) 的基础上进行二次开发
-
-> [!IMPORTANT]
-> - 本项目仅供个人学习使用,不保证稳定性,且不提供任何技术支持
-> - 使用者必须在遵循 OpenAI 的 [使用条款](https://openai.com/policies/terms-of-use) 以及**法律法规**的情况下使用,不得用于非法用途
-> - 根据 [《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm) 的要求,请勿对中国地区公众提供一切未经备案的生成式人工智能服务
+> [!IMPORTANT]
+> - This project is for personal learning purposes only, with no guarantee of stability or technical support
+> - Users must comply with OpenAI's [Terms of Use](https://openai.com/policies/terms-of-use) and **applicable laws and regulations**, and must not use it for illegal purposes
+> - According to the [《Interim Measures for the Management of Generative Artificial Intelligence Services》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm), please do not provide any unregistered generative AI services to the public in China.
---
-## 🤝 我们信任的合作伙伴
+## 🤝 Trusted Partners
---
-## 🚀 快速开始
+## 🚀 Quick Start
-### 使用 Docker Compose(推荐)
+### Using Docker Compose (Recommended)
```bash
-# 克隆项目
+# Clone the project
git clone https://github.com/QuantumNous/new-api.git
cd new-api
-# 编辑 docker-compose.yml 配置
+# Edit docker-compose.yml configuration
nano docker-compose.yml
-# 启动服务
+# Start the service
docker-compose up -d
```
---
-🎉 部署完成后,访问 `http://localhost:3000` 即可使用!
+🎉 After deployment is complete, visit `http://localhost:3000` to start using!
-📖 更多部署方式请参考 [部署指南](https://docs.newapi.pro/zh/docs/installation)
+📖 For more deployment methods, please refer to [Deployment Guide](https://docs.newapi.pro/en/docs/installation)
---
-## 📚 文档
+## 📚 Documentation
-### 📖 [官方文档](https://docs.newapi.pro/zh/docs) | [](https://deepwiki.com/QuantumNous/new-api)
+### 📖 [Official Documentation](https://docs.newapi.pro/en/docs) | [](https://deepwiki.com/QuantumNous/new-api)
-**快速导航:**
+**Quick Navigation:**
-| 分类 | 链接 |
+| Category | Link |
|------|------|
-| 🚀 部署指南 | [安装文档](https://docs.newapi.pro/zh/docs/installation) |
-| ⚙️ 环境配置 | [环境变量](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables) |
-| 📡 接口文档 | [API 文档](https://docs.newapi.pro/zh/docs/api) |
-| ❓ 常见问题 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
-| 💬 社区交流 | [交流渠道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
+| 🚀 Deployment Guide | [Installation Documentation](https://docs.newapi.pro/en/docs/installation) |
+| ⚙️ Environment Configuration | [Environment Variables](https://docs.newapi.pro/en/docs/installation/config-maintenance/environment-variables) |
+| 📡 API Documentation | [API Documentation](https://docs.newapi.pro/en/docs/api) |
+| ❓ FAQ | [FAQ](https://docs.newapi.pro/en/docs/support/faq) |
+| 💬 Community Interaction | [Communication Channels](https://docs.newapi.pro/en/docs/support/community-interaction) |
---
-## ✨ 主要特性
+## ✨ Key Features
-> 详细特性请参考 [特性说明](https://docs.newapi.pro/zh/docs/guide/wiki/basic-concepts/features-introduction)
+> For detailed features, please refer to [Features Introduction](https://docs.newapi.pro/en/docs/guide/wiki/basic-concepts/features-introduction)
-### 🎨 核心功能
+### 🎨 Core Functions
-| 特性 | 说明 |
+| Feature | Description |
|------|------|
-| 🎨 全新 UI | 现代化的用户界面设计 |
-| 🌍 多语言 | 支持中文、英文、法语、日语 |
-| 🔄 数据兼容 | 完全兼容原版 One API 数据库 |
-| 📈 数据看板 | 可视化控制台与统计分析 |
-| 🔒 权限管理 | 令牌分组、模型限制、用户管理 |
+| 🎨 New UI | Modern user interface design |
+| 🌍 Multi-language | Supports Simplified Chinese, Traditional Chinese, English, French, Japanese |
+| 🔄 Data Compatibility | Fully compatible with the original One API database |
+| 📈 Data Dashboard | Visual console and statistical analysis |
+| 🔒 Permission Management | Token grouping, model restrictions, user management |
-### 💰 支付与计费
+### 💰 Payment and Billing
-- ✅ 在线充值(易支付、Stripe)
-- ✅ 模型按次数收费
-- ✅ 缓存计费支持(OpenAI、Azure、DeepSeek、Claude、Qwen等所有支持的模型)
-- ✅ 灵活的计费策略配置
+- ✅ Online recharge (EPay, Stripe)
+- ✅ Pay-per-use model pricing
+- ✅ Cache billing support (OpenAI, Azure, DeepSeek, Claude, Qwen and all supported models)
+- ✅ Flexible billing policy configuration
-### 🔐 授权与安全
+### 🔐 Authorization and Security
-- 😈 Discord 授权登录
-- 🤖 LinuxDO 授权登录
-- 📱 Telegram 授权登录
-- 🔑 OIDC 统一认证
-- 🔍 Key 查询使用额度(配合 [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool))
+- 😈 Discord authorization login
+- 🤖 LinuxDO authorization login
+- 📱 Telegram authorization login
+- 🔑 OIDC unified authentication
+- 🔍 Key quota query usage (with [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool))
-### 🚀 高级功能
+### 🚀 Advanced Features
-**API 格式支持:**
-- ⚡ [OpenAI Responses](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/create-response)
-- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/zh/docs/api/ai-model/realtime/create-realtime-session)(含 Azure)
-- ⚡ [Claude Messages](https://docs.newapi.pro/zh/docs/api/ai-model/chat/create-message)
-- ⚡ [Google Gemini](https://doc.newapi.pro/api/google-gemini-chat)
-- 🔄 [Rerank 模型](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank)(Cohere、Jina)
+**API Format Support:**
+- ⚡ [OpenAI Responses](https://docs.newapi.pro/en/docs/api/ai-model/chat/openai/create-response)
+- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/en/docs/api/ai-model/realtime/create-realtime-session) (including Azure)
+- ⚡ [Claude Messages](https://docs.newapi.pro/en/docs/api/ai-model/chat/create-message)
+- ⚡ [Google Gemini](https://doc.newapi.pro/en/api/google-gemini-chat)
+- 🔄 [Rerank Models](https://docs.newapi.pro/en/docs/api/ai-model/rerank/create-rerank) (Cohere, Jina)
-**智能路由:**
-- ⚖️ 渠道加权随机
-- 🔄 失败自动重试
-- 🚦 用户级别模型限流
+**Intelligent Routing:**
+- ⚖️ Channel weighted random
+- 🔄 Automatic retry on failure
+- 🚦 User-level model rate limiting
-**格式转换:**
+**Format Conversion:**
- 🔄 **OpenAI Compatible ⇄ Claude Messages**
- 🔄 **OpenAI Compatible → Google Gemini**
-- 🔄 **Google Gemini → OpenAI Compatible** - 仅支持文本,暂不支持函数调用
-- 🚧 **OpenAI Compatible ⇄ OpenAI Responses** - 开发中
-- 🔄 **思考转内容功能**
+- 🔄 **Google Gemini → OpenAI Compatible** - Text only, function calling not supported yet
+- 🚧 **OpenAI Compatible ⇄ OpenAI Responses** - In development
+- 🔄 **Thinking-to-content functionality**
-**Reasoning Effort 支持:**
+**Reasoning Effort Support:**
---
-## 🤖 模型支持
+## 🤖 Model Support
-> 详情请参考 [接口文档 - 中继接口](https://docs.newapi.pro/zh/docs/api)
+> For details, please refer to [API Documentation - Relay Interface](https://docs.newapi.pro/en/docs/api)
-| 模型类型 | 说明 | 文档 |
+| Model Type | Description | Documentation |
|---------|------|------|
-| 🤖 OpenAI GPTs | gpt-4-gizmo-* 系列 | - |
-| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [文档](https://doc.newapi.pro/api/midjourney-proxy-image) |
-| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [文档](https://doc.newapi.pro/api/suno-music) |
-| 🔄 Rerank | Cohere、Jina | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank) |
-| 💬 Claude | Messages 格式 | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/chat/create-message) |
-| 🌐 Gemini | Google Gemini 格式 | [文档](https://doc.newapi.pro/api/google-gemini-chat) |
-| 🔧 Dify | ChatFlow 模式 | - |
-| 🎯 自定义 | 支持完整调用地址 | - |
+| 🤖 OpenAI-Compatible | OpenAI compatible models | [Documentation](https://docs.newapi.pro/en/docs/api/ai-model/chat/openai/createchatcompletion) |
+| 🤖 OpenAI Responses | OpenAI Responses format | [Documentation](https://docs.newapi.pro/en/docs/api/ai-model/chat/openai/createresponse) |
+| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [Documentation](https://doc.newapi.pro/api/midjourney-proxy-image) |
+| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [Documentation](https://doc.newapi.pro/api/suno-music) |
+| 🔄 Rerank | Cohere, Jina | [Documentation](https://docs.newapi.pro/en/docs/api/ai-model/rerank/creatererank) |
+| 💬 Claude | Messages format | [Documentation](https://docs.newapi.pro/en/docs/api/ai-model/chat/createmessage) |
+| 🌐 Gemini | Google Gemini format | [Documentation](https://docs.newapi.pro/en/docs/api/ai-model/chat/gemini/geminirelayv1beta) |
+| 🔧 Dify | ChatFlow mode | - |
+| 🎯 Custom | Supports complete call address | - |
-### 📡 支持的接口
+### 📡 Supported Interfaces
---
-## 🚢 部署
+## 🚢 Deployment
> [!TIP]
-> **最新版 Docker 镜像:** `calciumion/new-api:latest`
+> **Latest Docker image:** `calciumion/new-api:latest`
-### 📋 部署要求
+### 📋 Deployment Requirements
-| 组件 | 要求 |
+| Component | Requirement |
|------|------|
-| **本地数据库** | SQLite(Docker 需挂载 `/data` 目录)|
-| **远程数据库** | MySQL ≥ 5.7.8 或 PostgreSQL ≥ 9.6 |
-| **容器引擎** | Docker / Docker Compose |
+| **Local database** | SQLite (Docker must mount `/data` directory)|
+| **Remote database** | MySQL ≥ 5.7.8 or PostgreSQL ≥ 9.6 |
+| **Container engine** | Docker / Docker Compose |
-### ⚙️ 环境变量配置
+### ⚙️ Environment Variable Configuration
-### ⚠️ 多机部署注意事项
+### ⚠️ Multi-machine Deployment Considerations
> [!WARNING]
-> - **必须设置** `SESSION_SECRET` - 否则登录状态不一致
-> - **公用 Redis 必须设置** `CRYPTO_SECRET` - 否则数据无法解密
+> - **Must set** `SESSION_SECRET` - Otherwise login status inconsistent
+> - **Shared Redis must set** `CRYPTO_SECRET` - Otherwise data cannot be decrypted
-### 🔄 渠道重试与缓存
+### 🔄 Channel Retry and Cache
-**重试配置:** `设置 → 运营设置 → 通用设置 → 失败重试次数`
+**Retry configuration:** `Settings → Operation Settings → General Settings → Failure Retry Count`
-**缓存配置:**
-- `REDIS_CONN_STRING`:Redis 缓存(推荐)
-- `MEMORY_CACHE_ENABLED`:内存缓存
+**Cache configuration:**
+- `REDIS_CONN_STRING`: Redis cache (recommended)
+- `MEMORY_CACHE_ENABLED`: Memory cache
---
-## 🔗 相关项目
+## 🔗 Related Projects
-### 上游项目
+### Upstream Projects
-| 项目 | 说明 |
+| Project | Description |
|------|------|
-| [One API](https://github.com/songquanpeng/one-api) | 原版项目基础 |
-| [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney 接口支持 |
+| [One API](https://github.com/songquanpeng/one-api) | Original project base |
+| [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney interface support |
-### 配套工具
+### Supporting Tools
-| 项目 | 说明 |
+| Project | Description |
|------|------|
-| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key 额度查询工具 |
-| [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API 高性能优化版 |
+| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key quota query tool |
+| [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API high-performance optimized version |
---
-## 💬 帮助支持
+## 💬 Help Support
-### 📖 文档资源
+### 📖 Documentation Resources
-| 资源 | 链接 |
+| Resource | Link |
|------|------|
-| 📘 常见问题 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
-| 💬 社区交流 | [交流渠道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
-| 🐛 反馈问题 | [问题反馈](https://docs.newapi.pro/zh/docs/support/feedback-issues) |
-| 📚 完整文档 | [官方文档](https://docs.newapi.pro/zh/docs) |
+| 📘 FAQ | [FAQ](https://docs.newapi.pro/en/docs/support/faq) |
+| 💬 Community Interaction | [Communication Channels](https://docs.newapi.pro/en/docs/support/community-interaction) |
+| 🐛 Issue Feedback | [Issue Feedback](https://docs.newapi.pro/en/docs/support/feedback-issues) |
+| 📚 Complete Documentation | [Official Documentation](https://docs.newapi.pro/en/docs) |
-### 🤝 贡献指南
+### 🤝 Contribution Guide
-欢迎各种形式的贡献!
+Welcome all forms of contribution!
-- 🐛 报告 Bug
-- 💡 提出新功能
-- 📝 改进文档
-- 🔧 提交代码
+- 🐛 Report Bugs
+- 💡 Propose New Features
+- 📝 Improve Documentation
+- 🔧 Submit Code
+
+---
+
+## 📜 License
+
+This project is licensed under the [GNU Affero General Public License v3.0 (AGPLv3)](./LICENSE).
+
+This is an open-source project developed based on [One API](https://github.com/songquanpeng/one-api) (MIT License).
+
+If your organization's policies do not permit the use of AGPLv3-licensed software, or if you wish to avoid the open-source obligations of AGPLv3, please contact us at: [support@quantumnous.com](mailto:support@quantumnous.com)
---
@@ -449,11 +465,11 @@ docker run --name new-api -d --restart always \
-### 💖 感谢使用 New API
+### 💖 Thank you for using New API
-如果这个项目对你有帮助,欢迎给我们一个 ⭐️ Star!
+If this project is helpful to you, welcome to give us a ⭐️ Star!
-**[官方文档](https://docs.newapi.pro/zh/docs)** • **[问题反馈](https://github.com/Calcium-Ion/new-api/issues)** • **[最新发布](https://github.com/Calcium-Ion/new-api/releases)**
+**[Official Documentation](https://docs.newapi.pro/en/docs)** • **[Issue Feedback](https://github.com/Calcium-Ion/new-api/issues)** • **[Latest Release](https://github.com/Calcium-Ion/new-api/releases)**
Built with ❤️ by QuantumNous
diff --git a/README.zh_CN.md b/README.zh_CN.md
new file mode 100644
index 0000000000..92e5baa1d2
--- /dev/null
+++ b/README.zh_CN.md
@@ -0,0 +1,476 @@
+
+
+## 📝 项目说明
+
+> [!IMPORTANT]
+> - 本项目仅供个人学习使用,不保证稳定性,且不提供任何技术支持
+> - 使用者必须在遵循 OpenAI 的 [使用条款](https://openai.com/policies/terms-of-use) 以及**法律法规**的情况下使用,不得用于非法用途
+> - 根据 [《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm) 的要求,请勿对中国地区公众提供一切未经备案的生成式人工智能服务
+
+---
+
+## 🤝 我们信任的合作伙伴
+
+
+ 排名不分先后
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+## 🙏 特别鸣谢
+
+
+
+
+
+
+
+
+ 感谢 JetBrains 为本项目提供免费的开源开发许可证
+
+
+---
+
+## 🚀 快速开始
+
+### 使用 Docker Compose(推荐)
+
+```bash
+# 克隆项目
+git clone https://github.com/QuantumNous/new-api.git
+cd new-api
+
+# 编辑 docker-compose.yml 配置
+nano docker-compose.yml
+
+# 启动服务
+docker-compose up -d
+```
+
+
+使用 Docker 命令
+
+```bash
+# 拉取最新镜像
+docker pull calciumion/new-api:latest
+
+# 使用 SQLite(默认)
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+
+# 使用 MySQL
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+> **💡 提示:** `-v ./data:/data` 会将数据保存在当前目录的 `data` 文件夹中,你也可以改为绝对路径如 `-v /your/custom/path:/data`
+
+
+
+---
+
+🎉 部署完成后,访问 `http://localhost:3000` 即可使用!
+
+📖 更多部署方式请参考 [部署指南](https://docs.newapi.pro/zh/docs/installation)
+
+---
+
+## 📚 文档
+
+
+
+### 📖 [官方文档](https://docs.newapi.pro/zh/docs) | [](https://deepwiki.com/QuantumNous/new-api)
+
+
+
+**快速导航:**
+
+| 分类 | 链接 |
+|------|------|
+| 🚀 部署指南 | [安装文档](https://docs.newapi.pro/zh/docs/installation) |
+| ⚙️ 环境配置 | [环境变量](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables) |
+| 📡 接口文档 | [API 文档](https://docs.newapi.pro/zh/docs/api) |
+| ❓ 常见问题 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
+| 💬 社区交流 | [交流渠道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
+
+---
+
+## ✨ 主要特性
+
+> 详细特性请参考 [特性说明](https://docs.newapi.pro/zh/docs/guide/wiki/basic-concepts/features-introduction)
+
+### 🎨 核心功能
+
+| 特性 | 说明 |
+|------|------|
+| 🎨 全新 UI | 现代化的用户界面设计 |
+| 🌍 多语言 | 支持中文、英文、法语、日语 |
+| 🔄 数据兼容 | 完全兼容原版 One API 数据库 |
+| 📈 数据看板 | 可视化控制台与统计分析 |
+| 🔒 权限管理 | 令牌分组、模型限制、用户管理 |
+
+### 💰 支付与计费
+
+- ✅ 在线充值(易支付、Stripe)
+- ✅ 模型按次数收费
+- ✅ 缓存计费支持(OpenAI、Azure、DeepSeek、Claude、Qwen等所有支持的模型)
+- ✅ 灵活的计费策略配置
+
+### 🔐 授权与安全
+
+- 😈 Discord 授权登录
+- 🤖 LinuxDO 授权登录
+- 📱 Telegram 授权登录
+- 🔑 OIDC 统一认证
+- 🔍 Key 查询使用额度(配合 [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool))
+
+### 🚀 高级功能
+
+**API 格式支持:**
+- ⚡ [OpenAI Responses](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/create-response)
+- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/zh/docs/api/ai-model/realtime/create-realtime-session)(含 Azure)
+- ⚡ [Claude Messages](https://docs.newapi.pro/zh/docs/api/ai-model/chat/create-message)
+- ⚡ [Google Gemini](https://doc.newapi.pro/api/google-gemini-chat)
+- 🔄 [Rerank 模型](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank)(Cohere、Jina)
+
+**智能路由:**
+- ⚖️ 渠道加权随机
+- 🔄 失败自动重试
+- 🚦 用户级别模型限流
+
+**格式转换:**
+- 🔄 **OpenAI Compatible ⇄ Claude Messages**
+- 🔄 **OpenAI Compatible → Google Gemini**
+- 🔄 **Google Gemini → OpenAI Compatible** - 仅支持文本,暂不支持函数调用
+- 🚧 **OpenAI Compatible ⇄ OpenAI Responses** - 开发中
+- 🔄 **思考转内容功能**
+
+**Reasoning Effort 支持:**
+
+
+查看详细配置
+
+**OpenAI 系列模型:**
+- `o3-mini-high` - High reasoning effort
+- `o3-mini-medium` - Medium reasoning effort
+- `o3-mini-low` - Low reasoning effort
+- `gpt-5-high` - High reasoning effort
+- `gpt-5-medium` - Medium reasoning effort
+- `gpt-5-low` - Low reasoning effort
+
+**Claude 思考模型:**
+- `claude-3-7-sonnet-20250219-thinking` - 启用思考模式
+
+**Google Gemini 系列模型:**
+- `gemini-2.5-flash-thinking` - 启用思考模式
+- `gemini-2.5-flash-nothinking` - 禁用思考模式
+- `gemini-2.5-pro-thinking` - 启用思考模式
+- `gemini-2.5-pro-thinking-128` - 启用思考模式,并设置思考预算为128tokens
+- 也可以直接在 Gemini 模型名称后追加 `-low` / `-medium` / `-high` 来控制思考力度(无需再设置思考预算后缀)
+
+
+
+---
+
+## 🤖 模型支持
+
+> 详情请参考 [接口文档 - 中继接口](https://docs.newapi.pro/zh/docs/api)
+
+| 模型类型 | 说明 | 文档 |
+|---------|------|------|
+| 🤖 OpenAI-Compatible | OpenAI 兼容模型 | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createchatcompletion) |
+| 🤖 OpenAI Responses | OpenAI Responses 格式 | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createresponse) |
+| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [文档](https://doc.newapi.pro/api/midjourney-proxy-image) |
+| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [文档](https://doc.newapi.pro/api/suno-music) |
+| 🔄 Rerank | Cohere、Jina | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank) |
+| 💬 Claude | Messages 格式 | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/chat/createmessage) |
+| 🌐 Gemini | Google Gemini 格式 | [文档](https://docs.newapi.pro/zh/docs/api/ai-model/chat/gemini/geminirelayv1beta) |
+| 🔧 Dify | ChatFlow 模式 | - |
+| 🎯 自定义 | 支持完整调用地址 | - |
+
+### 📡 支持的接口
+
+
+查看完整接口列表
+
+- [聊天接口 (Chat Completions)](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createchatcompletion)
+- [响应接口 (Responses)](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createresponse)
+- [图像接口 (Image)](https://docs.newapi.pro/zh/docs/api/ai-model/images/openai/post-v1-images-generations)
+- [音频接口 (Audio)](https://docs.newapi.pro/zh/docs/api/ai-model/audio/openai/create-transcription)
+- [视频接口 (Video)](https://docs.newapi.pro/zh/docs/api/ai-model/audio/openai/createspeech)
+- [嵌入接口 (Embeddings)](https://docs.newapi.pro/zh/docs/api/ai-model/embeddings/createembedding)
+- [重排序接口 (Rerank)](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/creatererank)
+- [实时对话 (Realtime)](https://docs.newapi.pro/zh/docs/api/ai-model/realtime/createrealtimesession)
+- [Claude 聊天](https://docs.newapi.pro/zh/docs/api/ai-model/chat/createmessage)
+- [Google Gemini 聊天](https://docs.newapi.pro/zh/docs/api/ai-model/chat/gemini/geminirelayv1beta)
+
+
+
+---
+
+## 🚢 部署
+
+> [!TIP]
+> **最新版 Docker 镜像:** `calciumion/new-api:latest`
+
+### 📋 部署要求
+
+| 组件 | 要求 |
+|------|------|
+| **本地数据库** | SQLite(Docker 需挂载 `/data` 目录)|
+| **远程数据库** | MySQL ≥ 5.7.8 或 PostgreSQL ≥ 9.6 |
+| **容器引擎** | Docker / Docker Compose |
+
+### ⚙️ 环境变量配置
+
+
+常用环境变量配置
+
+| 变量名 | 说明 | 默认值 |
+|--------|--------------------------------------------------------------|--------|
+| `SESSION_SECRET` | 会话密钥(多机部署必须) | - |
+| `CRYPTO_SECRET` | 加密密钥(Redis 必须) | - |
+| `SQL_DSN` | 数据库连接字符串 | - |
+| `REDIS_CONN_STRING` | Redis 连接字符串 | - |
+| `STREAMING_TIMEOUT` | 流式超时时间(秒) | `300` |
+| `STREAM_SCANNER_MAX_BUFFER_MB` | 流式扫描器单行最大缓冲(MB),图像生成等超大 `data:` 片段(如 4K 图片 base64)需适当调大 | `64` |
+| `MAX_REQUEST_BODY_MB` | 请求体最大大小(MB,**解压后**计;防止超大请求/zip bomb 导致内存暴涨),超过将返回 `413` | `32` |
+| `AZURE_DEFAULT_API_VERSION` | Azure API 版本 | `2025-04-01-preview` |
+| `ERROR_LOG_ENABLED` | 错误日志开关 | `false` |
+| `PYROSCOPE_URL` | Pyroscope 服务地址 | - |
+| `PYROSCOPE_APP_NAME` | Pyroscope 应用名 | `new-api` |
+| `PYROSCOPE_BASIC_AUTH_USER` | Pyroscope Basic Auth 用户名 | - |
+| `PYROSCOPE_BASIC_AUTH_PASSWORD` | Pyroscope Basic Auth 密码 | - |
+| `PYROSCOPE_MUTEX_RATE` | Pyroscope mutex 采样率 | `5` |
+| `PYROSCOPE_BLOCK_RATE` | Pyroscope block 采样率 | `5` |
+| `HOSTNAME` | Pyroscope 标签里的主机名 | `new-api` |
+
+📖 **完整配置:** [环境变量文档](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables)
+
+
+
+### 🔧 部署方式
+
+
+方式 1:Docker Compose(推荐)
+
+```bash
+# 克隆项目
+git clone https://github.com/QuantumNous/new-api.git
+cd new-api
+
+# 编辑配置
+nano docker-compose.yml
+
+# 启动服务
+docker-compose up -d
+```
+
+
+
+
+方式 2:Docker 命令
+
+**使用 SQLite:**
+```bash
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+**使用 MySQL:**
+```bash
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+> **💡 路径说明:**
+> - `./data:/data` - 相对路径,数据保存在当前目录的 data 文件夹
+> - 也可使用绝对路径,如:`/your/custom/path:/data`
+
+
+
+
+方式 3:宝塔面板
+
+1. 安装宝塔面板(≥ 9.2.0 版本)
+2. 在应用商店搜索 **New-API**
+3. 一键安装
+
+📖 [图文教程](./docs/installation/BT.md)
+
+
+
+### ⚠️ 多机部署注意事项
+
+> [!WARNING]
+> - **必须设置** `SESSION_SECRET` - 否则登录状态不一致
+> - **公用 Redis 必须设置** `CRYPTO_SECRET` - 否则数据无法解密
+
+### 🔄 渠道重试与缓存
+
+**重试配置:** `设置 → 运营设置 → 通用设置 → 失败重试次数`
+
+**缓存配置:**
+- `REDIS_CONN_STRING`:Redis 缓存(推荐)
+- `MEMORY_CACHE_ENABLED`:内存缓存
+
+---
+
+## 🔗 相关项目
+
+### 上游项目
+
+| 项目 | 说明 |
+|------|------|
+| [One API](https://github.com/songquanpeng/one-api) | 原版项目基础 |
+| [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney 接口支持 |
+
+### 配套工具
+
+| 项目 | 说明 |
+|------|------|
+| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key 额度查询工具 |
+| [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API 高性能优化版 |
+
+---
+
+## 💬 帮助支持
+
+### 📖 文档资源
+
+| 资源 | 链接 |
+|------|------|
+| 📘 常见问题 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
+| 💬 社区交流 | [交流渠道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
+| 🐛 反馈问题 | [问题反馈](https://docs.newapi.pro/zh/docs/support/feedback-issues) |
+| 📚 完整文档 | [官方文档](https://docs.newapi.pro/zh/docs) |
+
+### 🤝 贡献指南
+
+欢迎各种形式的贡献!
+
+- 🐛 报告 Bug
+- 💡 提出新功能
+- 📝 改进文档
+- 🔧 提交代码
+
+---
+
+## 📜 许可证
+
+本项目采用 [GNU Affero 通用公共许可证 v3.0 (AGPLv3)](./LICENSE) 授权。
+
+本项目为开源项目,在 [One API](https://github.com/songquanpeng/one-api)(MIT 许可证)的基础上进行二次开发。
+
+如果您所在的组织政策不允许使用 AGPLv3 许可的软件,或您希望规避 AGPLv3 的开源义务,请发送邮件至:[support@quantumnous.com](mailto:support@quantumnous.com)
+
+---
+
+## 🌟 Star History
+
+
+
+[](https://star-history.com/#Calcium-Ion/new-api&Date)
+
+
+
+---
+
+
+
+### 💖 感谢使用 New API
+
+如果这个项目对你有帮助,欢迎给我们一个 ⭐️ Star!
+
+**[官方文档](https://docs.newapi.pro/zh/docs)** • **[问题反馈](https://github.com/Calcium-Ion/new-api/issues)** • **[最新发布](https://github.com/Calcium-Ion/new-api/releases)**
+
+Built with ❤️ by QuantumNous
+
+
diff --git a/README.zh_TW.md b/README.zh_TW.md
new file mode 100644
index 0000000000..63664f0c86
--- /dev/null
+++ b/README.zh_TW.md
@@ -0,0 +1,476 @@
+
+
+## 📝 項目說明
+
+> [!IMPORTANT]
+> - 本項目僅供個人學習使用,不保證穩定性,且不提供任何技術支援
+> - 使用者必須在遵循 OpenAI 的 [使用條款](https://openai.com/policies/terms-of-use) 以及**法律法規**的情況下使用,不得用於非法用途
+> - 根據 [《生成式人工智慧服務管理暫行辦法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm) 的要求,請勿對中國地區公眾提供一切未經備案的生成式人工智慧服務
+
+---
+
+## 🤝 我們信任的合作伙伴
+
+
+ 排名不分先後
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+## 🙏 特別鳴謝
+
+
+
+
+
+
+
+
+ 感謝 JetBrains 為本項目提供免費的開源開發許可證
+
+
+---
+
+## 🚀 快速開始
+
+### 使用 Docker Compose(推薦)
+
+```bash
+# 複製項目
+git clone https://github.com/QuantumNous/new-api.git
+cd new-api
+
+# 編輯 docker-compose.yml 配置
+nano docker-compose.yml
+
+# 啟動服務
+docker-compose up -d
+```
+
+
+使用 Docker 命令
+
+```bash
+# 拉取最新鏡像
+docker pull calciumion/new-api:latest
+
+# 使用 SQLite(預設)
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+
+# 使用 MySQL
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+> **💡 提示:** `-v ./data:/data` 會將數據保存在當前目錄的 `data` 資料夾中,你也可以改為絕對路徑如 `-v /your/custom/path:/data`
+
+
+
+---
+
+🎉 部署完成後,訪問 `http://localhost:3000` 即可使用!
+
+📖 更多部署方式請參考 [部署指南](https://docs.newapi.pro/zh/docs/installation)
+
+---
+
+## 📚 文件
+
+
+
+### 📖 [官方文件](https://docs.newapi.pro/zh/docs) | [](https://deepwiki.com/QuantumNous/new-api)
+
+
+
+**快速導航:**
+
+| 分類 | 連結 |
+|------|------|
+| 🚀 部署指南 | [安裝文件](https://docs.newapi.pro/zh/docs/installation) |
+| ⚙️ 環境配置 | [環境變數](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables) |
+| 📡 接口文件 | [API 文件](https://docs.newapi.pro/zh/docs/api) |
+| ❓ 常見問題 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
+| 💬 社群交流 | [交流管道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
+
+---
+
+## ✨ 主要特性
+
+> 詳細特性請參考 [特性說明](https://docs.newapi.pro/zh/docs/guide/wiki/basic-concepts/features-introduction)
+
+### 🎨 核心功能
+
+| 特性 | 說明 |
+|------|------|
+| 🎨 全新 UI | 現代化的用戶界面設計 |
+| 🌍 多語言 | 支援簡體中文、繁體中文、英文、法語、日語 |
+| 🔄 數據兼容 | 完全兼容原版 One API 資料庫 |
+| 📈 數據看板 | 視覺化控制檯與統計分析 |
+| 🔒 權限管理 | 令牌分組、模型限制、用戶管理 |
+
+### 💰 支付與計費
+
+- ✅ 在線儲值(易支付、Stripe)
+- ✅ 模型按次數收費
+- ✅ 快取計費支援(OpenAI、Azure、DeepSeek、Claude、Qwen等所有支援的模型)
+- ✅ 靈活的計費策略配置
+
+### 🔐 授權與安全
+
+- 😈 Discord 授權登錄
+- 🤖 LinuxDO 授權登錄
+- 📱 Telegram 授權登錄
+- 🔑 OIDC 統一認證
+- 🔍 Key 查詢使用額度(配合 [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool))
+
+### 🚀 高級功能
+
+**API 格式支援:**
+- ⚡ [OpenAI Responses](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/create-response)
+- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/zh/docs/api/ai-model/realtime/create-realtime-session)(含 Azure)
+- ⚡ [Claude Messages](https://docs.newapi.pro/zh/docs/api/ai-model/chat/create-message)
+- ⚡ [Google Gemini](https://doc.newapi.pro/api/google-gemini-chat)
+- 🔄 [Rerank 模型](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank)(Cohere、Jina)
+
+**智慧路由:**
+- ⚖️ 管道加權隨機
+- 🔄 失敗自動重試
+- 🚦 用戶級別模型限流
+
+**格式轉換:**
+- 🔄 **OpenAI Compatible ⇄ Claude Messages**
+- 🔄 **OpenAI Compatible → Google Gemini**
+- 🔄 **Google Gemini → OpenAI Compatible** - 僅支援文本,暫不支援函數調用
+- 🚧 **OpenAI Compatible ⇄ OpenAI Responses** - 開發中
+- 🔄 **思考轉內容功能**
+
+**Reasoning Effort 支援:**
+
+
+查看詳細配置
+
+**OpenAI 系列模型:**
+- `o3-mini-high` - High reasoning effort
+- `o3-mini-medium` - Medium reasoning effort
+- `o3-mini-low` - Low reasoning effort
+- `gpt-5-high` - High reasoning effort
+- `gpt-5-medium` - Medium reasoning effort
+- `gpt-5-low` - Low reasoning effort
+
+**Claude 思考模型:**
+- `claude-3-7-sonnet-20250219-thinking` - 啟用思考模式
+
+**Google Gemini 系列模型:**
+- `gemini-2.5-flash-thinking` - 啟用思考模式
+- `gemini-2.5-flash-nothinking` - 禁用思考模式
+- `gemini-2.5-pro-thinking` - 啟用思考模式
+- `gemini-2.5-pro-thinking-128` - 啟用思考模式,並設置思考預算為128tokens
+- 也可以直接在 Gemini 模型名稱後追加 `-low` / `-medium` / `-high` 來控制思考力道(無需再設置思考預算後綴)
+
+
+
+---
+
+## 🤖 模型支援
+
+> 詳情請參考 [接口文件 - 中繼接口](https://docs.newapi.pro/zh/docs/api)
+
+| 模型類型 | 說明 | 文件 |
+|---------|------|------|
+| 🤖 OpenAI-Compatible | OpenAI 兼容模型 | [文件](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createchatcompletion) |
+| 🤖 OpenAI Responses | OpenAI Responses 格式 | [文件](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createresponse) |
+| 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [文件](https://doc.newapi.pro/api/midjourney-proxy-image) |
+| 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [文件](https://doc.newapi.pro/api/suno-music) |
+| 🔄 Rerank | Cohere、Jina | [文件](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/create-rerank) |
+| 💬 Claude | Messages 格式 | [文件](https://docs.newapi.pro/zh/docs/api/ai-model/chat/createmessage) |
+| 🌐 Gemini | Google Gemini 格式 | [文件](https://docs.newapi.pro/zh/docs/api/ai-model/chat/gemini/geminirelayv1beta) |
+| 🔧 Dify | ChatFlow 模式 | - |
+| 🎯 自訂 | 支援完整調用位址 | - |
+
+### 📡 支援的接口
+
+
+查看完整接口列表
+
+- [聊天接口 (Chat Completions)](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createchatcompletion)
+- [響應接口 (Responses)](https://docs.newapi.pro/zh/docs/api/ai-model/chat/openai/createresponse)
+- [圖像接口 (Image)](https://docs.newapi.pro/zh/docs/api/ai-model/images/openai/post-v1-images-generations)
+- [音訊接口 (Audio)](https://docs.newapi.pro/zh/docs/api/ai-model/audio/openai/create-transcription)
+- [影片接口 (Video)](https://docs.newapi.pro/zh/docs/api/ai-model/audio/openai/createspeech)
+- [嵌入接口 (Embeddings)](https://docs.newapi.pro/zh/docs/api/ai-model/embeddings/createembedding)
+- [重排序接口 (Rerank)](https://docs.newapi.pro/zh/docs/api/ai-model/rerank/creatererank)
+- [即時對話 (Realtime)](https://docs.newapi.pro/zh/docs/api/ai-model/realtime/createrealtimesession)
+- [Claude 聊天](https://docs.newapi.pro/zh/docs/api/ai-model/chat/createmessage)
+- [Google Gemini 聊天](https://docs.newapi.pro/zh/docs/api/ai-model/chat/gemini/geminirelayv1beta)
+
+
+
+---
+
+## 🚢 部署
+
+> [!TIP]
+> **最新版 Docker 鏡像:** `calciumion/new-api:latest`
+
+### 📋 部署要求
+
+| 組件 | 要求 |
+|------|------|
+| **本地資料庫** | SQLite(Docker 需掛載 `/data` 目錄)|
+| **遠端資料庫** | MySQL ≥ 5.7.8 或 PostgreSQL ≥ 9.6 |
+| **容器引擎** | Docker / Docker Compose |
+
+### ⚙️ 環境變數配置
+
+
+常用環境變數配置
+
+| 變數名 | 說明 | 預設值 |
+|--------|--------------------------------------------------------------|--------|
+| `SESSION_SECRET` | 會話密鑰(多機部署必須) | - |
+| `CRYPTO_SECRET` | 加密密鑰(Redis 必須) | - |
+| `SQL_DSN` | 資料庫連接字符串 | - |
+| `REDIS_CONN_STRING` | Redis 連接字符串 | - |
+| `STREAMING_TIMEOUT` | 流式超時時間(秒) | `300` |
+| `STREAM_SCANNER_MAX_BUFFER_MB` | 流式掃描器單行最大緩衝(MB),圖像生成等超大 `data:` 片段(如 4K 圖片 base64)需適當調大 | `64` |
+| `MAX_REQUEST_BODY_MB` | 請求體最大大小(MB,**解壓縮後**計;防止超大請求/zip bomb 導致記憶體暴漲),超過將返回 `413` | `32` |
+| `AZURE_DEFAULT_API_VERSION` | Azure API 版本 | `2025-04-01-preview` |
+| `ERROR_LOG_ENABLED` | 錯誤日誌開關 | `false` |
+| `PYROSCOPE_URL` | Pyroscope 服務位址 | - |
+| `PYROSCOPE_APP_NAME` | Pyroscope 應用名 | `new-api` |
+| `PYROSCOPE_BASIC_AUTH_USER` | Pyroscope Basic Auth 用戶名 | - |
+| `PYROSCOPE_BASIC_AUTH_PASSWORD` | Pyroscope Basic Auth 密碼 | - |
+| `PYROSCOPE_MUTEX_RATE` | Pyroscope mutex 採樣率 | `5` |
+| `PYROSCOPE_BLOCK_RATE` | Pyroscope block 採樣率 | `5` |
+| `HOSTNAME` | Pyroscope 標籤裡的主機名 | `new-api` |
+
+📖 **完整配置:** [環境變數文件](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables)
+
+
+
+### 🔧 部署方式
+
+
+方式 1:Docker Compose(推薦)
+
+```bash
+# 複製項目
+git clone https://github.com/QuantumNous/new-api.git
+cd new-api
+
+# 編輯配置
+nano docker-compose.yml
+
+# 啟動服務
+docker-compose up -d
+```
+
+
+
+
+方式 2:Docker 命令
+
+**使用 SQLite:**
+```bash
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+**使用 MySQL:**
+```bash
+docker run --name new-api -d --restart always \
+ -p 3000:3000 \
+ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \
+ -e TZ=Asia/Shanghai \
+ -v ./data:/data \
+ calciumion/new-api:latest
+```
+
+> **💡 路徑說明:**
+> - `./data:/data` - 相對路徑,數據保存在當前目錄的 data 資料夾
+> - 也可使用絕對路徑,如:`/your/custom/path:/data`
+
+
+
+
+方式 3:寶塔面板
+
+1. 安裝寶塔面板(≥ 9.2.0 版本)
+2. 在應用商店搜尋 **New-API**
+3. 一鍵安裝
+
+📖 [圖文教學](./docs/BT.md)
+
+
+
+### ⚠️ 多機部署注意事項
+
+> [!WARNING]
+> - **必須設置** `SESSION_SECRET` - 否則登錄狀態不一致
+> - **公用 Redis 必須設置** `CRYPTO_SECRET` - 否則數據無法解密
+
+### 🔄 管道重試與快取
+
+**重試配置:** `設置 → 運營設置 → 通用設置 → 失敗重試次數`
+
+**快取配置:**
+- `REDIS_CONN_STRING`:Redis 快取(推薦)
+- `MEMORY_CACHE_ENABLED`:記憶體快取
+
+---
+
+## 🔗 相關項目
+
+### 上游項目
+
+| 項目 | 說明 |
+|------|------|
+| [One API](https://github.com/songquanpeng/one-api) | 原版項目基礎 |
+| [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney 接口支援 |
+
+### 配套工具
+
+| 項目 | 說明 |
+|------|------|
+| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key 額度查詢工具 |
+| [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API 高性能優化版 |
+
+---
+
+## 💬 幫助支援
+
+### 📖 文件資源
+
+| 資源 | 連結 |
+|------|------|
+| 📘 常見問題 | [FAQ](https://docs.newapi.pro/zh/docs/support/faq) |
+| 💬 社群交流 | [交流管道](https://docs.newapi.pro/zh/docs/support/community-interaction) |
+| 🐛 回饋問題 | [問題回饋](https://docs.newapi.pro/zh/docs/support/feedback-issues) |
+| 📚 完整文件 | [官方文件](https://docs.newapi.pro/zh/docs) |
+
+### 🤝 貢獻指南
+
+歡迎各種形式的貢獻!
+
+- 🐛 報告 Bug
+- 💡 提出新功能
+- 📝 改進文件
+- 🔧 提交程式碼
+
+---
+
+## 📜 許可證
+
+本項目採用 [GNU Affero 通用公共許可證 v3.0 (AGPLv3)](./LICENSE) 授權。
+
+本項目為開源項目,在 [One API](https://github.com/songquanpeng/one-api)(MIT 許可證)的基礎上進行二次開發。
+
+如果您所在的組織政策不允許使用 AGPLv3 許可的軟體,或您希望規避 AGPLv3 的開源義務,請發送郵件至:[support@quantumnous.com](mailto:support@quantumnous.com)
+
+---
+
+## 🌟 Star History
+
+
+
+[](https://star-history.com/#Calcium-Ion/new-api&Date)
+
+
+
+---
+
+
+
+### 💖 感謝使用 New API
+
+如果這個項目對你有幫助,歡迎給我們一個 ⭐️ Star!
+
+**[官方文件](https://docs.newapi.pro/zh/docs)** • **[問題回饋](https://github.com/Calcium-Ion/new-api/issues)** • **[最新發布](https://github.com/Calcium-Ion/new-api/releases)**
+
+Built with ❤️ by QuantumNous
+
+
diff --git a/common/body_storage.go b/common/body_storage.go
new file mode 100644
index 0000000000..094dbda36d
--- /dev/null
+++ b/common/body_storage.go
@@ -0,0 +1,315 @@
+package common
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// BodyStorage 请求体存储接口
+type BodyStorage interface {
+ io.ReadSeeker
+ io.Closer
+ // Bytes 获取全部内容
+ Bytes() ([]byte, error)
+ // Size 获取数据大小
+ Size() int64
+ // IsDisk 是否是磁盘存储
+ IsDisk() bool
+}
+
+// ErrStorageClosed 存储已关闭错误
+var ErrStorageClosed = fmt.Errorf("body storage is closed")
+
+// memoryStorage 内存存储实现
+type memoryStorage struct {
+ data []byte
+ reader *bytes.Reader
+ size int64
+ closed int32
+ mu sync.Mutex
+}
+
+func newMemoryStorage(data []byte) *memoryStorage {
+ size := int64(len(data))
+ IncrementMemoryBuffers(size)
+ return &memoryStorage{
+ data: data,
+ reader: bytes.NewReader(data),
+ size: size,
+ }
+}
+
+func (m *memoryStorage) Read(p []byte) (n int, err error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if atomic.LoadInt32(&m.closed) == 1 {
+ return 0, ErrStorageClosed
+ }
+ return m.reader.Read(p)
+}
+
+func (m *memoryStorage) Seek(offset int64, whence int) (int64, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if atomic.LoadInt32(&m.closed) == 1 {
+ return 0, ErrStorageClosed
+ }
+ return m.reader.Seek(offset, whence)
+}
+
+func (m *memoryStorage) Close() error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if atomic.CompareAndSwapInt32(&m.closed, 0, 1) {
+ DecrementMemoryBuffers(m.size)
+ }
+ return nil
+}
+
+func (m *memoryStorage) Bytes() ([]byte, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if atomic.LoadInt32(&m.closed) == 1 {
+ return nil, ErrStorageClosed
+ }
+ return m.data, nil
+}
+
+func (m *memoryStorage) Size() int64 {
+ return m.size
+}
+
+func (m *memoryStorage) IsDisk() bool {
+ return false
+}
+
+// diskStorage 磁盘存储实现
+type diskStorage struct {
+ file *os.File
+ filePath string
+ size int64
+ closed int32
+ mu sync.Mutex
+}
+
+func newDiskStorage(data []byte, cachePath string) (*diskStorage, error) {
+ // 使用统一的缓存目录管理
+ filePath, file, err := CreateDiskCacheFile(DiskCacheTypeBody)
+ if err != nil {
+ return nil, err
+ }
+
+ // 写入数据
+ n, err := file.Write(data)
+ if err != nil {
+ file.Close()
+ os.Remove(filePath)
+ return nil, fmt.Errorf("failed to write to temp file: %w", err)
+ }
+
+ // 重置文件指针
+ if _, err := file.Seek(0, io.SeekStart); err != nil {
+ file.Close()
+ os.Remove(filePath)
+ return nil, fmt.Errorf("failed to seek temp file: %w", err)
+ }
+
+ size := int64(n)
+ IncrementDiskFiles(size)
+
+ return &diskStorage{
+ file: file,
+ filePath: filePath,
+ size: size,
+ }, nil
+}
+
+func newDiskStorageFromReader(reader io.Reader, maxBytes int64, cachePath string) (*diskStorage, error) {
+ // 使用统一的缓存目录管理
+ filePath, file, err := CreateDiskCacheFile(DiskCacheTypeBody)
+ if err != nil {
+ return nil, err
+ }
+
+ // 从 reader 读取并写入文件
+ written, err := io.Copy(file, io.LimitReader(reader, maxBytes+1))
+ if err != nil {
+ file.Close()
+ os.Remove(filePath)
+ return nil, fmt.Errorf("failed to write to temp file: %w", err)
+ }
+
+ if written > maxBytes {
+ file.Close()
+ os.Remove(filePath)
+ return nil, ErrRequestBodyTooLarge
+ }
+
+ // 重置文件指针
+ if _, err := file.Seek(0, io.SeekStart); err != nil {
+ file.Close()
+ os.Remove(filePath)
+ return nil, fmt.Errorf("failed to seek temp file: %w", err)
+ }
+
+ IncrementDiskFiles(written)
+
+ return &diskStorage{
+ file: file,
+ filePath: filePath,
+ size: written,
+ }, nil
+}
+
+func (d *diskStorage) Read(p []byte) (n int, err error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if atomic.LoadInt32(&d.closed) == 1 {
+ return 0, ErrStorageClosed
+ }
+ return d.file.Read(p)
+}
+
+func (d *diskStorage) Seek(offset int64, whence int) (int64, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if atomic.LoadInt32(&d.closed) == 1 {
+ return 0, ErrStorageClosed
+ }
+ return d.file.Seek(offset, whence)
+}
+
+func (d *diskStorage) Close() error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if atomic.CompareAndSwapInt32(&d.closed, 0, 1) {
+ d.file.Close()
+ os.Remove(d.filePath)
+ DecrementDiskFiles(d.size)
+ }
+ return nil
+}
+
+func (d *diskStorage) Bytes() ([]byte, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ if atomic.LoadInt32(&d.closed) == 1 {
+ return nil, ErrStorageClosed
+ }
+
+ // 保存当前位置
+ currentPos, err := d.file.Seek(0, io.SeekCurrent)
+ if err != nil {
+ return nil, err
+ }
+
+ // 移动到开头
+ if _, err := d.file.Seek(0, io.SeekStart); err != nil {
+ return nil, err
+ }
+
+ // 读取全部内容
+ data := make([]byte, d.size)
+ _, err = io.ReadFull(d.file, data)
+ if err != nil {
+ return nil, err
+ }
+
+ // 恢复位置
+ if _, err := d.file.Seek(currentPos, io.SeekStart); err != nil {
+ return nil, err
+ }
+
+ return data, nil
+}
+
+func (d *diskStorage) Size() int64 {
+ return d.size
+}
+
+func (d *diskStorage) IsDisk() bool {
+ return true
+}
+
+// CreateBodyStorage 根据数据大小创建合适的存储
+func CreateBodyStorage(data []byte) (BodyStorage, error) {
+ size := int64(len(data))
+ threshold := GetDiskCacheThresholdBytes()
+
+ // 检查是否应该使用磁盘缓存
+ if IsDiskCacheEnabled() &&
+ size >= threshold &&
+ IsDiskCacheAvailable(size) {
+ storage, err := newDiskStorage(data, GetDiskCachePath())
+ if err != nil {
+ // 如果磁盘存储失败,回退到内存存储
+ SysError(fmt.Sprintf("failed to create disk storage, falling back to memory: %v", err))
+ return newMemoryStorage(data), nil
+ }
+ return storage, nil
+ }
+
+ return newMemoryStorage(data), nil
+}
+
+// CreateBodyStorageFromReader 从 Reader 创建存储(用于大请求的流式处理)
+func CreateBodyStorageFromReader(reader io.Reader, contentLength int64, maxBytes int64) (BodyStorage, error) {
+ threshold := GetDiskCacheThresholdBytes()
+
+ // 如果启用了磁盘缓存且内容长度超过阈值,直接使用磁盘存储
+ if IsDiskCacheEnabled() &&
+ contentLength > 0 &&
+ contentLength >= threshold &&
+ IsDiskCacheAvailable(contentLength) {
+ storage, err := newDiskStorageFromReader(reader, maxBytes, GetDiskCachePath())
+ if err != nil {
+ if IsRequestBodyTooLargeError(err) {
+ return nil, err
+ }
+ // 磁盘存储失败,reader 已被消费,无法安全回退
+ // 直接返回错误而非尝试回退(因为 reader 数据已丢失)
+ return nil, fmt.Errorf("disk storage creation failed: %w", err)
+ }
+ IncrementDiskCacheHits()
+ return storage, nil
+ }
+
+ // 使用内存读取
+ data, err := io.ReadAll(io.LimitReader(reader, maxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > maxBytes {
+ return nil, ErrRequestBodyTooLarge
+ }
+
+ storage, err := CreateBodyStorage(data)
+ if err != nil {
+ return nil, err
+ }
+ // 如果最终使用内存存储,记录内存缓存命中
+ if !storage.IsDisk() {
+ IncrementMemoryCacheHits()
+ } else {
+ IncrementDiskCacheHits()
+ }
+ return storage, nil
+}
+
+// ReaderOnly wraps an io.Reader to hide io.Closer, preventing http.NewRequest
+// from type-asserting io.ReadCloser and closing the underlying BodyStorage.
+func ReaderOnly(r io.Reader) io.Reader {
+ return struct{ io.Reader }{r}
+}
+
+// CleanupOldCacheFiles 清理旧的缓存文件(用于启动时清理残留)
+func CleanupOldCacheFiles() {
+ // 使用统一的缓存管理
+ CleanupOldDiskCacheFiles(5 * time.Minute)
+}
diff --git a/common/constants.go b/common/constants.go
index 51b798dbc8..6caa7f5c00 100644
--- a/common/constants.go
+++ b/common/constants.go
@@ -39,7 +39,7 @@ var OptionMap map[string]string
var OptionMapRWMutex sync.RWMutex
var ItemsPerPage = 10
-var MaxRecentItems = 100
+var MaxRecentItems = 1000
var PasswordLoginEnabled = true
var PasswordRegisterEnabled = true
@@ -80,6 +80,7 @@ var InsecureTLSConfig = &tls.Config{InsecureSkipVerify: true}
var SMTPServer = ""
var SMTPPort = 587
var SMTPSSLEnabled = false
+var SMTPForceAuthLogin = false
var SMTPAccount = ""
var SMTPFrom = ""
var SMTPToken = ""
@@ -175,6 +176,11 @@ var (
DownloadRateLimitNum = 10
DownloadRateLimitDuration int64 = 60
+
+ // Per-user search rate limit (applies after authentication, keyed by user ID)
+ SearchRateLimitEnable = true
+ SearchRateLimitNum = 10
+ SearchRateLimitDuration int64 = 60
)
var RateLimitKeyExpirationDuration = 20 * time.Minute
@@ -207,5 +213,6 @@ const (
const (
TopUpStatusPending = "pending"
TopUpStatusSuccess = "success"
+ TopUpStatusFailed = "failed"
TopUpStatusExpired = "expired"
)
diff --git a/common/disk_cache.go b/common/disk_cache.go
new file mode 100644
index 0000000000..bea3de044e
--- /dev/null
+++ b/common/disk_cache.go
@@ -0,0 +1,176 @@
+package common
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// DiskCacheType 磁盘缓存类型
+type DiskCacheType string
+
+const (
+ DiskCacheTypeBody DiskCacheType = "body" // 请求体缓存
+ DiskCacheTypeFile DiskCacheType = "file" // 文件数据缓存
+)
+
+// 统一的缓存目录名
+const diskCacheDir = "new-api-body-cache"
+
+// GetDiskCacheDir 获取统一的磁盘缓存目录
+// 注意:每次调用都会重新计算,以响应配置变化
+func GetDiskCacheDir() string {
+ cachePath := GetDiskCachePath()
+ if cachePath == "" {
+ cachePath = os.TempDir()
+ }
+ return filepath.Join(cachePath, diskCacheDir)
+}
+
+// EnsureDiskCacheDir 确保缓存目录存在
+func EnsureDiskCacheDir() error {
+ dir := GetDiskCacheDir()
+ return os.MkdirAll(dir, 0755)
+}
+
+// CreateDiskCacheFile 创建磁盘缓存文件
+// cacheType: 缓存类型(body/file)
+// 返回文件路径和文件句柄
+func CreateDiskCacheFile(cacheType DiskCacheType) (string, *os.File, error) {
+ if err := EnsureDiskCacheDir(); err != nil {
+ return "", nil, fmt.Errorf("failed to create cache directory: %w", err)
+ }
+
+ dir := GetDiskCacheDir()
+ filename := fmt.Sprintf("%s-%s-%d.tmp", cacheType, uuid.New().String()[:8], time.Now().UnixNano())
+ filePath := filepath.Join(dir, filename)
+
+ file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0600)
+ if err != nil {
+ return "", nil, fmt.Errorf("failed to create cache file: %w", err)
+ }
+
+ return filePath, file, nil
+}
+
+// WriteDiskCacheFile 写入数据到磁盘缓存文件
+// 返回文件路径
+func WriteDiskCacheFile(cacheType DiskCacheType, data []byte) (string, error) {
+ filePath, file, err := CreateDiskCacheFile(cacheType)
+ if err != nil {
+ return "", err
+ }
+
+ _, err = file.Write(data)
+ if err != nil {
+ file.Close()
+ os.Remove(filePath)
+ return "", fmt.Errorf("failed to write cache file: %w", err)
+ }
+
+ if err := file.Close(); err != nil {
+ os.Remove(filePath)
+ return "", fmt.Errorf("failed to close cache file: %w", err)
+ }
+
+ return filePath, nil
+}
+
+// WriteDiskCacheFileString 写入字符串到磁盘缓存文件
+func WriteDiskCacheFileString(cacheType DiskCacheType, data string) (string, error) {
+ return WriteDiskCacheFile(cacheType, []byte(data))
+}
+
+// ReadDiskCacheFile 读取磁盘缓存文件
+func ReadDiskCacheFile(filePath string) ([]byte, error) {
+ return os.ReadFile(filePath)
+}
+
+// ReadDiskCacheFileString 读取磁盘缓存文件为字符串
+func ReadDiskCacheFileString(filePath string) (string, error) {
+ data, err := os.ReadFile(filePath)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
+
+// RemoveDiskCacheFile 删除磁盘缓存文件
+func RemoveDiskCacheFile(filePath string) error {
+ return os.Remove(filePath)
+}
+
+// CleanupOldDiskCacheFiles 清理旧的缓存文件
+// maxAge: 文件最大存活时间
+// 注意:此函数只删除文件,不更新统计(因为无法知道每个文件的原始大小)
+func CleanupOldDiskCacheFiles(maxAge time.Duration) error {
+ dir := GetDiskCacheDir()
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil // 目录不存在,无需清理
+ }
+ return err
+ }
+
+ now := time.Now()
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ info, err := entry.Info()
+ if err != nil {
+ continue
+ }
+ if now.Sub(info.ModTime()) > maxAge {
+ // 注意:后台清理任务删除文件时,由于无法得知原始 base64Size,
+ // 只能按磁盘文件大小扣减。这在目前 base64 存储模式下是准确的。
+ if err := os.Remove(filepath.Join(dir, entry.Name())); err == nil {
+ DecrementDiskFiles(info.Size())
+ }
+ }
+ }
+ return nil
+}
+
+// GetDiskCacheInfo 获取磁盘缓存目录信息
+func GetDiskCacheInfo() (fileCount int, totalSize int64, err error) {
+ dir := GetDiskCacheDir()
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return 0, 0, nil
+ }
+ return 0, 0, err
+ }
+
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ info, err := entry.Info()
+ if err != nil {
+ continue
+ }
+ fileCount++
+ totalSize += info.Size()
+ }
+ return fileCount, totalSize, nil
+}
+
+// ShouldUseDiskCache 判断是否应该使用磁盘缓存
+func ShouldUseDiskCache(dataSize int64) bool {
+ if !IsDiskCacheEnabled() {
+ return false
+ }
+ threshold := GetDiskCacheThresholdBytes()
+ if dataSize < threshold {
+ return false
+ }
+ return IsDiskCacheAvailable(dataSize)
+}
diff --git a/common/disk_cache_config.go b/common/disk_cache_config.go
new file mode 100644
index 0000000000..b629c9ce79
--- /dev/null
+++ b/common/disk_cache_config.go
@@ -0,0 +1,177 @@
+package common
+
+import (
+ "sync"
+ "sync/atomic"
+)
+
+// DiskCacheConfig 磁盘缓存配置(由 performance_setting 包更新)
+type DiskCacheConfig struct {
+ // Enabled 是否启用磁盘缓存
+ Enabled bool
+ // ThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
+ ThresholdMB int
+ // MaxSizeMB 磁盘缓存最大总大小(MB)
+ MaxSizeMB int
+ // Path 磁盘缓存目录
+ Path string
+}
+
+// 全局磁盘缓存配置
+var diskCacheConfig = DiskCacheConfig{
+ Enabled: false,
+ ThresholdMB: 10,
+ MaxSizeMB: 1024,
+ Path: "",
+}
+var diskCacheConfigMu sync.RWMutex
+
+// GetDiskCacheConfig 获取磁盘缓存配置
+func GetDiskCacheConfig() DiskCacheConfig {
+ diskCacheConfigMu.RLock()
+ defer diskCacheConfigMu.RUnlock()
+ return diskCacheConfig
+}
+
+// SetDiskCacheConfig 设置磁盘缓存配置
+func SetDiskCacheConfig(config DiskCacheConfig) {
+ diskCacheConfigMu.Lock()
+ defer diskCacheConfigMu.Unlock()
+ diskCacheConfig = config
+}
+
+// IsDiskCacheEnabled 是否启用磁盘缓存
+func IsDiskCacheEnabled() bool {
+ diskCacheConfigMu.RLock()
+ defer diskCacheConfigMu.RUnlock()
+ return diskCacheConfig.Enabled
+}
+
+// GetDiskCacheThresholdBytes 获取磁盘缓存阈值(字节)
+func GetDiskCacheThresholdBytes() int64 {
+ diskCacheConfigMu.RLock()
+ defer diskCacheConfigMu.RUnlock()
+ return int64(diskCacheConfig.ThresholdMB) << 20
+}
+
+// GetDiskCacheMaxSizeBytes 获取磁盘缓存最大大小(字节)
+func GetDiskCacheMaxSizeBytes() int64 {
+ diskCacheConfigMu.RLock()
+ defer diskCacheConfigMu.RUnlock()
+ return int64(diskCacheConfig.MaxSizeMB) << 20
+}
+
+// GetDiskCachePath 获取磁盘缓存目录
+func GetDiskCachePath() string {
+ diskCacheConfigMu.RLock()
+ defer diskCacheConfigMu.RUnlock()
+ return diskCacheConfig.Path
+}
+
+// DiskCacheStats 磁盘缓存统计信息
+type DiskCacheStats struct {
+ // 当前活跃的磁盘缓存文件数
+ ActiveDiskFiles int64 `json:"active_disk_files"`
+ // 当前磁盘缓存总大小(字节)
+ CurrentDiskUsageBytes int64 `json:"current_disk_usage_bytes"`
+ // 当前内存缓存数量
+ ActiveMemoryBuffers int64 `json:"active_memory_buffers"`
+ // 当前内存缓存总大小(字节)
+ CurrentMemoryUsageBytes int64 `json:"current_memory_usage_bytes"`
+ // 磁盘缓存命中次数
+ DiskCacheHits int64 `json:"disk_cache_hits"`
+ // 内存缓存命中次数
+ MemoryCacheHits int64 `json:"memory_cache_hits"`
+ // 磁盘缓存最大限制(字节)
+ DiskCacheMaxBytes int64 `json:"disk_cache_max_bytes"`
+ // 磁盘缓存阈值(字节)
+ DiskCacheThresholdBytes int64 `json:"disk_cache_threshold_bytes"`
+}
+
+var diskCacheStats DiskCacheStats
+
+// GetDiskCacheStats 获取缓存统计信息
+func GetDiskCacheStats() DiskCacheStats {
+ stats := DiskCacheStats{
+ ActiveDiskFiles: atomic.LoadInt64(&diskCacheStats.ActiveDiskFiles),
+ CurrentDiskUsageBytes: atomic.LoadInt64(&diskCacheStats.CurrentDiskUsageBytes),
+ ActiveMemoryBuffers: atomic.LoadInt64(&diskCacheStats.ActiveMemoryBuffers),
+ CurrentMemoryUsageBytes: atomic.LoadInt64(&diskCacheStats.CurrentMemoryUsageBytes),
+ DiskCacheHits: atomic.LoadInt64(&diskCacheStats.DiskCacheHits),
+ MemoryCacheHits: atomic.LoadInt64(&diskCacheStats.MemoryCacheHits),
+ DiskCacheMaxBytes: GetDiskCacheMaxSizeBytes(),
+ DiskCacheThresholdBytes: GetDiskCacheThresholdBytes(),
+ }
+ return stats
+}
+
+// IncrementDiskFiles 增加磁盘文件计数
+func IncrementDiskFiles(size int64) {
+ atomic.AddInt64(&diskCacheStats.ActiveDiskFiles, 1)
+ atomic.AddInt64(&diskCacheStats.CurrentDiskUsageBytes, size)
+}
+
+// DecrementDiskFiles 减少磁盘文件计数
+func DecrementDiskFiles(size int64) {
+ if atomic.AddInt64(&diskCacheStats.ActiveDiskFiles, -1) < 0 {
+ atomic.StoreInt64(&diskCacheStats.ActiveDiskFiles, 0)
+ }
+ if atomic.AddInt64(&diskCacheStats.CurrentDiskUsageBytes, -size) < 0 {
+ atomic.StoreInt64(&diskCacheStats.CurrentDiskUsageBytes, 0)
+ }
+}
+
+// IncrementMemoryBuffers 增加内存缓存计数
+func IncrementMemoryBuffers(size int64) {
+ atomic.AddInt64(&diskCacheStats.ActiveMemoryBuffers, 1)
+ atomic.AddInt64(&diskCacheStats.CurrentMemoryUsageBytes, size)
+}
+
+// DecrementMemoryBuffers 减少内存缓存计数
+func DecrementMemoryBuffers(size int64) {
+ atomic.AddInt64(&diskCacheStats.ActiveMemoryBuffers, -1)
+ atomic.AddInt64(&diskCacheStats.CurrentMemoryUsageBytes, -size)
+}
+
+// IncrementDiskCacheHits 增加磁盘缓存命中次数
+func IncrementDiskCacheHits() {
+ atomic.AddInt64(&diskCacheStats.DiskCacheHits, 1)
+}
+
+// IncrementMemoryCacheHits 增加内存缓存命中次数
+func IncrementMemoryCacheHits() {
+ atomic.AddInt64(&diskCacheStats.MemoryCacheHits, 1)
+}
+
+// ResetDiskCacheStats 重置命中统计信息(不重置当前使用量)
+func ResetDiskCacheStats() {
+ atomic.StoreInt64(&diskCacheStats.DiskCacheHits, 0)
+ atomic.StoreInt64(&diskCacheStats.MemoryCacheHits, 0)
+}
+
+// ResetDiskCacheUsage 重置磁盘缓存使用量统计(用于清理缓存后)
+func ResetDiskCacheUsage() {
+ atomic.StoreInt64(&diskCacheStats.ActiveDiskFiles, 0)
+ atomic.StoreInt64(&diskCacheStats.CurrentDiskUsageBytes, 0)
+}
+
+// SyncDiskCacheStats 从实际磁盘状态同步统计信息
+// 用于修正统计与实际不符的情况
+func SyncDiskCacheStats() {
+ fileCount, totalSize, err := GetDiskCacheInfo()
+ if err != nil {
+ return
+ }
+ atomic.StoreInt64(&diskCacheStats.ActiveDiskFiles, int64(fileCount))
+ atomic.StoreInt64(&diskCacheStats.CurrentDiskUsageBytes, totalSize)
+}
+
+// IsDiskCacheAvailable 检查是否可以创建新的磁盘缓存
+func IsDiskCacheAvailable(requestSize int64) bool {
+ if !IsDiskCacheEnabled() {
+ return false
+ }
+ maxBytes := GetDiskCacheMaxSizeBytes()
+ currentUsage := atomic.LoadInt64(&diskCacheStats.CurrentDiskUsageBytes)
+ return currentUsage+requestSize <= maxBytes
+}
diff --git a/common/email.go b/common/email.go
index 9f574f06e5..c43ddec912 100644
--- a/common/email.go
+++ b/common/email.go
@@ -19,6 +19,20 @@ func generateMessageID() (string, error) {
return fmt.Sprintf("<%d.%s@%s>", time.Now().UnixNano(), GetRandomString(12), domain), nil
}
+func shouldUseSMTPLoginAuth() bool {
+ if SMTPForceAuthLogin {
+ return true
+ }
+ return isOutlookServer(SMTPAccount) || slices.Contains(EmailLoginAuthServerList, SMTPServer)
+}
+
+func getSMTPAuth() smtp.Auth {
+ if shouldUseSMTPLoginAuth() {
+ return LoginAuth(SMTPAccount, SMTPToken)
+ }
+ return smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer)
+}
+
func SendEmail(subject string, receiver string, content string) error {
if SMTPFrom == "" { // for compatibility
SMTPFrom = SMTPAccount
@@ -38,7 +52,7 @@ func SendEmail(subject string, receiver string, content string) error {
"Message-ID: %s\r\n"+ // 添加 Message-ID 头
"Content-Type: text/html; charset=UTF-8\r\n\r\n%s\r\n",
receiver, SystemName, SMTPFrom, encodedSubject, time.Now().Format(time.RFC1123Z), id, content))
- auth := smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer)
+ auth := getSMTPAuth()
addr := fmt.Sprintf("%s:%d", SMTPServer, SMTPPort)
to := strings.Split(receiver, ";")
var err error
@@ -80,9 +94,6 @@ func SendEmail(subject string, receiver string, content string) error {
if err != nil {
return err
}
- } else if isOutlookServer(SMTPAccount) || slices.Contains(EmailLoginAuthServerList, SMTPServer) {
- auth = LoginAuth(SMTPAccount, SMTPToken)
- err = smtp.SendMail(addr, auth, SMTPFrom, to, mail)
} else {
err = smtp.SendMail(addr, auth, SMTPFrom, to, mail)
}
diff --git a/common/endpoint_defaults.go b/common/endpoint_defaults.go
index c04c5f6d8e..11ec792175 100644
--- a/common/endpoint_defaults.go
+++ b/common/endpoint_defaults.go
@@ -17,13 +17,14 @@ type EndpointInfo struct {
// defaultEndpointInfoMap 保存内置端点的默认 Path 与 Method
var defaultEndpointInfoMap = map[constant.EndpointType]EndpointInfo{
- constant.EndpointTypeOpenAI: {Path: "/v1/chat/completions", Method: "POST"},
- constant.EndpointTypeOpenAIResponse: {Path: "/v1/responses", Method: "POST"},
- constant.EndpointTypeAnthropic: {Path: "/v1/messages", Method: "POST"},
- constant.EndpointTypeGemini: {Path: "/v1beta/models/{model}:generateContent", Method: "POST"},
- constant.EndpointTypeJinaRerank: {Path: "/rerank", Method: "POST"},
- constant.EndpointTypeImageGeneration: {Path: "/v1/images/generations", Method: "POST"},
- constant.EndpointTypeEmbeddings: {Path: "/v1/embeddings", Method: "POST"},
+ constant.EndpointTypeOpenAI: {Path: "/v1/chat/completions", Method: "POST"},
+ constant.EndpointTypeOpenAIResponse: {Path: "/v1/responses", Method: "POST"},
+ constant.EndpointTypeOpenAIResponseCompact: {Path: "/v1/responses/compact", Method: "POST"},
+ constant.EndpointTypeAnthropic: {Path: "/v1/messages", Method: "POST"},
+ constant.EndpointTypeGemini: {Path: "/v1beta/models/{model}:generateContent", Method: "POST"},
+ constant.EndpointTypeJinaRerank: {Path: "/v1/rerank", Method: "POST"},
+ constant.EndpointTypeImageGeneration: {Path: "/v1/images/generations", Method: "POST"},
+ constant.EndpointTypeEmbeddings: {Path: "/v1/embeddings", Method: "POST"},
}
// GetDefaultEndpointInfo 返回指定端点类型的默认信息以及是否存在
diff --git a/common/endpoint_type.go b/common/endpoint_type.go
index 65e80ce2f7..a5e2ff8412 100644
--- a/common/endpoint_type.go
+++ b/common/endpoint_type.go
@@ -26,6 +26,8 @@ func GetEndpointTypesByChannelType(channelType int, modelName string) []constant
endpointTypes = []constant.EndpointType{constant.EndpointTypeGemini, constant.EndpointTypeOpenAI}
case constant.ChannelTypeOpenRouter: // OpenRouter 只支持 OpenAI 端点
endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI}
+ case constant.ChannelTypeXai:
+ endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI, constant.EndpointTypeOpenAIResponse}
case constant.ChannelTypeSora:
endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAIVideo}
default:
diff --git a/common/gin.go b/common/gin.go
index 9acb349386..da7f8be4b0 100644
--- a/common/gin.go
+++ b/common/gin.go
@@ -18,6 +18,7 @@ import (
)
const KeyRequestBody = "key_request_body"
+const KeyBodyStorage = "key_body_storage"
var ErrRequestBodyTooLarge = errors.New("request body too large")
@@ -32,51 +33,87 @@ func IsRequestBodyTooLargeError(err error) bool {
return errors.As(err, &mbe)
}
-func GetRequestBody(c *gin.Context) ([]byte, error) {
+func GetRequestBody(c *gin.Context) (io.Seeker, error) {
+ // 首先检查是否有 BodyStorage 缓存
+ if storage, exists := c.Get(KeyBodyStorage); exists && storage != nil {
+ if bs, ok := storage.(BodyStorage); ok {
+ if _, err := bs.Seek(0, io.SeekStart); err != nil {
+ return nil, fmt.Errorf("failed to seek body storage: %w", err)
+ }
+ return bs, nil
+ }
+ }
+
+ // 检查旧的缓存方式
cached, exists := c.Get(KeyRequestBody)
if exists && cached != nil {
if b, ok := cached.([]byte); ok {
- return b, nil
+ bs, err := CreateBodyStorage(b)
+ if err != nil {
+ return nil, err
+ }
+ c.Set(KeyBodyStorage, bs)
+ return bs, nil
}
}
+
maxMB := constant.MaxRequestBodyMB
if maxMB <= 0 {
- // no limit
- body, err := io.ReadAll(c.Request.Body)
- _ = c.Request.Body.Close()
- if err != nil {
- return nil, err
- }
- c.Set(KeyRequestBody, body)
- return body, nil
+ maxMB = 128 // 默认 128MB
}
maxBytes := int64(maxMB) << 20
- limited := io.LimitReader(c.Request.Body, maxBytes+1)
- body, err := io.ReadAll(limited)
+ contentLength := c.Request.ContentLength
+
+ // 使用新的存储系统
+ storage, err := CreateBodyStorageFromReader(c.Request.Body, contentLength, maxBytes)
+ _ = c.Request.Body.Close()
+
if err != nil {
- _ = c.Request.Body.Close()
if IsRequestBodyTooLargeError(err) {
return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
}
return nil, err
}
- _ = c.Request.Body.Close()
- if int64(len(body)) > maxBytes {
- return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
+
+ // 缓存存储对象
+ c.Set(KeyBodyStorage, storage)
+
+ return storage, nil
+}
+
+// GetBodyStorage 获取请求体存储对象(用于需要多次读取的场景)
+func GetBodyStorage(c *gin.Context) (BodyStorage, error) {
+ seeker, err := GetRequestBody(c)
+ if err != nil {
+ return nil, err
+ }
+ bs, ok := seeker.(BodyStorage)
+ if !ok {
+ return nil, errors.New("unexpected body storage type")
+ }
+ return bs, nil
+}
+
+// CleanupBodyStorage 清理请求体存储(应在请求结束时调用)
+func CleanupBodyStorage(c *gin.Context) {
+ if storage, exists := c.Get(KeyBodyStorage); exists && storage != nil {
+ if bs, ok := storage.(BodyStorage); ok {
+ bs.Close()
+ }
+ c.Set(KeyBodyStorage, nil)
}
- c.Set(KeyRequestBody, body)
- return body, nil
}
func UnmarshalBodyReusable(c *gin.Context, v any) error {
- requestBody, err := GetRequestBody(c)
+ storage, err := GetBodyStorage(c)
+ if err != nil {
+ return err
+ }
+ requestBody, err := storage.Bytes()
if err != nil {
return err
}
- //if DebugEnabled {
- // println("UnmarshalBodyReusable request body:", string(requestBody))
- //}
contentType := c.Request.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
err = Unmarshal(requestBody, v)
@@ -92,7 +129,10 @@ func UnmarshalBodyReusable(c *gin.Context, v any) error {
return err
}
// Reset request body
- c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
+ if _, seekErr := storage.Seek(0, io.SeekStart); seekErr != nil {
+ return seekErr
+ }
+ c.Request.Body = io.NopCloser(storage)
return nil
}
@@ -160,13 +200,59 @@ func ApiSuccess(c *gin.Context, data any) {
})
}
+// ApiErrorI18n returns a translated error message based on the user's language preference
+// key is the i18n message key, args is optional template data
+func ApiErrorI18n(c *gin.Context, key string, args ...map[string]any) {
+ msg := TranslateMessage(c, key, args...)
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": msg,
+ })
+}
+
+// ApiSuccessI18n returns a translated success message based on the user's language preference
+func ApiSuccessI18n(c *gin.Context, key string, data any, args ...map[string]any) {
+ msg := TranslateMessage(c, key, args...)
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": msg,
+ "data": data,
+ })
+}
+
+// TranslateMessage is a helper function that calls i18n.T
+// This function is defined here to avoid circular imports
+// The actual implementation will be set during init
+var TranslateMessage func(c *gin.Context, key string, args ...map[string]any) string
+
+func init() {
+ // Default implementation that returns the key as-is
+ // This will be replaced by i18n.T during i18n initialization
+ TranslateMessage = func(c *gin.Context, key string, args ...map[string]any) string {
+ c.Header("X-Translate-id", "d5e7afdfc7f03414b941f9c1e7096be9966510e7")
+ return key
+ }
+}
+
func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error) {
- requestBody, err := GetRequestBody(c)
+ storage, err := GetBodyStorage(c)
+ if err != nil {
+ return nil, err
+ }
+ requestBody, err := storage.Bytes()
if err != nil {
return nil, err
}
- contentType := c.Request.Header.Get("Content-Type")
+ // Use the original Content-Type saved on first call to avoid boundary
+ // mismatch when callers overwrite c.Request.Header after multipart rebuild.
+ var contentType string
+ if saved, ok := c.Get("_original_multipart_ct"); ok {
+ contentType = saved.(string)
+ } else {
+ contentType = c.Request.Header.Get("Content-Type")
+ c.Set("_original_multipart_ct", contentType)
+ }
boundary, err := parseBoundary(contentType)
if err != nil {
return nil, err
@@ -179,7 +265,10 @@ func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error) {
}
// Reset request body
- c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
+ if _, seekErr := storage.Seek(0, io.SeekStart); seekErr != nil {
+ return nil, seekErr
+ }
+ c.Request.Body = io.NopCloser(storage)
return form, nil
}
@@ -215,7 +304,13 @@ func parseFormData(data []byte, v any) error {
}
func parseMultipartFormData(c *gin.Context, data []byte, v any) error {
- contentType := c.Request.Header.Get("Content-Type")
+ var contentType string
+ if saved, ok := c.Get("_original_multipart_ct"); ok {
+ contentType = saved.(string)
+ } else {
+ contentType = c.Request.Header.Get("Content-Type")
+ c.Set("_original_multipart_ct", contentType)
+ }
boundary, err := parseBoundary(contentType)
if err != nil {
if errors.Is(err, errBoundaryNotFound) {
diff --git a/common/init.go b/common/init.go
index 9501ce3be5..e9cfc98bbf 100644
--- a/common/init.go
+++ b/common/init.go
@@ -120,6 +120,10 @@ func InitEnv() {
CriticalRateLimitEnable = GetEnvOrDefaultBool("CRITICAL_RATE_LIMIT_ENABLE", true)
CriticalRateLimitNum = GetEnvOrDefault("CRITICAL_RATE_LIMIT", 20)
CriticalRateLimitDuration = int64(GetEnvOrDefault("CRITICAL_RATE_LIMIT_DURATION", 20*60))
+
+ SearchRateLimitEnable = GetEnvOrDefaultBool("SEARCH_RATE_LIMIT_ENABLE", true)
+ SearchRateLimitNum = GetEnvOrDefault("SEARCH_RATE_LIMIT", 10)
+ SearchRateLimitDuration = int64(GetEnvOrDefault("SEARCH_RATE_LIMIT_DURATION", 60))
initConstantEnv()
}
@@ -127,7 +131,7 @@ func initConstantEnv() {
constant.StreamingTimeout = GetEnvOrDefault("STREAMING_TIMEOUT", 300)
constant.DifyDebug = GetEnvOrDefaultBool("DIFY_DEBUG", true)
constant.MaxFileDownloadMB = GetEnvOrDefault("MAX_FILE_DOWNLOAD_MB", 64)
- constant.StreamScannerMaxBufferMB = GetEnvOrDefault("STREAM_SCANNER_MAX_BUFFER_MB", 64)
+ constant.StreamScannerMaxBufferMB = GetEnvOrDefault("STREAM_SCANNER_MAX_BUFFER_MB", 128)
// MaxRequestBodyMB 请求体最大大小(解压后),用于防止超大请求/zip bomb导致内存暴涨
constant.MaxRequestBodyMB = GetEnvOrDefault("MAX_REQUEST_BODY_MB", 128)
// ForceStreamOption 覆盖请求参数,强制返回usage信息
@@ -137,7 +141,6 @@ func initConstantEnv() {
constant.GetMediaTokenNotStream = GetEnvOrDefaultBool("GET_MEDIA_TOKEN_NOT_STREAM", false)
constant.UpdateTask = GetEnvOrDefaultBool("UPDATE_TASK", true)
constant.AzureDefaultAPIVersion = GetEnvOrDefaultString("AZURE_DEFAULT_API_VERSION", "2025-04-01-preview")
- constant.GeminiVisionMaxImageNum = GetEnvOrDefault("GEMINI_VISION_MAX_IMAGE_NUM", 16)
constant.NotifyLimitCount = GetEnvOrDefault("NOTIFY_LIMIT_COUNT", 2)
constant.NotificationLimitDurationMinute = GetEnvOrDefault("NOTIFICATION_LIMIT_DURATION_MINUTE", 10)
// GenerateDefaultToken 是否生成初始令牌,默认关闭。
@@ -146,6 +149,8 @@ func initConstantEnv() {
constant.ErrorLogEnabled = GetEnvOrDefaultBool("ERROR_LOG_ENABLED", false)
// 任务轮询时查询的最大数量
constant.TaskQueryLimit = GetEnvOrDefault("TASK_QUERY_LIMIT", 1000)
+ // 异步任务超时时间(分钟),超过此时间未完成的任务将被标记为失败并退款。0 表示禁用。
+ constant.TaskTimeoutMinutes = GetEnvOrDefault("TASK_TIMEOUT_MINUTES", 1440)
soraPatchStr := GetEnvOrDefaultString("TASK_PRICE_PATCH", "")
if soraPatchStr != "" {
@@ -159,4 +164,17 @@ func initConstantEnv() {
}
constant.TaskPricePatches = taskPricePatches
}
+
+ // Initialize trusted redirect domains for URL validation
+ trustedDomainsStr := GetEnvOrDefaultString("TRUSTED_REDIRECT_DOMAINS", "")
+ var trustedDomains []string
+ domains := strings.Split(trustedDomainsStr, ",")
+ for _, domain := range domains {
+ trimmedDomain := strings.TrimSpace(domain)
+ if trimmedDomain != "" {
+ // Normalize domain to lowercase
+ trustedDomains = append(trustedDomains, strings.ToLower(trimmedDomain))
+ }
+ }
+ constant.TrustedRedirectDomains = trustedDomains
}
diff --git a/common/performance_config.go b/common/performance_config.go
new file mode 100644
index 0000000000..941d9eab88
--- /dev/null
+++ b/common/performance_config.go
@@ -0,0 +1,33 @@
+package common
+
+import "sync/atomic"
+
+// PerformanceMonitorConfig 性能监控配置
+type PerformanceMonitorConfig struct {
+ Enabled bool
+ CPUThreshold int
+ MemoryThreshold int
+ DiskThreshold int
+}
+
+var performanceMonitorConfig atomic.Value
+
+func init() {
+ // 初始化默认配置
+ performanceMonitorConfig.Store(PerformanceMonitorConfig{
+ Enabled: true,
+ CPUThreshold: 90,
+ MemoryThreshold: 90,
+ DiskThreshold: 90,
+ })
+}
+
+// GetPerformanceMonitorConfig 获取性能监控配置
+func GetPerformanceMonitorConfig() PerformanceMonitorConfig {
+ return performanceMonitorConfig.Load().(PerformanceMonitorConfig)
+}
+
+// SetPerformanceMonitorConfig 设置性能监控配置
+func SetPerformanceMonitorConfig(config PerformanceMonitorConfig) {
+ performanceMonitorConfig.Store(config)
+}
diff --git a/common/str.go b/common/str.go
index 4f0e81466b..71391f722a 100644
--- a/common/str.go
+++ b/common/str.go
@@ -106,6 +106,16 @@ func GetJsonString(data any) string {
return string(b)
}
+// NormalizeBillingPreference clamps the billing preference to valid values.
+func NormalizeBillingPreference(pref string) string {
+ switch strings.TrimSpace(pref) {
+ case "subscription_first", "wallet_first", "subscription_only", "wallet_only":
+ return strings.TrimSpace(pref)
+ default:
+ return "subscription_first"
+ }
+}
+
// MaskEmail masks a user email to prevent PII leakage in logs
// Returns "***masked***" if email is empty, otherwise shows only the domain part
func MaskEmail(email string) string {
diff --git a/common/sys_log.go b/common/sys_log.go
index b29adc3e63..6e5b3622f2 100644
--- a/common/sys_log.go
+++ b/common/sys_log.go
@@ -3,53 +3,60 @@ package common
import (
"fmt"
"os"
+ "sync"
"time"
"github.com/gin-gonic/gin"
)
+// LogWriterMu protects concurrent access to gin.DefaultWriter/gin.DefaultErrorWriter
+// during log file rotation. Acquire RLock when reading/writing through the writers,
+// acquire Lock when swapping writers and closing old files.
+var LogWriterMu sync.RWMutex
+
func SysLog(s string) {
t := time.Now()
+ LogWriterMu.RLock()
_, _ = fmt.Fprintf(gin.DefaultWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
+ LogWriterMu.RUnlock()
}
func SysError(s string) {
t := time.Now()
+ LogWriterMu.RLock()
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
+ LogWriterMu.RUnlock()
}
func FatalLog(v ...any) {
t := time.Now()
+ LogWriterMu.RLock()
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[FATAL] %v | %v \n", t.Format("2006/01/02 - 15:04:05"), v)
+ LogWriterMu.RUnlock()
os.Exit(1)
}
func LogStartupSuccess(startTime time.Time, port string) {
-
duration := time.Since(startTime)
durationMs := duration.Milliseconds()
// Get network IPs
networkIps := GetNetworkIps()
- // Print blank line for spacing
- fmt.Fprintf(gin.DefaultWriter, "\n")
+ LogWriterMu.RLock()
+ defer LogWriterMu.RUnlock()
- // Print the main success message
+ fmt.Fprintf(gin.DefaultWriter, "\n")
fmt.Fprintf(gin.DefaultWriter, " \033[32m%s %s\033[0m ready in %d ms\n", SystemName, Version, durationMs)
fmt.Fprintf(gin.DefaultWriter, "\n")
- // Skip fancy startup message in container environments
if !IsRunningInContainer() {
- // Print local URL
fmt.Fprintf(gin.DefaultWriter, " ➜ \033[1mLocal:\033[0m http://localhost:%s/\n", port)
}
- // Print network URLs
for _, ip := range networkIps {
fmt.Fprintf(gin.DefaultWriter, " ➜ \033[1mNetwork:\033[0m http://%s:%s/\n", ip, port)
}
- // Print blank line for spacing
fmt.Fprintf(gin.DefaultWriter, "\n")
}
diff --git a/common/system_monitor.go b/common/system_monitor.go
new file mode 100644
index 0000000000..26710faede
--- /dev/null
+++ b/common/system_monitor.go
@@ -0,0 +1,81 @@
+package common
+
+import (
+ "sync/atomic"
+ "time"
+
+ "github.com/shirou/gopsutil/cpu"
+ "github.com/shirou/gopsutil/mem"
+)
+
+// DiskSpaceInfo 磁盘空间信息
+type DiskSpaceInfo struct {
+ // 总空间(字节)
+ Total uint64 `json:"total"`
+ // 可用空间(字节)
+ Free uint64 `json:"free"`
+ // 已用空间(字节)
+ Used uint64 `json:"used"`
+ // 使用百分比
+ UsedPercent float64 `json:"used_percent"`
+}
+
+// SystemStatus 系统状态信息
+type SystemStatus struct {
+ CPUUsage float64
+ MemoryUsage float64
+ DiskUsage float64
+}
+
+var latestSystemStatus atomic.Value
+
+func init() {
+ latestSystemStatus.Store(SystemStatus{})
+}
+
+// StartSystemMonitor 启动系统监控
+func StartSystemMonitor() {
+ go func() {
+ for {
+ config := GetPerformanceMonitorConfig()
+ if !config.Enabled {
+ time.Sleep(30 * time.Second)
+ continue
+ }
+
+ updateSystemStatus()
+ time.Sleep(5 * time.Second)
+ }
+ }()
+}
+
+func updateSystemStatus() {
+ var status SystemStatus
+
+ // CPU
+ // 注意:cpu.Percent(0, false) 返回自上次调用以来的 CPU 使用率
+ // 如果是第一次调用,可能会返回错误或不准确的值,但在循环中会逐渐正常
+ percents, err := cpu.Percent(0, false)
+ if err == nil && len(percents) > 0 {
+ status.CPUUsage = percents[0]
+ }
+
+ // Memory
+ memInfo, err := mem.VirtualMemory()
+ if err == nil {
+ status.MemoryUsage = memInfo.UsedPercent
+ }
+
+ // Disk
+ diskInfo := GetDiskSpaceInfo()
+ if diskInfo.Total > 0 {
+ status.DiskUsage = diskInfo.UsedPercent
+ }
+
+ latestSystemStatus.Store(status)
+}
+
+// GetSystemStatus 获取当前系统状态
+func GetSystemStatus() SystemStatus {
+ return latestSystemStatus.Load().(SystemStatus)
+}
diff --git a/common/system_monitor_unix.go b/common/system_monitor_unix.go
new file mode 100644
index 0000000000..673b964d2d
--- /dev/null
+++ b/common/system_monitor_unix.go
@@ -0,0 +1,37 @@
+//go:build !windows
+
+package common
+
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Unix/Linux/macOS)
+func GetDiskSpaceInfo() DiskSpaceInfo {
+ cachePath := GetDiskCachePath()
+ if cachePath == "" {
+ cachePath = os.TempDir()
+ }
+
+ info := DiskSpaceInfo{}
+
+ var stat unix.Statfs_t
+ err := unix.Statfs(cachePath, &stat)
+ if err != nil {
+ return info
+ }
+
+ // 计算磁盘空间 (显式转换以兼容 FreeBSD,其字段类型为 int64)
+ bsize := uint64(stat.Bsize)
+ info.Total = uint64(stat.Blocks) * bsize
+ info.Free = uint64(stat.Bavail) * bsize
+ info.Used = info.Total - uint64(stat.Bfree)*bsize
+
+ if info.Total > 0 {
+ info.UsedPercent = float64(info.Used) / float64(info.Total) * 100
+ }
+
+ return info
+}
diff --git a/common/system_monitor_windows.go b/common/system_monitor_windows.go
new file mode 100644
index 0000000000..7db7667317
--- /dev/null
+++ b/common/system_monitor_windows.go
@@ -0,0 +1,50 @@
+//go:build windows
+
+package common
+
+import (
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// GetDiskSpaceInfo 获取缓存目录所在磁盘的空间信息 (Windows)
+func GetDiskSpaceInfo() DiskSpaceInfo {
+ cachePath := GetDiskCachePath()
+ if cachePath == "" {
+ cachePath = os.TempDir()
+ }
+
+ info := DiskSpaceInfo{}
+
+ kernel32 := syscall.NewLazyDLL("kernel32.dll")
+ getDiskFreeSpaceEx := kernel32.NewProc("GetDiskFreeSpaceExW")
+
+ var freeBytesAvailable, totalBytes, totalFreeBytes uint64
+
+ pathPtr, err := syscall.UTF16PtrFromString(cachePath)
+ if err != nil {
+ return info
+ }
+
+ ret, _, _ := getDiskFreeSpaceEx.Call(
+ uintptr(unsafe.Pointer(pathPtr)),
+ uintptr(unsafe.Pointer(&freeBytesAvailable)),
+ uintptr(unsafe.Pointer(&totalBytes)),
+ uintptr(unsafe.Pointer(&totalFreeBytes)),
+ )
+
+ if ret == 0 {
+ return info
+ }
+
+ info.Total = totalBytes
+ info.Free = freeBytesAvailable
+ info.Used = totalBytes - totalFreeBytes
+
+ if info.Total > 0 {
+ info.UsedPercent = float64(info.Used) / float64(info.Total) * 100
+ }
+
+ return info
+}
diff --git a/common/topup-ratio.go b/common/topup-ratio.go
index 8f03395d2f..2b60cde7d1 100644
--- a/common/topup-ratio.go
+++ b/common/topup-ratio.go
@@ -2,29 +2,37 @@ package common
import (
"encoding/json"
+ "sync"
)
-var TopupGroupRatio = map[string]float64{
+var topupGroupRatio = map[string]float64{
"default": 1,
"vip": 1,
"svip": 1,
}
+var topupGroupRatioMutex sync.RWMutex
func TopupGroupRatio2JSONString() string {
- jsonBytes, err := json.Marshal(TopupGroupRatio)
+ topupGroupRatioMutex.RLock()
+ defer topupGroupRatioMutex.RUnlock()
+ jsonBytes, err := json.Marshal(topupGroupRatio)
if err != nil {
- SysError("error marshalling model ratio: " + err.Error())
+ SysError("error marshalling topup group ratio: " + err.Error())
}
return string(jsonBytes)
}
func UpdateTopupGroupRatioByJSONString(jsonStr string) error {
- TopupGroupRatio = make(map[string]float64)
- return json.Unmarshal([]byte(jsonStr), &TopupGroupRatio)
+ topupGroupRatioMutex.Lock()
+ defer topupGroupRatioMutex.Unlock()
+ topupGroupRatio = make(map[string]float64)
+ return json.Unmarshal([]byte(jsonStr), &topupGroupRatio)
}
func GetTopupGroupRatio(name string) float64 {
- ratio, ok := TopupGroupRatio[name]
+ topupGroupRatioMutex.RLock()
+ defer topupGroupRatioMutex.RUnlock()
+ ratio, ok := topupGroupRatio[name]
if !ok {
SysError("topup group ratio not found: " + name)
return 1
diff --git a/common/url_validator.go b/common/url_validator.go
new file mode 100644
index 0000000000..151f643f1d
--- /dev/null
+++ b/common/url_validator.go
@@ -0,0 +1,39 @@
+package common
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/QuantumNous/new-api/constant"
+)
+
+// ValidateRedirectURL validates that a redirect URL is safe to use.
+// It checks that:
+// - The URL is properly formatted
+// - The scheme is either http or https
+// - The domain is in the trusted domains list (exact match or subdomain)
+//
+// Returns nil if the URL is valid and trusted, otherwise returns an error
+// describing why the validation failed.
+func ValidateRedirectURL(rawURL string) error {
+ // Parse the URL
+ parsedURL, err := url.Parse(rawURL)
+ if err != nil {
+ return fmt.Errorf("invalid URL format: %s", err.Error())
+ }
+
+ if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
+ return fmt.Errorf("invalid URL scheme: only http and https are allowed")
+ }
+
+ domain := strings.ToLower(parsedURL.Hostname())
+
+ for _, trustedDomain := range constant.TrustedRedirectDomains {
+ if domain == trustedDomain || strings.HasSuffix(domain, "."+trustedDomain) {
+ return nil
+ }
+ }
+
+ return fmt.Errorf("domain %s is not in the trusted domains list", domain)
+}
diff --git a/common/url_validator_test.go b/common/url_validator_test.go
new file mode 100644
index 0000000000..b87b6787e3
--- /dev/null
+++ b/common/url_validator_test.go
@@ -0,0 +1,134 @@
+package common
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/constant"
+)
+
+func TestValidateRedirectURL(t *testing.T) {
+ // Save original trusted domains and restore after test
+ originalDomains := constant.TrustedRedirectDomains
+ defer func() {
+ constant.TrustedRedirectDomains = originalDomains
+ }()
+
+ tests := []struct {
+ name string
+ url string
+ trustedDomains []string
+ wantErr bool
+ errContains string
+ }{
+ // Valid cases
+ {
+ name: "exact domain match with https",
+ url: "https://example.com/success",
+ trustedDomains: []string{"example.com"},
+ wantErr: false,
+ },
+ {
+ name: "exact domain match with http",
+ url: "http://example.com/callback",
+ trustedDomains: []string{"example.com"},
+ wantErr: false,
+ },
+ {
+ name: "subdomain match",
+ url: "https://sub.example.com/success",
+ trustedDomains: []string{"example.com"},
+ wantErr: false,
+ },
+ {
+ name: "case insensitive domain",
+ url: "https://EXAMPLE.COM/success",
+ trustedDomains: []string{"example.com"},
+ wantErr: false,
+ },
+
+ // Invalid cases - untrusted domain
+ {
+ name: "untrusted domain",
+ url: "https://evil.com/phishing",
+ trustedDomains: []string{"example.com"},
+ wantErr: true,
+ errContains: "not in the trusted domains list",
+ },
+ {
+ name: "suffix attack - fakeexample.com",
+ url: "https://fakeexample.com/success",
+ trustedDomains: []string{"example.com"},
+ wantErr: true,
+ errContains: "not in the trusted domains list",
+ },
+ {
+ name: "empty trusted domains list",
+ url: "https://example.com/success",
+ trustedDomains: []string{},
+ wantErr: true,
+ errContains: "not in the trusted domains list",
+ },
+
+ // Invalid cases - scheme
+ {
+ name: "javascript scheme",
+ url: "javascript:alert('xss')",
+ trustedDomains: []string{"example.com"},
+ wantErr: true,
+ errContains: "invalid URL scheme",
+ },
+ {
+ name: "data scheme",
+ url: "data:text/html,",
+ trustedDomains: []string{"example.com"},
+ wantErr: true,
+ errContains: "invalid URL scheme",
+ },
+
+ // Edge cases
+ {
+ name: "empty URL",
+ url: "",
+ trustedDomains: []string{"example.com"},
+ wantErr: true,
+ errContains: "invalid URL scheme",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Set up trusted domains for this test case
+ constant.TrustedRedirectDomains = tt.trustedDomains
+
+ err := ValidateRedirectURL(tt.url)
+
+ if tt.wantErr {
+ if err == nil {
+ t.Errorf("ValidateRedirectURL(%q) expected error containing %q, got nil", tt.url, tt.errContains)
+ return
+ }
+ if tt.errContains != "" && !contains(err.Error(), tt.errContains) {
+ t.Errorf("ValidateRedirectURL(%q) error = %q, want error containing %q", tt.url, err.Error(), tt.errContains)
+ }
+ } else {
+ if err != nil {
+ t.Errorf("ValidateRedirectURL(%q) unexpected error: %v", tt.url, err)
+ }
+ }
+ })
+ }
+}
+
+func contains(s, substr string) bool {
+ return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
+ (len(s) > 0 && len(substr) > 0 && findSubstring(s, substr)))
+}
+
+func findSubstring(s, substr string) bool {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+}
diff --git a/common/utils.go b/common/utils.go
index b67fe1c5f6..3a8be45b31 100644
--- a/common/utils.go
+++ b/common/utils.go
@@ -192,7 +192,7 @@ func Interface2String(inter interface{}) string {
case int:
return fmt.Sprintf("%d", inter.(int))
case float64:
- return fmt.Sprintf("%f", inter.(float64))
+ return strconv.FormatFloat(inter.(float64), 'f', -1, 64)
case bool:
if inter.(bool) {
return "true"
diff --git a/constant/context_key.go b/constant/context_key.go
index 833aabae10..2ba2fe2748 100644
--- a/constant/context_key.go
+++ b/constant/context_key.go
@@ -55,4 +55,14 @@ const (
ContextKeyLocalCountTokens ContextKey = "local_count_tokens"
ContextKeySystemPromptOverride ContextKey = "system_prompt_override"
+
+ // ContextKeyFileSourcesToCleanup stores file sources that need cleanup when request ends
+ ContextKeyFileSourcesToCleanup ContextKey = "file_sources_to_cleanup"
+
+ // ContextKeyAdminRejectReason stores an admin-only reject/block reason extracted from upstream responses.
+ // It is not returned to end users, but can be persisted into consume/error logs for debugging.
+ ContextKeyAdminRejectReason ContextKey = "admin_reject_reason"
+
+ // ContextKeyLanguage stores the user's language preference for i18n
+ ContextKeyLanguage ContextKey = "language"
)
diff --git a/constant/endpoint_type.go b/constant/endpoint_type.go
index 29c0d31e37..8681bf06e3 100644
--- a/constant/endpoint_type.go
+++ b/constant/endpoint_type.go
@@ -3,14 +3,15 @@ package constant
type EndpointType string
const (
- EndpointTypeOpenAI EndpointType = "openai"
- EndpointTypeOpenAIResponse EndpointType = "openai-response"
- EndpointTypeAnthropic EndpointType = "anthropic"
- EndpointTypeGemini EndpointType = "gemini"
- EndpointTypeJinaRerank EndpointType = "jina-rerank"
- EndpointTypeImageGeneration EndpointType = "image-generation"
- EndpointTypeEmbeddings EndpointType = "embeddings"
- EndpointTypeOpenAIVideo EndpointType = "openai-video"
+ EndpointTypeOpenAI EndpointType = "openai"
+ EndpointTypeOpenAIResponse EndpointType = "openai-response"
+ EndpointTypeOpenAIResponseCompact EndpointType = "openai-response-compact"
+ EndpointTypeAnthropic EndpointType = "anthropic"
+ EndpointTypeGemini EndpointType = "gemini"
+ EndpointTypeJinaRerank EndpointType = "jina-rerank"
+ EndpointTypeImageGeneration EndpointType = "image-generation"
+ EndpointTypeEmbeddings EndpointType = "embeddings"
+ EndpointTypeOpenAIVideo EndpointType = "openai-video"
//EndpointTypeMidjourney EndpointType = "midjourney-proxy"
//EndpointTypeSuno EndpointType = "suno-proxy"
//EndpointTypeKling EndpointType = "kling"
diff --git a/constant/env.go b/constant/env.go
index c561c207df..d5aff1b0b1 100644
--- a/constant/env.go
+++ b/constant/env.go
@@ -11,12 +11,16 @@ var GetMediaTokenNotStream bool
var UpdateTask bool
var MaxRequestBodyMB int
var AzureDefaultAPIVersion string
-var GeminiVisionMaxImageNum int
var NotifyLimitCount int
var NotificationLimitDurationMinute int
var GenerateDefaultToken bool
var ErrorLogEnabled bool
var TaskQueryLimit int
+var TaskTimeoutMinutes int
// temporary variable for sora patch, will be removed in future
var TaskPricePatches []string
+
+// TrustedRedirectDomains is a list of trusted domains for redirect URL validation.
+// Domains support subdomain matching (e.g., "example.com" matches "sub.example.com").
+var TrustedRedirectDomains []string
diff --git a/constant/waffo_pay_method.go b/constant/waffo_pay_method.go
new file mode 100644
index 0000000000..0cee72a884
--- /dev/null
+++ b/constant/waffo_pay_method.go
@@ -0,0 +1,16 @@
+package constant
+
+// WaffoPayMethod defines the display and API parameter mapping for Waffo payment methods.
+type WaffoPayMethod struct {
+ Name string `json:"name"` // Frontend display name
+ Icon string `json:"icon"` // Frontend icon identifier: credit-card, apple, google
+ PayMethodType string `json:"payMethodType"` // Waffo API PayMethodType, can be comma-separated
+ PayMethodName string `json:"payMethodName"` // Waffo API PayMethodName, empty means auto-select by Waffo checkout
+}
+
+// DefaultWaffoPayMethods is the default list of supported payment methods.
+var DefaultWaffoPayMethods = []WaffoPayMethod{
+ {Name: "Card", Icon: "/pay-card.png", PayMethodType: "CREDITCARD,DEBITCARD", PayMethodName: ""},
+ {Name: "Apple Pay", Icon: "/pay-apple.png", PayMethodType: "APPLEPAY", PayMethodName: "APPLEPAY"},
+ {Name: "Google Pay", Icon: "/pay-google.png", PayMethodType: "GOOGLEPAY", PayMethodName: "GOOGLEPAY"},
+}
diff --git a/controller/channel-test.go b/controller/channel-test.go
index 2ae8b0ef65..bdd67d27a9 100644
--- a/controller/channel-test.go
+++ b/controller/channel-test.go
@@ -26,10 +26,12 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/QuantumNous/new-api/types"
"github.com/bytedance/gopkg/util/gopool"
"github.com/samber/lo"
+ "github.com/tidwall/gjson"
"github.com/gin-gonic/gin"
)
@@ -40,7 +42,21 @@ type testResult struct {
newAPIError *types.NewAPIError
}
-func testChannel(channel *model.Channel, testModel string, endpointType string) testResult {
+func normalizeChannelTestEndpoint(channel *model.Channel, modelName, endpointType string) string {
+ normalized := strings.TrimSpace(endpointType)
+ if normalized != "" {
+ return normalized
+ }
+ if strings.HasSuffix(modelName, ratio_setting.CompactModelSuffix) {
+ return string(constant.EndpointTypeOpenAIResponseCompact)
+ }
+ if channel != nil && channel.Type == constant.ChannelTypeCodex {
+ return string(constant.EndpointTypeOpenAIResponse)
+ }
+ return normalized
+}
+
+func testChannel(channel *model.Channel, testModel string, endpointType string, isStream bool) testResult {
tik := time.Now()
var unsupportedTestChannelTypes = []int{
constant.ChannelTypeMidjourney,
@@ -75,6 +91,8 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
}
}
+ endpointType = normalizeChannelTestEndpoint(channel, testModel, endpointType)
+
requestPath := "/v1/chat/completions"
// 如果指定了端点类型,使用指定的端点类型
@@ -84,6 +102,11 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
}
} else {
// 如果没有指定端点类型,使用原有的自动检测逻辑
+
+ if strings.Contains(strings.ToLower(testModel), "rerank") {
+ requestPath = "/v1/rerank"
+ }
+
// 先判断是否为 Embedding 模型
if strings.Contains(strings.ToLower(testModel), "embedding") ||
strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
@@ -102,6 +125,14 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
if strings.Contains(strings.ToLower(testModel), "codex") {
requestPath = "/v1/responses"
}
+
+ // responses compaction models (must use /v1/responses/compact)
+ if strings.HasSuffix(testModel, ratio_setting.CompactModelSuffix) {
+ requestPath = "/v1/responses/compact"
+ }
+ }
+ if strings.HasPrefix(requestPath, "/v1/responses/compact") {
+ testModel = ratio_setting.WithCompactModelSuffix(testModel)
}
c.Request = &http.Request{
@@ -145,6 +176,8 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
relayFormat = types.RelayFormatOpenAI
case constant.EndpointTypeOpenAIResponse:
relayFormat = types.RelayFormatOpenAIResponses
+ case constant.EndpointTypeOpenAIResponseCompact:
+ relayFormat = types.RelayFormatOpenAIResponsesCompaction
case constant.EndpointTypeAnthropic:
relayFormat = types.RelayFormatClaude
case constant.EndpointTypeGemini:
@@ -179,9 +212,12 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
if c.Request.URL.Path == "/v1/responses" {
relayFormat = types.RelayFormatOpenAIResponses
}
+ if strings.HasPrefix(c.Request.URL.Path, "/v1/responses/compact") {
+ relayFormat = types.RelayFormatOpenAIResponsesCompaction
+ }
}
- request := buildTestRequest(testModel, endpointType, channel)
+ request := buildTestRequest(testModel, endpointType, channel, isStream)
info, err := relaycommon.GenRelayInfo(c, relayFormat, request, nil)
@@ -210,6 +246,15 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
request.SetModelName(testModel)
apiType, _ := common.ChannelType2APIType(channel.Type)
+ if info.RelayMode == relayconstant.RelayModeResponsesCompact &&
+ apiType != constant.APITypeOpenAI &&
+ apiType != constant.APITypeCodex {
+ return testResult{
+ context: c,
+ localErr: fmt.Errorf("responses compaction test only supports openai/codex channels, got api type %d", apiType),
+ newAPIError: types.NewError(fmt.Errorf("unsupported api type: %d", apiType), types.ErrorCodeInvalidApiType),
+ }
+ }
adaptor := relay.GetAdaptor(apiType)
if adaptor == nil {
return testResult{
@@ -282,6 +327,25 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
newAPIError: types.NewError(errors.New("invalid response request type"), types.ErrorCodeConvertRequestFailed),
}
}
+ case relayconstant.RelayModeResponsesCompact:
+ // Response compaction request - convert to OpenAIResponsesRequest before adapting
+ switch req := request.(type) {
+ case *dto.OpenAIResponsesCompactionRequest:
+ convertedRequest, err = adaptor.ConvertOpenAIResponsesRequest(c, info, dto.OpenAIResponsesRequest{
+ Model: req.Model,
+ Input: req.Input,
+ Instructions: req.Instructions,
+ PreviousResponseID: req.PreviousResponseID,
+ })
+ case *dto.OpenAIResponsesRequest:
+ convertedRequest, err = adaptor.ConvertOpenAIResponsesRequest(c, info, *req)
+ default:
+ return testResult{
+ context: c,
+ localErr: errors.New("invalid response compaction request type"),
+ newAPIError: types.NewError(errors.New("invalid response compaction request type"), types.ErrorCodeConvertRequestFailed),
+ }
+ }
default:
// Chat/Completion 等其他请求类型
if generalReq, ok := request.(*dto.GeneralOpenAIRequest); ok {
@@ -302,7 +366,7 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
newAPIError: types.NewError(err, types.ErrorCodeConvertRequestFailed),
}
}
- jsonData, err := json.Marshal(convertedRequest)
+ jsonData, err := common.Marshal(convertedRequest)
if err != nil {
return testResult{
context: c,
@@ -321,8 +385,15 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
//}
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
+ if fixedErr, ok := relaycommon.AsParamOverrideReturnError(err); ok {
+ return testResult{
+ context: c,
+ localErr: fixedErr,
+ newAPIError: relaycommon.NewAPIErrorFromParamOverride(fixedErr),
+ }
+ }
return testResult{
context: c,
localErr: err,
@@ -332,7 +403,7 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
}
requestBody := bytes.NewBuffer(jsonData)
- c.Request.Body = io.NopCloser(requestBody)
+ c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonData))
resp, err := adaptor.DoRequest(c, info, requestBody)
if err != nil {
return testResult{
@@ -371,16 +442,16 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
newAPIError: respErr,
}
}
- if usageA == nil {
+ usage, usageErr := coerceTestUsage(usageA, isStream, info.GetEstimatePromptTokens())
+ if usageErr != nil {
return testResult{
context: c,
- localErr: errors.New("usage is nil"),
- newAPIError: types.NewOpenAIError(errors.New("usage is nil"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError),
+ localErr: usageErr,
+ newAPIError: types.NewOpenAIError(usageErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError),
}
}
- usage := usageA.(*dto.Usage)
result := w.Result()
- respBody, err := io.ReadAll(result.Body)
+ respBody, err := readTestResponseBody(result.Body, isStream)
if err != nil {
return testResult{
context: c,
@@ -388,6 +459,13 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
newAPIError: types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError),
}
}
+ if bodyErr := detectErrorFromTestResponseBody(respBody); bodyErr != nil {
+ return testResult{
+ context: c,
+ localErr: bodyErr,
+ newAPIError: types.NewOpenAIError(bodyErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError),
+ }
+ }
info.SetEstimatePromptTokens(usage.PromptTokens)
quota := 0
@@ -426,7 +504,103 @@ func testChannel(channel *model.Channel, testModel string, endpointType string)
}
}
-func buildTestRequest(model string, endpointType string, channel *model.Channel) dto.Request {
+func coerceTestUsage(usageAny any, isStream bool, estimatePromptTokens int) (*dto.Usage, error) {
+ switch u := usageAny.(type) {
+ case *dto.Usage:
+ return u, nil
+ case dto.Usage:
+ return &u, nil
+ case nil:
+ if !isStream {
+ return nil, errors.New("usage is nil")
+ }
+ usage := &dto.Usage{
+ PromptTokens: estimatePromptTokens,
+ }
+ usage.TotalTokens = usage.PromptTokens
+ return usage, nil
+ default:
+ if !isStream {
+ return nil, fmt.Errorf("invalid usage type: %T", usageAny)
+ }
+ usage := &dto.Usage{
+ PromptTokens: estimatePromptTokens,
+ }
+ usage.TotalTokens = usage.PromptTokens
+ return usage, nil
+ }
+}
+
+func readTestResponseBody(body io.ReadCloser, isStream bool) ([]byte, error) {
+ defer func() { _ = body.Close() }()
+ const maxStreamLogBytes = 8 << 10
+ if isStream {
+ return io.ReadAll(io.LimitReader(body, maxStreamLogBytes))
+ }
+ return io.ReadAll(body)
+}
+
+func detectErrorFromTestResponseBody(respBody []byte) error {
+ b := bytes.TrimSpace(respBody)
+ if len(b) == 0 {
+ return nil
+ }
+ if message := detectErrorMessageFromJSONBytes(b); message != "" {
+ return fmt.Errorf("upstream error: %s", message)
+ }
+
+ for _, line := range bytes.Split(b, []byte{'\n'}) {
+ line = bytes.TrimSpace(line)
+ if len(line) == 0 {
+ continue
+ }
+ if !bytes.HasPrefix(line, []byte("data:")) {
+ continue
+ }
+ payload := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))
+ if len(payload) == 0 || bytes.Equal(payload, []byte("[DONE]")) {
+ continue
+ }
+ if message := detectErrorMessageFromJSONBytes(payload); message != "" {
+ return fmt.Errorf("upstream error: %s", message)
+ }
+ }
+
+ return nil
+}
+
+func detectErrorMessageFromJSONBytes(jsonBytes []byte) string {
+ if len(jsonBytes) == 0 {
+ return ""
+ }
+ if jsonBytes[0] != '{' && jsonBytes[0] != '[' {
+ return ""
+ }
+ errVal := gjson.GetBytes(jsonBytes, "error")
+ if !errVal.Exists() || errVal.Type == gjson.Null {
+ return ""
+ }
+
+ message := gjson.GetBytes(jsonBytes, "error.message").String()
+ if message == "" {
+ message = gjson.GetBytes(jsonBytes, "error.error.message").String()
+ }
+ if message == "" && errVal.Type == gjson.String {
+ message = errVal.String()
+ }
+ if message == "" {
+ message = errVal.Raw
+ }
+ message = strings.TrimSpace(message)
+ if message == "" {
+ return "upstream returned error payload"
+ }
+ return message
+}
+
+func buildTestRequest(model string, endpointType string, channel *model.Channel, isStream bool) dto.Request {
+ testResponsesInput := json.RawMessage(`[{"role":"user","content":"hi"}]`)
+
// 根据端点类型构建不同的测试请求
if endpointType != "" {
switch constant.EndpointType(endpointType) {
@@ -441,7 +615,7 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel)
return &dto.ImageRequest{
Model: model,
Prompt: "a cute cat",
- N: 1,
+ N: lo.ToPtr(uint(1)),
Size: "1024x1024",
}
case constant.EndpointTypeJinaRerank:
@@ -450,13 +624,20 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel)
Model: model,
Query: "What is Deep Learning?",
Documents: []any{"Deep Learning is a subset of machine learning.", "Machine learning is a field of artificial intelligence."},
- TopN: 2,
+ TopN: lo.ToPtr(2),
}
case constant.EndpointTypeOpenAIResponse:
// 返回 OpenAIResponsesRequest
return &dto.OpenAIResponsesRequest{
+ Model: model,
+ Input: json.RawMessage(`[{"role":"user","content":"hi"}]`),
+ Stream: lo.ToPtr(isStream),
+ }
+ case constant.EndpointTypeOpenAIResponseCompact:
+ // 返回 OpenAIResponsesCompactionRequest
+ return &dto.OpenAIResponsesCompactionRequest{
Model: model,
- Input: json.RawMessage("\"hi\""),
+ Input: testResponsesInput,
}
case constant.EndpointTypeAnthropic, constant.EndpointTypeGemini, constant.EndpointTypeOpenAI:
// 返回 GeneralOpenAIRequest
@@ -464,21 +645,34 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel)
if constant.EndpointType(endpointType) == constant.EndpointTypeGemini {
maxTokens = 3000
}
- return &dto.GeneralOpenAIRequest{
+ req := &dto.GeneralOpenAIRequest{
Model: model,
- Stream: false,
+ Stream: lo.ToPtr(isStream),
Messages: []dto.Message{
{
Role: "user",
Content: "hi",
},
},
- MaxTokens: maxTokens,
+ MaxTokens: lo.ToPtr(maxTokens),
}
+ if isStream {
+ req.StreamOptions = &dto.StreamOptions{IncludeUsage: true}
+ }
+ return req
}
}
// 自动检测逻辑(保持原有行为)
+ if strings.Contains(strings.ToLower(model), "rerank") {
+ return &dto.RerankRequest{
+ Model: model,
+ Query: "What is Deep Learning?",
+ Documents: []any{"Deep Learning is a subset of machine learning.", "Machine learning is a field of artificial intelligence."},
+ TopN: lo.ToPtr(2),
+ }
+ }
+
// 先判断是否为 Embedding 模型
if strings.Contains(strings.ToLower(model), "embedding") ||
strings.HasPrefix(model, "m3e") ||
@@ -490,18 +684,27 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel)
}
}
+ // Responses compaction models (must use /v1/responses/compact)
+ if strings.HasSuffix(model, ratio_setting.CompactModelSuffix) {
+ return &dto.OpenAIResponsesCompactionRequest{
+ Model: model,
+ Input: testResponsesInput,
+ }
+ }
+
// Responses-only models (e.g. codex series)
if strings.Contains(strings.ToLower(model), "codex") {
return &dto.OpenAIResponsesRequest{
- Model: model,
- Input: json.RawMessage("\"hi\""),
+ Model: model,
+ Input: json.RawMessage(`[{"role":"user","content":"hi"}]`),
+ Stream: lo.ToPtr(isStream),
}
}
// Chat/Completion 请求 - 返回 GeneralOpenAIRequest
testRequest := &dto.GeneralOpenAIRequest{
Model: model,
- Stream: false,
+ Stream: lo.ToPtr(isStream),
Messages: []dto.Message{
{
Role: "user",
@@ -509,17 +712,20 @@ func buildTestRequest(model string, endpointType string, channel *model.Channel)
},
},
}
+ if isStream {
+ testRequest.StreamOptions = &dto.StreamOptions{IncludeUsage: true}
+ }
if strings.HasPrefix(model, "o") {
- testRequest.MaxCompletionTokens = 16
+ testRequest.MaxCompletionTokens = lo.ToPtr(uint(16))
} else if strings.Contains(model, "thinking") {
if !strings.Contains(model, "claude") {
- testRequest.MaxTokens = 50
+ testRequest.MaxTokens = lo.ToPtr(uint(50))
}
} else if strings.Contains(model, "gemini") {
- testRequest.MaxTokens = 3000
+ testRequest.MaxTokens = lo.ToPtr(uint(3000))
} else {
- testRequest.MaxTokens = 16
+ testRequest.MaxTokens = lo.ToPtr(uint(16))
}
return testRequest
@@ -546,8 +752,9 @@ func TestChannel(c *gin.Context) {
//}()
testModel := c.Query("model")
endpointType := c.Query("endpoint_type")
+ isStream, _ := strconv.ParseBool(c.Query("stream"))
tik := time.Now()
- result := testChannel(channel, testModel, endpointType)
+ result := testChannel(channel, testModel, endpointType, isStream)
if result.localErr != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
@@ -604,9 +811,12 @@ func testAllChannels(notify bool) error {
}()
for _, channel := range channels {
+ if channel.Status == common.ChannelStatusManuallyDisabled {
+ continue
+ }
isChannelEnabled := channel.Status == common.ChannelStatusEnabled
tik := time.Now()
- result := testChannel(channel, "", "")
+ result := testChannel(channel, "", "", false)
tok := time.Now()
milliseconds := tok.Sub(tik).Milliseconds()
diff --git a/controller/channel.go b/controller/channel.go
index 3ac29d7c6e..b0dd228615 100644
--- a/controller/channel.go
+++ b/controller/channel.go
@@ -13,6 +13,7 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
+ relaychannel "github.com/QuantumNous/new-api/relay/channel"
"github.com/QuantumNous/new-api/relay/channel/gemini"
"github.com/QuantumNous/new-api/relay/channel/ollama"
"github.com/QuantumNous/new-api/service"
@@ -89,7 +90,8 @@ func GetAllChannels(c *gin.Context) {
if enableTagMode {
tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to get paginated tags: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取标签失败,请稍后重试"})
return
}
for _, tag := range tags {
@@ -136,7 +138,8 @@ func GetAllChannels(c *gin.Context) {
err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to get channels: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取渠道列表失败,请稍后重试"})
return
}
}
@@ -181,6 +184,9 @@ func buildFetchModelsHeaders(channel *model.Channel, key string) (http.Header, e
headerOverride := channel.GetHeaderOverride()
for k, v := range headerOverride {
+ if relaychannel.IsHeaderPassthroughRuleKey(k) {
+ continue
+ }
str, ok := v.(string)
if !ok {
return nil, fmt.Errorf("invalid header override for key %s", k)
@@ -207,157 +213,14 @@ func FetchUpstreamModels(c *gin.Context) {
return
}
- baseURL := constant.ChannelBaseURLs[channel.Type]
- if channel.GetBaseURL() != "" {
- baseURL = channel.GetBaseURL()
- }
-
- // 对于 Ollama 渠道,使用特殊处理
- if channel.Type == constant.ChannelTypeOllama {
- key := strings.Split(channel.Key, "\n")[0]
- models, err := ollama.FetchOllamaModels(baseURL, key)
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()),
- })
- return
- }
-
- result := OpenAIModelsResponse{
- Data: make([]OpenAIModel, 0, len(models)),
- }
-
- for _, modelInfo := range models {
- metadata := map[string]any{}
- if modelInfo.Size > 0 {
- metadata["size"] = modelInfo.Size
- }
- if modelInfo.Digest != "" {
- metadata["digest"] = modelInfo.Digest
- }
- if modelInfo.ModifiedAt != "" {
- metadata["modified_at"] = modelInfo.ModifiedAt
- }
- details := modelInfo.Details
- if details.ParentModel != "" || details.Format != "" || details.Family != "" || len(details.Families) > 0 || details.ParameterSize != "" || details.QuantizationLevel != "" {
- metadata["details"] = modelInfo.Details
- }
- if len(metadata) == 0 {
- metadata = nil
- }
-
- result.Data = append(result.Data, OpenAIModel{
- ID: modelInfo.Name,
- Object: "model",
- Created: 0,
- OwnedBy: "ollama",
- Metadata: metadata,
- })
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": result.Data,
- })
- return
- }
-
- // 对于 Gemini 渠道,使用特殊处理
- if channel.Type == constant.ChannelTypeGemini {
- // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
- key, _, apiErr := channel.GetNextEnabledKey()
- if apiErr != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
- })
- return
- }
- key = strings.TrimSpace(key)
- models, err := gemini.FetchGeminiModels(baseURL, key, channel.GetSetting().Proxy)
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": models,
- })
- return
- }
-
- var url string
- switch channel.Type {
- case constant.ChannelTypeAli:
- url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
- case constant.ChannelTypeZhipu_v4:
- if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
- url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
- } else {
- url = fmt.Sprintf("%s/api/paas/v4/models", baseURL)
- }
- case constant.ChannelTypeVolcEngine:
- if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
- url = fmt.Sprintf("%s/v1/models", plan.OpenAIBaseURL)
- } else {
- url = fmt.Sprintf("%s/v1/models", baseURL)
- }
- case constant.ChannelTypeMoonshot:
- if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
- url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
- } else {
- url = fmt.Sprintf("%s/v1/models", baseURL)
- }
- default:
- url = fmt.Sprintf("%s/v1/models", baseURL)
- }
-
- // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
- key, _, apiErr := channel.GetNextEnabledKey()
- if apiErr != nil {
+ ids, err := fetchChannelUpstreamModelIDs(channel)
+ if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
- "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
+ "message": fmt.Sprintf("获取模型列表失败: %s", err.Error()),
})
return
}
- key = strings.TrimSpace(key)
-
- headers, err := buildFetchModelsHeaders(channel, key)
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- body, err := GetResponseBody("GET", url, channel, headers)
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- var result OpenAIModelsResponse
- if err = json.Unmarshal(body, &result); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
- })
- return
- }
-
- var ids []string
- for _, model := range result.Data {
- id := model.ID
- if channel.Type == constant.ChannelTypeGemini {
- id = strings.TrimPrefix(id, "models/")
- }
- ids = append(ids, id)
- }
c.JSON(http.StatusOK, gin.H{
"success": true,
@@ -641,7 +504,8 @@ func RefreshCodexChannelCredential(c *gin.Context) {
oauthKey, ch, err := service.RefreshCodexChannelCredential(ctx, channelId, service.CodexCredentialRefreshOptions{ResetCaches: true})
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to refresh codex channel credential: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "刷新凭证失败,请稍后重试"})
return
}
@@ -1315,7 +1179,8 @@ func CopyChannel(c *gin.Context) {
// fetch original channel with key
origin, err := model.GetChannelById(id, true)
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to get channel by id: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取渠道信息失败,请稍后重试"})
return
}
@@ -1333,7 +1198,8 @@ func CopyChannel(c *gin.Context) {
// insert
if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to clone channel: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "复制渠道失败,请稍后重试"})
return
}
model.InitChannelCache()
diff --git a/controller/channel_affinity_cache.go b/controller/channel_affinity_cache.go
new file mode 100644
index 0000000000..a72b04b8b9
--- /dev/null
+++ b/controller/channel_affinity_cache.go
@@ -0,0 +1,88 @@
+package controller
+
+import (
+ "net/http"
+ "strings"
+
+ "github.com/QuantumNous/new-api/service"
+ "github.com/gin-gonic/gin"
+)
+
+func GetChannelAffinityCacheStats(c *gin.Context) {
+ stats := service.GetChannelAffinityCacheStats()
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": stats,
+ })
+}
+
+func ClearChannelAffinityCache(c *gin.Context) {
+ all := strings.TrimSpace(c.Query("all"))
+ ruleName := strings.TrimSpace(c.Query("rule_name"))
+
+ if all == "true" {
+ deleted := service.ClearChannelAffinityCacheAll()
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "deleted": deleted,
+ },
+ })
+ return
+ }
+
+ if ruleName == "" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "message": "缺少参数:rule_name,或使用 all=true 清空全部",
+ })
+ return
+ }
+
+ deleted, err := service.ClearChannelAffinityCacheByRuleName(ruleName)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "message": err.Error(),
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "deleted": deleted,
+ },
+ })
+}
+
+func GetChannelAffinityUsageCacheStats(c *gin.Context) {
+ ruleName := strings.TrimSpace(c.Query("rule_name"))
+ usingGroup := strings.TrimSpace(c.Query("using_group"))
+ keyFp := strings.TrimSpace(c.Query("key_fp"))
+
+ if ruleName == "" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "message": "missing param: rule_name",
+ })
+ return
+ }
+ if keyFp == "" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "message": "missing param: key_fp",
+ })
+ return
+ }
+
+ stats := service.GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFp)
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": stats,
+ })
+}
diff --git a/controller/channel_upstream_update.go b/controller/channel_upstream_update.go
new file mode 100644
index 0000000000..1d851949fd
--- /dev/null
+++ b/controller/channel_upstream_update.go
@@ -0,0 +1,979 @@
+package controller
+
+import (
+ "fmt"
+ "net/http"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/relay/channel/gemini"
+ "github.com/QuantumNous/new-api/relay/channel/ollama"
+ "github.com/QuantumNous/new-api/service"
+
+ "github.com/gin-gonic/gin"
+ "github.com/samber/lo"
+)
+
+const (
+ channelUpstreamModelUpdateTaskDefaultIntervalMinutes = 30
+ channelUpstreamModelUpdateTaskBatchSize = 100
+ channelUpstreamModelUpdateMinCheckIntervalSeconds = 300
+ channelUpstreamModelUpdateNotifySuppressWindowSeconds = 86400
+ channelUpstreamModelUpdateNotifyMaxChannelDetails = 8
+ channelUpstreamModelUpdateNotifyMaxModelDetails = 12
+ channelUpstreamModelUpdateNotifyMaxFailedChannelIDs = 10
+)
+
+var (
+ channelUpstreamModelUpdateTaskOnce sync.Once
+ channelUpstreamModelUpdateTaskRunning atomic.Bool
+ channelUpstreamModelUpdateNotifyState = struct {
+ sync.Mutex
+ lastNotifiedAt int64
+ lastChangedChannels int
+ lastFailedChannels int
+ }{}
+)
+
+type applyChannelUpstreamModelUpdatesRequest struct {
+ ID int `json:"id"`
+ AddModels []string `json:"add_models"`
+ RemoveModels []string `json:"remove_models"`
+ IgnoreModels []string `json:"ignore_models"`
+}
+
+type applyAllChannelUpstreamModelUpdatesResult struct {
+ ChannelID int `json:"channel_id"`
+ ChannelName string `json:"channel_name"`
+ AddedModels []string `json:"added_models"`
+ RemovedModels []string `json:"removed_models"`
+ RemainingModels []string `json:"remaining_models"`
+ RemainingRemoveModels []string `json:"remaining_remove_models"`
+}
+
+type detectChannelUpstreamModelUpdatesResult struct {
+ ChannelID int `json:"channel_id"`
+ ChannelName string `json:"channel_name"`
+ AddModels []string `json:"add_models"`
+ RemoveModels []string `json:"remove_models"`
+ LastCheckTime int64 `json:"last_check_time"`
+ AutoAddedModels int `json:"auto_added_models"`
+}
+
+type upstreamModelUpdateChannelSummary struct {
+ ChannelName string
+ AddCount int
+ RemoveCount int
+}
+
+func normalizeModelNames(models []string) []string {
+ return lo.Uniq(lo.FilterMap(models, func(model string, _ int) (string, bool) {
+ trimmed := strings.TrimSpace(model)
+ return trimmed, trimmed != ""
+ }))
+}
+
+func mergeModelNames(base []string, appended []string) []string {
+ merged := normalizeModelNames(base)
+ seen := make(map[string]struct{}, len(merged))
+ for _, model := range merged {
+ seen[model] = struct{}{}
+ }
+ for _, model := range normalizeModelNames(appended) {
+ if _, ok := seen[model]; ok {
+ continue
+ }
+ seen[model] = struct{}{}
+ merged = append(merged, model)
+ }
+ return merged
+}
+
+func subtractModelNames(base []string, removed []string) []string {
+ removeSet := make(map[string]struct{}, len(removed))
+ for _, model := range normalizeModelNames(removed) {
+ removeSet[model] = struct{}{}
+ }
+ return lo.Filter(normalizeModelNames(base), func(model string, _ int) bool {
+ _, ok := removeSet[model]
+ return !ok
+ })
+}
+
+func intersectModelNames(base []string, allowed []string) []string {
+ allowedSet := make(map[string]struct{}, len(allowed))
+ for _, model := range normalizeModelNames(allowed) {
+ allowedSet[model] = struct{}{}
+ }
+ return lo.Filter(normalizeModelNames(base), func(model string, _ int) bool {
+ _, ok := allowedSet[model]
+ return ok
+ })
+}
+
+func applySelectedModelChanges(originModels []string, addModels []string, removeModels []string) []string {
+ // Add wins when the same model appears in both selected lists.
+ normalizedAdd := normalizeModelNames(addModels)
+ normalizedRemove := subtractModelNames(normalizeModelNames(removeModels), normalizedAdd)
+ return subtractModelNames(mergeModelNames(originModels, normalizedAdd), normalizedRemove)
+}
+
+func normalizeChannelModelMapping(channel *model.Channel) map[string]string {
+ if channel == nil || channel.ModelMapping == nil {
+ return nil
+ }
+ rawMapping := strings.TrimSpace(*channel.ModelMapping)
+ if rawMapping == "" || rawMapping == "{}" {
+ return nil
+ }
+ parsed := make(map[string]string)
+ if err := common.UnmarshalJsonStr(rawMapping, &parsed); err != nil {
+ return nil
+ }
+ normalized := make(map[string]string, len(parsed))
+ for source, target := range parsed {
+ normalizedSource := strings.TrimSpace(source)
+ normalizedTarget := strings.TrimSpace(target)
+ if normalizedSource == "" || normalizedTarget == "" {
+ continue
+ }
+ normalized[normalizedSource] = normalizedTarget
+ }
+ if len(normalized) == 0 {
+ return nil
+ }
+ return normalized
+}
+
+func collectPendingUpstreamModelChangesFromModels(
+ localModels []string,
+ upstreamModels []string,
+ ignoredModels []string,
+ modelMapping map[string]string,
+) (pendingAddModels []string, pendingRemoveModels []string) {
+ localSet := make(map[string]struct{})
+ localModels = normalizeModelNames(localModels)
+ upstreamModels = normalizeModelNames(upstreamModels)
+ for _, modelName := range localModels {
+ localSet[modelName] = struct{}{}
+ }
+ upstreamSet := make(map[string]struct{}, len(upstreamModels))
+ for _, modelName := range upstreamModels {
+ upstreamSet[modelName] = struct{}{}
+ }
+
+ normalizedIgnoredModels := normalizeModelNames(ignoredModels)
+
+ redirectSourceSet := make(map[string]struct{}, len(modelMapping))
+ redirectTargetSet := make(map[string]struct{}, len(modelMapping))
+ for source, target := range modelMapping {
+ redirectSourceSet[source] = struct{}{}
+ redirectTargetSet[target] = struct{}{}
+ }
+
+ coveredUpstreamSet := make(map[string]struct{}, len(localSet)+len(redirectTargetSet))
+ for modelName := range localSet {
+ coveredUpstreamSet[modelName] = struct{}{}
+ }
+ for modelName := range redirectTargetSet {
+ coveredUpstreamSet[modelName] = struct{}{}
+ }
+
+ pendingAdd := lo.Filter(upstreamModels, func(modelName string, _ int) bool {
+ if _, ok := coveredUpstreamSet[modelName]; ok {
+ return false
+ }
+ if lo.ContainsBy(normalizedIgnoredModels, func(ignoredModel string) bool {
+ if regexBody, ok := strings.CutPrefix(ignoredModel, "regex:"); ok {
+ matched, err := regexp.MatchString(strings.TrimSpace(regexBody), modelName)
+ return err == nil && matched
+ }
+ return ignoredModel == modelName
+ }) {
+ return false
+ }
+ return true
+ })
+ pendingRemove := lo.Filter(localModels, func(modelName string, _ int) bool {
+ // Redirect source models are virtual aliases and should not be removed
+ // only because they are absent from upstream model list.
+ if _, ok := redirectSourceSet[modelName]; ok {
+ return false
+ }
+ _, ok := upstreamSet[modelName]
+ return !ok
+ })
+ return normalizeModelNames(pendingAdd), normalizeModelNames(pendingRemove)
+}
+
+func collectPendingUpstreamModelChanges(channel *model.Channel, settings dto.ChannelOtherSettings) (pendingAddModels []string, pendingRemoveModels []string, err error) {
+ upstreamModels, err := fetchChannelUpstreamModelIDs(channel)
+ if err != nil {
+ return nil, nil, err
+ }
+ pendingAddModels, pendingRemoveModels = collectPendingUpstreamModelChangesFromModels(
+ channel.GetModels(),
+ upstreamModels,
+ settings.UpstreamModelUpdateIgnoredModels,
+ normalizeChannelModelMapping(channel),
+ )
+ return pendingAddModels, pendingRemoveModels, nil
+}
+
+func getUpstreamModelUpdateMinCheckIntervalSeconds() int64 {
+ interval := int64(common.GetEnvOrDefault(
+ "CHANNEL_UPSTREAM_MODEL_UPDATE_MIN_CHECK_INTERVAL_SECONDS",
+ channelUpstreamModelUpdateMinCheckIntervalSeconds,
+ ))
+ if interval < 0 {
+ return channelUpstreamModelUpdateMinCheckIntervalSeconds
+ }
+ return interval
+}
+
+func fetchChannelUpstreamModelIDs(channel *model.Channel) ([]string, error) {
+ baseURL := constant.ChannelBaseURLs[channel.Type]
+ if channel.GetBaseURL() != "" {
+ baseURL = channel.GetBaseURL()
+ }
+
+ if channel.Type == constant.ChannelTypeOllama {
+ key := strings.TrimSpace(strings.Split(channel.Key, "\n")[0])
+ models, err := ollama.FetchOllamaModels(baseURL, key)
+ if err != nil {
+ return nil, err
+ }
+ return normalizeModelNames(lo.Map(models, func(item ollama.OllamaModel, _ int) string {
+ return item.Name
+ })), nil
+ }
+
+ if channel.Type == constant.ChannelTypeGemini {
+ key, _, apiErr := channel.GetNextEnabledKey()
+ if apiErr != nil {
+ return nil, fmt.Errorf("获取渠道密钥失败: %w", apiErr)
+ }
+ key = strings.TrimSpace(key)
+ models, err := gemini.FetchGeminiModels(baseURL, key, channel.GetSetting().Proxy)
+ if err != nil {
+ return nil, err
+ }
+ return normalizeModelNames(models), nil
+ }
+
+ var url string
+ switch channel.Type {
+ case constant.ChannelTypeAli:
+ url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
+ case constant.ChannelTypeZhipu_v4:
+ if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
+ url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
+ } else {
+ url = fmt.Sprintf("%s/api/paas/v4/models", baseURL)
+ }
+ case constant.ChannelTypeVolcEngine:
+ if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
+ url = fmt.Sprintf("%s/v1/models", plan.OpenAIBaseURL)
+ } else {
+ url = fmt.Sprintf("%s/v1/models", baseURL)
+ }
+ case constant.ChannelTypeMoonshot:
+ if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
+ url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
+ } else {
+ url = fmt.Sprintf("%s/v1/models", baseURL)
+ }
+ default:
+ url = fmt.Sprintf("%s/v1/models", baseURL)
+ }
+
+ key, _, apiErr := channel.GetNextEnabledKey()
+ if apiErr != nil {
+ return nil, fmt.Errorf("获取渠道密钥失败: %w", apiErr)
+ }
+ key = strings.TrimSpace(key)
+
+ headers, err := buildFetchModelsHeaders(channel, key)
+ if err != nil {
+ return nil, err
+ }
+
+ body, err := GetResponseBody(http.MethodGet, url, channel, headers)
+ if err != nil {
+ return nil, err
+ }
+
+ var result OpenAIModelsResponse
+ if err := common.Unmarshal(body, &result); err != nil {
+ return nil, err
+ }
+
+ ids := lo.Map(result.Data, func(item OpenAIModel, _ int) string {
+ if channel.Type == constant.ChannelTypeGemini {
+ return strings.TrimPrefix(item.ID, "models/")
+ }
+ return item.ID
+ })
+
+ return normalizeModelNames(ids), nil
+}
+
+func updateChannelUpstreamModelSettings(channel *model.Channel, settings dto.ChannelOtherSettings, updateModels bool) error {
+ channel.SetOtherSettings(settings)
+ updates := map[string]interface{}{
+ "settings": channel.OtherSettings,
+ }
+ if updateModels {
+ updates["models"] = channel.Models
+ }
+ return model.DB.Model(&model.Channel{}).Where("id = ?", channel.Id).Updates(updates).Error
+}
+
+func checkAndPersistChannelUpstreamModelUpdates(
+ channel *model.Channel,
+ settings *dto.ChannelOtherSettings,
+ force bool,
+ allowAutoApply bool,
+) (modelsChanged bool, autoAdded int, err error) {
+ now := common.GetTimestamp()
+ if !force {
+ minInterval := getUpstreamModelUpdateMinCheckIntervalSeconds()
+ if settings.UpstreamModelUpdateLastCheckTime > 0 &&
+ now-settings.UpstreamModelUpdateLastCheckTime < minInterval {
+ return false, 0, nil
+ }
+ }
+
+ pendingAddModels, pendingRemoveModels, fetchErr := collectPendingUpstreamModelChanges(channel, *settings)
+ settings.UpstreamModelUpdateLastCheckTime = now
+ if fetchErr != nil {
+ if err = updateChannelUpstreamModelSettings(channel, *settings, false); err != nil {
+ return false, 0, err
+ }
+ return false, 0, fetchErr
+ }
+
+ if allowAutoApply && settings.UpstreamModelUpdateAutoSyncEnabled && len(pendingAddModels) > 0 {
+ originModels := normalizeModelNames(channel.GetModels())
+ mergedModels := mergeModelNames(originModels, pendingAddModels)
+ if len(mergedModels) > len(originModels) {
+ channel.Models = strings.Join(mergedModels, ",")
+ autoAdded = len(mergedModels) - len(originModels)
+ modelsChanged = true
+ }
+ settings.UpstreamModelUpdateLastDetectedModels = []string{}
+ } else {
+ settings.UpstreamModelUpdateLastDetectedModels = pendingAddModels
+ }
+ settings.UpstreamModelUpdateLastRemovedModels = pendingRemoveModels
+
+ if err = updateChannelUpstreamModelSettings(channel, *settings, modelsChanged); err != nil {
+ return false, autoAdded, err
+ }
+ if modelsChanged {
+ if err = channel.UpdateAbilities(nil); err != nil {
+ return true, autoAdded, err
+ }
+ }
+ return modelsChanged, autoAdded, nil
+}
+
+func refreshChannelRuntimeCache() {
+ if common.MemoryCacheEnabled {
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ common.SysLog(fmt.Sprintf("InitChannelCache panic: %v", r))
+ }
+ }()
+ model.InitChannelCache()
+ }()
+ }
+ service.ResetProxyClientCache()
+}
+
+func shouldSendUpstreamModelUpdateNotification(now int64, changedChannels int, failedChannels int) bool {
+ if changedChannels <= 0 && failedChannels <= 0 {
+ return true
+ }
+
+ channelUpstreamModelUpdateNotifyState.Lock()
+ defer channelUpstreamModelUpdateNotifyState.Unlock()
+
+ if channelUpstreamModelUpdateNotifyState.lastNotifiedAt > 0 &&
+ now-channelUpstreamModelUpdateNotifyState.lastNotifiedAt < channelUpstreamModelUpdateNotifySuppressWindowSeconds &&
+ channelUpstreamModelUpdateNotifyState.lastChangedChannels == changedChannels &&
+ channelUpstreamModelUpdateNotifyState.lastFailedChannels == failedChannels {
+ return false
+ }
+
+ channelUpstreamModelUpdateNotifyState.lastNotifiedAt = now
+ channelUpstreamModelUpdateNotifyState.lastChangedChannels = changedChannels
+ channelUpstreamModelUpdateNotifyState.lastFailedChannels = failedChannels
+ return true
+}
+
+func buildUpstreamModelUpdateTaskNotificationContent(
+ checkedChannels int,
+ changedChannels int,
+ detectedAddModels int,
+ detectedRemoveModels int,
+ autoAddedModels int,
+ failedChannelIDs []int,
+ channelSummaries []upstreamModelUpdateChannelSummary,
+ addModelSamples []string,
+ removeModelSamples []string,
+) string {
+ var builder strings.Builder
+ failedChannels := len(failedChannelIDs)
+ builder.WriteString(fmt.Sprintf(
+ "上游模型巡检摘要:检测渠道 %d 个,发现变更 %d 个,新增 %d 个,删除 %d 个,自动同步新增 %d 个,失败 %d 个。",
+ checkedChannels,
+ changedChannels,
+ detectedAddModels,
+ detectedRemoveModels,
+ autoAddedModels,
+ failedChannels,
+ ))
+
+ if len(channelSummaries) > 0 {
+ displayCount := min(len(channelSummaries), channelUpstreamModelUpdateNotifyMaxChannelDetails)
+ builder.WriteString(fmt.Sprintf("\n\n变更渠道明细(展示 %d/%d):", displayCount, len(channelSummaries)))
+ for _, summary := range channelSummaries[:displayCount] {
+ builder.WriteString(fmt.Sprintf("\n- %s (+%d / -%d)", summary.ChannelName, summary.AddCount, summary.RemoveCount))
+ }
+ if len(channelSummaries) > displayCount {
+ builder.WriteString(fmt.Sprintf("\n- 其余 %d 个渠道已省略", len(channelSummaries)-displayCount))
+ }
+ }
+
+ normalizedAddModelSamples := normalizeModelNames(addModelSamples)
+ if len(normalizedAddModelSamples) > 0 {
+ displayCount := min(len(normalizedAddModelSamples), channelUpstreamModelUpdateNotifyMaxModelDetails)
+ builder.WriteString(fmt.Sprintf("\n\n新增模型示例(展示 %d/%d):%s",
+ displayCount,
+ len(normalizedAddModelSamples),
+ strings.Join(normalizedAddModelSamples[:displayCount], ", "),
+ ))
+ if len(normalizedAddModelSamples) > displayCount {
+ builder.WriteString(fmt.Sprintf("(其余 %d 个已省略)", len(normalizedAddModelSamples)-displayCount))
+ }
+ }
+
+ normalizedRemoveModelSamples := normalizeModelNames(removeModelSamples)
+ if len(normalizedRemoveModelSamples) > 0 {
+ displayCount := min(len(normalizedRemoveModelSamples), channelUpstreamModelUpdateNotifyMaxModelDetails)
+ builder.WriteString(fmt.Sprintf("\n\n删除模型示例(展示 %d/%d):%s",
+ displayCount,
+ len(normalizedRemoveModelSamples),
+ strings.Join(normalizedRemoveModelSamples[:displayCount], ", "),
+ ))
+ if len(normalizedRemoveModelSamples) > displayCount {
+ builder.WriteString(fmt.Sprintf("(其余 %d 个已省略)", len(normalizedRemoveModelSamples)-displayCount))
+ }
+ }
+
+ if failedChannels > 0 {
+ displayCount := min(failedChannels, channelUpstreamModelUpdateNotifyMaxFailedChannelIDs)
+ displayIDs := lo.Map(failedChannelIDs[:displayCount], func(channelID int, _ int) string {
+ return fmt.Sprintf("%d", channelID)
+ })
+ builder.WriteString(fmt.Sprintf(
+ "\n\n失败渠道 ID(展示 %d/%d):%s",
+ displayCount,
+ failedChannels,
+ strings.Join(displayIDs, ", "),
+ ))
+ if failedChannels > displayCount {
+ builder.WriteString(fmt.Sprintf("(其余 %d 个已省略)", failedChannels-displayCount))
+ }
+ }
+ return builder.String()
+}
+
+func runChannelUpstreamModelUpdateTaskOnce() {
+ if !channelUpstreamModelUpdateTaskRunning.CompareAndSwap(false, true) {
+ return
+ }
+ defer channelUpstreamModelUpdateTaskRunning.Store(false)
+
+ checkedChannels := 0
+ failedChannels := 0
+ failedChannelIDs := make([]int, 0)
+ changedChannels := 0
+ detectedAddModels := 0
+ detectedRemoveModels := 0
+ autoAddedModels := 0
+ channelSummaries := make([]upstreamModelUpdateChannelSummary, 0)
+ addModelSamples := make([]string, 0)
+ removeModelSamples := make([]string, 0)
+ refreshNeeded := false
+
+ lastID := 0
+ for {
+ var channels []*model.Channel
+ query := model.DB.
+ Select("id", "name", "type", "key", "status", "base_url", "models", "settings", "setting", "other", "group", "priority", "weight", "tag", "channel_info", "header_override").
+ Where("status = ?", common.ChannelStatusEnabled).
+ Order("id asc").
+ Limit(channelUpstreamModelUpdateTaskBatchSize)
+ if lastID > 0 {
+ query = query.Where("id > ?", lastID)
+ }
+ err := query.Find(&channels).Error
+ if err != nil {
+ common.SysLog(fmt.Sprintf("upstream model update task query failed: %v", err))
+ break
+ }
+ if len(channels) == 0 {
+ break
+ }
+ lastID = channels[len(channels)-1].Id
+
+ for _, channel := range channels {
+ if channel == nil {
+ continue
+ }
+
+ settings := channel.GetOtherSettings()
+ if !settings.UpstreamModelUpdateCheckEnabled {
+ continue
+ }
+
+ checkedChannels++
+ modelsChanged, autoAdded, err := checkAndPersistChannelUpstreamModelUpdates(channel, &settings, false, true)
+ if err != nil {
+ failedChannels++
+ failedChannelIDs = append(failedChannelIDs, channel.Id)
+ common.SysLog(fmt.Sprintf("upstream model update check failed: channel_id=%d channel_name=%s err=%v", channel.Id, channel.Name, err))
+ continue
+ }
+ currentAddModels := normalizeModelNames(settings.UpstreamModelUpdateLastDetectedModels)
+ currentRemoveModels := normalizeModelNames(settings.UpstreamModelUpdateLastRemovedModels)
+ currentAddCount := len(currentAddModels) + autoAdded
+ currentRemoveCount := len(currentRemoveModels)
+ detectedAddModels += currentAddCount
+ detectedRemoveModels += currentRemoveCount
+ if currentAddCount > 0 || currentRemoveCount > 0 {
+ changedChannels++
+ channelSummaries = append(channelSummaries, upstreamModelUpdateChannelSummary{
+ ChannelName: channel.Name,
+ AddCount: currentAddCount,
+ RemoveCount: currentRemoveCount,
+ })
+ }
+ addModelSamples = mergeModelNames(addModelSamples, currentAddModels)
+ removeModelSamples = mergeModelNames(removeModelSamples, currentRemoveModels)
+ if modelsChanged {
+ refreshNeeded = true
+ }
+ autoAddedModels += autoAdded
+
+ if common.RequestInterval > 0 {
+ time.Sleep(common.RequestInterval)
+ }
+ }
+
+ if len(channels) < channelUpstreamModelUpdateTaskBatchSize {
+ break
+ }
+ }
+
+ if refreshNeeded {
+ refreshChannelRuntimeCache()
+ }
+
+ if checkedChannels > 0 || common.DebugEnabled {
+ common.SysLog(fmt.Sprintf(
+ "upstream model update task done: checked_channels=%d changed_channels=%d detected_add_models=%d detected_remove_models=%d failed_channels=%d auto_added_models=%d",
+ checkedChannels,
+ changedChannels,
+ detectedAddModels,
+ detectedRemoveModels,
+ failedChannels,
+ autoAddedModels,
+ ))
+ }
+ if changedChannels > 0 || failedChannels > 0 {
+ now := common.GetTimestamp()
+ if !shouldSendUpstreamModelUpdateNotification(now, changedChannels, failedChannels) {
+ common.SysLog(fmt.Sprintf(
+ "upstream model update notification skipped in 24h window: changed_channels=%d failed_channels=%d",
+ changedChannels,
+ failedChannels,
+ ))
+ return
+ }
+ service.NotifyUpstreamModelUpdateWatchers(
+ "上游模型巡检通知",
+ buildUpstreamModelUpdateTaskNotificationContent(
+ checkedChannels,
+ changedChannels,
+ detectedAddModels,
+ detectedRemoveModels,
+ autoAddedModels,
+ failedChannelIDs,
+ channelSummaries,
+ addModelSamples,
+ removeModelSamples,
+ ),
+ )
+ }
+}
+
+func StartChannelUpstreamModelUpdateTask() {
+ channelUpstreamModelUpdateTaskOnce.Do(func() {
+ if !common.IsMasterNode {
+ return
+ }
+ if !common.GetEnvOrDefaultBool("CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_ENABLED", true) {
+ common.SysLog("upstream model update task disabled by CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_ENABLED")
+ return
+ }
+
+ intervalMinutes := common.GetEnvOrDefault(
+ "CHANNEL_UPSTREAM_MODEL_UPDATE_TASK_INTERVAL_MINUTES",
+ channelUpstreamModelUpdateTaskDefaultIntervalMinutes,
+ )
+ if intervalMinutes < 1 {
+ intervalMinutes = channelUpstreamModelUpdateTaskDefaultIntervalMinutes
+ }
+ interval := time.Duration(intervalMinutes) * time.Minute
+
+ go func() {
+ common.SysLog(fmt.Sprintf("upstream model update task started: interval=%s", interval))
+ runChannelUpstreamModelUpdateTaskOnce()
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for range ticker.C {
+ runChannelUpstreamModelUpdateTaskOnce()
+ }
+ }()
+ })
+}
+
+func ApplyChannelUpstreamModelUpdates(c *gin.Context) {
+ var req applyChannelUpstreamModelUpdatesRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if req.ID <= 0 {
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": "invalid channel id",
+ })
+ return
+ }
+
+ channel, err := model.GetChannelById(req.ID, true)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ beforeSettings := channel.GetOtherSettings()
+ ignoredModels := intersectModelNames(req.IgnoreModels, beforeSettings.UpstreamModelUpdateLastDetectedModels)
+
+ addedModels, removedModels, remainingModels, remainingRemoveModels, modelsChanged, err := applyChannelUpstreamModelUpdates(
+ channel,
+ req.AddModels,
+ req.IgnoreModels,
+ req.RemoveModels,
+ )
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ if modelsChanged {
+ refreshChannelRuntimeCache()
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "id": channel.Id,
+ "added_models": addedModels,
+ "removed_models": removedModels,
+ "ignored_models": ignoredModels,
+ "remaining_models": remainingModels,
+ "remaining_remove_models": remainingRemoveModels,
+ "models": channel.Models,
+ "settings": channel.OtherSettings,
+ },
+ })
+}
+
+func DetectChannelUpstreamModelUpdates(c *gin.Context) {
+ var req applyChannelUpstreamModelUpdatesRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if req.ID <= 0 {
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": "invalid channel id",
+ })
+ return
+ }
+
+ channel, err := model.GetChannelById(req.ID, true)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ settings := channel.GetOtherSettings()
+ modelsChanged, autoAdded, err := checkAndPersistChannelUpstreamModelUpdates(channel, &settings, true, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if modelsChanged {
+ refreshChannelRuntimeCache()
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": detectChannelUpstreamModelUpdatesResult{
+ ChannelID: channel.Id,
+ ChannelName: channel.Name,
+ AddModels: normalizeModelNames(settings.UpstreamModelUpdateLastDetectedModels),
+ RemoveModels: normalizeModelNames(settings.UpstreamModelUpdateLastRemovedModels),
+ LastCheckTime: settings.UpstreamModelUpdateLastCheckTime,
+ AutoAddedModels: autoAdded,
+ },
+ })
+}
+
+func applyChannelUpstreamModelUpdates(
+ channel *model.Channel,
+ addModelsInput []string,
+ ignoreModelsInput []string,
+ removeModelsInput []string,
+) (
+ addedModels []string,
+ removedModels []string,
+ remainingModels []string,
+ remainingRemoveModels []string,
+ modelsChanged bool,
+ err error,
+) {
+ settings := channel.GetOtherSettings()
+ pendingAddModels := normalizeModelNames(settings.UpstreamModelUpdateLastDetectedModels)
+ pendingRemoveModels := normalizeModelNames(settings.UpstreamModelUpdateLastRemovedModels)
+ addModels := intersectModelNames(addModelsInput, pendingAddModels)
+ ignoreModels := intersectModelNames(ignoreModelsInput, pendingAddModels)
+ removeModels := intersectModelNames(removeModelsInput, pendingRemoveModels)
+ removeModels = subtractModelNames(removeModels, addModels)
+
+ originModels := normalizeModelNames(channel.GetModels())
+ nextModels := applySelectedModelChanges(originModels, addModels, removeModels)
+ modelsChanged = !slices.Equal(originModels, nextModels)
+ if modelsChanged {
+ channel.Models = strings.Join(nextModels, ",")
+ }
+
+ settings.UpstreamModelUpdateIgnoredModels = mergeModelNames(settings.UpstreamModelUpdateIgnoredModels, ignoreModels)
+ if len(addModels) > 0 {
+ settings.UpstreamModelUpdateIgnoredModels = subtractModelNames(settings.UpstreamModelUpdateIgnoredModels, addModels)
+ }
+ remainingModels = subtractModelNames(pendingAddModels, append(addModels, ignoreModels...))
+ remainingRemoveModels = subtractModelNames(pendingRemoveModels, removeModels)
+ settings.UpstreamModelUpdateLastDetectedModels = remainingModels
+ settings.UpstreamModelUpdateLastRemovedModels = remainingRemoveModels
+ settings.UpstreamModelUpdateLastCheckTime = common.GetTimestamp()
+
+ if err := updateChannelUpstreamModelSettings(channel, settings, modelsChanged); err != nil {
+ return nil, nil, nil, nil, false, err
+ }
+
+ if modelsChanged {
+ if err := channel.UpdateAbilities(nil); err != nil {
+ return addModels, removeModels, remainingModels, remainingRemoveModels, true, err
+ }
+ }
+ return addModels, removeModels, remainingModels, remainingRemoveModels, modelsChanged, nil
+}
+
+func collectPendingApplyUpstreamModelChanges(settings dto.ChannelOtherSettings) (pendingAddModels []string, pendingRemoveModels []string) {
+ return normalizeModelNames(settings.UpstreamModelUpdateLastDetectedModels), normalizeModelNames(settings.UpstreamModelUpdateLastRemovedModels)
+}
+
+func findEnabledChannelsAfterID(lastID int, batchSize int) ([]*model.Channel, error) {
+ var channels []*model.Channel
+ query := model.DB.
+ Select("id", "name", "type", "key", "status", "base_url", "models", "settings", "setting", "other", "group", "priority", "weight", "tag", "channel_info", "header_override").
+ Where("status = ?", common.ChannelStatusEnabled).
+ Order("id asc").
+ Limit(batchSize)
+ if lastID > 0 {
+ query = query.Where("id > ?", lastID)
+ }
+ return channels, query.Find(&channels).Error
+}
+
+func ApplyAllChannelUpstreamModelUpdates(c *gin.Context) {
+ results := make([]applyAllChannelUpstreamModelUpdatesResult, 0)
+ failed := make([]int, 0)
+ refreshNeeded := false
+ addedModelCount := 0
+ removedModelCount := 0
+
+ lastID := 0
+ for {
+ channels, err := findEnabledChannelsAfterID(lastID, channelUpstreamModelUpdateTaskBatchSize)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if len(channels) == 0 {
+ break
+ }
+ lastID = channels[len(channels)-1].Id
+
+ for _, channel := range channels {
+ if channel == nil {
+ continue
+ }
+
+ settings := channel.GetOtherSettings()
+ if !settings.UpstreamModelUpdateCheckEnabled {
+ continue
+ }
+
+ pendingAddModels, pendingRemoveModels := collectPendingApplyUpstreamModelChanges(settings)
+ if len(pendingAddModels) == 0 && len(pendingRemoveModels) == 0 {
+ continue
+ }
+
+ addedModels, removedModels, remainingModels, remainingRemoveModels, modelsChanged, err := applyChannelUpstreamModelUpdates(
+ channel,
+ pendingAddModels,
+ nil,
+ pendingRemoveModels,
+ )
+ if err != nil {
+ failed = append(failed, channel.Id)
+ continue
+ }
+ if modelsChanged {
+ refreshNeeded = true
+ }
+ addedModelCount += len(addedModels)
+ removedModelCount += len(removedModels)
+ results = append(results, applyAllChannelUpstreamModelUpdatesResult{
+ ChannelID: channel.Id,
+ ChannelName: channel.Name,
+ AddedModels: addedModels,
+ RemovedModels: removedModels,
+ RemainingModels: remainingModels,
+ RemainingRemoveModels: remainingRemoveModels,
+ })
+ }
+
+ if len(channels) < channelUpstreamModelUpdateTaskBatchSize {
+ break
+ }
+ }
+
+ if refreshNeeded {
+ refreshChannelRuntimeCache()
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "processed_channels": len(results),
+ "added_models": addedModelCount,
+ "removed_models": removedModelCount,
+ "failed_channel_ids": failed,
+ "results": results,
+ },
+ })
+}
+
+func DetectAllChannelUpstreamModelUpdates(c *gin.Context) {
+ results := make([]detectChannelUpstreamModelUpdatesResult, 0)
+ failed := make([]int, 0)
+ detectedAddCount := 0
+ detectedRemoveCount := 0
+ refreshNeeded := false
+
+ lastID := 0
+ for {
+ channels, err := findEnabledChannelsAfterID(lastID, channelUpstreamModelUpdateTaskBatchSize)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if len(channels) == 0 {
+ break
+ }
+ lastID = channels[len(channels)-1].Id
+
+ for _, channel := range channels {
+ if channel == nil {
+ continue
+ }
+ settings := channel.GetOtherSettings()
+ if !settings.UpstreamModelUpdateCheckEnabled {
+ continue
+ }
+
+ modelsChanged, autoAdded, err := checkAndPersistChannelUpstreamModelUpdates(channel, &settings, true, false)
+ if err != nil {
+ failed = append(failed, channel.Id)
+ continue
+ }
+ if modelsChanged {
+ refreshNeeded = true
+ }
+
+ addModels := normalizeModelNames(settings.UpstreamModelUpdateLastDetectedModels)
+ removeModels := normalizeModelNames(settings.UpstreamModelUpdateLastRemovedModels)
+ detectedAddCount += len(addModels)
+ detectedRemoveCount += len(removeModels)
+ results = append(results, detectChannelUpstreamModelUpdatesResult{
+ ChannelID: channel.Id,
+ ChannelName: channel.Name,
+ AddModels: addModels,
+ RemoveModels: removeModels,
+ LastCheckTime: settings.UpstreamModelUpdateLastCheckTime,
+ AutoAddedModels: autoAdded,
+ })
+ }
+
+ if len(channels) < channelUpstreamModelUpdateTaskBatchSize {
+ break
+ }
+ }
+
+ if refreshNeeded {
+ refreshChannelRuntimeCache()
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "processed_channels": len(results),
+ "failed_channel_ids": failed,
+ "detected_add_models": detectedAddCount,
+ "detected_remove_models": detectedRemoveCount,
+ "channel_detected_results": results,
+ },
+ })
+}
diff --git a/controller/channel_upstream_update_test.go b/controller/channel_upstream_update_test.go
new file mode 100644
index 0000000000..52de830b9a
--- /dev/null
+++ b/controller/channel_upstream_update_test.go
@@ -0,0 +1,179 @@
+package controller
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNormalizeModelNames(t *testing.T) {
+ result := normalizeModelNames([]string{
+ " gpt-4o ",
+ "",
+ "gpt-4o",
+ "gpt-4.1",
+ " ",
+ })
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1"}, result)
+}
+
+func TestMergeModelNames(t *testing.T) {
+ result := mergeModelNames(
+ []string{"gpt-4o", "gpt-4.1"},
+ []string{"gpt-4.1", " gpt-4.1-mini ", "gpt-4o"},
+ )
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1", "gpt-4.1-mini"}, result)
+}
+
+func TestSubtractModelNames(t *testing.T) {
+ result := subtractModelNames(
+ []string{"gpt-4o", "gpt-4.1", "gpt-4.1-mini"},
+ []string{"gpt-4.1", "not-exists"},
+ )
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1-mini"}, result)
+}
+
+func TestIntersectModelNames(t *testing.T) {
+ result := intersectModelNames(
+ []string{"gpt-4o", "gpt-4.1", "gpt-4.1", "not-exists"},
+ []string{"gpt-4.1", "gpt-4o-mini", "gpt-4o"},
+ )
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1"}, result)
+}
+
+func TestApplySelectedModelChanges(t *testing.T) {
+ t.Run("add and remove together", func(t *testing.T) {
+ result := applySelectedModelChanges(
+ []string{"gpt-4o", "gpt-4.1", "claude-3"},
+ []string{"gpt-4.1-mini"},
+ []string{"claude-3"},
+ )
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1", "gpt-4.1-mini"}, result)
+ })
+
+ t.Run("add wins when conflict with remove", func(t *testing.T) {
+ result := applySelectedModelChanges(
+ []string{"gpt-4o"},
+ []string{"gpt-4.1"},
+ []string{"gpt-4.1"},
+ )
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1"}, result)
+ })
+}
+
+func TestCollectPendingApplyUpstreamModelChanges(t *testing.T) {
+ settings := dto.ChannelOtherSettings{
+ UpstreamModelUpdateLastDetectedModels: []string{" gpt-4o ", "gpt-4o", "gpt-4.1"},
+ UpstreamModelUpdateLastRemovedModels: []string{" old-model ", "", "old-model"},
+ }
+
+ pendingAddModels, pendingRemoveModels := collectPendingApplyUpstreamModelChanges(settings)
+
+ require.Equal(t, []string{"gpt-4o", "gpt-4.1"}, pendingAddModels)
+ require.Equal(t, []string{"old-model"}, pendingRemoveModels)
+}
+
+func TestNormalizeChannelModelMapping(t *testing.T) {
+ modelMapping := `{
+ " alias-model ": " upstream-model ",
+ "": "invalid",
+ "invalid-target": ""
+ }`
+ channel := &model.Channel{
+ ModelMapping: &modelMapping,
+ }
+
+ result := normalizeChannelModelMapping(channel)
+ require.Equal(t, map[string]string{
+ "alias-model": "upstream-model",
+ }, result)
+}
+
+func TestCollectPendingUpstreamModelChangesFromModels_WithModelMapping(t *testing.T) {
+ pendingAddModels, pendingRemoveModels := collectPendingUpstreamModelChangesFromModels(
+ []string{"alias-model", "gpt-4o", "stale-model"},
+ []string{"gpt-4o", "gpt-4.1", "mapped-target"},
+ []string{"gpt-4.1"},
+ map[string]string{
+ "alias-model": "mapped-target",
+ },
+ )
+
+ require.Equal(t, []string{}, pendingAddModels)
+ require.Equal(t, []string{"stale-model"}, pendingRemoveModels)
+}
+
+func TestCollectPendingUpstreamModelChangesFromModels_WithIgnoredRegexPatterns(t *testing.T) {
+ pendingAddModels, pendingRemoveModels := collectPendingUpstreamModelChangesFromModels(
+ []string{"gpt-4o"},
+ []string{"gpt-4o", "claude-3-5-sonnet", "sora-video", "gpt-4.1"},
+ []string{"regex:^sora-.*$", "gpt-4.1"},
+ nil,
+ )
+
+ require.Equal(t, []string{"claude-3-5-sonnet"}, pendingAddModels)
+ require.Equal(t, []string{}, pendingRemoveModels)
+}
+
+func TestBuildUpstreamModelUpdateTaskNotificationContent_OmitOverflowDetails(t *testing.T) {
+ channelSummaries := make([]upstreamModelUpdateChannelSummary, 0, 12)
+ for i := 0; i < 12; i++ {
+ channelSummaries = append(channelSummaries, upstreamModelUpdateChannelSummary{
+ ChannelName: "channel-" + string(rune('A'+i)),
+ AddCount: i + 1,
+ RemoveCount: i,
+ })
+ }
+
+ content := buildUpstreamModelUpdateTaskNotificationContent(
+ 24,
+ 12,
+ 56,
+ 21,
+ 9,
+ []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
+ channelSummaries,
+ []string{
+ "gpt-4.1", "gpt-4.1-mini", "o3", "o4-mini", "gemini-2.5-pro", "claude-3.7-sonnet",
+ "qwen-max", "deepseek-r1", "llama-3.3-70b", "mistral-large", "command-r-plus", "doubao-pro-32k",
+ "hunyuan-large",
+ },
+ []string{
+ "gpt-3.5-turbo", "claude-2.1", "gemini-1.5-pro", "mixtral-8x7b", "qwen-plus", "glm-4",
+ "yi-large", "moonshot-v1", "doubao-lite",
+ },
+ )
+
+ require.Contains(t, content, "其余 4 个渠道已省略")
+ require.Contains(t, content, "其余 1 个已省略")
+ require.Contains(t, content, "失败渠道 ID(展示 10/12)")
+ require.Contains(t, content, "其余 2 个已省略")
+}
+
+func TestShouldSendUpstreamModelUpdateNotification(t *testing.T) {
+ channelUpstreamModelUpdateNotifyState.Lock()
+ channelUpstreamModelUpdateNotifyState.lastNotifiedAt = 0
+ channelUpstreamModelUpdateNotifyState.lastChangedChannels = 0
+ channelUpstreamModelUpdateNotifyState.lastFailedChannels = 0
+ channelUpstreamModelUpdateNotifyState.Unlock()
+
+ baseTime := int64(2000000)
+
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime, 6, 0))
+ require.False(t, shouldSendUpstreamModelUpdateNotification(baseTime+3600, 6, 0))
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime+3600, 7, 0))
+ require.False(t, shouldSendUpstreamModelUpdateNotification(baseTime+7200, 7, 0))
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime+8000, 0, 3))
+ require.False(t, shouldSendUpstreamModelUpdateNotification(baseTime+9000, 0, 3))
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime+10000, 0, 4))
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime+90000, 7, 0))
+ require.True(t, shouldSendUpstreamModelUpdateNotification(baseTime+90001, 0, 0))
+}
diff --git a/controller/codex_oauth.go b/controller/codex_oauth.go
index 3c881ebb53..de9743ab78 100644
--- a/controller/codex_oauth.go
+++ b/controller/codex_oauth.go
@@ -132,7 +132,8 @@ func completeCodexOAuthWithChannelID(c *gin.Context, channelID int) {
code, state, err := parseCodexAuthorizationInput(req.Input)
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to parse codex authorization input: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "解析授权信息失败,请检查输入格式"})
return
}
if strings.TrimSpace(code) == "" {
@@ -144,6 +145,7 @@ func completeCodexOAuthWithChannelID(c *gin.Context, channelID int) {
return
}
+ channelProxy := ""
if channelID > 0 {
ch, err := model.GetChannelById(channelID, false)
if err != nil {
@@ -158,6 +160,7 @@ func completeCodexOAuthWithChannelID(c *gin.Context, channelID int) {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "channel type is not Codex"})
return
}
+ channelProxy = ch.GetSetting().Proxy
}
session := sessions.Default(c)
@@ -175,9 +178,10 @@ func completeCodexOAuthWithChannelID(c *gin.Context, channelID int) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
defer cancel()
- tokenRes, err := service.ExchangeCodexAuthorizationCode(ctx, code, verifier)
+ tokenRes, err := service.ExchangeCodexAuthorizationCodeWithProxy(ctx, code, verifier, channelProxy)
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to exchange codex authorization code: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "授权码交换失败,请重试"})
return
}
diff --git a/controller/codex_usage.go b/controller/codex_usage.go
index 61614b4605..52fdbdf6fb 100644
--- a/controller/codex_usage.go
+++ b/controller/codex_usage.go
@@ -2,7 +2,6 @@ package controller
import (
"context"
- "encoding/json"
"fmt"
"net/http"
"strconv"
@@ -45,7 +44,8 @@ func GetCodexChannelUsage(c *gin.Context) {
oauthKey, err := codex.ParseOAuthKey(strings.TrimSpace(ch.Key))
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to parse oauth key: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "解析凭证失败,请检查渠道配置"})
return
}
accessToken := strings.TrimSpace(oauthKey.AccessToken)
@@ -70,7 +70,8 @@ func GetCodexChannelUsage(c *gin.Context) {
statusCode, body, err := service.FetchCodexWhamUsage(ctx, client, ch.GetBaseURL(), accessToken, accountID)
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to fetch codex usage: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取用量信息失败,请稍后重试"})
return
}
@@ -78,7 +79,7 @@ func GetCodexChannelUsage(c *gin.Context) {
refreshCtx, refreshCancel := context.WithTimeout(c.Request.Context(), 10*time.Second)
defer refreshCancel()
- res, refreshErr := service.RefreshCodexOAuthToken(refreshCtx, oauthKey.RefreshToken)
+ res, refreshErr := service.RefreshCodexOAuthTokenWithProxy(refreshCtx, oauthKey.RefreshToken, ch.GetSetting().Proxy)
if refreshErr == nil {
oauthKey.AccessToken = res.AccessToken
oauthKey.RefreshToken = res.RefreshToken
@@ -99,14 +100,15 @@ func GetCodexChannelUsage(c *gin.Context) {
defer cancel2()
statusCode, body, err = service.FetchCodexWhamUsage(ctx2, client, ch.GetBaseURL(), oauthKey.AccessToken, accountID)
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to fetch codex usage after refresh: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取用量信息失败,请稍后重试"})
return
}
}
}
var payload any
- if json.Unmarshal(body, &payload) != nil {
+ if common.Unmarshal(body, &payload) != nil {
payload = string(body)
}
diff --git a/controller/console_migrate.go b/controller/console_migrate.go
index 011ab09d43..4584961047 100644
--- a/controller/console_migrate.go
+++ b/controller/console_migrate.go
@@ -17,7 +17,8 @@ func MigrateConsoleSetting(c *gin.Context) {
// 读取全部 option
opts, err := model.AllOption()
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to get all options: " + err.Error())
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "获取配置失败,请稍后重试"})
return
}
// 建立 map
diff --git a/controller/custom_oauth.go b/controller/custom_oauth.go
new file mode 100644
index 0000000000..c21ec7910b
--- /dev/null
+++ b/controller/custom_oauth.go
@@ -0,0 +1,584 @@
+package controller
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/oauth"
+ "github.com/gin-gonic/gin"
+)
+
+// CustomOAuthProviderResponse is the response structure for custom OAuth providers
+// It excludes sensitive fields like client_secret
+type CustomOAuthProviderResponse struct {
+ Id int `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Icon string `json:"icon"`
+ Enabled bool `json:"enabled"`
+ ClientId string `json:"client_id"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ UserInfoEndpoint string `json:"user_info_endpoint"`
+ Scopes string `json:"scopes"`
+ UserIdField string `json:"user_id_field"`
+ UsernameField string `json:"username_field"`
+ DisplayNameField string `json:"display_name_field"`
+ EmailField string `json:"email_field"`
+ WellKnown string `json:"well_known"`
+ AuthStyle int `json:"auth_style"`
+ AccessPolicy string `json:"access_policy"`
+ AccessDeniedMessage string `json:"access_denied_message"`
+}
+
+type UserOAuthBindingResponse struct {
+ ProviderId int `json:"provider_id"`
+ ProviderName string `json:"provider_name"`
+ ProviderSlug string `json:"provider_slug"`
+ ProviderIcon string `json:"provider_icon"`
+ ProviderUserId string `json:"provider_user_id"`
+}
+
+func toCustomOAuthProviderResponse(p *model.CustomOAuthProvider) *CustomOAuthProviderResponse {
+ return &CustomOAuthProviderResponse{
+ Id: p.Id,
+ Name: p.Name,
+ Slug: p.Slug,
+ Icon: p.Icon,
+ Enabled: p.Enabled,
+ ClientId: p.ClientId,
+ AuthorizationEndpoint: p.AuthorizationEndpoint,
+ TokenEndpoint: p.TokenEndpoint,
+ UserInfoEndpoint: p.UserInfoEndpoint,
+ Scopes: p.Scopes,
+ UserIdField: p.UserIdField,
+ UsernameField: p.UsernameField,
+ DisplayNameField: p.DisplayNameField,
+ EmailField: p.EmailField,
+ WellKnown: p.WellKnown,
+ AuthStyle: p.AuthStyle,
+ AccessPolicy: p.AccessPolicy,
+ AccessDeniedMessage: p.AccessDeniedMessage,
+ }
+}
+
+// GetCustomOAuthProviders returns all custom OAuth providers
+func GetCustomOAuthProviders(c *gin.Context) {
+ providers, err := model.GetAllCustomOAuthProviders()
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ response := make([]*CustomOAuthProviderResponse, len(providers))
+ for i, p := range providers {
+ response[i] = toCustomOAuthProviderResponse(p)
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": response,
+ })
+}
+
+// GetCustomOAuthProvider returns a single custom OAuth provider by ID
+func GetCustomOAuthProvider(c *gin.Context) {
+ idStr := c.Param("id")
+ id, err := strconv.Atoi(idStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "无效的 ID")
+ return
+ }
+
+ provider, err := model.GetCustomOAuthProviderById(id)
+ if err != nil {
+ common.ApiErrorMsg(c, "未找到该 OAuth 提供商")
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": toCustomOAuthProviderResponse(provider),
+ })
+}
+
+// CreateCustomOAuthProviderRequest is the request structure for creating a custom OAuth provider
+type CreateCustomOAuthProviderRequest struct {
+ Name string `json:"name" binding:"required"`
+ Slug string `json:"slug" binding:"required"`
+ Icon string `json:"icon"`
+ Enabled bool `json:"enabled"`
+ ClientId string `json:"client_id" binding:"required"`
+ ClientSecret string `json:"client_secret" binding:"required"`
+ AuthorizationEndpoint string `json:"authorization_endpoint" binding:"required"`
+ TokenEndpoint string `json:"token_endpoint" binding:"required"`
+ UserInfoEndpoint string `json:"user_info_endpoint" binding:"required"`
+ Scopes string `json:"scopes"`
+ UserIdField string `json:"user_id_field"`
+ UsernameField string `json:"username_field"`
+ DisplayNameField string `json:"display_name_field"`
+ EmailField string `json:"email_field"`
+ WellKnown string `json:"well_known"`
+ AuthStyle int `json:"auth_style"`
+ AccessPolicy string `json:"access_policy"`
+ AccessDeniedMessage string `json:"access_denied_message"`
+}
+
+type FetchCustomOAuthDiscoveryRequest struct {
+ WellKnownURL string `json:"well_known_url"`
+ IssuerURL string `json:"issuer_url"`
+}
+
+// FetchCustomOAuthDiscovery fetches OIDC discovery document via backend (root-only route)
+func FetchCustomOAuthDiscovery(c *gin.Context) {
+ var req FetchCustomOAuthDiscoveryRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "无效的请求参数: "+err.Error())
+ return
+ }
+
+ wellKnownURL := strings.TrimSpace(req.WellKnownURL)
+ issuerURL := strings.TrimSpace(req.IssuerURL)
+
+ if wellKnownURL == "" && issuerURL == "" {
+ common.ApiErrorMsg(c, "请先填写 Discovery URL 或 Issuer URL")
+ return
+ }
+
+ targetURL := wellKnownURL
+ if targetURL == "" {
+ targetURL = strings.TrimRight(issuerURL, "/") + "/.well-known/openid-configuration"
+ }
+ targetURL = strings.TrimSpace(targetURL)
+
+ parsedURL, err := url.Parse(targetURL)
+ if err != nil || parsedURL.Host == "" || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
+ common.ApiErrorMsg(c, "Discovery URL 无效,仅支持 http/https")
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(c.Request.Context(), 20*time.Second)
+ defer cancel()
+
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
+ if err != nil {
+ common.ApiErrorMsg(c, "创建 Discovery 请求失败: "+err.Error())
+ return
+ }
+ httpReq.Header.Set("Accept", "application/json")
+
+ client := &http.Client{Timeout: 20 * time.Second}
+ resp, err := client.Do(httpReq)
+ if err != nil {
+ common.ApiErrorMsg(c, "获取 Discovery 配置失败: "+err.Error())
+ return
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ message := strings.TrimSpace(string(body))
+ if message == "" {
+ message = resp.Status
+ }
+ common.ApiErrorMsg(c, "获取 Discovery 配置失败: "+message)
+ return
+ }
+
+ var discovery map[string]any
+ if err = common.DecodeJson(resp.Body, &discovery); err != nil {
+ common.ApiErrorMsg(c, "解析 Discovery 配置失败: "+err.Error())
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": gin.H{
+ "well_known_url": targetURL,
+ "discovery": discovery,
+ },
+ })
+}
+
+// CreateCustomOAuthProvider creates a new custom OAuth provider
+func CreateCustomOAuthProvider(c *gin.Context) {
+ var req CreateCustomOAuthProviderRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "无效的请求参数: "+err.Error())
+ return
+ }
+
+ // Check if slug is already taken
+ if model.IsSlugTaken(req.Slug, 0) {
+ common.ApiErrorMsg(c, "该 Slug 已被使用")
+ return
+ }
+
+ // Check if slug conflicts with built-in providers
+ if oauth.IsProviderRegistered(req.Slug) && !oauth.IsCustomProvider(req.Slug) {
+ common.ApiErrorMsg(c, "该 Slug 与内置 OAuth 提供商冲突")
+ return
+ }
+
+ provider := &model.CustomOAuthProvider{
+ Name: req.Name,
+ Slug: req.Slug,
+ Icon: req.Icon,
+ Enabled: req.Enabled,
+ ClientId: req.ClientId,
+ ClientSecret: req.ClientSecret,
+ AuthorizationEndpoint: req.AuthorizationEndpoint,
+ TokenEndpoint: req.TokenEndpoint,
+ UserInfoEndpoint: req.UserInfoEndpoint,
+ Scopes: req.Scopes,
+ UserIdField: req.UserIdField,
+ UsernameField: req.UsernameField,
+ DisplayNameField: req.DisplayNameField,
+ EmailField: req.EmailField,
+ WellKnown: req.WellKnown,
+ AuthStyle: req.AuthStyle,
+ AccessPolicy: req.AccessPolicy,
+ AccessDeniedMessage: req.AccessDeniedMessage,
+ }
+
+ if err := model.CreateCustomOAuthProvider(provider); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ // Register the provider in the OAuth registry
+ oauth.RegisterOrUpdateCustomProvider(provider)
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "创建成功",
+ "data": toCustomOAuthProviderResponse(provider),
+ })
+}
+
+// UpdateCustomOAuthProviderRequest is the request structure for updating a custom OAuth provider
+type UpdateCustomOAuthProviderRequest struct {
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Icon *string `json:"icon"` // Optional: if nil, keep existing
+ Enabled *bool `json:"enabled"` // Optional: if nil, keep existing
+ ClientId string `json:"client_id"`
+ ClientSecret string `json:"client_secret"` // Optional: if empty, keep existing
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ UserInfoEndpoint string `json:"user_info_endpoint"`
+ Scopes string `json:"scopes"`
+ UserIdField string `json:"user_id_field"`
+ UsernameField string `json:"username_field"`
+ DisplayNameField string `json:"display_name_field"`
+ EmailField string `json:"email_field"`
+ WellKnown *string `json:"well_known"` // Optional: if nil, keep existing
+ AuthStyle *int `json:"auth_style"` // Optional: if nil, keep existing
+ AccessPolicy *string `json:"access_policy"` // Optional: if nil, keep existing
+ AccessDeniedMessage *string `json:"access_denied_message"` // Optional: if nil, keep existing
+}
+
+// UpdateCustomOAuthProvider updates an existing custom OAuth provider
+func UpdateCustomOAuthProvider(c *gin.Context) {
+ idStr := c.Param("id")
+ id, err := strconv.Atoi(idStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "无效的 ID")
+ return
+ }
+
+ var req UpdateCustomOAuthProviderRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "无效的请求参数: "+err.Error())
+ return
+ }
+
+ // Get existing provider
+ provider, err := model.GetCustomOAuthProviderById(id)
+ if err != nil {
+ common.ApiErrorMsg(c, "未找到该 OAuth 提供商")
+ return
+ }
+
+ oldSlug := provider.Slug
+
+ // Check if new slug is taken by another provider
+ if req.Slug != "" && req.Slug != provider.Slug {
+ if model.IsSlugTaken(req.Slug, id) {
+ common.ApiErrorMsg(c, "该 Slug 已被使用")
+ return
+ }
+ // Check if slug conflicts with built-in providers
+ if oauth.IsProviderRegistered(req.Slug) && !oauth.IsCustomProvider(req.Slug) {
+ common.ApiErrorMsg(c, "该 Slug 与内置 OAuth 提供商冲突")
+ return
+ }
+ }
+
+ // Update fields
+ if req.Name != "" {
+ provider.Name = req.Name
+ }
+ if req.Slug != "" {
+ provider.Slug = req.Slug
+ }
+ if req.Icon != nil {
+ provider.Icon = *req.Icon
+ }
+ if req.Enabled != nil {
+ provider.Enabled = *req.Enabled
+ }
+ if req.ClientId != "" {
+ provider.ClientId = req.ClientId
+ }
+ if req.ClientSecret != "" {
+ provider.ClientSecret = req.ClientSecret
+ }
+ if req.AuthorizationEndpoint != "" {
+ provider.AuthorizationEndpoint = req.AuthorizationEndpoint
+ }
+ if req.TokenEndpoint != "" {
+ provider.TokenEndpoint = req.TokenEndpoint
+ }
+ if req.UserInfoEndpoint != "" {
+ provider.UserInfoEndpoint = req.UserInfoEndpoint
+ }
+ if req.Scopes != "" {
+ provider.Scopes = req.Scopes
+ }
+ if req.UserIdField != "" {
+ provider.UserIdField = req.UserIdField
+ }
+ if req.UsernameField != "" {
+ provider.UsernameField = req.UsernameField
+ }
+ if req.DisplayNameField != "" {
+ provider.DisplayNameField = req.DisplayNameField
+ }
+ if req.EmailField != "" {
+ provider.EmailField = req.EmailField
+ }
+ if req.WellKnown != nil {
+ provider.WellKnown = *req.WellKnown
+ }
+ if req.AuthStyle != nil {
+ provider.AuthStyle = *req.AuthStyle
+ }
+ if req.AccessPolicy != nil {
+ provider.AccessPolicy = *req.AccessPolicy
+ }
+ if req.AccessDeniedMessage != nil {
+ provider.AccessDeniedMessage = *req.AccessDeniedMessage
+ }
+
+ if err := model.UpdateCustomOAuthProvider(provider); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ // Update the provider in the OAuth registry
+ if oldSlug != provider.Slug {
+ oauth.UnregisterCustomProvider(oldSlug)
+ }
+ oauth.RegisterOrUpdateCustomProvider(provider)
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "更新成功",
+ "data": toCustomOAuthProviderResponse(provider),
+ })
+}
+
+// DeleteCustomOAuthProvider deletes a custom OAuth provider
+func DeleteCustomOAuthProvider(c *gin.Context) {
+ idStr := c.Param("id")
+ id, err := strconv.Atoi(idStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "无效的 ID")
+ return
+ }
+
+ // Get existing provider to get slug
+ provider, err := model.GetCustomOAuthProviderById(id)
+ if err != nil {
+ common.ApiErrorMsg(c, "未找到该 OAuth 提供商")
+ return
+ }
+
+ // Check if there are any user bindings
+ count, err := model.GetBindingCountByProviderId(id)
+ if err != nil {
+ common.SysError("Failed to get binding count for provider " + strconv.Itoa(id) + ": " + err.Error())
+ common.ApiErrorMsg(c, "检查用户绑定时发生错误,请稍后重试")
+ return
+ }
+ if count > 0 {
+ common.ApiErrorMsg(c, "该 OAuth 提供商还有用户绑定,无法删除。请先解除所有用户绑定。")
+ return
+ }
+
+ if err := model.DeleteCustomOAuthProvider(id); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ // Unregister the provider from the OAuth registry
+ oauth.UnregisterCustomProvider(provider.Slug)
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "删除成功",
+ })
+}
+
+func buildUserOAuthBindingsResponse(userId int) ([]UserOAuthBindingResponse, error) {
+ bindings, err := model.GetUserOAuthBindingsByUserId(userId)
+ if err != nil {
+ return nil, err
+ }
+
+ response := make([]UserOAuthBindingResponse, 0, len(bindings))
+ for _, binding := range bindings {
+ provider, err := model.GetCustomOAuthProviderById(binding.ProviderId)
+ if err != nil {
+ continue
+ }
+ response = append(response, UserOAuthBindingResponse{
+ ProviderId: binding.ProviderId,
+ ProviderName: provider.Name,
+ ProviderSlug: provider.Slug,
+ ProviderIcon: provider.Icon,
+ ProviderUserId: binding.ProviderUserId,
+ })
+ }
+
+ return response, nil
+}
+
+// GetUserOAuthBindings returns all OAuth bindings for the current user
+func GetUserOAuthBindings(c *gin.Context) {
+ userId := c.GetInt("id")
+ if userId == 0 {
+ common.ApiErrorMsg(c, "未登录")
+ return
+ }
+
+ response, err := buildUserOAuthBindingsResponse(userId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": response,
+ })
+}
+
+func GetUserOAuthBindingsByAdmin(c *gin.Context) {
+ userIdStr := c.Param("id")
+ userId, err := strconv.Atoi(userIdStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "invalid user id")
+ return
+ }
+
+ targetUser, err := model.GetUserById(userId, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ myRole := c.GetInt("role")
+ if myRole <= targetUser.Role && myRole != common.RoleRootUser {
+ common.ApiErrorMsg(c, "no permission")
+ return
+ }
+
+ response, err := buildUserOAuthBindingsResponse(userId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": response,
+ })
+}
+
+// UnbindCustomOAuth unbinds a custom OAuth provider from the current user
+func UnbindCustomOAuth(c *gin.Context) {
+ userId := c.GetInt("id")
+ if userId == 0 {
+ common.ApiErrorMsg(c, "未登录")
+ return
+ }
+
+ providerIdStr := c.Param("provider_id")
+ providerId, err := strconv.Atoi(providerIdStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "无效的提供商 ID")
+ return
+ }
+
+ if err := model.DeleteUserOAuthBinding(userId, providerId); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "解绑成功",
+ })
+}
+
+func UnbindCustomOAuthByAdmin(c *gin.Context) {
+ userIdStr := c.Param("id")
+ userId, err := strconv.Atoi(userIdStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "invalid user id")
+ return
+ }
+
+ targetUser, err := model.GetUserById(userId, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ myRole := c.GetInt("role")
+ if myRole <= targetUser.Role && myRole != common.RoleRootUser {
+ common.ApiErrorMsg(c, "no permission")
+ return
+ }
+
+ providerIdStr := c.Param("provider_id")
+ providerId, err := strconv.Atoi(providerIdStr)
+ if err != nil {
+ common.ApiErrorMsg(c, "invalid provider id")
+ return
+ }
+
+ if err := model.DeleteUserOAuthBinding(userId, providerId); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "success",
+ })
+}
diff --git a/controller/log.go b/controller/log.go
index da9bca468a..cf3825f16d 100644
--- a/controller/log.go
+++ b/controller/log.go
@@ -20,7 +20,8 @@ func GetAllLogs(c *gin.Context) {
modelName := c.Query("model_name")
channel, _ := strconv.Atoi(c.Query("channel"))
group := c.Query("group")
- logs, total, err := model.GetAllLogs(logType, startTimestamp, endTimestamp, modelName, username, tokenName, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), channel, group)
+ requestId := c.Query("request_id")
+ logs, total, err := model.GetAllLogs(logType, startTimestamp, endTimestamp, modelName, username, tokenName, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), channel, group, requestId)
if err != nil {
common.ApiError(c, err)
return
@@ -40,7 +41,8 @@ func GetUserLogs(c *gin.Context) {
tokenName := c.Query("token_name")
modelName := c.Query("model_name")
group := c.Query("group")
- logs, total, err := model.GetUserLogs(userId, logType, startTimestamp, endTimestamp, modelName, tokenName, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), group)
+ requestId := c.Query("request_id")
+ logs, total, err := model.GetUserLogs(userId, logType, startTimestamp, endTimestamp, modelName, tokenName, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), group, requestId)
if err != nil {
common.ApiError(c, err)
return
@@ -51,40 +53,32 @@ func GetUserLogs(c *gin.Context) {
return
}
+// Deprecated: SearchAllLogs 已废弃,前端未使用该接口。
func SearchAllLogs(c *gin.Context) {
- keyword := c.Query("keyword")
- logs, err := model.SearchAllLogs(keyword)
- if err != nil {
- common.ApiError(c, err)
- return
- }
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": logs,
+ "success": false,
+ "message": "该接口已废弃",
})
- return
}
+// Deprecated: SearchUserLogs 已废弃,前端未使用该接口。
func SearchUserLogs(c *gin.Context) {
- keyword := c.Query("keyword")
- userId := c.GetInt("id")
- logs, err := model.SearchUserLogs(userId, keyword)
- if err != nil {
- common.ApiError(c, err)
- return
- }
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": logs,
+ "success": false,
+ "message": "该接口已废弃",
})
- return
}
func GetLogByKey(c *gin.Context) {
- key := c.Query("key")
- logs, err := model.GetLogByKey(key)
+ tokenId := c.GetInt("token_id")
+ if tokenId == 0 {
+ c.JSON(200, gin.H{
+ "success": false,
+ "message": "无效的令牌",
+ })
+ return
+ }
+ logs, err := model.GetLogByTokenId(tokenId)
if err != nil {
c.JSON(200, gin.H{
"success": false,
@@ -108,7 +102,11 @@ func GetLogsStat(c *gin.Context) {
modelName := c.Query("model_name")
channel, _ := strconv.Atoi(c.Query("channel"))
group := c.Query("group")
- stat := model.SumUsedQuota(logType, startTimestamp, endTimestamp, modelName, username, tokenName, channel, group)
+ stat, err := model.SumUsedQuota(logType, startTimestamp, endTimestamp, modelName, username, tokenName, channel, group)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
//tokenNum := model.SumUsedToken(logType, startTimestamp, endTimestamp, modelName, username, "")
c.JSON(http.StatusOK, gin.H{
"success": true,
@@ -131,7 +129,11 @@ func GetLogsSelfStat(c *gin.Context) {
modelName := c.Query("model_name")
channel, _ := strconv.Atoi(c.Query("channel"))
group := c.Query("group")
- quotaNum := model.SumUsedQuota(logType, startTimestamp, endTimestamp, modelName, username, tokenName, channel, group)
+ quotaNum, err := model.SumUsedQuota(logType, startTimestamp, endTimestamp, modelName, username, tokenName, channel, group)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
//tokenNum := model.SumUsedToken(logType, startTimestamp, endTimestamp, modelName, username, tokenName)
c.JSON(200, gin.H{
"success": true,
diff --git a/controller/midjourney.go b/controller/midjourney.go
index c480c12bb9..69aa5ccd43 100644
--- a/controller/midjourney.go
+++ b/controller/midjourney.go
@@ -105,13 +105,13 @@ func UpdateMidjourneyTaskBulk() {
}
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
- logger.LogError(ctx, fmt.Sprintf("Get Task parse body error: %v", err))
+ logger.LogError(ctx, fmt.Sprintf("Get Mjp Task parse body error: %v", err))
continue
}
var responseItems []dto.MidjourneyDto
err = json.Unmarshal(responseBody, &responseItems)
if err != nil {
- logger.LogError(ctx, fmt.Sprintf("Get Task parse body error2: %v, body: %s", err, string(responseBody)))
+ logger.LogError(ctx, fmt.Sprintf("Get Mjp Task parse body error2: %v, body: %s", err, string(responseBody)))
continue
}
resp.Body.Close()
@@ -130,6 +130,7 @@ func UpdateMidjourneyTaskBulk() {
if !checkMjTaskNeedUpdate(task, responseItem) {
continue
}
+ preStatus := task.Status
task.Code = 1
task.Progress = responseItem.Progress
task.PromptEn = responseItem.PromptEn
@@ -172,18 +173,26 @@ func UpdateMidjourneyTaskBulk() {
shouldReturnQuota = true
}
}
- err = task.Update()
+ won, err := task.UpdateWithStatus(preStatus)
if err != nil {
logger.LogError(ctx, "UpdateMidjourneyTask task error: "+err.Error())
- } else {
- if shouldReturnQuota {
- err = model.IncreaseUserQuota(task.UserId, task.Quota, false)
- if err != nil {
- logger.LogError(ctx, "fail to increase user quota: "+err.Error())
- }
- logContent := fmt.Sprintf("构图失败 %s,补偿 %s", task.MjId, logger.LogQuota(task.Quota))
- model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
+ } else if won && shouldReturnQuota {
+ err = model.IncreaseUserQuota(task.UserId, task.Quota, false)
+ if err != nil {
+ logger.LogError(ctx, "fail to increase user quota: "+err.Error())
}
+ model.RecordTaskBillingLog(model.RecordTaskBillingLogParams{
+ UserId: task.UserId,
+ LogType: model.LogTypeRefund,
+ Content: "",
+ ChannelId: task.ChannelId,
+ ModelName: service.CovertMjpActionToModelName(task.Action),
+ Quota: task.Quota,
+ Other: map[string]interface{}{
+ "task_id": task.MjId,
+ "reason": "构图失败",
+ },
+ })
}
}
}
diff --git a/controller/misc.go b/controller/misc.go
index 4d299fc814..519caed57b 100644
--- a/controller/misc.go
+++ b/controller/misc.go
@@ -8,8 +8,10 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/oauth"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/console_setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
@@ -128,6 +130,34 @@ func GetStatus(c *gin.Context) {
data["faq"] = console_setting.GetFAQ()
}
+ // Add enabled custom OAuth providers
+ customProviders := oauth.GetEnabledCustomProviders()
+ if len(customProviders) > 0 {
+ type CustomOAuthInfo struct {
+ Id int `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Icon string `json:"icon"`
+ ClientId string `json:"client_id"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ Scopes string `json:"scopes"`
+ }
+ providersInfo := make([]CustomOAuthInfo, 0, len(customProviders))
+ for _, p := range customProviders {
+ config := p.GetConfig()
+ providersInfo = append(providersInfo, CustomOAuthInfo{
+ Id: config.Id,
+ Name: config.Name,
+ Slug: config.Slug,
+ Icon: config.Icon,
+ ClientId: config.ClientId,
+ AuthorizationEndpoint: config.AuthorizationEndpoint,
+ Scopes: config.Scopes,
+ })
+ }
+ data["custom_oauth_providers"] = providersInfo
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
@@ -278,31 +308,24 @@ func SendPasswordResetEmail(c *gin.Context) {
})
return
}
- if !model.IsEmailAlreadyTaken(email) {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "该邮箱地址未注册",
- })
- return
- }
- code := common.GenerateVerificationCode(0)
- common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
- link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
- subject := fmt.Sprintf("%s密码重置", common.SystemName)
- content := fmt.Sprintf("
您好,你正在进行%s密码重置。
"+
- "
点击 此处 进行密码重置。
"+
- "
如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开: %s
"+
- "
重置链接 %d 分钟内有效,如果不是本人操作,请忽略。
", common.SystemName, link, link, common.VerificationValidMinutes)
- err := common.SendEmail(subject, email, content)
- if err != nil {
- common.ApiError(c, err)
- return
+ if model.IsEmailAlreadyTaken(email) {
+ code := common.GenerateVerificationCode(0)
+ common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
+ link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
+ subject := fmt.Sprintf("%s密码重置", common.SystemName)
+ content := fmt.Sprintf("
您好,你正在进行%s密码重置。
"+
+ "
点击 此处 进行密码重置。
"+
+ "
如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开: %s
"+
+ "
重置链接 %d 分钟内有效,如果不是本人操作,请忽略。
", common.SystemName, link, link, common.VerificationValidMinutes)
+ err := common.SendEmail(subject, email, content)
+ if err != nil {
+ logger.LogError(c.Request.Context(), fmt.Sprintf("failed to send password reset email to %s: %s", email, err.Error()))
+ }
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
})
- return
}
type PasswordResetRequest struct {
diff --git a/controller/model_meta.go b/controller/model_meta.go
index 2b0634a860..fd3626442a 100644
--- a/controller/model_meta.go
+++ b/controller/model_meta.go
@@ -13,66 +13,27 @@ import (
"github.com/gin-gonic/gin"
)
-// parseModelID 解析并验证模型ID
-func parseModelID(c *gin.Context) (int, error) {
- idStr := c.Param("id")
- return strconv.Atoi(idStr)
-}
-
-// checkModelNameDuplicate 检查模型名称是否重复,返回错误消息
-func checkModelNameDuplicate(id int, name string) string {
- if name == "" {
- return "模型名称不能为空"
- }
- if dup, err := model.IsModelNameDuplicated(id, name); err != nil {
- return err.Error()
- } else if dup {
- return "模型名称已存在"
- }
- return ""
-}
-
// GetAllModelsMeta 获取模型列表(分页)
func GetAllModelsMeta(c *gin.Context) {
- pageInfo := common.GetPageQuery(c)
- status := c.Query("status")
- syncOfficial := c.Query("sync_official")
- modelsMeta, total, err := model.GetAllModels(pageInfo.GetStartIdx(), pageInfo.GetPageSize(), status, syncOfficial)
+ pageInfo := common.GetPageQuery(c)
+ modelsMeta, err := model.GetAllModels(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
if err != nil {
common.ApiError(c, err)
return
}
+ // 批量填充附加字段,提升列表接口性能
+ enrichModels(modelsMeta)
+ var total int64
+ model.DB.Model(&model.Model{}).Count(&total)
- respondWithModels(c, modelsMeta, total, pageInfo, status, syncOfficial)
-}
-
-// SearchModelsMeta 搜索模型列表
-func SearchModelsMeta(c *gin.Context) {
- keyword := c.Query("keyword")
- vendor := c.Query("vendor")
- status := c.Query("status")
- syncOfficial := c.Query("sync_official")
- pageInfo := common.GetPageQuery(c)
-
- modelsMeta, total, err := model.SearchModels(keyword, vendor, status, syncOfficial, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- respondWithModels(c, modelsMeta, total, pageInfo, status, syncOfficial)
-}
-
-// respondWithModels 统一处理模型列表响应
-func respondWithModels(c *gin.Context, models []*model.Model, total int64, pageInfo *common.PageInfo, status, syncOfficial string) {
- enrichModels(models)
- vendorCounts, _ := model.GetVendorModelCounts(status, syncOfficial)
+ // 统计供应商计数(全部数据,不受分页影响)
+ vendorCounts, _ := model.GetVendorModelCounts()
pageInfo.SetTotal(int(total))
- pageInfo.SetItems(models)
+ pageInfo.SetItems(modelsMeta)
common.ApiSuccess(c, gin.H{
- "items": models,
+ "items": modelsMeta,
"total": total,
"page": pageInfo.GetPage(),
"page_size": pageInfo.GetPageSize(),
@@ -80,9 +41,29 @@ func respondWithModels(c *gin.Context, models []*model.Model, total int64, pageI
})
}
+// SearchModelsMeta 搜索模型列表
+func SearchModelsMeta(c *gin.Context) {
+
+ keyword := c.Query("keyword")
+ vendor := c.Query("vendor")
+ pageInfo := common.GetPageQuery(c)
+
+ modelsMeta, total, err := model.SearchModels(keyword, vendor, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ // 批量填充附加字段,提升列表接口性能
+ enrichModels(modelsMeta)
+ pageInfo.SetTotal(int(total))
+ pageInfo.SetItems(modelsMeta)
+ common.ApiSuccess(c, pageInfo)
+}
+
// GetModelMeta 根据 ID 获取单条模型信息
func GetModelMeta(c *gin.Context) {
- id, err := parseModelID(c)
+ idStr := c.Param("id")
+ id, err := strconv.Atoi(idStr)
if err != nil {
common.ApiError(c, err)
return
@@ -103,10 +84,16 @@ func CreateModelMeta(c *gin.Context) {
common.ApiError(c, err)
return
}
-
- // 验证模型名称
- if errMsg := checkModelNameDuplicate(0, m.ModelName); errMsg != "" {
- common.ApiErrorMsg(c, errMsg)
+ if m.ModelName == "" {
+ common.ApiErrorMsg(c, "模型名称不能为空")
+ return
+ }
+ // 名称冲突检查
+ if dup, err := model.IsModelNameDuplicated(0, m.ModelName); err != nil {
+ common.ApiError(c, err)
+ return
+ } else if dup {
+ common.ApiErrorMsg(c, "模型名称已存在")
return
}
@@ -139,9 +126,12 @@ func UpdateModelMeta(c *gin.Context) {
return
}
} else {
- // 验证模型名称
- if errMsg := checkModelNameDuplicate(m.Id, m.ModelName); errMsg != "" {
- common.ApiErrorMsg(c, errMsg)
+ // 名称冲突检查
+ if dup, err := model.IsModelNameDuplicated(m.Id, m.ModelName); err != nil {
+ common.ApiError(c, err)
+ return
+ } else if dup {
+ common.ApiErrorMsg(c, "模型名称已存在")
return
}
@@ -156,7 +146,8 @@ func UpdateModelMeta(c *gin.Context) {
// DeleteModelMeta 删除模型
func DeleteModelMeta(c *gin.Context) {
- id, err := parseModelID(c)
+ idStr := c.Param("id")
+ id, err := strconv.Atoi(idStr)
if err != nil {
common.ApiError(c, err)
return
@@ -175,23 +166,10 @@ func enrichModels(models []*model.Model) {
return
}
- exactNames, exactIdx, ruleIndices := classifyModels(models)
-
- // 处理精确匹配模型
- enrichExactModels(models, exactNames, exactIdx)
-
- // 处理规则匹配模型
- if len(ruleIndices) > 0 {
- enrichRuleModels(models, ruleIndices)
- }
-}
-
-// classifyModels 将模型分类为精确匹配和规则匹配
-func classifyModels(models []*model.Model) ([]string, map[string][]int, []int) {
+ // 1) 拆分精确与规则匹配
exactNames := make([]string, 0)
- exactIdx := make(map[string][]int)
+ exactIdx := make(map[string][]int) // modelName -> indices in models
ruleIndices := make([]int, 0)
-
for i, m := range models {
if m == nil {
continue
@@ -204,17 +182,10 @@ func classifyModels(models []*model.Model) ([]string, map[string][]int, []int) {
}
}
- return exactNames, exactIdx, ruleIndices
-}
-
-// enrichExactModels 填充精确匹配模型的信息
-func enrichExactModels(models []*model.Model, exactNames []string, exactIdx map[string][]int) {
- if len(exactNames) == 0 {
- return
- }
-
+ // 2) 批量查询精确模型的绑定渠道
channelsByModel, _ := model.GetBoundChannelsByModelsMap(exactNames)
+ // 3) 精确模型:端点从缓存、渠道批量映射、分组/计费类型从缓存
for name, indices := range exactIdx {
chs := channelsByModel[name]
for _, idx := range indices {
@@ -230,30 +201,15 @@ func enrichExactModels(models []*model.Model, exactNames []string, exactIdx map[
mm.QuotaTypes = model.GetModelQuotaTypes(mm.ModelName)
}
}
-}
-// enrichRuleModels 填充规则匹配模型的信息
-func enrichRuleModels(models []*model.Model, ruleIndices []int) {
+ if len(ruleIndices) == 0 {
+ return
+ }
+
+ // 4) 一次性读取定价缓存,内存匹配所有规则模型
pricings := model.GetPricing()
- // 收集匹配信息
- matchedNamesByIdx, endpointSetByIdx, groupSetByIdx, quotaSetByIdx := collectRuleMatches(models, ruleIndices, pricings)
-
- // 批量查询渠道信息
- allMatched := extractAllMatchedNames(matchedNamesByIdx)
- matchedChannelsByModel, _ := model.GetBoundChannelsByModelsMap(allMatched)
-
- // 回填模型信息
- fillRuleModelData(models, ruleIndices, matchedNamesByIdx, endpointSetByIdx, groupSetByIdx, quotaSetByIdx, matchedChannelsByModel)
-}
-
-// collectRuleMatches 收集规则模型的匹配信息
-func collectRuleMatches(models []*model.Model, ruleIndices []int, pricings []model.Pricing) (
- map[int][]string,
- map[int]map[constant.EndpointType]struct{},
- map[int]map[string]struct{},
- map[int]map[int]struct{},
-) {
+ // 为全部规则模型收集匹配名集合、端点并集、分组并集、配额集合
matchedNamesByIdx := make(map[int][]string)
endpointSetByIdx := make(map[int]map[constant.EndpointType]struct{})
groupSetByIdx := make(map[int]map[string]struct{})
@@ -262,80 +218,65 @@ func collectRuleMatches(models []*model.Model, ruleIndices []int, pricings []mod
for _, p := range pricings {
for _, idx := range ruleIndices {
mm := models[idx]
- if !matchNameRule(p.ModelName, mm.ModelName, mm.NameRule) {
+ var matched bool
+ switch mm.NameRule {
+ case model.NameRulePrefix:
+ matched = strings.HasPrefix(p.ModelName, mm.ModelName)
+ case model.NameRuleSuffix:
+ matched = strings.HasSuffix(p.ModelName, mm.ModelName)
+ case model.NameRuleContains:
+ matched = strings.Contains(p.ModelName, mm.ModelName)
+ }
+ if !matched {
continue
}
-
matchedNamesByIdx[idx] = append(matchedNamesByIdx[idx], p.ModelName)
- if endpointSetByIdx[idx] == nil {
- endpointSetByIdx[idx] = make(map[constant.EndpointType]struct{})
+ es := endpointSetByIdx[idx]
+ if es == nil {
+ es = make(map[constant.EndpointType]struct{})
+ endpointSetByIdx[idx] = es
}
for _, et := range p.SupportedEndpointTypes {
- endpointSetByIdx[idx][et] = struct{}{}
+ es[et] = struct{}{}
}
- if groupSetByIdx[idx] == nil {
- groupSetByIdx[idx] = make(map[string]struct{})
+ gs := groupSetByIdx[idx]
+ if gs == nil {
+ gs = make(map[string]struct{})
+ groupSetByIdx[idx] = gs
}
for _, g := range p.EnableGroup {
- groupSetByIdx[idx][g] = struct{}{}
+ gs[g] = struct{}{}
}
- if quotaSetByIdx[idx] == nil {
- quotaSetByIdx[idx] = make(map[int]struct{})
+ qs := quotaSetByIdx[idx]
+ if qs == nil {
+ qs = make(map[int]struct{})
+ quotaSetByIdx[idx] = qs
}
- quotaSetByIdx[idx][p.QuotaType] = struct{}{}
+ qs[p.QuotaType] = struct{}{}
}
}
- return matchedNamesByIdx, endpointSetByIdx, groupSetByIdx, quotaSetByIdx
-}
-
-// matchNameRule 根据规则匹配模型名称
-func matchNameRule(pricingModel, modelName string, nameRule int) bool {
- switch nameRule {
- case model.NameRulePrefix:
- return strings.HasPrefix(pricingModel, modelName)
- case model.NameRuleSuffix:
- return strings.HasSuffix(pricingModel, modelName)
- case model.NameRuleContains:
- return strings.Contains(pricingModel, modelName)
- default:
- return false
- }
-}
-
-// extractAllMatchedNames 提取所有匹配的模型名称
-func extractAllMatchedNames(matchedNamesByIdx map[int][]string) []string {
+ // 5) 汇总所有匹配到的模型名称,批量查询一次渠道
allMatchedSet := make(map[string]struct{})
for _, names := range matchedNamesByIdx {
for _, n := range names {
allMatchedSet[n] = struct{}{}
}
}
-
allMatched := make([]string, 0, len(allMatchedSet))
for n := range allMatchedSet {
allMatched = append(allMatched, n)
}
- return allMatched
-}
+ matchedChannelsByModel, _ := model.GetBoundChannelsByModelsMap(allMatched)
-// fillRuleModelData 回填规则模型的数据
-func fillRuleModelData(
- models []*model.Model,
- ruleIndices []int,
- matchedNamesByIdx map[int][]string,
- endpointSetByIdx map[int]map[constant.EndpointType]struct{},
- groupSetByIdx map[int]map[string]struct{},
- quotaSetByIdx map[int]map[int]struct{},
- matchedChannelsByModel map[string][]model.BoundChannel,
-) {
+ // 6) 回填每个规则模型的并集信息
for _, idx := range ruleIndices {
mm := models[idx]
- // 填充端点
+ // 端点并集 -> 序列化
if es, ok := endpointSetByIdx[idx]; ok && mm.Endpoints == "" {
eps := make([]constant.EndpointType, 0, len(es))
for et := range es {
@@ -346,7 +287,7 @@ func fillRuleModelData(
}
}
- // 填充分组
+ // 分组并集
if gs, ok := groupSetByIdx[idx]; ok {
groups := make([]string, 0, len(gs))
for g := range gs {
@@ -355,7 +296,7 @@ func fillRuleModelData(
mm.EnableGroups = groups
}
- // 填充配额类型
+ // 配额类型集合(保持去重并排序)
if qs, ok := quotaSetByIdx[idx]; ok {
arr := make([]int, 0, len(qs))
for k := range qs {
@@ -365,7 +306,7 @@ func fillRuleModelData(
mm.QuotaTypes = arr
}
- // 填充渠道
+ // 渠道并集
names := matchedNamesByIdx[idx]
channelSet := make(map[string]model.BoundChannel)
for _, n := range names {
@@ -382,7 +323,7 @@ func fillRuleModelData(
mm.BoundChannels = chs
}
- // 填充匹配信息
+ // 匹配信息
mm.MatchedModels = names
mm.MatchedCount = len(names)
}
diff --git a/controller/model_sync.go b/controller/model_sync.go
index 737f92d400..f254dc88ee 100644
--- a/controller/model_sync.go
+++ b/controller/model_sync.go
@@ -29,7 +29,7 @@ const (
func normalizeLocale(locale string) (string, bool) {
l := strings.ToLower(strings.TrimSpace(locale))
switch l {
- case "en", "zh", "ja":
+ case "en", "zh-CN", "zh-TW", "ja":
return l, true
default:
return "", false
@@ -272,7 +272,8 @@ func SyncUpstreamModels(c *gin.Context) {
// 1) 获取未配置模型列表
missing, err := model.GetMissingModels()
if err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to get missing models: " + err.Error())
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取模型列表失败,请稍后重试"})
return
}
diff --git a/controller/oauth.go b/controller/oauth.go
new file mode 100644
index 0000000000..9951f22b03
--- /dev/null
+++ b/controller/oauth.go
@@ -0,0 +1,362 @@
+package controller
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/oauth"
+ "github.com/gin-contrib/sessions"
+ "github.com/gin-gonic/gin"
+ "gorm.io/gorm"
+)
+
+// providerParams returns map with Provider key for i18n templates
+func providerParams(name string) map[string]any {
+ return map[string]any{"Provider": name}
+}
+
+// GenerateOAuthCode generates a state code for OAuth CSRF protection
+func GenerateOAuthCode(c *gin.Context) {
+ session := sessions.Default(c)
+ state := common.GetRandomString(12)
+ affCode := c.Query("aff")
+ if affCode != "" {
+ session.Set("aff", affCode)
+ }
+ session.Set("oauth_state", state)
+ err := session.Save()
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": state,
+ })
+}
+
+// HandleOAuth handles OAuth callback for all standard OAuth providers
+func HandleOAuth(c *gin.Context) {
+ providerName := c.Param("provider")
+ provider := oauth.GetProvider(providerName)
+ if provider == nil {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "message": i18n.T(c, i18n.MsgOAuthUnknownProvider),
+ })
+ return
+ }
+
+ session := sessions.Default(c)
+
+ // 1. Validate state (CSRF protection)
+ state := c.Query("state")
+ if state == "" || session.Get("oauth_state") == nil || state != session.Get("oauth_state").(string) {
+ c.JSON(http.StatusForbidden, gin.H{
+ "success": false,
+ "message": i18n.T(c, i18n.MsgOAuthStateInvalid),
+ })
+ return
+ }
+
+ // 2. Check if user is already logged in (bind flow)
+ username := session.Get("username")
+ if username != nil {
+ handleOAuthBind(c, provider)
+ return
+ }
+
+ // 3. Check if provider is enabled
+ if !provider.IsEnabled() {
+ common.ApiErrorI18n(c, i18n.MsgOAuthNotEnabled, providerParams(provider.GetName()))
+ return
+ }
+
+ // 4. Handle error from provider
+ errorCode := c.Query("error")
+ if errorCode != "" {
+ errorDescription := c.Query("error_description")
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": errorDescription,
+ })
+ return
+ }
+
+ // 5. Exchange code for token
+ code := c.Query("code")
+ token, err := provider.ExchangeToken(c.Request.Context(), code, c)
+ if err != nil {
+ handleOAuthError(c, err)
+ return
+ }
+
+ // 6. Get user info
+ oauthUser, err := provider.GetUserInfo(c.Request.Context(), token)
+ if err != nil {
+ handleOAuthError(c, err)
+ return
+ }
+
+ // 7. Find or create user
+ user, err := findOrCreateOAuthUser(c, provider, oauthUser, session)
+ if err != nil {
+ switch err.(type) {
+ case *OAuthUserDeletedError:
+ common.ApiErrorI18n(c, i18n.MsgOAuthUserDeleted)
+ case *OAuthRegistrationDisabledError:
+ common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
+ default:
+ common.ApiError(c, err)
+ }
+ return
+ }
+
+ // 8. Check user status
+ if user.Status != common.UserStatusEnabled {
+ common.ApiErrorI18n(c, i18n.MsgOAuthUserBanned)
+ return
+ }
+
+ // 9. Setup login
+ setupLogin(user, c)
+}
+
+// handleOAuthBind handles binding OAuth account to existing user
+func handleOAuthBind(c *gin.Context, provider oauth.Provider) {
+ if !provider.IsEnabled() {
+ common.ApiErrorI18n(c, i18n.MsgOAuthNotEnabled, providerParams(provider.GetName()))
+ return
+ }
+
+ // Exchange code for token
+ code := c.Query("code")
+ token, err := provider.ExchangeToken(c.Request.Context(), code, c)
+ if err != nil {
+ handleOAuthError(c, err)
+ return
+ }
+
+ // Get user info
+ oauthUser, err := provider.GetUserInfo(c.Request.Context(), token)
+ if err != nil {
+ handleOAuthError(c, err)
+ return
+ }
+
+ // Check if this OAuth account is already bound (check both new ID and legacy ID)
+ if provider.IsUserIDTaken(oauthUser.ProviderUserID) {
+ common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
+ return
+ }
+ // Also check legacy ID to prevent duplicate bindings during migration period
+ if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" {
+ if provider.IsUserIDTaken(legacyID) {
+ common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
+ return
+ }
+ }
+
+ // Get current user from session
+ session := sessions.Default(c)
+ id := session.Get("id")
+ user := model.User{Id: id.(int)}
+ err = user.FillUserById()
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ // Handle binding based on provider type
+ if genericProvider, ok := provider.(*oauth.GenericOAuthProvider); ok {
+ // Custom provider: use user_oauth_bindings table
+ err = model.UpdateUserOAuthBinding(user.Id, genericProvider.GetProviderId(), oauthUser.ProviderUserID)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ } else {
+ // Built-in provider: update user record directly
+ provider.SetProviderUserID(&user, oauthUser.ProviderUserID)
+ err = user.Update(false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ }
+
+ common.ApiSuccessI18n(c, i18n.MsgOAuthBindSuccess, gin.H{
+ "action": "bind",
+ })
+}
+
+// findOrCreateOAuthUser finds existing user or creates new user
+func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, session sessions.Session) (*model.User, error) {
+ user := &model.User{}
+
+ // Check if user already exists with new ID
+ if provider.IsUserIDTaken(oauthUser.ProviderUserID) {
+ err := provider.FillUserByProviderID(user, oauthUser.ProviderUserID)
+ if err != nil {
+ return nil, err
+ }
+ // Check if user has been deleted
+ if user.Id == 0 {
+ return nil, &OAuthUserDeletedError{}
+ }
+ return user, nil
+ }
+
+ // Try to find user with legacy ID (for GitHub migration from login to numeric ID)
+ if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" {
+ if provider.IsUserIDTaken(legacyID) {
+ err := provider.FillUserByProviderID(user, legacyID)
+ if err != nil {
+ return nil, err
+ }
+ if user.Id != 0 {
+ // Found user with legacy ID, migrate to new ID
+ common.SysLog(fmt.Sprintf("[OAuth] Migrating user %d from legacy_id=%s to new_id=%s",
+ user.Id, legacyID, oauthUser.ProviderUserID))
+ if err := user.UpdateGitHubId(oauthUser.ProviderUserID); err != nil {
+ common.SysError(fmt.Sprintf("[OAuth] Failed to migrate user %d: %s", user.Id, err.Error()))
+ // Continue with login even if migration fails
+ }
+ return user, nil
+ }
+ }
+ }
+
+ // User doesn't exist, create new user if registration is enabled
+ if !common.RegisterEnabled {
+ return nil, &OAuthRegistrationDisabledError{}
+ }
+
+ // Set up new user
+ user.Username = provider.GetProviderPrefix() + strconv.Itoa(model.GetMaxUserId()+1)
+
+ if oauthUser.Username != "" {
+ if exists, err := model.CheckUserExistOrDeleted(oauthUser.Username, ""); err == nil && !exists {
+ // 防止索引退化
+ if len(oauthUser.Username) <= model.UserNameMaxLength {
+ user.Username = oauthUser.Username
+ }
+ }
+ }
+
+ if oauthUser.DisplayName != "" {
+ user.DisplayName = oauthUser.DisplayName
+ } else if oauthUser.Username != "" {
+ user.DisplayName = oauthUser.Username
+ } else {
+ user.DisplayName = provider.GetName() + " User"
+ }
+ if oauthUser.Email != "" {
+ user.Email = oauthUser.Email
+ }
+ user.Role = common.RoleCommonUser
+ user.Status = common.UserStatusEnabled
+
+ // Handle affiliate code
+ affCode := session.Get("aff")
+ inviterId := 0
+ if affCode != nil {
+ inviterId, _ = model.GetUserIdByAffCode(affCode.(string))
+ }
+
+ // Use transaction to ensure user creation and OAuth binding are atomic
+ if genericProvider, ok := provider.(*oauth.GenericOAuthProvider); ok {
+ // Custom provider: create user and binding in a transaction
+ err := model.DB.Transaction(func(tx *gorm.DB) error {
+ // Create user
+ if err := user.InsertWithTx(tx, inviterId); err != nil {
+ return err
+ }
+
+ // Create OAuth binding
+ binding := &model.UserOAuthBinding{
+ UserId: user.Id,
+ ProviderId: genericProvider.GetProviderId(),
+ ProviderUserId: oauthUser.ProviderUserID,
+ }
+ if err := model.CreateUserOAuthBindingWithTx(tx, binding); err != nil {
+ return err
+ }
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Perform post-transaction tasks (logs, sidebar config, inviter rewards)
+ user.FinalizeOAuthUserCreation(inviterId)
+ } else {
+ // Built-in provider: create user and update provider ID in a transaction
+ err := model.DB.Transaction(func(tx *gorm.DB) error {
+ // Create user
+ if err := user.InsertWithTx(tx, inviterId); err != nil {
+ return err
+ }
+
+ // Set the provider user ID on the user model and update
+ provider.SetProviderUserID(user, oauthUser.ProviderUserID)
+ if err := tx.Model(user).Updates(map[string]interface{}{
+ "github_id": user.GitHubId,
+ "discord_id": user.DiscordId,
+ "oidc_id": user.OidcId,
+ "linux_do_id": user.LinuxDOId,
+ "wechat_id": user.WeChatId,
+ "telegram_id": user.TelegramId,
+ }).Error; err != nil {
+ return err
+ }
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Perform post-transaction tasks
+ user.FinalizeOAuthUserCreation(inviterId)
+ }
+
+ return user, nil
+}
+
+// Error types for OAuth
+type OAuthUserDeletedError struct{}
+
+func (e *OAuthUserDeletedError) Error() string {
+ return "user has been deleted"
+}
+
+type OAuthRegistrationDisabledError struct{}
+
+func (e *OAuthRegistrationDisabledError) Error() string {
+ return "registration is disabled"
+}
+
+// handleOAuthError handles OAuth errors and returns translated message
+func handleOAuthError(c *gin.Context, err error) {
+ switch e := err.(type) {
+ case *oauth.OAuthError:
+ if e.Params != nil {
+ common.ApiErrorI18n(c, e.MsgKey, e.Params)
+ } else {
+ common.ApiErrorI18n(c, e.MsgKey)
+ }
+ case *oauth.AccessDeniedError:
+ common.ApiErrorMsg(c, e.Message)
+ case *oauth.TrustLevelError:
+ common.ApiErrorI18n(c, i18n.MsgOAuthTrustLevelLow)
+ default:
+ common.ApiError(c, err)
+ }
+}
diff --git a/controller/option.go b/controller/option.go
index 959f2f9b8f..ecb1e25e86 100644
--- a/controller/option.go
+++ b/controller/option.go
@@ -1,7 +1,6 @@
package controller
import (
- "encoding/json"
"fmt"
"net/http"
"strings"
@@ -17,10 +16,56 @@ import (
"github.com/gin-gonic/gin"
)
+var completionRatioMetaOptionKeys = []string{
+ "ModelPrice",
+ "ModelRatio",
+ "CompletionRatio",
+ "CacheRatio",
+ "CreateCacheRatio",
+ "ImageRatio",
+ "AudioRatio",
+ "AudioCompletionRatio",
+}
+
+func collectModelNamesFromOptionValue(raw string, modelNames map[string]struct{}) {
+ if strings.TrimSpace(raw) == "" {
+ return
+ }
+
+ var parsed map[string]any
+ if err := common.UnmarshalJsonStr(raw, &parsed); err != nil {
+ return
+ }
+
+ for modelName := range parsed {
+ modelNames[modelName] = struct{}{}
+ }
+}
+
+func buildCompletionRatioMetaValue(optionValues map[string]string) string {
+ modelNames := make(map[string]struct{})
+ for _, key := range completionRatioMetaOptionKeys {
+ collectModelNamesFromOptionValue(optionValues[key], modelNames)
+ }
+
+ meta := make(map[string]ratio_setting.CompletionRatioInfo, len(modelNames))
+ for modelName := range modelNames {
+ meta[modelName] = ratio_setting.GetCompletionRatioInfo(modelName)
+ }
+
+ jsonBytes, err := common.Marshal(meta)
+ if err != nil {
+ return "{}"
+ }
+ return string(jsonBytes)
+}
+
func GetOptions(c *gin.Context) {
var options []*model.Option
+ optionValues := make(map[string]string)
common.OptionMapRWMutex.Lock()
for k, v := range common.OptionMap {
+ value := common.Interface2String(v)
if strings.HasSuffix(k, "Token") ||
strings.HasSuffix(k, "Secret") ||
strings.HasSuffix(k, "Key") ||
@@ -30,10 +75,20 @@ func GetOptions(c *gin.Context) {
}
options = append(options, &model.Option{
Key: k,
- Value: common.Interface2String(v),
+ Value: value,
})
+ for _, optionKey := range completionRatioMetaOptionKeys {
+ if optionKey == k {
+ optionValues[k] = value
+ break
+ }
+ }
}
common.OptionMapRWMutex.Unlock()
+ options = append(options, &model.Option{
+ Key: "CompletionRatioMeta",
+ Value: buildCompletionRatioMetaValue(optionValues),
+ })
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
@@ -49,7 +104,7 @@ type OptionUpdateRequest struct {
func UpdateOption(c *gin.Context) {
var option OptionUpdateRequest
- err := json.NewDecoder(c.Request.Body).Decode(&option)
+ err := common.DecodeJson(c.Request.Body, &option)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
@@ -169,6 +224,15 @@ func UpdateOption(c *gin.Context) {
})
return
}
+ case "CreateCacheRatio":
+ err = ratio_setting.UpdateCreateCacheRatioByJSONString(option.Value.(string))
+ if err != nil {
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": "缓存创建倍率设置失败: " + err.Error(),
+ })
+ return
+ }
case "ModelRequestRateLimitGroup":
err = setting.CheckModelRequestRateLimitGroup(option.Value.(string))
if err != nil {
diff --git a/controller/passkey.go b/controller/passkey.go
index a2cc53699b..d37fb9f735 100644
--- a/controller/passkey.go
+++ b/controller/passkey.go
@@ -470,6 +470,15 @@ func PasskeyVerifyFinish(c *gin.Context) {
return
}
+ session := sessions.Default(c)
+ // Mark passkey as ready; /api/verify will convert this into the final secure verification session.
+ session.Set(PasskeyReadySessionKey, time.Now().Unix())
+ session.Delete(SecureVerificationSessionKey)
+ if err := session.Save(); err != nil {
+ common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Passkey 验证成功",
diff --git a/controller/performance.go b/controller/performance.go
new file mode 100644
index 0000000000..69324475cd
--- /dev/null
+++ b/controller/performance.go
@@ -0,0 +1,385 @@
+package controller
+
+import (
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/gin-gonic/gin"
+)
+
+// PerformanceStats 性能统计信息
+type PerformanceStats struct {
+ // 缓存统计
+ CacheStats common.DiskCacheStats `json:"cache_stats"`
+ // 系统内存统计
+ MemoryStats MemoryStats `json:"memory_stats"`
+ // 磁盘缓存目录信息
+ DiskCacheInfo DiskCacheInfo `json:"disk_cache_info"`
+ // 磁盘空间信息
+ DiskSpaceInfo common.DiskSpaceInfo `json:"disk_space_info"`
+ // 配置信息
+ Config PerformanceConfig `json:"config"`
+}
+
+// MemoryStats 内存统计
+type MemoryStats struct {
+ // 已分配内存(字节)
+ Alloc uint64 `json:"alloc"`
+ // 总分配内存(字节)
+ TotalAlloc uint64 `json:"total_alloc"`
+ // 系统内存(字节)
+ Sys uint64 `json:"sys"`
+ // GC 次数
+ NumGC uint32 `json:"num_gc"`
+ // Goroutine 数量
+ NumGoroutine int `json:"num_goroutine"`
+}
+
+// DiskCacheInfo 磁盘缓存目录信息
+type DiskCacheInfo struct {
+ // 缓存目录路径
+ Path string `json:"path"`
+ // 目录是否存在
+ Exists bool `json:"exists"`
+ // 文件数量
+ FileCount int `json:"file_count"`
+ // 总大小(字节)
+ TotalSize int64 `json:"total_size"`
+}
+
+// PerformanceConfig 性能配置
+type PerformanceConfig struct {
+ // 是否启用磁盘缓存
+ DiskCacheEnabled bool `json:"disk_cache_enabled"`
+ // 磁盘缓存阈值(MB)
+ DiskCacheThresholdMB int `json:"disk_cache_threshold_mb"`
+ // 磁盘缓存最大大小(MB)
+ DiskCacheMaxSizeMB int `json:"disk_cache_max_size_mb"`
+ // 磁盘缓存路径
+ DiskCachePath string `json:"disk_cache_path"`
+ // 是否在容器中运行
+ IsRunningInContainer bool `json:"is_running_in_container"`
+
+ // MonitorEnabled 是否启用性能监控
+ MonitorEnabled bool `json:"monitor_enabled"`
+ // MonitorCPUThreshold CPU 使用率阈值(%)
+ MonitorCPUThreshold int `json:"monitor_cpu_threshold"`
+ // MonitorMemoryThreshold 内存使用率阈值(%)
+ MonitorMemoryThreshold int `json:"monitor_memory_threshold"`
+ // MonitorDiskThreshold 磁盘使用率阈值(%)
+ MonitorDiskThreshold int `json:"monitor_disk_threshold"`
+}
+
+// GetPerformanceStats 获取性能统计信息
+func GetPerformanceStats(c *gin.Context) {
+ // 不再每次获取统计都全量扫描磁盘,依赖原子计数器保证性能
+ // 仅在系统启动或显式清理时同步
+ cacheStats := common.GetDiskCacheStats()
+
+ // 获取内存统计
+ var memStats runtime.MemStats
+ runtime.ReadMemStats(&memStats)
+
+ // 获取磁盘缓存目录信息
+ diskCacheInfo := getDiskCacheInfo()
+
+ // 获取配置信息
+ diskConfig := common.GetDiskCacheConfig()
+ monitorConfig := common.GetPerformanceMonitorConfig()
+ config := PerformanceConfig{
+ DiskCacheEnabled: diskConfig.Enabled,
+ DiskCacheThresholdMB: diskConfig.ThresholdMB,
+ DiskCacheMaxSizeMB: diskConfig.MaxSizeMB,
+ DiskCachePath: diskConfig.Path,
+ IsRunningInContainer: common.IsRunningInContainer(),
+ MonitorEnabled: monitorConfig.Enabled,
+ MonitorCPUThreshold: monitorConfig.CPUThreshold,
+ MonitorMemoryThreshold: monitorConfig.MemoryThreshold,
+ MonitorDiskThreshold: monitorConfig.DiskThreshold,
+ }
+
+ // 获取磁盘空间信息
+ // 使用缓存的系统状态,避免频繁调用系统 API
+ systemStatus := common.GetSystemStatus()
+ diskSpaceInfo := common.DiskSpaceInfo{
+ UsedPercent: systemStatus.DiskUsage,
+ }
+ // 如果需要详细信息,可以按需获取,或者扩展 SystemStatus
+ // 这里为了保持接口兼容性,我们仍然调用 GetDiskSpaceInfo,但注意这可能会有性能开销
+ // 考虑到 GetPerformanceStats 是管理接口,频率较低,直接调用是可以接受的
+ // 但为了一致性,我们也可以考虑从 SystemStatus 中获取部分信息
+ diskSpaceInfo = common.GetDiskSpaceInfo()
+
+ stats := PerformanceStats{
+ CacheStats: cacheStats,
+ MemoryStats: MemoryStats{
+ Alloc: memStats.Alloc,
+ TotalAlloc: memStats.TotalAlloc,
+ Sys: memStats.Sys,
+ NumGC: memStats.NumGC,
+ NumGoroutine: runtime.NumGoroutine(),
+ },
+ DiskCacheInfo: diskCacheInfo,
+ DiskSpaceInfo: diskSpaceInfo,
+ Config: config,
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": stats,
+ })
+}
+
+// ClearDiskCache 清理不活跃的磁盘缓存
+func ClearDiskCache(c *gin.Context) {
+ // 清理超过 10 分钟未使用的缓存文件
+ // 10 分钟是一个安全的阈值,确保正在进行的请求不会被误删
+ err := common.CleanupOldDiskCacheFiles(10 * time.Minute)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "不活跃的磁盘缓存已清理",
+ })
+}
+
+// ResetPerformanceStats 重置性能统计
+func ResetPerformanceStats(c *gin.Context) {
+ common.ResetDiskCacheStats()
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "统计信息已重置",
+ })
+}
+
+// ForceGC 强制执行 GC
+func ForceGC(c *gin.Context) {
+ runtime.GC()
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "GC 已执行",
+ })
+}
+
+// LogFileInfo 日志文件信息
+type LogFileInfo struct {
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+ ModTime time.Time `json:"mod_time"`
+}
+
+// LogFilesResponse 日志文件列表响应
+type LogFilesResponse struct {
+ LogDir string `json:"log_dir"`
+ Enabled bool `json:"enabled"`
+ FileCount int `json:"file_count"`
+ TotalSize int64 `json:"total_size"`
+ OldestTime *time.Time `json:"oldest_time,omitempty"`
+ NewestTime *time.Time `json:"newest_time,omitempty"`
+ Files []LogFileInfo `json:"files"`
+}
+
+// getLogFiles 读取日志目录中的日志文件列表
+func getLogFiles() ([]LogFileInfo, error) {
+ if *common.LogDir == "" {
+ return nil, nil
+ }
+ entries, err := os.ReadDir(*common.LogDir)
+ if err != nil {
+ return nil, err
+ }
+ var files []LogFileInfo
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ name := entry.Name()
+ if !strings.HasPrefix(name, "oneapi-") || !strings.HasSuffix(name, ".log") {
+ continue
+ }
+ info, err := entry.Info()
+ if err != nil {
+ continue
+ }
+ files = append(files, LogFileInfo{
+ Name: name,
+ Size: info.Size(),
+ ModTime: info.ModTime(),
+ })
+ }
+ // 按文件名降序排列(最新在前)
+ sort.Slice(files, func(i, j int) bool {
+ return files[i].Name > files[j].Name
+ })
+ return files, nil
+}
+
+// GetLogFiles 获取日志文件列表
+func GetLogFiles(c *gin.Context) {
+ if *common.LogDir == "" {
+ common.ApiSuccess(c, LogFilesResponse{Enabled: false})
+ return
+ }
+ files, err := getLogFiles()
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ var totalSize int64
+ var oldest, newest time.Time
+ for i, f := range files {
+ totalSize += f.Size
+ if i == 0 || f.ModTime.Before(oldest) {
+ oldest = f.ModTime
+ }
+ if i == 0 || f.ModTime.After(newest) {
+ newest = f.ModTime
+ }
+ }
+ resp := LogFilesResponse{
+ LogDir: *common.LogDir,
+ Enabled: true,
+ FileCount: len(files),
+ TotalSize: totalSize,
+ Files: files,
+ }
+ if len(files) > 0 {
+ resp.OldestTime = &oldest
+ resp.NewestTime = &newest
+ }
+ common.ApiSuccess(c, resp)
+}
+
+// CleanupLogFiles 清理过期日志文件
+func CleanupLogFiles(c *gin.Context) {
+ mode := c.Query("mode")
+ valueStr := c.Query("value")
+ if mode != "by_count" && mode != "by_days" {
+ common.ApiErrorMsg(c, "invalid mode, must be by_count or by_days")
+ return
+ }
+ value, err := strconv.Atoi(valueStr)
+ if err != nil || value < 1 {
+ common.ApiErrorMsg(c, "invalid value, must be a positive integer")
+ return
+ }
+ if *common.LogDir == "" {
+ common.ApiErrorMsg(c, "log directory not configured")
+ return
+ }
+
+ files, err := getLogFiles()
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ activeLogPath := logger.GetCurrentLogPath()
+ var toDelete []LogFileInfo
+
+ switch mode {
+ case "by_count":
+ // files 已按名称降序(最新在前),保留前 value 个
+ for i, f := range files {
+ if i < value {
+ continue
+ }
+ fullPath := filepath.Join(*common.LogDir, f.Name)
+ if fullPath == activeLogPath {
+ continue
+ }
+ toDelete = append(toDelete, f)
+ }
+ case "by_days":
+ cutoff := time.Now().AddDate(0, 0, -value)
+ for _, f := range files {
+ if f.ModTime.Before(cutoff) {
+ fullPath := filepath.Join(*common.LogDir, f.Name)
+ if fullPath == activeLogPath {
+ continue
+ }
+ toDelete = append(toDelete, f)
+ }
+ }
+ }
+
+ var deletedCount int
+ var freedBytes int64
+ var failedFiles []string
+ for _, f := range toDelete {
+ fullPath := filepath.Join(*common.LogDir, f.Name)
+ if err := os.Remove(fullPath); err != nil {
+ failedFiles = append(failedFiles, f.Name)
+ continue
+ }
+ deletedCount++
+ freedBytes += f.Size
+ }
+
+ result := gin.H{
+ "deleted_count": deletedCount,
+ "freed_bytes": freedBytes,
+ "failed_files": failedFiles,
+ }
+
+ if len(failedFiles) > 0 {
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": fmt.Sprintf("部分文件删除失败(%d/%d)", len(failedFiles), len(toDelete)),
+ "data": result,
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": result,
+ })
+}
+
+// getDiskCacheInfo 获取磁盘缓存目录信息
+func getDiskCacheInfo() DiskCacheInfo {
+ // 使用统一的缓存目录
+ dir := common.GetDiskCacheDir()
+
+ info := DiskCacheInfo{
+ Path: dir,
+ Exists: false,
+ }
+
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return info
+ }
+
+ info.Exists = true
+ info.FileCount = 0
+ info.TotalSize = 0
+
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ info.FileCount++
+ if fileInfo, err := entry.Info(); err == nil {
+ info.TotalSize += fileInfo.Size()
+ }
+ }
+
+ return info
+}
diff --git a/controller/pricing.go b/controller/pricing.go
index dd3f7edca3..8252327244 100644
--- a/controller/pricing.go
+++ b/controller/pricing.go
@@ -1,6 +1,7 @@
package controller
import (
+ "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/ratio_setting"
@@ -8,6 +9,30 @@ import (
"github.com/gin-gonic/gin"
)
+func filterPricingByUsableGroups(pricing []model.Pricing, usableGroup map[string]string) []model.Pricing {
+ if len(pricing) == 0 {
+ return pricing
+ }
+ if len(usableGroup) == 0 {
+ return []model.Pricing{}
+ }
+
+ filtered := make([]model.Pricing, 0, len(pricing))
+ for _, item := range pricing {
+ if common.StringsContains(item.EnableGroup, "all") {
+ filtered = append(filtered, item)
+ continue
+ }
+ for _, group := range item.EnableGroup {
+ if _, ok := usableGroup[group]; ok {
+ filtered = append(filtered, item)
+ break
+ }
+ }
+ }
+ return filtered
+}
+
func GetPricing(c *gin.Context) {
pricing := model.GetPricing()
userId, exists := c.Get("id")
@@ -31,6 +56,7 @@ func GetPricing(c *gin.Context) {
}
usableGroup = service.GetUserUsableGroups(group)
+ pricing = filterPricingByUsableGroups(pricing, usableGroup)
// check groupRatio contains usableGroup
for group := range ratio_setting.GetGroupRatioCopy() {
if _, ok := usableGroup[group]; !ok {
@@ -46,6 +72,7 @@ func GetPricing(c *gin.Context) {
"usable_group": usableGroup,
"supported_endpoint": model.GetSupportedEndpointMap(),
"auto_groups": service.GetUserAutoGroup(group),
+ "pricing_version": "a42d372ccf0b5dd13ecf71203521f9d2",
})
}
diff --git a/controller/ratio_sync.go b/controller/ratio_sync.go
index 0b6a6dff0a..8388e8af3a 100644
--- a/controller/ratio_sync.go
+++ b/controller/ratio_sync.go
@@ -1,12 +1,17 @@
package controller
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
"io"
+ "math"
"net"
"net/http"
+ "net/url"
+ "sort"
+ "strconv"
"strings"
"sync"
"time"
@@ -22,11 +27,20 @@ import (
)
const (
- defaultTimeoutSeconds = 10
- defaultEndpoint = "/api/ratio_config"
- maxConcurrentFetches = 8
- maxRatioConfigBytes = 10 << 20 // 10MB
- floatEpsilon = 1e-9
+ defaultTimeoutSeconds = 10
+ defaultEndpoint = "/api/ratio_config"
+ maxConcurrentFetches = 8
+ maxRatioConfigBytes = 10 << 20 // 10MB
+ floatEpsilon = 1e-9
+ officialRatioPresetID = -100
+ officialRatioPresetName = "官方倍率预设"
+ officialRatioPresetBaseURL = "https://basellm.github.io"
+ modelsDevPresetID = -101
+ modelsDevPresetName = "models.dev 价格预设"
+ modelsDevPresetBaseURL = "https://models.dev"
+ modelsDevHost = "models.dev"
+ modelsDevPath = "/api.json"
+ modelsDevInputCostRatioBase = 1000.0
)
func nearlyEqual(a, b float64) bool {
@@ -56,7 +70,8 @@ type upstreamResult struct {
func FetchUpstreamRatios(c *gin.Context) {
var req dto.UpstreamRequest
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()})
+ common.SysError("failed to bind upstream request: " + err.Error())
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "请求参数格式错误"})
return
}
@@ -138,9 +153,13 @@ func FetchUpstreamRatios(c *gin.Context) {
sem <- struct{}{}
defer func() { <-sem }()
+ isOpenRouter := chItem.Endpoint == "openrouter"
+
endpoint := chItem.Endpoint
var fullURL string
- if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
+ if isOpenRouter {
+ fullURL = chItem.BaseURL + "/v1/models"
+ } else if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
fullURL = endpoint
} else {
if endpoint == "" {
@@ -150,6 +169,7 @@ func FetchUpstreamRatios(c *gin.Context) {
}
fullURL = chItem.BaseURL + endpoint
}
+ isModelsDev := isModelsDevAPIEndpoint(fullURL)
uniqueName := chItem.Name
if chItem.ID != 0 {
@@ -166,6 +186,28 @@ func FetchUpstreamRatios(c *gin.Context) {
return
}
+ // OpenRouter requires Bearer token auth
+ if isOpenRouter && chItem.ID != 0 {
+ dbCh, err := model.GetChannelById(chItem.ID, true)
+ if err != nil {
+ ch <- upstreamResult{Name: uniqueName, Err: "failed to get channel key: " + err.Error()}
+ return
+ }
+ key, _, apiErr := dbCh.GetNextEnabledKey()
+ if apiErr != nil {
+ ch <- upstreamResult{Name: uniqueName, Err: "failed to get enabled channel key: " + apiErr.Error()}
+ return
+ }
+ if strings.TrimSpace(key) == "" {
+ ch <- upstreamResult{Name: uniqueName, Err: "no API key configured for this channel"}
+ return
+ }
+ httpReq.Header.Set("Authorization", "Bearer "+strings.TrimSpace(key))
+ } else if isOpenRouter {
+ ch <- upstreamResult{Name: uniqueName, Err: "OpenRouter requires a valid channel with API key"}
+ return
+ }
+
// 简单重试:最多 3 次,指数退避
var resp *http.Response
var lastErr error
@@ -193,6 +235,37 @@ func FetchUpstreamRatios(c *gin.Context) {
logger.LogWarn(c.Request.Context(), "unexpected content-type from "+chItem.Name+": "+ct)
}
limited := io.LimitReader(resp.Body, maxRatioConfigBytes)
+ bodyBytes, err := io.ReadAll(limited)
+ if err != nil {
+ logger.LogWarn(c.Request.Context(), "read response failed from "+chItem.Name+": "+err.Error())
+ ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
+ return
+ }
+
+ // type3: OpenRouter /v1/models -> convert per-token pricing to ratios
+ if isOpenRouter {
+ converted, err := convertOpenRouterToRatioData(bytes.NewReader(bodyBytes))
+ if err != nil {
+ logger.LogWarn(c.Request.Context(), "OpenRouter parse failed from "+chItem.Name+": "+err.Error())
+ ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
+ return
+ }
+ ch <- upstreamResult{Name: uniqueName, Data: converted}
+ return
+ }
+
+ // type4: models.dev /api.json -> convert provider model pricing to ratios
+ if isModelsDev {
+ converted, err := convertModelsDevToRatioData(bytes.NewReader(bodyBytes))
+ if err != nil {
+ logger.LogWarn(c.Request.Context(), "models.dev parse failed from "+chItem.Name+": "+err.Error())
+ ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
+ return
+ }
+ ch <- upstreamResult{Name: uniqueName, Data: converted}
+ return
+ }
+
// 兼容两种上游接口格式:
// type1: /api/ratio_config -> data 为 map[string]any,包含 model_ratio/completion_ratio/cache_ratio/model_price
// type2: /api/pricing -> data 为 []Pricing 列表,需要转换为与 type1 相同的 map 格式
@@ -202,7 +275,7 @@ func FetchUpstreamRatios(c *gin.Context) {
Message string `json:"message"`
}
- if err := json.NewDecoder(limited).Decode(&body); err != nil {
+ if err := common.DecodeJson(bytes.NewReader(bodyBytes), &body); err != nil {
logger.LogWarn(c.Request.Context(), "json decode failed from "+chItem.Name+": "+err.Error())
ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
return
@@ -217,7 +290,7 @@ func FetchUpstreamRatios(c *gin.Context) {
// 尝试按 type1 解析
var type1Data map[string]any
- if err := json.Unmarshal(body.Data, &type1Data); err == nil {
+ if err := common.Unmarshal(body.Data, &type1Data); err == nil {
// 如果包含至少一个 ratioTypes 字段,则认为是 type1
isType1 := false
for _, rt := range ratioTypes {
@@ -240,7 +313,7 @@ func FetchUpstreamRatios(c *gin.Context) {
ModelPrice float64 `json:"model_price"`
CompletionRatio float64 `json:"completion_ratio"`
}
- if err := json.Unmarshal(body.Data, &pricingItems); err != nil {
+ if err := common.Unmarshal(body.Data, &pricingItems); err != nil {
logger.LogWarn(c.Request.Context(), "unrecognized data format from "+chItem.Name+": "+err.Error())
ch <- upstreamResult{Name: uniqueName, Err: "无法解析上游返回数据"}
return
@@ -507,6 +580,295 @@ func buildDifferences(localData map[string]any, successfulChannels []struct {
return differences
}
+func roundRatioValue(value float64) float64 {
+ return math.Round(value*1e6) / 1e6
+}
+
+func isModelsDevAPIEndpoint(rawURL string) bool {
+ parsedURL, err := url.Parse(rawURL)
+ if err != nil {
+ return false
+ }
+ if strings.ToLower(parsedURL.Hostname()) != modelsDevHost {
+ return false
+ }
+ path := strings.TrimSuffix(parsedURL.Path, "/")
+ if path == "" {
+ path = "/"
+ }
+ return path == modelsDevPath
+}
+
+// convertOpenRouterToRatioData parses OpenRouter's /v1/models response and converts
+// per-token USD pricing into the local ratio format.
+// model_ratio = prompt_price_per_token * 1_000_000 * (USD / 1000)
+//
+// since 1 ratio unit = $0.002/1K tokens and USD=500, the factor is 500_000
+//
+// completion_ratio = completion_price / prompt_price (output/input multiplier)
+func convertOpenRouterToRatioData(reader io.Reader) (map[string]any, error) {
+ var orResp struct {
+ Data []struct {
+ ID string `json:"id"`
+ Pricing struct {
+ Prompt string `json:"prompt"`
+ Completion string `json:"completion"`
+ InputCacheRead string `json:"input_cache_read"`
+ } `json:"pricing"`
+ } `json:"data"`
+ }
+
+ if err := common.DecodeJson(reader, &orResp); err != nil {
+ return nil, fmt.Errorf("failed to decode OpenRouter response: %w", err)
+ }
+
+ modelRatioMap := make(map[string]any)
+ completionRatioMap := make(map[string]any)
+ cacheRatioMap := make(map[string]any)
+
+ for _, m := range orResp.Data {
+ promptPrice, promptErr := strconv.ParseFloat(m.Pricing.Prompt, 64)
+ completionPrice, compErr := strconv.ParseFloat(m.Pricing.Completion, 64)
+
+ if promptErr != nil && compErr != nil {
+ // Both unparseable — skip this model
+ continue
+ }
+
+ // Treat parse errors as 0
+ if promptErr != nil {
+ promptPrice = 0
+ }
+ if compErr != nil {
+ completionPrice = 0
+ }
+
+ // Negative values are sentinel values (e.g., -1 for dynamic/variable pricing) — skip
+ if promptPrice < 0 || completionPrice < 0 {
+ continue
+ }
+
+ if promptPrice == 0 && completionPrice == 0 {
+ // Free model
+ modelRatioMap[m.ID] = 0.0
+ continue
+ }
+ if promptPrice <= 0 {
+ // No meaningful prompt baseline, cannot derive ratios safely.
+ continue
+ }
+
+ // Normal case: promptPrice > 0
+ ratio := promptPrice * 1000 * ratio_setting.USD
+ ratio = roundRatioValue(ratio)
+ modelRatioMap[m.ID] = ratio
+
+ compRatio := completionPrice / promptPrice
+ compRatio = roundRatioValue(compRatio)
+ completionRatioMap[m.ID] = compRatio
+
+ // Convert input_cache_read to cache_ratio (= cache_read_price / prompt_price)
+ if m.Pricing.InputCacheRead != "" {
+ if cachePrice, err := strconv.ParseFloat(m.Pricing.InputCacheRead, 64); err == nil && cachePrice >= 0 {
+ cacheRatio := cachePrice / promptPrice
+ cacheRatio = roundRatioValue(cacheRatio)
+ cacheRatioMap[m.ID] = cacheRatio
+ }
+ }
+ }
+
+ converted := make(map[string]any)
+ if len(modelRatioMap) > 0 {
+ converted["model_ratio"] = modelRatioMap
+ }
+ if len(completionRatioMap) > 0 {
+ converted["completion_ratio"] = completionRatioMap
+ }
+ if len(cacheRatioMap) > 0 {
+ converted["cache_ratio"] = cacheRatioMap
+ }
+
+ return converted, nil
+}
+
+type modelsDevProvider struct {
+ Models map[string]modelsDevModel `json:"models"`
+}
+
+type modelsDevModel struct {
+ Cost modelsDevCost `json:"cost"`
+}
+
+type modelsDevCost struct {
+ Input *float64 `json:"input"`
+ Output *float64 `json:"output"`
+ CacheRead *float64 `json:"cache_read"`
+}
+
+type modelsDevCandidate struct {
+ Provider string
+ Input float64
+ Output *float64
+ CacheRead *float64
+}
+
+func cloneFloatPtr(v *float64) *float64 {
+ if v == nil {
+ return nil
+ }
+ out := *v
+ return &out
+}
+
+func isValidNonNegativeCost(v float64) bool {
+ if math.IsNaN(v) || math.IsInf(v, 0) {
+ return false
+ }
+ return v >= 0
+}
+
+func buildModelsDevCandidate(provider string, cost modelsDevCost) (modelsDevCandidate, bool) {
+ if cost.Input == nil {
+ return modelsDevCandidate{}, false
+ }
+
+ input := *cost.Input
+ if !isValidNonNegativeCost(input) {
+ return modelsDevCandidate{}, false
+ }
+
+ var output *float64
+ if cost.Output != nil {
+ if !isValidNonNegativeCost(*cost.Output) {
+ return modelsDevCandidate{}, false
+ }
+ output = cloneFloatPtr(cost.Output)
+ }
+
+ // input=0/output>0 cannot be transformed into local ratio.
+ if input == 0 && output != nil && *output > 0 {
+ return modelsDevCandidate{}, false
+ }
+
+ var cacheRead *float64
+ if cost.CacheRead != nil && isValidNonNegativeCost(*cost.CacheRead) {
+ cacheRead = cloneFloatPtr(cost.CacheRead)
+ }
+
+ return modelsDevCandidate{
+ Provider: provider,
+ Input: input,
+ Output: output,
+ CacheRead: cacheRead,
+ }, true
+}
+
+func shouldReplaceModelsDevCandidate(current, next modelsDevCandidate) bool {
+ currentNonZero := current.Input > 0
+ nextNonZero := next.Input > 0
+ if currentNonZero != nextNonZero {
+ // Prefer non-zero pricing data; this matches "cheapest non-zero" conflict policy.
+ return nextNonZero
+ }
+ if nextNonZero && !nearlyEqual(next.Input, current.Input) {
+ return next.Input < current.Input
+ }
+ // Stable tie-breaker for deterministic result.
+ return next.Provider < current.Provider
+}
+
+// convertModelsDevToRatioData parses models.dev /api.json and converts
+// provider pricing metadata into local ratio format.
+// models.dev costs are USD per 1M tokens:
+//
+// model_ratio = input_cost_per_1M / 2
+// completion_ratio = output_cost / input_cost
+// cache_ratio = cache_read_cost / input_cost
+//
+// Duplicate model keys across providers are resolved by selecting the
+// cheapest non-zero input cost. If only zero-priced candidates exist,
+// a zero ratio is kept.
+func convertModelsDevToRatioData(reader io.Reader) (map[string]any, error) {
+ var upstreamData map[string]modelsDevProvider
+ if err := common.DecodeJson(reader, &upstreamData); err != nil {
+ return nil, fmt.Errorf("failed to decode models.dev response: %w", err)
+ }
+ if len(upstreamData) == 0 {
+ return nil, fmt.Errorf("empty models.dev response")
+ }
+
+ providers := make([]string, 0, len(upstreamData))
+ for provider := range upstreamData {
+ providers = append(providers, provider)
+ }
+ sort.Strings(providers)
+
+ selectedCandidates := make(map[string]modelsDevCandidate)
+ for _, provider := range providers {
+ providerData := upstreamData[provider]
+ if len(providerData.Models) == 0 {
+ continue
+ }
+
+ modelNames := make([]string, 0, len(providerData.Models))
+ for modelName := range providerData.Models {
+ modelNames = append(modelNames, modelName)
+ }
+ sort.Strings(modelNames)
+
+ for _, modelName := range modelNames {
+ candidate, ok := buildModelsDevCandidate(provider, providerData.Models[modelName].Cost)
+ if !ok {
+ continue
+ }
+ current, exists := selectedCandidates[modelName]
+ if !exists || shouldReplaceModelsDevCandidate(current, candidate) {
+ selectedCandidates[modelName] = candidate
+ }
+ }
+ }
+
+ if len(selectedCandidates) == 0 {
+ return nil, fmt.Errorf("no valid models.dev pricing entries found")
+ }
+
+ modelRatioMap := make(map[string]any)
+ completionRatioMap := make(map[string]any)
+ cacheRatioMap := make(map[string]any)
+
+ for modelName, candidate := range selectedCandidates {
+ if candidate.Input == 0 {
+ modelRatioMap[modelName] = 0.0
+ continue
+ }
+
+ modelRatio := candidate.Input * float64(ratio_setting.USD) / modelsDevInputCostRatioBase
+ modelRatioMap[modelName] = roundRatioValue(modelRatio)
+
+ if candidate.Output != nil {
+ completionRatio := *candidate.Output / candidate.Input
+ completionRatioMap[modelName] = roundRatioValue(completionRatio)
+ }
+
+ if candidate.CacheRead != nil {
+ cacheRatio := *candidate.CacheRead / candidate.Input
+ cacheRatioMap[modelName] = roundRatioValue(cacheRatio)
+ }
+ }
+
+ converted := make(map[string]any)
+ if len(modelRatioMap) > 0 {
+ converted["model_ratio"] = modelRatioMap
+ }
+ if len(completionRatioMap) > 0 {
+ converted["completion_ratio"] = completionRatioMap
+ }
+ if len(cacheRatioMap) > 0 {
+ converted["cache_ratio"] = cacheRatioMap
+ }
+ return converted, nil
+}
+
func GetSyncableChannels(c *gin.Context) {
channels, err := model.GetAllChannels(0, 0, true, false)
if err != nil {
@@ -525,14 +887,22 @@ func GetSyncableChannels(c *gin.Context) {
Name: channel.Name,
BaseURL: channel.GetBaseURL(),
Status: channel.Status,
+ Type: channel.Type,
})
}
}
syncableChannels = append(syncableChannels, dto.SyncableChannel{
- ID: -100,
- Name: "官方倍率预设",
- BaseURL: "https://basellm.github.io",
+ ID: officialRatioPresetID,
+ Name: officialRatioPresetName,
+ BaseURL: officialRatioPresetBaseURL,
+ Status: 1,
+ })
+
+ syncableChannels = append(syncableChannels, dto.SyncableChannel{
+ ID: modelsDevPresetID,
+ Name: modelsDevPresetName,
+ BaseURL: modelsDevPresetBaseURL,
Status: 1,
})
diff --git a/controller/redemption.go b/controller/redemption.go
index 945cefa353..76c35bc32b 100644
--- a/controller/redemption.go
+++ b/controller/redemption.go
@@ -1,12 +1,12 @@
package controller
import (
- "errors"
"net/http"
"strconv"
"unicode/utf8"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
"github.com/gin-gonic/gin"
@@ -66,28 +66,19 @@ func AddRedemption(c *gin.Context) {
return
}
if utf8.RuneCountInString(redemption.Name) == 0 || utf8.RuneCountInString(redemption.Name) > 20 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "兑换码名称长度必须在1-20之间",
- })
+ common.ApiErrorI18n(c, i18n.MsgRedemptionNameLength)
return
}
if redemption.Count <= 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "兑换码个数必须大于0",
- })
+ common.ApiErrorI18n(c, i18n.MsgRedemptionCountPositive)
return
}
if redemption.Count > 100 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "一次兑换码批量生成的个数不能大于 100",
- })
+ common.ApiErrorI18n(c, i18n.MsgRedemptionCountMax)
return
}
- if err := validateExpiredTime(redemption.ExpiredTime); err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ if valid, msg := validateExpiredTime(c, redemption.ExpiredTime); !valid {
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": msg})
return
}
var keys []string
@@ -103,9 +94,10 @@ func AddRedemption(c *gin.Context) {
}
err = cleanRedemption.Insert()
if err != nil {
+ common.SysError("failed to insert redemption: " + err.Error())
c.JSON(http.StatusOK, gin.H{
"success": false,
- "message": err.Error(),
+ "message": i18n.T(c, i18n.MsgRedemptionCreateFailed),
"data": keys,
})
return
@@ -148,8 +140,8 @@ func UpdateRedemption(c *gin.Context) {
return
}
if statusOnly == "" {
- if err := validateExpiredTime(redemption.ExpiredTime); err != nil {
- c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
+ if valid, msg := validateExpiredTime(c, redemption.ExpiredTime); !valid {
+ c.JSON(http.StatusOK, gin.H{"success": false, "message": msg})
return
}
// If you add more fields, please also update redemption.Update()
@@ -187,9 +179,9 @@ func DeleteInvalidRedemption(c *gin.Context) {
return
}
-func validateExpiredTime(expired int64) error {
+func validateExpiredTime(c *gin.Context, expired int64) (bool, string) {
if expired != 0 && expired < common.GetTimestamp() {
- return errors.New("过期时间不能早于当前时间")
+ return false, i18n.T(c, i18n.MsgRedemptionExpireTimeInvalid)
}
- return nil
+ return true, ""
}
diff --git a/controller/relay.go b/controller/relay.go
index 4fba947f74..593b31b7ca 100644
--- a/controller/relay.go
+++ b/controller/relay.go
@@ -1,13 +1,13 @@
package controller
import (
- "bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
+ "time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
@@ -25,6 +25,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/bytedance/gopkg/util/gopool"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -45,7 +46,7 @@ func relayHandler(c *gin.Context, info *relaycommon.RelayInfo) *types.NewAPIErro
err = relay.RerankHelper(c, info)
case relayconstant.RelayModeEmbeddings:
err = relay.EmbeddingHelper(c, info)
- case relayconstant.RelayModeResponses:
+ case relayconstant.RelayModeResponses, relayconstant.RelayModeResponsesCompact:
err = relay.ResponsesHelper(c, info)
default:
err = relay.TextHelper(c, info)
@@ -159,7 +160,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
if priceData.FreeModel {
logger.LogInfo(c, fmt.Sprintf("模型 %s 免费,跳过预扣费", relayInfo.OriginModelName))
} else {
- newAPIError = service.PreConsumeQuota(c, priceData.QuotaToPreConsume, relayInfo)
+ newAPIError = service.PreConsumeBilling(c, priceData.QuotaToPreConsume, relayInfo)
if newAPIError != nil {
return
}
@@ -167,8 +168,12 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
defer func() {
// Only return quota if downstream failed and quota was actually pre-consumed
- if newAPIError != nil && relayInfo.FinalPreConsumedQuota != 0 {
- service.ReturnPreConsumedQuota(c, relayInfo)
+ if newAPIError != nil {
+ newAPIError = service.NormalizeViolationFeeError(newAPIError)
+ if relayInfo.Billing != nil {
+ relayInfo.Billing.Refund(c)
+ }
+ service.ChargeViolationFeeIfNeeded(c, relayInfo, newAPIError)
}
}()
@@ -178,8 +183,11 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
ModelName: relayInfo.OriginModelName,
Retry: common.GetPointer(0),
}
+ relayInfo.RetryIndex = 0
+ relayInfo.LastError = nil
for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
+ relayInfo.RetryIndex = retryParam.GetRetry()
channel, channelErr := getChannel(c, relayInfo, retryParam)
if channelErr != nil {
logger.LogError(c, channelErr.Error())
@@ -188,7 +196,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
addUsedChannel(c, channel.Id)
- requestBody, bodyErr := common.GetRequestBody(c)
+ bodyStorage, bodyErr := common.GetBodyStorage(c)
if bodyErr != nil {
// Ensure consistent 413 for oversized bodies even when error occurs later (e.g., retry path)
if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
@@ -198,7 +206,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
break
}
- c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
+ c.Request.Body = io.NopCloser(bodyStorage)
switch relayFormat {
case types.RelayFormatOpenAIRealtime:
@@ -212,9 +220,13 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
if newAPIError == nil {
+ relayInfo.LastError = nil
return
}
+ newAPIError = service.NormalizeViolationFeeError(newAPIError)
+ relayInfo.LastError = newAPIError
+
processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) {
@@ -251,15 +263,17 @@ func fastTokenCountMetaForPricing(request dto.Request) *types.TokenCountMeta {
}
switch r := request.(type) {
case *dto.GeneralOpenAIRequest:
- if r.MaxCompletionTokens > r.MaxTokens {
- meta.MaxTokens = int(r.MaxCompletionTokens)
+ maxCompletionTokens := lo.FromPtrOr(r.MaxCompletionTokens, uint(0))
+ maxTokens := lo.FromPtrOr(r.MaxTokens, uint(0))
+ if maxCompletionTokens > maxTokens {
+ meta.MaxTokens = int(maxCompletionTokens)
} else {
- meta.MaxTokens = int(r.MaxTokens)
+ meta.MaxTokens = int(maxTokens)
}
case *dto.OpenAIResponsesRequest:
- meta.MaxTokens = int(r.MaxOutputTokens)
+ meta.MaxTokens = int(lo.FromPtrOr(r.MaxOutputTokens, uint(0)))
case *dto.ClaudeRequest:
- meta.MaxTokens = int(r.MaxTokens)
+ meta.MaxTokens = int(lo.FromPtr(r.MaxTokens))
case *dto.ImageRequest:
// Pricing for image requests depends on ImagePriceRatio; safe to compute even when CountToken is disabled.
return r.GetTokenCountMeta()
@@ -305,6 +319,9 @@ func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) b
if openaiErr == nil {
return false
}
+ if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
+ return false
+ }
if types.IsChannelError(openaiErr) {
return true
}
@@ -324,6 +341,9 @@ func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) b
if code < 100 || code > 599 {
return true
}
+ if operation_setting.IsAlwaysSkipRetryCode(openaiErr.GetErrorCode()) {
+ return false
+ }
return operation_setting.ShouldRetryByStatusCode(code)
}
@@ -362,8 +382,14 @@ func processChannelError(c *gin.Context, channelError types.ChannelError, err *t
adminInfo["is_multi_key"] = true
adminInfo["multi_key_index"] = common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex)
}
+ service.AppendChannelAffinityAdminInfo(c, adminInfo)
other["admin_info"] = adminInfo
- model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveErrorWithStatusCode(), tokenId, 0, false, userGroup, other)
+ startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
+ if startTime.IsZero() {
+ startTime = time.Now()
+ }
+ useTimeSeconds := int(time.Since(startTime).Seconds())
+ model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveErrorWithStatusCode(), tokenId, useTimeSeconds, false, userGroup, other)
}
}
@@ -435,78 +461,156 @@ func RelayNotFound(c *gin.Context) {
})
}
-func RelayTask(c *gin.Context) {
- retryTimes := common.RetryTimes
- channelId := c.GetInt("channel_id")
- c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
+func RelayTaskFetch(c *gin.Context) {
relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
if err != nil {
+ c.JSON(http.StatusInternalServerError, &dto.TaskError{
+ Code: "gen_relay_info_failed",
+ Message: err.Error(),
+ StatusCode: http.StatusInternalServerError,
+ })
return
}
- taskErr := taskRelayHandler(c, relayInfo)
- if taskErr == nil {
- retryTimes = 0
+ if taskErr := relay.RelayTaskFetch(c, relayInfo.RelayMode); taskErr != nil {
+ respondTaskError(c, taskErr)
}
+}
+
+func RelayTask(c *gin.Context) {
+ relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, &dto.TaskError{
+ Code: "gen_relay_info_failed",
+ Message: err.Error(),
+ StatusCode: http.StatusInternalServerError,
+ })
+ return
+ }
+
+ if taskErr := relay.ResolveOriginTask(c, relayInfo); taskErr != nil {
+ respondTaskError(c, taskErr)
+ return
+ }
+
+ var result *relay.TaskSubmitResult
+ var taskErr *dto.TaskError
+ defer func() {
+ if taskErr != nil && relayInfo.Billing != nil {
+ relayInfo.Billing.Refund(c)
+ }
+ }()
+
retryParam := &service.RetryParam{
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
ModelName: relayInfo.OriginModelName,
Retry: common.GetPointer(0),
}
- for ; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && retryParam.GetRetry() < retryTimes; retryParam.IncreaseRetry() {
- channel, newAPIError := getChannel(c, relayInfo, retryParam)
- if newAPIError != nil {
- logger.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", newAPIError.Error()))
- taskErr = service.TaskErrorWrapperLocal(newAPIError.Err, "get_channel_failed", http.StatusInternalServerError)
- break
- }
- channelId = channel.Id
- useChannel := c.GetStringSlice("use_channel")
- useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
- c.Set("use_channel", useChannel)
- logger.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, retryParam.GetRetry()))
- //middleware.SetupContextForSelectedChannel(c, channel, originalModel)
- requestBody, err := common.GetRequestBody(c)
- if err != nil {
- if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
- taskErr = service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusRequestEntityTooLarge)
+ for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
+ var channel *model.Channel
+
+ if lockedCh, ok := relayInfo.LockedChannel.(*model.Channel); ok && lockedCh != nil {
+ channel = lockedCh
+ if retryParam.GetRetry() > 0 {
+ if setupErr := middleware.SetupContextForSelectedChannel(c, channel, relayInfo.OriginModelName); setupErr != nil {
+ taskErr = service.TaskErrorWrapperLocal(setupErr.Err, "setup_locked_channel_failed", http.StatusInternalServerError)
+ break
+ }
+ }
+ } else {
+ var channelErr *types.NewAPIError
+ channel, channelErr = getChannel(c, relayInfo, retryParam)
+ if channelErr != nil {
+ logger.LogError(c, channelErr.Error())
+ taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", http.StatusInternalServerError)
+ break
+ }
+ }
+
+ addUsedChannel(c, channel.Id)
+ bodyStorage, bodyErr := common.GetBodyStorage(c)
+ if bodyErr != nil {
+ if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
+ taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusRequestEntityTooLarge)
} else {
- taskErr = service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusBadRequest)
+ taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusBadRequest)
}
break
}
- c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
- taskErr = taskRelayHandler(c, relayInfo)
+ c.Request.Body = io.NopCloser(bodyStorage)
+
+ result, taskErr = relay.RelayTaskSubmit(c, relayInfo)
+ if taskErr == nil {
+ break
+ }
+
+ if !taskErr.LocalError {
+ processChannelError(c,
+ *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey,
+ common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()),
+ types.NewOpenAIError(taskErr.Error, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode))
+ }
+
+ if !shouldRetryTaskRelay(c, channel.Id, taskErr, common.RetryTimes-retryParam.GetRetry()) {
+ break
+ }
}
+
useChannel := c.GetStringSlice("use_channel")
if len(useChannel) > 1 {
retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
logger.LogInfo(c, retryLogStr)
}
- if taskErr != nil {
- if taskErr.StatusCode == http.StatusTooManyRequests {
- taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
+
+ // ── 成功:结算 + 日志 + 插入任务 ──
+ if taskErr == nil {
+ if settleErr := service.SettleBilling(c, relayInfo, result.Quota); settleErr != nil {
+ common.SysError("settle task billing error: " + settleErr.Error())
}
- c.JSON(taskErr.StatusCode, taskErr)
+ service.LogTaskConsumption(c, relayInfo)
+
+ task := model.InitTask(result.Platform, relayInfo)
+ task.PrivateData.UpstreamTaskID = result.UpstreamTaskID
+ task.PrivateData.BillingSource = relayInfo.BillingSource
+ task.PrivateData.SubscriptionId = relayInfo.SubscriptionId
+ task.PrivateData.TokenId = relayInfo.TokenId
+ task.PrivateData.BillingContext = &model.TaskBillingContext{
+ ModelPrice: relayInfo.PriceData.ModelPrice,
+ GroupRatio: relayInfo.PriceData.GroupRatioInfo.GroupRatio,
+ ModelRatio: relayInfo.PriceData.ModelRatio,
+ OtherRatios: relayInfo.PriceData.OtherRatios,
+ OriginModelName: relayInfo.OriginModelName,
+ PerCallBilling: common.StringsContains(constant.TaskPricePatches, relayInfo.OriginModelName) || relayInfo.PriceData.UsePrice,
+ }
+ task.Quota = result.Quota
+ task.Data = result.TaskData
+ task.Action = relayInfo.Action
+ if insertErr := task.Insert(); insertErr != nil {
+ common.SysError("insert task error: " + insertErr.Error())
+ }
+ }
+
+ if taskErr != nil {
+ respondTaskError(c, taskErr)
}
}
-func taskRelayHandler(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dto.TaskError {
- var err *dto.TaskError
- switch relayInfo.RelayMode {
- case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID, relayconstant.RelayModeVideoFetchByID:
- err = relay.RelayTaskFetch(c, relayInfo.RelayMode)
- default:
- err = relay.RelayTaskSubmit(c, relayInfo)
+// respondTaskError 统一输出 Task 错误响应(含 429 限流提示改写)
+func respondTaskError(c *gin.Context, taskErr *dto.TaskError) {
+ if taskErr.StatusCode == http.StatusTooManyRequests {
+ taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
}
- return err
+ c.JSON(taskErr.StatusCode, taskErr)
}
func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
if taskErr == nil {
return false
}
+ if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
+ return false
+ }
if retryTimes <= 0 {
return false
}
@@ -521,7 +625,7 @@ func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError,
}
if taskErr.StatusCode/100 == 5 {
// 超时不重试
- if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
+ if operation_setting.IsAlwaysSkipRetryStatusCode(taskErr.StatusCode) {
return false
}
return true
diff --git a/controller/secure_verification.go b/controller/secure_verification.go
index f30c259e62..b229a66b1c 100644
--- a/controller/secure_verification.go
+++ b/controller/secure_verification.go
@@ -7,18 +7,19 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
- passkeysvc "github.com/QuantumNous/new-api/service/passkey"
- "github.com/QuantumNous/new-api/setting/system_setting"
-
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
const (
- // SecureVerificationSessionKey 安全验证的 session key
+ // SecureVerificationSessionKey means the user has fully passed secure verification.
SecureVerificationSessionKey = "secure_verified_at"
+ // PasskeyReadySessionKey means WebAuthn finished and /api/verify can finalize step-up verification.
+ PasskeyReadySessionKey = "secure_passkey_ready_at"
// SecureVerificationTimeout 验证有效期(秒)
SecureVerificationTimeout = 300 // 5分钟
+ // PasskeyReadyTimeout passkey ready 标记有效期(秒)
+ PasskeyReadyTimeout = 60
)
type UniversalVerifyRequest struct {
@@ -76,6 +77,7 @@ func UniversalVerify(c *gin.Context) {
// 根据验证方式进行验证
var verified bool
var verifyMethod string
+ var err error
switch req.Method {
case "2fa":
@@ -95,10 +97,16 @@ func UniversalVerify(c *gin.Context) {
common.ApiError(c, fmt.Errorf("用户未启用Passkey"))
return
}
- // Passkey 验证需要先调用 PasskeyVerifyBegin 和 PasskeyVerifyFinish
- // 这里只是验证 Passkey 验证流程是否已经完成
- // 实际上,前端应该先调用这两个接口,然后再调用本接口
- verified = true // Passkey 验证逻辑已在 PasskeyVerifyFinish 中完成
+ // Passkey branch only trusts the short-lived marker written by PasskeyVerifyFinish.
+ verified, err = consumePasskeyReady(c)
+ if err != nil {
+ common.ApiError(c, fmt.Errorf("Passkey 验证状态异常: %v", err))
+ return
+ }
+ if !verified {
+ common.ApiError(c, fmt.Errorf("请先完成 Passkey 验证"))
+ return
+ }
verifyMethod = "Passkey"
default:
@@ -112,10 +120,8 @@ func UniversalVerify(c *gin.Context) {
}
// 验证成功,在 session 中记录时间戳
- session := sessions.Default(c)
- now := time.Now().Unix()
- session.Set(SecureVerificationSessionKey, now)
- if err := session.Save(); err != nil {
+ now, err := setSecureVerificationSession(c)
+ if err != nil {
common.ApiError(c, fmt.Errorf("保存验证状态失败: %v", err))
return
}
@@ -133,182 +139,37 @@ func UniversalVerify(c *gin.Context) {
})
}
-// GetVerificationStatus 获取验证状态
-func GetVerificationStatus(c *gin.Context) {
- userId := c.GetInt("id")
- if userId == 0 {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "message": "未登录",
- })
- return
- }
-
- session := sessions.Default(c)
- verifiedAtRaw := session.Get(SecureVerificationSessionKey)
-
- if verifiedAtRaw == nil {
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": VerificationStatusResponse{
- Verified: false,
- },
- })
- return
- }
-
- verifiedAt, ok := verifiedAtRaw.(int64)
- if !ok {
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": VerificationStatusResponse{
- Verified: false,
- },
- })
- return
- }
-
- elapsed := time.Now().Unix() - verifiedAt
- if elapsed >= SecureVerificationTimeout {
- // 验证已过期
- session.Delete(SecureVerificationSessionKey)
- _ = session.Save()
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": VerificationStatusResponse{
- Verified: false,
- },
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": VerificationStatusResponse{
- Verified: true,
- ExpiresAt: verifiedAt + SecureVerificationTimeout,
- },
- })
-}
-
-// CheckSecureVerification 检查是否已通过安全验证
-// 返回 true 表示验证有效,false 表示需要重新验证
-func CheckSecureVerification(c *gin.Context) bool {
- session := sessions.Default(c)
- verifiedAtRaw := session.Get(SecureVerificationSessionKey)
-
- if verifiedAtRaw == nil {
- return false
- }
-
- verifiedAt, ok := verifiedAtRaw.(int64)
- if !ok {
- return false
- }
-
- elapsed := time.Now().Unix() - verifiedAt
- if elapsed >= SecureVerificationTimeout {
- // 验证已过期,清除 session
- session.Delete(SecureVerificationSessionKey)
- _ = session.Save()
- return false
- }
-
- return true
-}
-
-// PasskeyVerifyAndSetSession Passkey 验证完成后设置 session
-// 这是一个辅助函数,供 PasskeyVerifyFinish 调用
-func PasskeyVerifyAndSetSession(c *gin.Context) {
+func setSecureVerificationSession(c *gin.Context) (int64, error) {
session := sessions.Default(c)
+ session.Delete(PasskeyReadySessionKey)
now := time.Now().Unix()
session.Set(SecureVerificationSessionKey, now)
- _ = session.Save()
+ if err := session.Save(); err != nil {
+ return 0, err
+ }
+ return now, nil
}
-// PasskeyVerifyForSecure 用于安全验证的 Passkey 验证流程
-// 整合了 begin 和 finish 流程
-func PasskeyVerifyForSecure(c *gin.Context) {
- if !system_setting.GetPasskeySettings().Enabled {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "管理员未启用 Passkey 登录",
- })
- return
+func consumePasskeyReady(c *gin.Context) (bool, error) {
+ session := sessions.Default(c)
+ readyAtRaw := session.Get(PasskeyReadySessionKey)
+ if readyAtRaw == nil {
+ return false, nil
}
- userId := c.GetInt("id")
- if userId == 0 {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "message": "未登录",
- })
- return
+ readyAt, ok := readyAtRaw.(int64)
+ if !ok {
+ session.Delete(PasskeyReadySessionKey)
+ _ = session.Save()
+ return false, fmt.Errorf("无效的 Passkey 验证状态")
}
-
- user := &model.User{Id: userId}
- if err := user.FillUserById(); err != nil {
- common.ApiError(c, fmt.Errorf("获取用户信息失败: %v", err))
- return
+ session.Delete(PasskeyReadySessionKey)
+ if err := session.Save(); err != nil {
+ return false, err
}
-
- if user.Status != common.UserStatusEnabled {
- common.ApiError(c, fmt.Errorf("该用户已被禁用"))
- return
+ // Expired ready markers cannot be reused.
+ if time.Now().Unix()-readyAt >= PasskeyReadyTimeout {
+ return false, nil
}
-
- credential, err := model.GetPasskeyByUserID(userId)
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "该用户尚未绑定 Passkey",
- })
- return
- }
-
- wa, err := passkeysvc.BuildWebAuthn(c.Request)
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- waUser := passkeysvc.NewWebAuthnUser(user, credential)
- sessionData, err := passkeysvc.PopSessionData(c, passkeysvc.VerifySessionKey)
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- _, err = wa.FinishLogin(waUser, *sessionData, c.Request)
- if err != nil {
- common.ApiError(c, err)
- return
- }
-
- // 更新凭证的最后使用时间
- now := time.Now()
- credential.LastUsedAt = &now
- if err := model.UpsertPasskeyCredential(credential); err != nil {
- common.ApiError(c, err)
- return
- }
-
- // 验证成功,设置 session
- PasskeyVerifyAndSetSession(c)
-
- // 记录日志
- model.RecordLog(userId, model.LogTypeSystem, "Passkey 安全验证成功")
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Passkey 验证成功",
- "data": gin.H{
- "verified": true,
- "expires_at": time.Now().Unix() + SecureVerificationTimeout,
- },
- })
+ return true, nil
}
diff --git a/controller/subscription.go b/controller/subscription.go
new file mode 100644
index 0000000000..c6095312b7
--- /dev/null
+++ b/controller/subscription.go
@@ -0,0 +1,383 @@
+package controller
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
+ "github.com/gin-gonic/gin"
+ "gorm.io/gorm"
+)
+
+// ---- Shared types ----
+
+type SubscriptionPlanDTO struct {
+ Plan model.SubscriptionPlan `json:"plan"`
+}
+
+type BillingPreferenceRequest struct {
+ BillingPreference string `json:"billing_preference"`
+}
+
+// ---- User APIs ----
+
+func GetSubscriptionPlans(c *gin.Context) {
+ var plans []model.SubscriptionPlan
+ if err := model.DB.Where("enabled = ?", true).Order("sort_order desc, id desc").Find(&plans).Error; err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ result := make([]SubscriptionPlanDTO, 0, len(plans))
+ for _, p := range plans {
+ result = append(result, SubscriptionPlanDTO{
+ Plan: p,
+ })
+ }
+ common.ApiSuccess(c, result)
+}
+
+func GetSubscriptionSelf(c *gin.Context) {
+ userId := c.GetInt("id")
+ settingMap, _ := model.GetUserSetting(userId, false)
+ pref := common.NormalizeBillingPreference(settingMap.BillingPreference)
+
+ // Get all subscriptions (including expired)
+ allSubscriptions, err := model.GetAllUserSubscriptions(userId)
+ if err != nil {
+ allSubscriptions = []model.SubscriptionSummary{}
+ }
+
+ // Get active subscriptions for backward compatibility
+ activeSubscriptions, err := model.GetAllActiveUserSubscriptions(userId)
+ if err != nil {
+ activeSubscriptions = []model.SubscriptionSummary{}
+ }
+
+ common.ApiSuccess(c, gin.H{
+ "billing_preference": pref,
+ "subscriptions": activeSubscriptions, // all active subscriptions
+ "all_subscriptions": allSubscriptions, // all subscriptions including expired
+ })
+}
+
+func UpdateSubscriptionPreference(c *gin.Context) {
+ userId := c.GetInt("id")
+ var req BillingPreferenceRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ pref := common.NormalizeBillingPreference(req.BillingPreference)
+
+ user, err := model.GetUserById(userId, true)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ current := user.GetSetting()
+ current.BillingPreference = pref
+ user.SetSetting(current)
+ if err := user.Update(false); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ common.ApiSuccess(c, gin.H{"billing_preference": pref})
+}
+
+// ---- Admin APIs ----
+
+func AdminListSubscriptionPlans(c *gin.Context) {
+ var plans []model.SubscriptionPlan
+ if err := model.DB.Order("sort_order desc, id desc").Find(&plans).Error; err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ result := make([]SubscriptionPlanDTO, 0, len(plans))
+ for _, p := range plans {
+ result = append(result, SubscriptionPlanDTO{
+ Plan: p,
+ })
+ }
+ common.ApiSuccess(c, result)
+}
+
+type AdminUpsertSubscriptionPlanRequest struct {
+ Plan model.SubscriptionPlan `json:"plan"`
+}
+
+func AdminCreateSubscriptionPlan(c *gin.Context) {
+ var req AdminUpsertSubscriptionPlanRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ req.Plan.Id = 0
+ if strings.TrimSpace(req.Plan.Title) == "" {
+ common.ApiErrorMsg(c, "套餐标题不能为空")
+ return
+ }
+ if req.Plan.PriceAmount < 0 {
+ common.ApiErrorMsg(c, "价格不能为负数")
+ return
+ }
+ if req.Plan.PriceAmount > 9999 {
+ common.ApiErrorMsg(c, "价格不能超过9999")
+ return
+ }
+ if req.Plan.Currency == "" {
+ req.Plan.Currency = "USD"
+ }
+ req.Plan.Currency = "USD"
+ if req.Plan.DurationUnit == "" {
+ req.Plan.DurationUnit = model.SubscriptionDurationMonth
+ }
+ if req.Plan.DurationValue <= 0 && req.Plan.DurationUnit != model.SubscriptionDurationCustom {
+ req.Plan.DurationValue = 1
+ }
+ if req.Plan.MaxPurchasePerUser < 0 {
+ common.ApiErrorMsg(c, "购买上限不能为负数")
+ return
+ }
+ if req.Plan.TotalAmount < 0 {
+ common.ApiErrorMsg(c, "总额度不能为负数")
+ return
+ }
+ req.Plan.UpgradeGroup = strings.TrimSpace(req.Plan.UpgradeGroup)
+ if req.Plan.UpgradeGroup != "" {
+ if _, ok := ratio_setting.GetGroupRatioCopy()[req.Plan.UpgradeGroup]; !ok {
+ common.ApiErrorMsg(c, "升级分组不存在")
+ return
+ }
+ }
+ req.Plan.QuotaResetPeriod = model.NormalizeResetPeriod(req.Plan.QuotaResetPeriod)
+ if req.Plan.QuotaResetPeriod == model.SubscriptionResetCustom && req.Plan.QuotaResetCustomSeconds <= 0 {
+ common.ApiErrorMsg(c, "自定义重置周期需大于0秒")
+ return
+ }
+ err := model.DB.Create(&req.Plan).Error
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ model.InvalidateSubscriptionPlanCache(req.Plan.Id)
+ common.ApiSuccess(c, req.Plan)
+}
+
+func AdminUpdateSubscriptionPlan(c *gin.Context) {
+ id, _ := strconv.Atoi(c.Param("id"))
+ if id <= 0 {
+ common.ApiErrorMsg(c, "无效的ID")
+ return
+ }
+ var req AdminUpsertSubscriptionPlanRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ if strings.TrimSpace(req.Plan.Title) == "" {
+ common.ApiErrorMsg(c, "套餐标题不能为空")
+ return
+ }
+ if req.Plan.PriceAmount < 0 {
+ common.ApiErrorMsg(c, "价格不能为负数")
+ return
+ }
+ if req.Plan.PriceAmount > 9999 {
+ common.ApiErrorMsg(c, "价格不能超过9999")
+ return
+ }
+ req.Plan.Id = id
+ if req.Plan.Currency == "" {
+ req.Plan.Currency = "USD"
+ }
+ req.Plan.Currency = "USD"
+ if req.Plan.DurationUnit == "" {
+ req.Plan.DurationUnit = model.SubscriptionDurationMonth
+ }
+ if req.Plan.DurationValue <= 0 && req.Plan.DurationUnit != model.SubscriptionDurationCustom {
+ req.Plan.DurationValue = 1
+ }
+ if req.Plan.MaxPurchasePerUser < 0 {
+ common.ApiErrorMsg(c, "购买上限不能为负数")
+ return
+ }
+ if req.Plan.TotalAmount < 0 {
+ common.ApiErrorMsg(c, "总额度不能为负数")
+ return
+ }
+ req.Plan.UpgradeGroup = strings.TrimSpace(req.Plan.UpgradeGroup)
+ if req.Plan.UpgradeGroup != "" {
+ if _, ok := ratio_setting.GetGroupRatioCopy()[req.Plan.UpgradeGroup]; !ok {
+ common.ApiErrorMsg(c, "升级分组不存在")
+ return
+ }
+ }
+ req.Plan.QuotaResetPeriod = model.NormalizeResetPeriod(req.Plan.QuotaResetPeriod)
+ if req.Plan.QuotaResetPeriod == model.SubscriptionResetCustom && req.Plan.QuotaResetCustomSeconds <= 0 {
+ common.ApiErrorMsg(c, "自定义重置周期需大于0秒")
+ return
+ }
+
+ err := model.DB.Transaction(func(tx *gorm.DB) error {
+ // update plan (allow zero values updates with map)
+ updateMap := map[string]interface{}{
+ "title": req.Plan.Title,
+ "subtitle": req.Plan.Subtitle,
+ "price_amount": req.Plan.PriceAmount,
+ "currency": req.Plan.Currency,
+ "duration_unit": req.Plan.DurationUnit,
+ "duration_value": req.Plan.DurationValue,
+ "custom_seconds": req.Plan.CustomSeconds,
+ "enabled": req.Plan.Enabled,
+ "sort_order": req.Plan.SortOrder,
+ "stripe_price_id": req.Plan.StripePriceId,
+ "creem_product_id": req.Plan.CreemProductId,
+ "max_purchase_per_user": req.Plan.MaxPurchasePerUser,
+ "total_amount": req.Plan.TotalAmount,
+ "upgrade_group": req.Plan.UpgradeGroup,
+ "quota_reset_period": req.Plan.QuotaResetPeriod,
+ "quota_reset_custom_seconds": req.Plan.QuotaResetCustomSeconds,
+ "updated_at": common.GetTimestamp(),
+ }
+ if err := tx.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Updates(updateMap).Error; err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ model.InvalidateSubscriptionPlanCache(id)
+ common.ApiSuccess(c, nil)
+}
+
+type AdminUpdateSubscriptionPlanStatusRequest struct {
+ Enabled *bool `json:"enabled"`
+}
+
+func AdminUpdateSubscriptionPlanStatus(c *gin.Context) {
+ id, _ := strconv.Atoi(c.Param("id"))
+ if id <= 0 {
+ common.ApiErrorMsg(c, "无效的ID")
+ return
+ }
+ var req AdminUpdateSubscriptionPlanStatusRequest
+ if err := c.ShouldBindJSON(&req); err != nil || req.Enabled == nil {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ if err := model.DB.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Update("enabled", *req.Enabled).Error; err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ model.InvalidateSubscriptionPlanCache(id)
+ common.ApiSuccess(c, nil)
+}
+
+type AdminBindSubscriptionRequest struct {
+ UserId int `json:"user_id"`
+ PlanId int `json:"plan_id"`
+}
+
+func AdminBindSubscription(c *gin.Context) {
+ var req AdminBindSubscriptionRequest
+ if err := c.ShouldBindJSON(&req); err != nil || req.UserId <= 0 || req.PlanId <= 0 {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ msg, err := model.AdminBindSubscription(req.UserId, req.PlanId, "")
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if msg != "" {
+ common.ApiSuccess(c, gin.H{"message": msg})
+ return
+ }
+ common.ApiSuccess(c, nil)
+}
+
+// ---- Admin: user subscription management ----
+
+func AdminListUserSubscriptions(c *gin.Context) {
+ userId, _ := strconv.Atoi(c.Param("id"))
+ if userId <= 0 {
+ common.ApiErrorMsg(c, "无效的用户ID")
+ return
+ }
+ subs, err := model.GetAllUserSubscriptions(userId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ common.ApiSuccess(c, subs)
+}
+
+type AdminCreateUserSubscriptionRequest struct {
+ PlanId int `json:"plan_id"`
+}
+
+// AdminCreateUserSubscription creates a new user subscription from a plan (no payment).
+func AdminCreateUserSubscription(c *gin.Context) {
+ userId, _ := strconv.Atoi(c.Param("id"))
+ if userId <= 0 {
+ common.ApiErrorMsg(c, "无效的用户ID")
+ return
+ }
+ var req AdminCreateUserSubscriptionRequest
+ if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+ msg, err := model.AdminBindSubscription(userId, req.PlanId, "")
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if msg != "" {
+ common.ApiSuccess(c, gin.H{"message": msg})
+ return
+ }
+ common.ApiSuccess(c, nil)
+}
+
+// AdminInvalidateUserSubscription cancels a user subscription immediately.
+func AdminInvalidateUserSubscription(c *gin.Context) {
+ subId, _ := strconv.Atoi(c.Param("id"))
+ if subId <= 0 {
+ common.ApiErrorMsg(c, "无效的订阅ID")
+ return
+ }
+ msg, err := model.AdminInvalidateUserSubscription(subId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if msg != "" {
+ common.ApiSuccess(c, gin.H{"message": msg})
+ return
+ }
+ common.ApiSuccess(c, nil)
+}
+
+// AdminDeleteUserSubscription hard-deletes a user subscription.
+func AdminDeleteUserSubscription(c *gin.Context) {
+ subId, _ := strconv.Atoi(c.Param("id"))
+ if subId <= 0 {
+ common.ApiErrorMsg(c, "无效的订阅ID")
+ return
+ }
+ msg, err := model.AdminDeleteUserSubscription(subId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if msg != "" {
+ common.ApiSuccess(c, gin.H{"message": msg})
+ return
+ }
+ common.ApiSuccess(c, nil)
+}
diff --git a/controller/subscription_payment_creem.go b/controller/subscription_payment_creem.go
new file mode 100644
index 0000000000..258d4fb357
--- /dev/null
+++ b/controller/subscription_payment_creem.go
@@ -0,0 +1,129 @@
+package controller
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/thanhpk/randstr"
+)
+
+type SubscriptionCreemPayRequest struct {
+ PlanId int `json:"plan_id"`
+}
+
+func SubscriptionRequestCreemPay(c *gin.Context) {
+ var req SubscriptionCreemPayRequest
+
+ // Keep body for debugging consistency (like RequestCreemPay)
+ bodyBytes, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ log.Printf("read subscription creem pay req body err: %v", err)
+ c.JSON(200, gin.H{"message": "error", "data": "read query error"})
+ return
+ }
+ c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
+
+ if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
+ c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
+ return
+ }
+
+ plan, err := model.GetSubscriptionPlanById(req.PlanId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if !plan.Enabled {
+ common.ApiErrorMsg(c, "套餐未启用")
+ return
+ }
+ if plan.CreemProductId == "" {
+ common.ApiErrorMsg(c, "该套餐未配置 CreemProductId")
+ return
+ }
+ if setting.CreemWebhookSecret == "" && !setting.CreemTestMode {
+ common.ApiErrorMsg(c, "Creem Webhook 未配置")
+ return
+ }
+
+ userId := c.GetInt("id")
+ user, err := model.GetUserById(userId, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if user == nil {
+ common.ApiErrorMsg(c, "用户不存在")
+ return
+ }
+
+ if plan.MaxPurchasePerUser > 0 {
+ count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if count >= int64(plan.MaxPurchasePerUser) {
+ common.ApiErrorMsg(c, "已达到该套餐购买上限")
+ return
+ }
+ }
+
+ reference := "sub-creem-ref-" + randstr.String(6)
+ referenceId := "sub_ref_" + common.Sha1([]byte(reference+time.Now().String()+user.Username))
+
+ // create pending order first
+ order := &model.SubscriptionOrder{
+ UserId: userId,
+ PlanId: plan.Id,
+ Money: plan.PriceAmount,
+ TradeNo: referenceId,
+ PaymentMethod: PaymentMethodCreem,
+ CreateTime: time.Now().Unix(),
+ Status: common.TopUpStatusPending,
+ }
+ if err := order.Insert(); err != nil {
+ c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
+ return
+ }
+
+ // Reuse Creem checkout generator by building a lightweight product reference.
+ currency := "USD"
+ switch operation_setting.GetGeneralSetting().QuotaDisplayType {
+ case operation_setting.QuotaDisplayTypeCNY:
+ currency = "CNY"
+ case operation_setting.QuotaDisplayTypeUSD:
+ currency = "USD"
+ default:
+ currency = "USD"
+ }
+ product := &CreemProduct{
+ ProductId: plan.CreemProductId,
+ Name: plan.Title,
+ Price: plan.PriceAmount,
+ Currency: currency,
+ Quota: 0,
+ }
+
+ checkoutUrl, err := genCreemLink(referenceId, product, user.Email, user.Username)
+ if err != nil {
+ log.Printf("获取Creem支付链接失败: %v", err)
+ c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
+ return
+ }
+
+ c.JSON(200, gin.H{
+ "message": "success",
+ "data": gin.H{
+ "checkout_url": checkoutUrl,
+ "order_id": referenceId,
+ },
+ })
+}
diff --git a/controller/subscription_payment_epay.go b/controller/subscription_payment_epay.go
new file mode 100644
index 0000000000..c45b391458
--- /dev/null
+++ b/controller/subscription_payment_epay.go
@@ -0,0 +1,216 @@
+package controller
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/Calcium-Ion/go-epay/epay"
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/samber/lo"
+)
+
+type SubscriptionEpayPayRequest struct {
+ PlanId int `json:"plan_id"`
+ PaymentMethod string `json:"payment_method"`
+}
+
+func SubscriptionRequestEpay(c *gin.Context) {
+ var req SubscriptionEpayPayRequest
+ if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+
+ plan, err := model.GetSubscriptionPlanById(req.PlanId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if !plan.Enabled {
+ common.ApiErrorMsg(c, "套餐未启用")
+ return
+ }
+ if plan.PriceAmount < 0.01 {
+ common.ApiErrorMsg(c, "套餐金额过低")
+ return
+ }
+ if !operation_setting.ContainsPayMethod(req.PaymentMethod) {
+ common.ApiErrorMsg(c, "支付方式不存在")
+ return
+ }
+
+ userId := c.GetInt("id")
+ if plan.MaxPurchasePerUser > 0 {
+ count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if count >= int64(plan.MaxPurchasePerUser) {
+ common.ApiErrorMsg(c, "已达到该套餐购买上限")
+ return
+ }
+ }
+
+ callBackAddress := service.GetCallbackAddress()
+ returnUrl, err := url.Parse(callBackAddress + "/api/subscription/epay/return")
+ if err != nil {
+ common.ApiErrorMsg(c, "回调地址配置错误")
+ return
+ }
+ notifyUrl, err := url.Parse(callBackAddress + "/api/subscription/epay/notify")
+ if err != nil {
+ common.ApiErrorMsg(c, "回调地址配置错误")
+ return
+ }
+
+ tradeNo := fmt.Sprintf("%s%d", common.GetRandomString(6), time.Now().Unix())
+ tradeNo = fmt.Sprintf("SUBUSR%dNO%s", userId, tradeNo)
+
+ client := GetEpayClient()
+ if client == nil {
+ common.ApiErrorMsg(c, "当前管理员未配置支付信息")
+ return
+ }
+
+ order := &model.SubscriptionOrder{
+ UserId: userId,
+ PlanId: plan.Id,
+ Money: plan.PriceAmount,
+ TradeNo: tradeNo,
+ PaymentMethod: req.PaymentMethod,
+ CreateTime: time.Now().Unix(),
+ Status: common.TopUpStatusPending,
+ }
+ if err := order.Insert(); err != nil {
+ common.ApiErrorMsg(c, "创建订单失败")
+ return
+ }
+ uri, params, err := client.Purchase(&epay.PurchaseArgs{
+ Type: req.PaymentMethod,
+ ServiceTradeNo: tradeNo,
+ Name: fmt.Sprintf("SUB:%s", plan.Title),
+ Money: strconv.FormatFloat(plan.PriceAmount, 'f', 2, 64),
+ Device: epay.PC,
+ NotifyUrl: notifyUrl,
+ ReturnUrl: returnUrl,
+ })
+ if err != nil {
+ _ = model.ExpireSubscriptionOrder(tradeNo)
+ common.ApiErrorMsg(c, "拉起支付失败")
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"message": "success", "data": params, "url": uri})
+}
+
+func SubscriptionEpayNotify(c *gin.Context) {
+ var params map[string]string
+
+ if c.Request.Method == "POST" {
+ // POST 请求:从 POST body 解析参数
+ if err := c.Request.ParseForm(); err != nil {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+ params = lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.PostForm.Get(t)
+ return r
+ }, map[string]string{})
+ } else {
+ // GET 请求:从 URL Query 解析参数
+ params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.URL.Query().Get(t)
+ return r
+ }, map[string]string{})
+ }
+
+ if len(params) == 0 {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+
+ client := GetEpayClient()
+ if client == nil {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+ verifyInfo, err := client.Verify(params)
+ if err != nil || !verifyInfo.VerifyStatus {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+
+ if verifyInfo.TradeStatus != epay.StatusTradeSuccess {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+
+ LockOrder(verifyInfo.ServiceTradeNo)
+ defer UnlockOrder(verifyInfo.ServiceTradeNo)
+
+ if err := model.CompleteSubscriptionOrder(verifyInfo.ServiceTradeNo, common.GetJsonString(verifyInfo)); err != nil {
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+
+ _, _ = c.Writer.Write([]byte("success"))
+}
+
+// SubscriptionEpayReturn handles browser return after payment.
+// It verifies the payload and completes the order, then redirects to console.
+func SubscriptionEpayReturn(c *gin.Context) {
+ var params map[string]string
+
+ if c.Request.Method == "POST" {
+ // POST 请求:从 POST body 解析参数
+ if err := c.Request.ParseForm(); err != nil {
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=fail")
+ return
+ }
+ params = lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.PostForm.Get(t)
+ return r
+ }, map[string]string{})
+ } else {
+ // GET 请求:从 URL Query 解析参数
+ params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.URL.Query().Get(t)
+ return r
+ }, map[string]string{})
+ }
+
+ if len(params) == 0 {
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=fail")
+ return
+ }
+
+ client := GetEpayClient()
+ if client == nil {
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=fail")
+ return
+ }
+ verifyInfo, err := client.Verify(params)
+ if err != nil || !verifyInfo.VerifyStatus {
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=fail")
+ return
+ }
+ if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
+ LockOrder(verifyInfo.ServiceTradeNo)
+ defer UnlockOrder(verifyInfo.ServiceTradeNo)
+ if err := model.CompleteSubscriptionOrder(verifyInfo.ServiceTradeNo, common.GetJsonString(verifyInfo)); err != nil {
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=fail")
+ return
+ }
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=success")
+ return
+ }
+ c.Redirect(http.StatusFound, system_setting.ServerAddress+"/console/topup?pay=pending")
+}
diff --git a/controller/subscription_payment_stripe.go b/controller/subscription_payment_stripe.go
new file mode 100644
index 0000000000..2603a82807
--- /dev/null
+++ b/controller/subscription_payment_stripe.go
@@ -0,0 +1,138 @@
+package controller
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/stripe/stripe-go/v81"
+ "github.com/stripe/stripe-go/v81/checkout/session"
+ "github.com/thanhpk/randstr"
+)
+
+type SubscriptionStripePayRequest struct {
+ PlanId int `json:"plan_id"`
+}
+
+func SubscriptionRequestStripePay(c *gin.Context) {
+ var req SubscriptionStripePayRequest
+ if err := c.ShouldBindJSON(&req); err != nil || req.PlanId <= 0 {
+ common.ApiErrorMsg(c, "参数错误")
+ return
+ }
+
+ plan, err := model.GetSubscriptionPlanById(req.PlanId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if !plan.Enabled {
+ common.ApiErrorMsg(c, "套餐未启用")
+ return
+ }
+ if plan.StripePriceId == "" {
+ common.ApiErrorMsg(c, "该套餐未配置 StripePriceId")
+ return
+ }
+ if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
+ common.ApiErrorMsg(c, "Stripe 未配置或密钥无效")
+ return
+ }
+ if setting.StripeWebhookSecret == "" {
+ common.ApiErrorMsg(c, "Stripe Webhook 未配置")
+ return
+ }
+
+ userId := c.GetInt("id")
+ user, err := model.GetUserById(userId, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if user == nil {
+ common.ApiErrorMsg(c, "用户不存在")
+ return
+ }
+
+ if plan.MaxPurchasePerUser > 0 {
+ count, err := model.CountUserSubscriptionsByPlan(userId, plan.Id)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if count >= int64(plan.MaxPurchasePerUser) {
+ common.ApiErrorMsg(c, "已达到该套餐购买上限")
+ return
+ }
+ }
+
+ reference := fmt.Sprintf("sub-stripe-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
+ referenceId := "sub_ref_" + common.Sha1([]byte(reference))
+
+ payLink, err := genStripeSubscriptionLink(referenceId, user.StripeCustomer, user.Email, plan.StripePriceId)
+ if err != nil {
+ log.Println("获取Stripe Checkout支付链接失败", err)
+ c.JSON(http.StatusOK, gin.H{"message": "error", "data": "拉起支付失败"})
+ return
+ }
+
+ order := &model.SubscriptionOrder{
+ UserId: userId,
+ PlanId: plan.Id,
+ Money: plan.PriceAmount,
+ TradeNo: referenceId,
+ PaymentMethod: PaymentMethodStripe,
+ CreateTime: time.Now().Unix(),
+ Status: common.TopUpStatusPending,
+ }
+ if err := order.Insert(); err != nil {
+ c.JSON(http.StatusOK, gin.H{"message": "error", "data": "创建订单失败"})
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "message": "success",
+ "data": gin.H{
+ "pay_link": payLink,
+ },
+ })
+}
+
+func genStripeSubscriptionLink(referenceId string, customerId string, email string, priceId string) (string, error) {
+ stripe.Key = setting.StripeApiSecret
+
+ params := &stripe.CheckoutSessionParams{
+ ClientReferenceID: stripe.String(referenceId),
+ SuccessURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
+ CancelURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
+ LineItems: []*stripe.CheckoutSessionLineItemParams{
+ {
+ Price: stripe.String(priceId),
+ Quantity: stripe.Int64(1),
+ },
+ },
+ Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
+ }
+
+ if "" == customerId {
+ if "" != email {
+ params.CustomerEmail = stripe.String(email)
+ }
+ params.CustomerCreation = stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways))
+ } else {
+ params.Customer = stripe.String(customerId)
+ }
+
+ result, err := session.New(params)
+ if err != nil {
+ return "", err
+ }
+ return result.URL, nil
+}
diff --git a/controller/task.go b/controller/task.go
index 244f9161c2..eac7db153b 100644
--- a/controller/task.go
+++ b/controller/task.go
@@ -1,231 +1,22 @@
package controller
import (
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "sort"
"strconv"
- "time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
- "github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
- "github.com/samber/lo"
)
+// UpdateTaskBulk 薄入口,实际轮询逻辑在 service 层
func UpdateTaskBulk() {
- //revocer
- //imageModel := "midjourney"
- for {
- time.Sleep(time.Duration(15) * time.Second)
- common.SysLog("任务进度轮询开始")
- ctx := context.TODO()
- allTasks := model.GetAllUnFinishSyncTasks(constant.TaskQueryLimit)
- platformTask := make(map[constant.TaskPlatform][]*model.Task)
- for _, t := range allTasks {
- platformTask[t.Platform] = append(platformTask[t.Platform], t)
- }
- for platform, tasks := range platformTask {
- if len(tasks) == 0 {
- continue
- }
- taskChannelM := make(map[int][]string)
- taskM := make(map[string]*model.Task)
- nullTaskIds := make([]int64, 0)
- for _, task := range tasks {
- if task.TaskID == "" {
- // 统计失败的未完成任务
- nullTaskIds = append(nullTaskIds, task.ID)
- continue
- }
- taskM[task.TaskID] = task
- taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], task.TaskID)
- }
- if len(nullTaskIds) > 0 {
- err := model.TaskBulkUpdateByID(nullTaskIds, map[string]any{
- "status": "FAILURE",
- "progress": "100%",
- })
- if err != nil {
- logger.LogError(ctx, fmt.Sprintf("Fix null task_id task error: %v", err))
- } else {
- logger.LogInfo(ctx, fmt.Sprintf("Fix null task_id task success: %v", nullTaskIds))
- }
- }
- if len(taskChannelM) == 0 {
- continue
- }
-
- UpdateTaskByPlatform(platform, taskChannelM, taskM)
- }
- common.SysLog("任务进度轮询完成")
- }
-}
-
-func UpdateTaskByPlatform(platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) {
- switch platform {
- case constant.TaskPlatformMidjourney:
- //_ = UpdateMidjourneyTaskAll(context.Background(), tasks)
- case constant.TaskPlatformSuno:
- _ = UpdateSunoTaskAll(context.Background(), taskChannelM, taskM)
- default:
- if err := UpdateVideoTaskAll(context.Background(), platform, taskChannelM, taskM); err != nil {
- common.SysLog(fmt.Sprintf("UpdateVideoTaskAll fail: %s", err))
- }
- }
-}
-
-func UpdateSunoTaskAll(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
- for channelId, taskIds := range taskChannelM {
- err := updateSunoTaskAll(ctx, channelId, taskIds, taskM)
- if err != nil {
- logger.LogError(ctx, fmt.Sprintf("渠道 #%d 更新异步任务失败: %s", channelId, err.Error()))
- }
- }
- return nil
-}
-
-func updateSunoTaskAll(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error {
- logger.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
- if len(taskIds) == 0 {
- return nil
- }
- channel, err := model.CacheGetChannel(channelId)
- if err != nil {
- common.SysLog(fmt.Sprintf("CacheGetChannel: %v", err))
- err = model.TaskBulkUpdate(taskIds, map[string]any{
- "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
- "status": "FAILURE",
- "progress": "100%",
- })
- if err != nil {
- common.SysLog(fmt.Sprintf("UpdateMidjourneyTask error2: %v", err))
- }
- return err
- }
- adaptor := relay.GetTaskAdaptor(constant.TaskPlatformSuno)
- if adaptor == nil {
- return errors.New("adaptor not found")
- }
- proxy := channel.GetSetting().Proxy
- resp, err := adaptor.FetchTask(*channel.BaseURL, channel.Key, map[string]any{
- "ids": taskIds,
- }, proxy)
- if err != nil {
- common.SysLog(fmt.Sprintf("Get Task Do req error: %v", err))
- return err
- }
- if resp.StatusCode != http.StatusOK {
- logger.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
- return errors.New(fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
- }
- defer resp.Body.Close()
- responseBody, err := io.ReadAll(resp.Body)
- if err != nil {
- common.SysLog(fmt.Sprintf("Get Task parse body error: %v", err))
- return err
- }
- var responseItems dto.TaskResponse[[]dto.SunoDataResponse]
- err = json.Unmarshal(responseBody, &responseItems)
- if err != nil {
- logger.LogError(ctx, fmt.Sprintf("Get Task parse body error2: %v, body: %s", err, string(responseBody)))
- return err
- }
- if !responseItems.IsSuccess() {
- common.SysLog(fmt.Sprintf("渠道 #%d 未完成的任务有: %d, 成功获取到任务数: %s", channelId, len(taskIds), string(responseBody)))
- return err
- }
-
- for _, responseItem := range responseItems.Data {
- task := taskM[responseItem.TaskID]
- if !checkTaskNeedUpdate(task, responseItem) {
- continue
- }
-
- task.Status = lo.If(model.TaskStatus(responseItem.Status) != "", model.TaskStatus(responseItem.Status)).Else(task.Status)
- task.FailReason = lo.If(responseItem.FailReason != "", responseItem.FailReason).Else(task.FailReason)
- task.SubmitTime = lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime)
- task.StartTime = lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime)
- task.FinishTime = lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime)
- if responseItem.FailReason != "" || task.Status == model.TaskStatusFailure {
- logger.LogInfo(ctx, task.TaskID+" 构建失败,"+task.FailReason)
- task.Progress = "100%"
- //err = model.CacheUpdateUserQuota(task.UserId) ?
- if err != nil {
- logger.LogError(ctx, "error update user quota cache: "+err.Error())
- } else {
- quota := task.Quota
- if quota != 0 {
- err = model.IncreaseUserQuota(task.UserId, quota, false)
- if err != nil {
- logger.LogError(ctx, "fail to increase user quota: "+err.Error())
- }
- logContent := fmt.Sprintf("异步任务执行失败 %s,补偿 %s", task.TaskID, logger.LogQuota(quota))
- model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
- }
- }
- }
- if responseItem.Status == model.TaskStatusSuccess {
- task.Progress = "100%"
- }
- task.Data = responseItem.Data
-
- err = task.Update()
- if err != nil {
- common.SysLog("UpdateMidjourneyTask task error: " + err.Error())
- }
- }
- return nil
-}
-
-func checkTaskNeedUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool {
-
- if oldTask.SubmitTime != newTask.SubmitTime {
- return true
- }
- if oldTask.StartTime != newTask.StartTime {
- return true
- }
- if oldTask.FinishTime != newTask.FinishTime {
- return true
- }
- if string(oldTask.Status) != newTask.Status {
- return true
- }
- if oldTask.FailReason != newTask.FailReason {
- return true
- }
- if oldTask.FinishTime != newTask.FinishTime {
- return true
- }
-
- if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != "100%" {
- return true
- }
-
- oldData, _ := json.Marshal(oldTask.Data)
- newData, _ := json.Marshal(newTask.Data)
-
- sort.Slice(oldData, func(i, j int) bool {
- return oldData[i] < oldData[j]
- })
- sort.Slice(newData, func(i, j int) bool {
- return newData[i] < newData[j]
- })
-
- if string(oldData) != string(newData) {
- return true
- }
- return false
+ service.TaskPollingLoop()
}
func GetAllTask(c *gin.Context) {
@@ -247,7 +38,7 @@ func GetAllTask(c *gin.Context) {
items := model.TaskGetAllTasks(pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
total := model.TaskCountAllTasks(queryParams)
pageInfo.SetTotal(int(total))
- pageInfo.SetItems(items)
+ pageInfo.SetItems(tasksToDto(items, true))
common.ApiSuccess(c, pageInfo)
}
@@ -271,6 +62,33 @@ func GetUserTask(c *gin.Context) {
items := model.TaskGetAllUserTask(userId, pageInfo.GetStartIdx(), pageInfo.GetPageSize(), queryParams)
total := model.TaskCountAllUserTask(userId, queryParams)
pageInfo.SetTotal(int(total))
- pageInfo.SetItems(items)
+ pageInfo.SetItems(tasksToDto(items, false))
common.ApiSuccess(c, pageInfo)
}
+
+func tasksToDto(tasks []*model.Task, fillUser bool) []*dto.TaskDto {
+ var userIdMap map[int]*model.UserBase
+ if fillUser {
+ userIdMap = make(map[int]*model.UserBase)
+ userIds := types.NewSet[int]()
+ for _, task := range tasks {
+ userIds.Add(task.UserId)
+ }
+ for _, userId := range userIds.Items() {
+ cacheUser, err := model.GetUserCache(userId)
+ if err == nil {
+ userIdMap[userId] = cacheUser
+ }
+ }
+ }
+ result := make([]*dto.TaskDto, len(tasks))
+ for i, task := range tasks {
+ if fillUser {
+ if user, ok := userIdMap[task.UserId]; ok {
+ task.Username = user.Username
+ }
+ }
+ result[i] = relay.TaskModel2Dto(task)
+ }
+ return result
+}
diff --git a/controller/token.go b/controller/token.go
index c5dc5ec42d..836e9b2952 100644
--- a/controller/token.go
+++ b/controller/token.go
@@ -7,11 +7,30 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
)
+func buildMaskedTokenResponse(token *model.Token) *model.Token {
+ if token == nil {
+ return nil
+ }
+ maskedToken := *token
+ maskedToken.Key = token.GetMaskedKey()
+ return &maskedToken
+}
+
+func buildMaskedTokenResponses(tokens []*model.Token) []*model.Token {
+ maskedTokens := make([]*model.Token, 0, len(tokens))
+ for _, token := range tokens {
+ maskedTokens = append(maskedTokens, buildMaskedTokenResponse(token))
+ }
+ return maskedTokens
+}
+
func GetAllTokens(c *gin.Context) {
userId := c.GetInt("id")
pageInfo := common.GetPageQuery(c)
@@ -22,26 +41,25 @@ func GetAllTokens(c *gin.Context) {
}
total, _ := model.CountUserTokens(userId)
pageInfo.SetTotal(int(total))
- pageInfo.SetItems(tokens)
+ pageInfo.SetItems(buildMaskedTokenResponses(tokens))
common.ApiSuccess(c, pageInfo)
- return
}
func SearchTokens(c *gin.Context) {
userId := c.GetInt("id")
keyword := c.Query("keyword")
token := c.Query("token")
- tokens, err := model.SearchUserTokens(userId, keyword, token)
+
+ pageInfo := common.GetPageQuery(c)
+
+ tokens, total, err := model.SearchUserTokens(userId, keyword, token, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
if err != nil {
common.ApiError(c, err)
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": tokens,
- })
- return
+ pageInfo.SetTotal(int(total))
+ pageInfo.SetItems(buildMaskedTokenResponses(tokens))
+ common.ApiSuccess(c, pageInfo)
}
func GetToken(c *gin.Context) {
@@ -56,12 +74,24 @@ func GetToken(c *gin.Context) {
common.ApiError(c, err)
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "",
- "data": token,
+ common.ApiSuccess(c, buildMaskedTokenResponse(token))
+}
+
+func GetTokenKey(c *gin.Context) {
+ id, err := strconv.Atoi(c.Param("id"))
+ userId := c.GetInt("id")
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ token, err := model.GetTokenByIds(id, userId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ common.ApiSuccess(c, gin.H{
+ "key": token.GetFullKey(),
})
- return
}
func GetTokenStatus(c *gin.Context) {
@@ -107,10 +137,8 @@ func GetTokenUsage(c *gin.Context) {
token, err := model.GetTokenByKey(strings.TrimPrefix(tokenKey, "sk-"), false)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": err.Error(),
- })
+ common.SysError("failed to get token by key: " + err.Error())
+ common.ApiErrorI18n(c, i18n.MsgTokenGetInfoFailed)
return
}
@@ -144,36 +172,38 @@ func AddToken(c *gin.Context) {
return
}
if len(token.Name) > 50 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "令牌名称过长",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenNameTooLong)
return
}
// 非无限额度时,检查额度值是否超出有效范围
if !token.UnlimitedQuota {
if token.RemainQuota < 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "额度值不能为负数",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenQuotaNegative)
return
}
maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
if token.RemainQuota > maxQuotaValue {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("额度值超出有效范围,最大值为 %d", maxQuotaValue),
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenQuotaExceedMax, map[string]any{"Max": maxQuotaValue})
return
}
}
- key, err := common.GenerateKey()
+ // 检查用户令牌数量是否已达上限
+ maxTokens := operation_setting.GetMaxUserTokens()
+ count, err := model.CountUserTokens(c.GetInt("id"))
if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ if int(count) >= maxTokens {
c.JSON(http.StatusOK, gin.H{
"success": false,
- "message": "生成令牌失败",
+ "message": fmt.Sprintf("已达到最大令牌数量限制 (%d)", maxTokens),
})
+ return
+ }
+ key, err := common.GenerateKey()
+ if err != nil {
+ common.ApiErrorI18n(c, i18n.MsgTokenGenerateFailed)
common.SysLog("failed to generate token key: " + err.Error())
return
}
@@ -201,7 +231,6 @@ func AddToken(c *gin.Context) {
"success": true,
"message": "",
})
- return
}
func DeleteToken(c *gin.Context) {
@@ -216,7 +245,6 @@ func DeleteToken(c *gin.Context) {
"success": true,
"message": "",
})
- return
}
func UpdateToken(c *gin.Context) {
@@ -229,26 +257,17 @@ func UpdateToken(c *gin.Context) {
return
}
if len(token.Name) > 50 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "令牌名称过长",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenNameTooLong)
return
}
if !token.UnlimitedQuota {
if token.RemainQuota < 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "额度值不能为负数",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenQuotaNegative)
return
}
maxQuotaValue := int((1000000000 * common.QuotaPerUnit))
if token.RemainQuota > maxQuotaValue {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": fmt.Sprintf("额度值超出有效范围,最大值为 %d", maxQuotaValue),
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenQuotaExceedMax, map[string]any{"Max": maxQuotaValue})
return
}
}
@@ -259,17 +278,11 @@ func UpdateToken(c *gin.Context) {
}
if token.Status == common.TokenStatusEnabled {
if cleanToken.Status == common.TokenStatusExpired && cleanToken.ExpiredTime <= common.GetTimestamp() && cleanToken.ExpiredTime != -1 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenExpiredCannotEnable)
return
}
if cleanToken.Status == common.TokenStatusExhausted && cleanToken.RemainQuota <= 0 && !cleanToken.UnlimitedQuota {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度",
- })
+ common.ApiErrorI18n(c, i18n.MsgTokenExhaustedCannotEable)
return
}
}
@@ -295,7 +308,7 @@ func UpdateToken(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
- "data": cleanToken,
+ "data": buildMaskedTokenResponse(cleanToken),
})
}
@@ -306,10 +319,7 @@ type TokenBatch struct {
func DeleteTokenBatch(c *gin.Context) {
tokenBatch := TokenBatch{}
if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "参数错误",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
userId := c.GetInt("id")
@@ -324,3 +334,26 @@ func DeleteTokenBatch(c *gin.Context) {
"data": count,
})
}
+
+func GetTokenKeysBatch(c *gin.Context) {
+ tokenBatch := TokenBatch{}
+ if err := c.ShouldBindJSON(&tokenBatch); err != nil || len(tokenBatch.Ids) == 0 {
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
+ return
+ }
+ if len(tokenBatch.Ids) > 100 {
+ common.ApiErrorI18n(c, i18n.MsgBatchTooMany, map[string]any{"Max": 100})
+ return
+ }
+ userId := c.GetInt("id")
+ tokens, err := model.GetTokenKeysByIds(tokenBatch.Ids, userId)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ keysMap := make(map[int]string)
+ for _, t := range tokens {
+ keysMap[t.Id] = t.GetFullKey()
+ }
+ common.ApiSuccess(c, gin.H{"keys": keysMap})
+}
diff --git a/controller/token_test.go b/controller/token_test.go
new file mode 100644
index 0000000000..3eea673051
--- /dev/null
+++ b/controller/token_test.go
@@ -0,0 +1,275 @@
+package controller
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/gin-gonic/gin"
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+)
+
+type tokenAPIResponse struct {
+ Success bool `json:"success"`
+ Message string `json:"message"`
+ Data json.RawMessage `json:"data"`
+}
+
+type tokenPageResponse struct {
+ Items []tokenResponseItem `json:"items"`
+}
+
+type tokenResponseItem struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Key string `json:"key"`
+ Status int `json:"status"`
+}
+
+type tokenKeyResponse struct {
+ Key string `json:"key"`
+}
+
+func setupTokenControllerTestDB(t *testing.T) *gorm.DB {
+ t.Helper()
+
+ gin.SetMode(gin.TestMode)
+ common.UsingSQLite = true
+ common.UsingMySQL = false
+ common.UsingPostgreSQL = false
+ common.RedisEnabled = false
+
+ dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.ReplaceAll(t.Name(), "/", "_"))
+ db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
+ if err != nil {
+ t.Fatalf("failed to open sqlite db: %v", err)
+ }
+ model.DB = db
+ model.LOG_DB = db
+
+ if err := db.AutoMigrate(&model.Token{}); err != nil {
+ t.Fatalf("failed to migrate token table: %v", err)
+ }
+
+ t.Cleanup(func() {
+ sqlDB, err := db.DB()
+ if err == nil {
+ _ = sqlDB.Close()
+ }
+ })
+
+ return db
+}
+
+func seedToken(t *testing.T, db *gorm.DB, userID int, name string, rawKey string) *model.Token {
+ t.Helper()
+
+ token := &model.Token{
+ UserId: userID,
+ Name: name,
+ Key: rawKey,
+ Status: common.TokenStatusEnabled,
+ CreatedTime: 1,
+ AccessedTime: 1,
+ ExpiredTime: -1,
+ RemainQuota: 100,
+ UnlimitedQuota: true,
+ Group: "default",
+ }
+ if err := db.Create(token).Error; err != nil {
+ t.Fatalf("failed to create token: %v", err)
+ }
+ return token
+}
+
+func newAuthenticatedContext(t *testing.T, method string, target string, body any, userID int) (*gin.Context, *httptest.ResponseRecorder) {
+ t.Helper()
+
+ var requestBody *bytes.Reader
+ if body != nil {
+ payload, err := common.Marshal(body)
+ if err != nil {
+ t.Fatalf("failed to marshal request body: %v", err)
+ }
+ requestBody = bytes.NewReader(payload)
+ } else {
+ requestBody = bytes.NewReader(nil)
+ }
+
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(method, target, requestBody)
+ if body != nil {
+ ctx.Request.Header.Set("Content-Type", "application/json")
+ }
+ ctx.Set("id", userID)
+ return ctx, recorder
+}
+
+func decodeAPIResponse(t *testing.T, recorder *httptest.ResponseRecorder) tokenAPIResponse {
+ t.Helper()
+
+ var response tokenAPIResponse
+ if err := common.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatalf("failed to decode api response: %v", err)
+ }
+ return response
+}
+
+func TestGetAllTokensMasksKeyInResponse(t *testing.T) {
+ db := setupTokenControllerTestDB(t)
+ token := seedToken(t, db, 1, "list-token", "abcd1234efgh5678")
+ seedToken(t, db, 2, "other-user-token", "zzzz1234yyyy5678")
+
+ ctx, recorder := newAuthenticatedContext(t, http.MethodGet, "/api/token/?p=1&size=10", nil, 1)
+ GetAllTokens(ctx)
+
+ response := decodeAPIResponse(t, recorder)
+ if !response.Success {
+ t.Fatalf("expected success response, got message: %s", response.Message)
+ }
+
+ var page tokenPageResponse
+ if err := common.Unmarshal(response.Data, &page); err != nil {
+ t.Fatalf("failed to decode token page response: %v", err)
+ }
+ if len(page.Items) != 1 {
+ t.Fatalf("expected exactly one token, got %d", len(page.Items))
+ }
+ if page.Items[0].Key != token.GetMaskedKey() {
+ t.Fatalf("expected masked key %q, got %q", token.GetMaskedKey(), page.Items[0].Key)
+ }
+ if strings.Contains(recorder.Body.String(), token.Key) {
+ t.Fatalf("list response leaked raw token key: %s", recorder.Body.String())
+ }
+}
+
+func TestSearchTokensMasksKeyInResponse(t *testing.T) {
+ db := setupTokenControllerTestDB(t)
+ token := seedToken(t, db, 1, "searchable-token", "ijkl1234mnop5678")
+
+ ctx, recorder := newAuthenticatedContext(t, http.MethodGet, "/api/token/search?keyword=searchable-token&p=1&size=10", nil, 1)
+ SearchTokens(ctx)
+
+ response := decodeAPIResponse(t, recorder)
+ if !response.Success {
+ t.Fatalf("expected success response, got message: %s", response.Message)
+ }
+
+ var page tokenPageResponse
+ if err := common.Unmarshal(response.Data, &page); err != nil {
+ t.Fatalf("failed to decode search response: %v", err)
+ }
+ if len(page.Items) != 1 {
+ t.Fatalf("expected exactly one search result, got %d", len(page.Items))
+ }
+ if page.Items[0].Key != token.GetMaskedKey() {
+ t.Fatalf("expected masked search key %q, got %q", token.GetMaskedKey(), page.Items[0].Key)
+ }
+ if strings.Contains(recorder.Body.String(), token.Key) {
+ t.Fatalf("search response leaked raw token key: %s", recorder.Body.String())
+ }
+}
+
+func TestGetTokenMasksKeyInResponse(t *testing.T) {
+ db := setupTokenControllerTestDB(t)
+ token := seedToken(t, db, 1, "detail-token", "qrst1234uvwx5678")
+
+ ctx, recorder := newAuthenticatedContext(t, http.MethodGet, "/api/token/"+strconv.Itoa(token.Id), nil, 1)
+ ctx.Params = gin.Params{{Key: "id", Value: strconv.Itoa(token.Id)}}
+ GetToken(ctx)
+
+ response := decodeAPIResponse(t, recorder)
+ if !response.Success {
+ t.Fatalf("expected success response, got message: %s", response.Message)
+ }
+
+ var detail tokenResponseItem
+ if err := common.Unmarshal(response.Data, &detail); err != nil {
+ t.Fatalf("failed to decode token detail response: %v", err)
+ }
+ if detail.Key != token.GetMaskedKey() {
+ t.Fatalf("expected masked detail key %q, got %q", token.GetMaskedKey(), detail.Key)
+ }
+ if strings.Contains(recorder.Body.String(), token.Key) {
+ t.Fatalf("detail response leaked raw token key: %s", recorder.Body.String())
+ }
+}
+
+func TestUpdateTokenMasksKeyInResponse(t *testing.T) {
+ db := setupTokenControllerTestDB(t)
+ token := seedToken(t, db, 1, "editable-token", "yzab1234cdef5678")
+
+ body := map[string]any{
+ "id": token.Id,
+ "name": "updated-token",
+ "expired_time": -1,
+ "remain_quota": 100,
+ "unlimited_quota": true,
+ "model_limits_enabled": false,
+ "model_limits": "",
+ "group": "default",
+ "cross_group_retry": false,
+ }
+
+ ctx, recorder := newAuthenticatedContext(t, http.MethodPut, "/api/token/", body, 1)
+ UpdateToken(ctx)
+
+ response := decodeAPIResponse(t, recorder)
+ if !response.Success {
+ t.Fatalf("expected success response, got message: %s", response.Message)
+ }
+
+ var detail tokenResponseItem
+ if err := common.Unmarshal(response.Data, &detail); err != nil {
+ t.Fatalf("failed to decode token update response: %v", err)
+ }
+ if detail.Key != token.GetMaskedKey() {
+ t.Fatalf("expected masked update key %q, got %q", token.GetMaskedKey(), detail.Key)
+ }
+ if strings.Contains(recorder.Body.String(), token.Key) {
+ t.Fatalf("update response leaked raw token key: %s", recorder.Body.String())
+ }
+}
+
+func TestGetTokenKeyRequiresOwnershipAndReturnsFullKey(t *testing.T) {
+ db := setupTokenControllerTestDB(t)
+ token := seedToken(t, db, 1, "owned-token", "owner1234token5678")
+
+ authorizedCtx, authorizedRecorder := newAuthenticatedContext(t, http.MethodPost, "/api/token/"+strconv.Itoa(token.Id)+"/key", nil, 1)
+ authorizedCtx.Params = gin.Params{{Key: "id", Value: strconv.Itoa(token.Id)}}
+ GetTokenKey(authorizedCtx)
+
+ authorizedResponse := decodeAPIResponse(t, authorizedRecorder)
+ if !authorizedResponse.Success {
+ t.Fatalf("expected authorized key fetch to succeed, got message: %s", authorizedResponse.Message)
+ }
+
+ var keyData tokenKeyResponse
+ if err := common.Unmarshal(authorizedResponse.Data, &keyData); err != nil {
+ t.Fatalf("failed to decode token key response: %v", err)
+ }
+ if keyData.Key != token.GetFullKey() {
+ t.Fatalf("expected full key %q, got %q", token.GetFullKey(), keyData.Key)
+ }
+
+ unauthorizedCtx, unauthorizedRecorder := newAuthenticatedContext(t, http.MethodPost, "/api/token/"+strconv.Itoa(token.Id)+"/key", nil, 2)
+ unauthorizedCtx.Params = gin.Params{{Key: "id", Value: strconv.Itoa(token.Id)}}
+ GetTokenKey(unauthorizedCtx)
+
+ unauthorizedResponse := decodeAPIResponse(t, unauthorizedRecorder)
+ if unauthorizedResponse.Success {
+ t.Fatalf("expected unauthorized key fetch to fail")
+ }
+ if strings.Contains(unauthorizedRecorder.Body.String(), token.Key) {
+ t.Fatalf("unauthorized key response leaked raw token key: %s", unauthorizedRecorder.Body.String())
+ }
+}
diff --git a/controller/topup.go b/controller/topup.go
index f34d4b892d..e7a392a4d3 100644
--- a/controller/topup.go
+++ b/controller/topup.go
@@ -48,14 +48,52 @@ func GetTopUpInfo(c *gin.Context) {
}
}
+ // 如果启用了 Waffo 支付,添加到支付方法列表
+ enableWaffo := setting.WaffoEnabled &&
+ ((!setting.WaffoSandbox &&
+ setting.WaffoApiKey != "" &&
+ setting.WaffoPrivateKey != "" &&
+ setting.WaffoPublicCert != "") ||
+ (setting.WaffoSandbox &&
+ setting.WaffoSandboxApiKey != "" &&
+ setting.WaffoSandboxPrivateKey != "" &&
+ setting.WaffoSandboxPublicCert != ""))
+ if enableWaffo {
+ hasWaffo := false
+ for _, method := range payMethods {
+ if method["type"] == "waffo" {
+ hasWaffo = true
+ break
+ }
+ }
+
+ if !hasWaffo {
+ waffoMethod := map[string]string{
+ "name": "Waffo (Global Payment)",
+ "type": "waffo",
+ "color": "rgba(var(--semi-blue-5), 1)",
+ "min_topup": strconv.Itoa(setting.WaffoMinTopUp),
+ }
+ payMethods = append(payMethods, waffoMethod)
+ }
+ }
+
data := gin.H{
"enable_online_topup": operation_setting.PayAddress != "" && operation_setting.EpayId != "" && operation_setting.EpayKey != "",
"enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
"enable_creem_topup": setting.CreemApiKey != "" && setting.CreemProducts != "[]",
- "creem_products": setting.CreemProducts,
+ "enable_waffo_topup": enableWaffo,
+ "waffo_pay_methods": func() interface{} {
+ if enableWaffo {
+ return setting.GetWaffoPayMethods()
+ }
+ return nil
+ }(),
+ "creem_products": setting.CreemProducts,
"pay_methods": payMethods,
"min_topup": operation_setting.MinTopUp,
"stripe_min_topup": setting.StripeMinTopUp,
+ "waffo_min_topup": setting.WaffoMinTopUp,
"amount_options": operation_setting.GetPaymentSetting().AmountOptions,
"discount": operation_setting.GetPaymentSetting().AmountDiscount,
}
@@ -65,12 +103,10 @@ func GetTopUpInfo(c *gin.Context) {
type EpayRequest struct {
Amount int64 `json:"amount"`
PaymentMethod string `json:"payment_method"`
- TopUpCode string `json:"top_up_code"`
}
type AmountRequest struct {
- Amount int64 `json:"amount"`
- TopUpCode string `json:"top_up_code"`
+ Amount int64 `json:"amount"`
}
func GetEpayClient() *epay.Client {
@@ -206,34 +242,71 @@ func RequestEpay(c *gin.Context) {
var orderLocks sync.Map
var createLock sync.Mutex
+// refCountedMutex 带引用计数的互斥锁,确保最后一个使用者才从 map 中删除
+type refCountedMutex struct {
+ mu sync.Mutex
+ refCount int
+}
+
// LockOrder 尝试对给定订单号加锁
func LockOrder(tradeNo string) {
- lock, ok := orderLocks.Load(tradeNo)
- if !ok {
- createLock.Lock()
- defer createLock.Unlock()
- lock, ok = orderLocks.Load(tradeNo)
- if !ok {
- lock = new(sync.Mutex)
- orderLocks.Store(tradeNo, lock)
- }
+ createLock.Lock()
+ var rcm *refCountedMutex
+ if v, ok := orderLocks.Load(tradeNo); ok {
+ rcm = v.(*refCountedMutex)
+ } else {
+ rcm = &refCountedMutex{}
+ orderLocks.Store(tradeNo, rcm)
}
- lock.(*sync.Mutex).Lock()
+ rcm.refCount++
+ createLock.Unlock()
+ rcm.mu.Lock()
}
// UnlockOrder 释放给定订单号的锁
func UnlockOrder(tradeNo string) {
- lock, ok := orderLocks.Load(tradeNo)
- if ok {
- lock.(*sync.Mutex).Unlock()
+ v, ok := orderLocks.Load(tradeNo)
+ if !ok {
+ return
}
+ rcm := v.(*refCountedMutex)
+ rcm.mu.Unlock()
+
+ createLock.Lock()
+ rcm.refCount--
+ if rcm.refCount == 0 {
+ orderLocks.Delete(tradeNo)
+ }
+ createLock.Unlock()
}
func EpayNotify(c *gin.Context) {
- params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
- r[t] = c.Request.URL.Query().Get(t)
- return r
- }, map[string]string{})
+ var params map[string]string
+
+ if c.Request.Method == "POST" {
+ // POST 请求:从 POST body 解析参数
+ if err := c.Request.ParseForm(); err != nil {
+ log.Println("易支付回调POST解析失败:", err)
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
+ params = lo.Reduce(lo.Keys(c.Request.PostForm), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.PostForm.Get(t)
+ return r
+ }, map[string]string{})
+ } else {
+ // GET 请求:从 URL Query 解析参数
+ params = lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
+ r[t] = c.Request.URL.Query().Get(t)
+ return r
+ }, map[string]string{})
+ }
+
+ if len(params) == 0 {
+ log.Println("易支付回调参数为空")
+ _, _ = c.Writer.Write([]byte("fail"))
+ return
+ }
client := GetEpayClient()
if client == nil {
log.Println("易支付回调失败 未找到配置信息")
@@ -390,3 +463,4 @@ func AdminCompleteTopUp(c *gin.Context) {
}
common.ApiSuccess(c, nil)
}
+
diff --git a/controller/topup_creem.go b/controller/topup_creem.go
index 80a869673b..54b67b854f 100644
--- a/controller/topup_creem.go
+++ b/controller/topup_creem.go
@@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "errors"
"fmt"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
@@ -227,16 +228,6 @@ type CreemWebhookEvent struct {
} `json:"object"`
}
-// 保留旧的结构体作为兼容
-type CreemWebhookData struct {
- Type string `json:"type"`
- Data struct {
- RequestId string `json:"request_id"`
- Status string `json:"status"`
- Metadata map[string]string `json:"metadata"`
- } `json:"data"`
-}
-
func CreemWebhook(c *gin.Context) {
// 读取body内容用于打印,同时保留原始数据供后续使用
bodyBytes, err := io.ReadAll(c.Request.Body)
@@ -308,7 +299,19 @@ func handleCheckoutCompleted(c *gin.Context, event *CreemWebhookEvent) {
return
}
- // 验证订单类型,目前只处理一次性付款
+ // Try complete subscription order first
+ LockOrder(referenceId)
+ defer UnlockOrder(referenceId)
+ if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(event)); err == nil {
+ c.Status(http.StatusOK)
+ return
+ } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
+ log.Printf("Creem订阅订单处理失败: %s, 订单号: %s", err.Error(), referenceId)
+ c.AbortWithStatus(http.StatusInternalServerError)
+ return
+ }
+
+ // 验证订单类型,目前只处理一次性付款(充值)
if event.Object.Order.Type != "onetime" {
log.Printf("暂不支持的订单类型: %s, 跳过处理", event.Object.Order.Type)
c.Status(http.StatusOK)
diff --git a/controller/topup_stripe.go b/controller/topup_stripe.go
index 337ff8e738..e1718cc5ec 100644
--- a/controller/topup_stripe.go
+++ b/controller/topup_stripe.go
@@ -1,6 +1,7 @@
package controller
import (
+ "errors"
"fmt"
"io"
"log"
@@ -28,9 +29,18 @@ const (
var stripeAdaptor = &StripeAdaptor{}
+// StripePayRequest represents a payment request for Stripe checkout.
type StripePayRequest struct {
- Amount int64 `json:"amount"`
+ // Amount is the quantity of units to purchase.
+ Amount int64 `json:"amount"`
+ // PaymentMethod specifies the payment method (e.g., "stripe").
PaymentMethod string `json:"payment_method"`
+ // SuccessURL is the optional custom URL to redirect after successful payment.
+ // If empty, defaults to the server's console log page.
+ SuccessURL string `json:"success_url,omitempty"`
+ // CancelURL is the optional custom URL to redirect when payment is canceled.
+ // If empty, defaults to the server's console topup page.
+ CancelURL string `json:"cancel_url,omitempty"`
}
type StripeAdaptor struct {
@@ -69,6 +79,16 @@ func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
return
}
+ if req.SuccessURL != "" && common.ValidateRedirectURL(req.SuccessURL) != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"message": "支付成功重定向URL不在可信任域名列表中", "data": ""})
+ return
+ }
+
+ if req.CancelURL != "" && common.ValidateRedirectURL(req.CancelURL) != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"message": "支付取消重定向URL不在可信任域名列表中", "data": ""})
+ return
+ }
+
id := c.GetInt("id")
user, _ := model.GetUserById(id, false)
chargedMoney := GetChargedAmount(float64(req.Amount), *user)
@@ -76,7 +96,7 @@ func (*StripeAdaptor) RequestPay(c *gin.Context, req *StripePayRequest) {
reference := fmt.Sprintf("new-api-ref-%d-%d-%s", user.Id, time.Now().UnixMilli(), randstr.String(4))
referenceId := "ref_" + common.Sha1([]byte(reference))
- payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount)
+ payLink, err := genStripeLink(referenceId, user.StripeCustomer, user.Email, req.Amount, req.SuccessURL, req.CancelURL)
if err != nil {
log.Println("获取Stripe Checkout支付链接失败", err)
c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
@@ -166,6 +186,22 @@ func sessionCompleted(event stripe.Event) {
return
}
+ // Try complete subscription order first
+ LockOrder(referenceId)
+ defer UnlockOrder(referenceId)
+ payload := map[string]any{
+ "customer": customerId,
+ "amount_total": event.GetObjectValue("amount_total"),
+ "currency": strings.ToUpper(event.GetObjectValue("currency")),
+ "event_type": string(event.Type),
+ }
+ if err := model.CompleteSubscriptionOrder(referenceId, common.GetJsonString(payload)); err == nil {
+ return
+ } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
+ log.Println("complete subscription order failed:", err.Error(), referenceId)
+ return
+ }
+
err := model.Recharge(referenceId, customerId)
if err != nil {
log.Println(err.Error(), referenceId)
@@ -190,6 +226,16 @@ func sessionExpired(event stripe.Event) {
return
}
+ // Subscription order expiration
+ LockOrder(referenceId)
+ defer UnlockOrder(referenceId)
+ if err := model.ExpireSubscriptionOrder(referenceId); err == nil {
+ return
+ } else if err != nil && !errors.Is(err, model.ErrSubscriptionOrderNotFound) {
+ log.Println("过期订阅订单失败", referenceId, ", err:", err.Error())
+ return
+ }
+
topUp := model.GetTopUpByTradeNo(referenceId)
if topUp == nil {
log.Println("充值订单不存在", referenceId)
@@ -210,17 +256,37 @@ func sessionExpired(event stripe.Event) {
log.Println("充值订单已过期", referenceId)
}
-func genStripeLink(referenceId string, customerId string, email string, amount int64) (string, error) {
+// genStripeLink generates a Stripe Checkout session URL for payment.
+// It creates a new checkout session with the specified parameters and returns the payment URL.
+//
+// Parameters:
+// - referenceId: unique reference identifier for the transaction
+// - customerId: existing Stripe customer ID (empty string if new customer)
+// - email: customer email address for new customer creation
+// - amount: quantity of units to purchase
+// - successURL: custom URL to redirect after successful payment (empty for default)
+// - cancelURL: custom URL to redirect when payment is canceled (empty for default)
+//
+// Returns the checkout session URL or an error if the session creation fails.
+func genStripeLink(referenceId string, customerId string, email string, amount int64, successURL string, cancelURL string) (string, error) {
if !strings.HasPrefix(setting.StripeApiSecret, "sk_") && !strings.HasPrefix(setting.StripeApiSecret, "rk_") {
return "", fmt.Errorf("无效的Stripe API密钥")
}
stripe.Key = setting.StripeApiSecret
+ // Use custom URLs if provided, otherwise use defaults
+ if successURL == "" {
+ successURL = system_setting.ServerAddress + "/console/log"
+ }
+ if cancelURL == "" {
+ cancelURL = system_setting.ServerAddress + "/console/topup"
+ }
+
params := &stripe.CheckoutSessionParams{
ClientReferenceID: stripe.String(referenceId),
- SuccessURL: stripe.String(system_setting.ServerAddress + "/console/log"),
- CancelURL: stripe.String(system_setting.ServerAddress + "/console/topup"),
+ SuccessURL: stripe.String(successURL),
+ CancelURL: stripe.String(cancelURL),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Price: stripe.String(setting.StripePriceId),
diff --git a/controller/topup_waffo.go b/controller/topup_waffo.go
new file mode 100644
index 0000000000..fce3764233
--- /dev/null
+++ b/controller/topup_waffo.go
@@ -0,0 +1,380 @@
+package controller
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/setting"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/thanhpk/randstr"
+ waffo "github.com/waffo-com/waffo-go"
+ "github.com/waffo-com/waffo-go/config"
+ "github.com/waffo-com/waffo-go/core"
+ "github.com/waffo-com/waffo-go/types/order"
+)
+
+func getWaffoSDK() (*waffo.Waffo, error) {
+ env := config.Sandbox
+ apiKey := setting.WaffoSandboxApiKey
+ privateKey := setting.WaffoSandboxPrivateKey
+ publicKey := setting.WaffoSandboxPublicCert
+ if !setting.WaffoSandbox {
+ env = config.Production
+ apiKey = setting.WaffoApiKey
+ privateKey = setting.WaffoPrivateKey
+ publicKey = setting.WaffoPublicCert
+ }
+ builder := config.NewConfigBuilder().
+ APIKey(apiKey).
+ PrivateKey(privateKey).
+ WaffoPublicKey(publicKey).
+ Environment(env)
+ if setting.WaffoMerchantId != "" {
+ builder = builder.MerchantID(setting.WaffoMerchantId)
+ }
+ cfg, err := builder.Build()
+ if err != nil {
+ return nil, err
+ }
+ return waffo.New(cfg), nil
+}
+
+func getWaffoUserEmail(user *model.User) string {
+ return fmt.Sprintf("%d@examples.com", user.Id)
+}
+
+func getWaffoCurrency() string {
+ if setting.WaffoCurrency != "" {
+ return setting.WaffoCurrency
+ }
+ return "USD"
+}
+
+// zeroDecimalCurrencies 零小数位币种,金额不能带小数点
+var zeroDecimalCurrencies = map[string]bool{
+ "IDR": true, "JPY": true, "KRW": true, "VND": true,
+}
+
+func formatWaffoAmount(amount float64, currency string) string {
+ if zeroDecimalCurrencies[currency] {
+ return fmt.Sprintf("%.0f", amount)
+ }
+ return fmt.Sprintf("%.2f", amount)
+}
+
+// getWaffoPayMoney converts the user-facing amount to USD for Waffo payment.
+// Waffo only accepts USD, so this function handles the conversion from different
+// display types (USD/CNY/TOKENS) to the actual USD amount to charge.
+func getWaffoPayMoney(amount float64, group string) float64 {
+ originalAmount := amount
+ if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
+ amount = amount / common.QuotaPerUnit
+ }
+ topupGroupRatio := common.GetTopupGroupRatio(group)
+ if topupGroupRatio == 0 {
+ topupGroupRatio = 1
+ }
+ discount := 1.0
+ if ds, ok := operation_setting.GetPaymentSetting().AmountDiscount[int(originalAmount)]; ok {
+ if ds > 0 {
+ discount = ds
+ }
+ }
+ return amount * setting.WaffoUnitPrice * topupGroupRatio * discount
+}
+
+type WaffoPayRequest struct {
+ Amount int64 `json:"amount"`
+ PayMethodIndex *int `json:"pay_method_index"` // 服务端支付方式列表的索引,nil 表示由 Waffo 自动选择
+ PayMethodType string `json:"pay_method_type"` // Deprecated: 兼容旧前端,优先使用 pay_method_index
+ PayMethodName string `json:"pay_method_name"` // Deprecated: 兼容旧前端,优先使用 pay_method_index
+}
+
+// RequestWaffoPay 创建 Waffo 支付订单
+func RequestWaffoPay(c *gin.Context) {
+ if !setting.WaffoEnabled {
+ c.JSON(200, gin.H{"message": "error", "data": "Waffo 支付未启用"})
+ return
+ }
+
+ var req WaffoPayRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
+ return
+ }
+ waffoMinTopup := int64(setting.WaffoMinTopUp)
+ if req.Amount < waffoMinTopup {
+ c.JSON(200, gin.H{"message": "error", "data": fmt.Sprintf("充值数量不能小于 %d", waffoMinTopup)})
+ return
+ }
+
+ id := c.GetInt("id")
+ user, err := model.GetUserById(id, false)
+ if err != nil || user == nil {
+ c.JSON(200, gin.H{"message": "error", "data": "用户不存在"})
+ return
+ }
+
+ // 从服务端配置查找支付方式,客户端只传索引或旧字段
+ var resolvedPayMethodType, resolvedPayMethodName string
+ methods := setting.GetWaffoPayMethods()
+ if req.PayMethodIndex != nil {
+ // 新协议:按索引查找
+ idx := *req.PayMethodIndex
+ if idx < 0 || idx >= len(methods) {
+ log.Printf("Waffo 无效的支付方式索引: %d, UserId=%d, 可用范围: [0, %d)", idx, id, len(methods))
+ c.JSON(200, gin.H{"message": "error", "data": "不支持的支付方式"})
+ return
+ }
+ resolvedPayMethodType = methods[idx].PayMethodType
+ resolvedPayMethodName = methods[idx].PayMethodName
+ } else if req.PayMethodType != "" {
+ // 兼容旧前端:验证客户端传的值在服务端列表中
+ valid := false
+ for _, m := range methods {
+ if m.PayMethodType == req.PayMethodType && m.PayMethodName == req.PayMethodName {
+ valid = true
+ resolvedPayMethodType = m.PayMethodType
+ resolvedPayMethodName = m.PayMethodName
+ break
+ }
+ }
+ if !valid {
+ log.Printf("Waffo 无效的支付方式: PayMethodType=%s, PayMethodName=%s, UserId=%d", req.PayMethodType, req.PayMethodName, id)
+ c.JSON(200, gin.H{"message": "error", "data": "不支持的支付方式"})
+ return
+ }
+ }
+ // resolvedPayMethodType/Name 为空时,Waffo 自动选择支付方式
+
+ group, _ := model.GetUserGroup(id, true)
+ payMoney := getWaffoPayMoney(float64(req.Amount), group)
+ if payMoney < 0.01 {
+ c.JSON(200, gin.H{"message": "error", "data": "充值金额过低"})
+ return
+ }
+
+ // 生成唯一订单号,paymentRequestId 与 merchantOrderId 保持一致,简化追踪
+ merchantOrderId := fmt.Sprintf("WAFFO-%d-%d-%s", id, time.Now().UnixMilli(), randstr.String(6))
+ paymentRequestId := merchantOrderId
+
+ // Token 模式下归一化 Amount(存等价美元/CNY 数量,避免 RechargeWaffo 双重放大)
+ amount := req.Amount
+ if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeTokens {
+ amount = int64(float64(req.Amount) / common.QuotaPerUnit)
+ if amount < 1 {
+ amount = 1
+ }
+ }
+
+ // 创建本地订单
+ topUp := &model.TopUp{
+ UserId: id,
+ Amount: amount,
+ Money: payMoney,
+ TradeNo: merchantOrderId,
+ PaymentMethod: "waffo",
+ CreateTime: time.Now().Unix(),
+ Status: common.TopUpStatusPending,
+ }
+ if err := topUp.Insert(); err != nil {
+ log.Printf("Waffo 创建本地订单失败: %v", err)
+ c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
+ return
+ }
+
+ sdk, err := getWaffoSDK()
+ if err != nil {
+ log.Printf("Waffo SDK 初始化失败: %v", err)
+ topUp.Status = common.TopUpStatusFailed
+ _ = topUp.Update()
+ c.JSON(200, gin.H{"message": "error", "data": "支付配置错误"})
+ return
+ }
+
+ callbackAddr := service.GetCallbackAddress()
+ notifyUrl := callbackAddr + "/api/waffo/webhook"
+ if setting.WaffoNotifyUrl != "" {
+ notifyUrl = setting.WaffoNotifyUrl
+ }
+ returnUrl := system_setting.ServerAddress + "/console/topup?show_history=true"
+ if setting.WaffoReturnUrl != "" {
+ returnUrl = setting.WaffoReturnUrl
+ }
+
+ currency := getWaffoCurrency()
+ createParams := &order.CreateOrderParams{
+ PaymentRequestID: paymentRequestId,
+ MerchantOrderID: merchantOrderId,
+ OrderAmount: formatWaffoAmount(payMoney, currency),
+ OrderCurrency: currency,
+ OrderDescription: fmt.Sprintf("Recharge %d credits", req.Amount),
+ OrderRequestedAt: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
+ NotifyURL: notifyUrl,
+ MerchantInfo: &order.MerchantInfo{
+ MerchantID: setting.WaffoMerchantId,
+ },
+ UserInfo: &order.UserInfo{
+ UserID: strconv.Itoa(user.Id),
+ UserEmail: getWaffoUserEmail(user),
+ UserTerminal: "WEB",
+ },
+ PaymentInfo: &order.PaymentInfo{
+ ProductName: "ONE_TIME_PAYMENT",
+ PayMethodType: resolvedPayMethodType,
+ PayMethodName: resolvedPayMethodName,
+ },
+ SuccessRedirectURL: returnUrl,
+ FailedRedirectURL: returnUrl,
+ }
+ resp, err := sdk.Order().Create(c.Request.Context(), createParams, nil)
+ if err != nil {
+ log.Printf("Waffo 创建订单失败: %v", err)
+ topUp.Status = common.TopUpStatusFailed
+ _ = topUp.Update()
+ c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
+ return
+ }
+ if !resp.IsSuccess() {
+ log.Printf("Waffo 创建订单业务失败: [%s] %s, 完整响应: %+v", resp.Code, resp.Message, resp)
+ topUp.Status = common.TopUpStatusFailed
+ _ = topUp.Update()
+ c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
+ return
+ }
+
+ orderData := resp.GetData()
+ log.Printf("Waffo 订单创建成功 - 用户: %d, 订单: %s, 金额: %.2f", id, merchantOrderId, payMoney)
+
+ paymentUrl := orderData.FetchRedirectURL()
+ if paymentUrl == "" {
+ paymentUrl = orderData.OrderAction
+ }
+
+ c.JSON(200, gin.H{
+ "message": "success",
+ "data": gin.H{
+ "payment_url": paymentUrl,
+ "order_id": merchantOrderId,
+ },
+ })
+}
+
+// webhookPayloadWithSubInfo 扩展 PAYMENT_NOTIFICATION,包含 SDK 未定义的 subscriptionInfo 字段
+type webhookPayloadWithSubInfo struct {
+ EventType string `json:"eventType"`
+ Result struct {
+ core.PaymentNotificationResult
+ SubscriptionInfo *webhookSubscriptionInfo `json:"subscriptionInfo,omitempty"`
+ } `json:"result"`
+}
+
+type webhookSubscriptionInfo struct {
+ Period string `json:"period,omitempty"`
+ MerchantRequest string `json:"merchantRequest,omitempty"`
+ SubscriptionID string `json:"subscriptionId,omitempty"`
+ SubscriptionRequest string `json:"subscriptionRequest,omitempty"`
+}
+
+// WaffoWebhook 处理 Waffo 回调通知(支付/退款/订阅)
+func WaffoWebhook(c *gin.Context) {
+ bodyBytes, err := io.ReadAll(c.Request.Body)
+ if err != nil {
+ log.Printf("Waffo Webhook 读取 body 失败: %v", err)
+ c.AbortWithStatus(http.StatusBadRequest)
+ return
+ }
+
+ sdk, err := getWaffoSDK()
+ if err != nil {
+ log.Printf("Waffo Webhook SDK 初始化失败: %v", err)
+ c.AbortWithStatus(http.StatusInternalServerError)
+ return
+ }
+
+ wh := sdk.Webhook()
+ bodyStr := string(bodyBytes)
+ signature := c.GetHeader("X-SIGNATURE")
+
+ // 验证请求签名
+ if !wh.VerifySignature(bodyStr, signature) {
+ log.Printf("Waffo webhook 签名验证失败")
+ c.AbortWithStatus(http.StatusBadRequest)
+ return
+ }
+
+ var event core.WebhookEvent
+ if err := common.Unmarshal(bodyBytes, &event); err != nil {
+ log.Printf("Waffo Webhook 解析失败: %v", err)
+ sendWaffoWebhookResponse(c, wh, false, "invalid payload")
+ return
+ }
+
+ switch event.EventType {
+ case core.EventPayment:
+ // 解析为扩展类型,区分普通支付和订阅支付
+ var payload webhookPayloadWithSubInfo
+ if err := common.Unmarshal(bodyBytes, &payload); err != nil {
+ sendWaffoWebhookResponse(c, wh, false, "invalid payment payload")
+ return
+ }
+ log.Printf("Waffo Webhook - EventType: %s, MerchantOrderId: %s, OrderStatus: %s",
+ event.EventType, payload.Result.MerchantOrderID, payload.Result.OrderStatus)
+ handleWaffoPayment(c, wh, &payload.Result.PaymentNotificationResult)
+ default:
+ log.Printf("Waffo Webhook 未知事件: %s", event.EventType)
+ sendWaffoWebhookResponse(c, wh, true, "")
+ }
+}
+
+// handleWaffoPayment 处理支付完成通知
+func handleWaffoPayment(c *gin.Context, wh *core.WebhookHandler, result *core.PaymentNotificationResult) {
+ if result.OrderStatus != "PAY_SUCCESS" {
+ log.Printf("Waffo 订单状态非成功: %s, 订单: %s", result.OrderStatus, result.MerchantOrderID)
+ // 终态失败订单标记为 failed,避免永远停在 pending
+ if result.MerchantOrderID != "" {
+ if topUp := model.GetTopUpByTradeNo(result.MerchantOrderID); topUp != nil &&
+ topUp.Status == common.TopUpStatusPending {
+ topUp.Status = common.TopUpStatusFailed
+ _ = topUp.Update()
+ }
+ }
+ sendWaffoWebhookResponse(c, wh, true, "")
+ return
+ }
+
+ merchantOrderId := result.MerchantOrderID
+
+ LockOrder(merchantOrderId)
+ defer UnlockOrder(merchantOrderId)
+
+ if err := model.RechargeWaffo(merchantOrderId); err != nil {
+ log.Printf("Waffo 充值处理失败: %v, 订单: %s", err, merchantOrderId)
+ sendWaffoWebhookResponse(c, wh, false, err.Error())
+ return
+ }
+
+ log.Printf("Waffo 充值成功 - 订单: %s", merchantOrderId)
+ sendWaffoWebhookResponse(c, wh, true, "")
+}
+
+// sendWaffoWebhookResponse 发送签名响应
+func sendWaffoWebhookResponse(c *gin.Context, wh *core.WebhookHandler, success bool, msg string) {
+ var body, sig string
+ if success {
+ body, sig = wh.BuildSuccessResponse()
+ } else {
+ body, sig = wh.BuildFailedResponse(msg)
+ }
+ c.Header("X-SIGNATURE", sig)
+ c.Data(http.StatusOK, "application/json", []byte(body))
+}
diff --git a/controller/usedata.go b/controller/usedata.go
index 816988a2bb..5e194c5175 100644
--- a/controller/usedata.go
+++ b/controller/usedata.go
@@ -27,6 +27,21 @@ func GetAllQuotaDates(c *gin.Context) {
return
}
+func GetQuotaDatesByUser(c *gin.Context) {
+ startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
+ endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64)
+ dates, err := model.GetQuotaDataGroupByUser(startTimestamp, endTimestamp)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "",
+ "data": dates,
+ })
+}
+
func GetUserQuotaDates(c *gin.Context) {
userId := c.GetInt("id")
startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64)
diff --git a/controller/user.go b/controller/user.go
index 1fc83c99e7..8229d0d2c2 100644
--- a/controller/user.go
+++ b/controller/user.go
@@ -2,6 +2,7 @@ package controller
import (
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/url"
@@ -11,6 +12,7 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
@@ -29,28 +31,19 @@ type LoginRequest struct {
func Login(c *gin.Context) {
if !common.PasswordLoginEnabled {
- c.JSON(http.StatusOK, gin.H{
- "message": "管理员关闭了密码登录",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgUserPasswordLoginDisabled)
return
}
var loginRequest LoginRequest
err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "message": "无效的参数",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
username := loginRequest.Username
password := loginRequest.Password
if username == "" || password == "" {
- c.JSON(http.StatusOK, gin.H{
- "message": "无效的参数",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
user := model.User{
@@ -74,15 +67,12 @@ func Login(c *gin.Context) {
session.Set("pending_user_id", user.Id)
err := session.Save()
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "message": "无法保存会话信息,请重试",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
return
}
c.JSON(http.StatusOK, gin.H{
- "message": "请输入两步验证码",
+ "message": i18n.T(c, i18n.MsgUserRequire2FA),
"success": true,
"data": map[string]interface{}{
"require_2fa": true,
@@ -104,10 +94,7 @@ func setupLogin(user *model.User, c *gin.Context) {
session.Set("group", user.Group)
err := session.Save()
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "message": "无法保存会话信息,请重试",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgUserSessionSaveFailed)
return
}
c.JSON(http.StatusOK, gin.H{
@@ -143,65 +130,41 @@ func Logout(c *gin.Context) {
func Register(c *gin.Context) {
if !common.RegisterEnabled {
- c.JSON(http.StatusOK, gin.H{
- "message": "管理员关闭了新用户注册",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
return
}
if !common.PasswordRegisterEnabled {
- c.JSON(http.StatusOK, gin.H{
- "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
- "success": false,
- })
+ common.ApiErrorI18n(c, i18n.MsgUserPasswordRegisterDisabled)
return
}
var user model.User
err := json.NewDecoder(c.Request.Body).Decode(&user)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
if err := common.Validate.Struct(&user); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "输入不合法 " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
return
}
if common.EmailVerificationEnabled {
if user.Email == "" || user.VerificationCode == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserEmailVerificationRequired)
return
}
if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "验证码错误或已过期",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
return
}
}
exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "数据库错误,请稍后重试",
- })
+ common.ApiErrorI18n(c, i18n.MsgDatabaseError)
common.SysLog(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
return
}
if exist {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "用户名已存在,或已注销",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserExists)
return
}
affCode := user.AffCode // this code is the inviter's code, not the user's own code
@@ -224,20 +187,14 @@ func Register(c *gin.Context) {
// 获取插入后的用户ID
var insertedUser model.User
if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "用户注册失败或用户ID获取失败",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserRegisterFailed)
return
}
// 生成默认令牌
if constant.GenerateDefaultToken {
key, err := common.GenerateKey()
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "生成默认令牌失败",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserDefaultTokenFailed)
common.SysLog("failed to generate token key: " + err.Error())
return
}
@@ -257,10 +214,7 @@ func Register(c *gin.Context) {
token.Group = "auto"
}
if err := token.Insert(); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "创建默认令牌失败",
- })
+ common.ApiErrorI18n(c, i18n.MsgCreateDefaultTokenErr)
return
}
}
@@ -316,10 +270,7 @@ func GetUser(c *gin.Context) {
}
myRole := c.GetInt("role")
if myRole <= user.Role && myRole != common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权获取同级或更高等级用户的信息",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
return
}
c.JSON(http.StatusOK, gin.H{
@@ -341,20 +292,14 @@ func GenerateAccessToken(c *gin.Context) {
randI := common.GetRandomInt(4)
key, err := common.GenerateRandomKey(29 + randI)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "生成失败",
- })
+ common.ApiErrorI18n(c, i18n.MsgGenerateFailed)
common.SysLog("failed to generate key: " + err.Error())
return
}
user.SetAccessToken(key)
if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "请重试,系统生成的 UUID 竟然重复了!",
- })
+ common.ApiErrorI18n(c, i18n.MsgUuidDuplicate)
return
}
@@ -389,16 +334,10 @@ func TransferAffQuota(c *gin.Context) {
}
err = user.TransferAffQuotaToQuota(tran.Quota)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "划转失败 " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUserTransferFailed, map[string]any{"Error": err.Error()})
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "划转成功",
- })
+ common.ApiSuccessI18n(c, i18n.MsgUserTransferSuccess, nil)
}
func GetAffCode(c *gin.Context) {
@@ -601,20 +540,14 @@ func UpdateUser(c *gin.Context) {
var updatedUser model.User
err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
if err != nil || updatedUser.Id == 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
if updatedUser.Password == "" {
updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
}
if err := common.Validate.Struct(&updatedUser); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "输入不合法 " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
return
}
originUser, err := model.GetUserById(updatedUser.Id, false)
@@ -624,17 +557,11 @@ func UpdateUser(c *gin.Context) {
}
myRole := c.GetInt("role")
if myRole <= originUser.Role && myRole != common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权更新同权限等级或更高权限等级的用户信息",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
return
}
if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
return
}
if updatedUser.Password == "$I_LOVE_U" {
@@ -655,19 +582,54 @@ func UpdateUser(c *gin.Context) {
return
}
+func AdminClearUserBinding(c *gin.Context) {
+ id, err := strconv.Atoi(c.Param("id"))
+ if err != nil {
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
+ return
+ }
+
+ bindingType := strings.ToLower(strings.TrimSpace(c.Param("binding_type")))
+ if bindingType == "" {
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
+ return
+ }
+
+ user, err := model.GetUserById(id, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ myRole := c.GetInt("role")
+ if myRole <= user.Role && myRole != common.RoleRootUser {
+ common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
+ return
+ }
+
+ if err := user.ClearBinding(bindingType); err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ model.RecordLog(user.Id, model.LogTypeManage, fmt.Sprintf("admin cleared %s binding for user %s", bindingType, user.Username))
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "message": "success",
+ })
+}
+
func UpdateSelf(c *gin.Context) {
var requestData map[string]interface{}
err := json.NewDecoder(c.Request.Body).Decode(&requestData)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
- // 检查是否是sidebar_modules更新请求
- if sidebarModules, exists := requestData["sidebar_modules"]; exists {
+ // 检查是否是用户设置更新请求 (sidebar_modules 或 language)
+ if sidebarModules, sidebarExists := requestData["sidebar_modules"]; sidebarExists {
userId := c.GetInt("id")
user, err := model.GetUserById(userId, false)
if err != nil {
@@ -686,17 +648,39 @@ func UpdateSelf(c *gin.Context) {
// 保存更新后的设置
user.SetSetting(currentSetting)
if err := user.Update(false); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "更新设置失败: " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "设置更新成功",
- })
+ common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
+ return
+ }
+
+ // 检查是否是语言偏好更新请求
+ if language, langExists := requestData["language"]; langExists {
+ userId := c.GetInt("id")
+ user, err := model.GetUserById(userId, false)
+ if err != nil {
+ common.ApiError(c, err)
+ return
+ }
+
+ // 获取当前用户设置
+ currentSetting := user.GetSetting()
+
+ // 更新language字段
+ if langStr, ok := language.(string); ok {
+ currentSetting.Language = langStr
+ }
+
+ // 保存更新后的设置
+ user.SetSetting(currentSetting)
+ if err := user.Update(false); err != nil {
+ common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
+ return
+ }
+
+ common.ApiSuccessI18n(c, i18n.MsgUpdateSuccess, nil)
return
}
@@ -704,18 +688,12 @@ func UpdateSelf(c *gin.Context) {
var user model.User
requestDataBytes, err := json.Marshal(requestData)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
err = json.Unmarshal(requestDataBytes, &user)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
@@ -723,10 +701,7 @@ func UpdateSelf(c *gin.Context) {
user.Password = "$I_LOVE_U" // make Validator happy :)
}
if err := common.Validate.Struct(&user); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "输入不合法 " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidInput)
return
}
@@ -790,10 +765,7 @@ func DeleteUser(c *gin.Context) {
}
myRole := c.GetInt("role")
if myRole <= originUser.Role {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权删除同权限等级或更高权限等级的用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
return
}
err = model.HardDeleteUserById(id)
@@ -811,10 +783,7 @@ func DeleteSelf(c *gin.Context) {
user, _ := model.GetUserById(id, false)
if user.Role == common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "不能删除超级管理员账户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
return
}
@@ -835,17 +804,11 @@ func CreateUser(c *gin.Context) {
err := json.NewDecoder(c.Request.Body).Decode(&user)
user.Username = strings.TrimSpace(user.Username)
if err != nil || user.Username == "" || user.Password == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
if err := common.Validate.Struct(&user); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "输入不合法 " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUserInputInvalid, map[string]any{"Error": err.Error()})
return
}
if user.DisplayName == "" {
@@ -853,10 +816,7 @@ func CreateUser(c *gin.Context) {
}
myRole := c.GetInt("role")
if user.Role >= myRole {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无法创建权限大于等于自己的用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
return
}
// Even for admin users, we cannot fully trust them!
@@ -889,10 +849,7 @@ func ManageUser(c *gin.Context) {
err := json.NewDecoder(c.Request.Body).Decode(&req)
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
user := model.User{
@@ -901,38 +858,26 @@ func ManageUser(c *gin.Context) {
// Fill attributes
model.DB.Unscoped().Where(&user).First(&user)
if user.Id == 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "用户不存在",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserNotExists)
return
}
myRole := c.GetInt("role")
if myRole <= user.Role && myRole != common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无权更新同权限等级或更高权限等级的用户信息",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
return
}
switch req.Action {
case "disable":
user.Status = common.UserStatusDisabled
if user.Role == common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无法禁用超级管理员用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotDisableRootUser)
return
}
case "enable":
user.Status = common.UserStatusEnabled
case "delete":
if user.Role == common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无法删除超级管理员用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotDeleteRootUser)
return
}
if err := user.Delete(); err != nil {
@@ -944,33 +889,21 @@ func ManageUser(c *gin.Context) {
}
case "promote":
if myRole != common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "普通管理员用户无法提升其他用户为管理员",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserAdminCannotPromote)
return
}
if user.Role >= common.RoleAdminUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "该用户已经是管理员",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserAlreadyAdmin)
return
}
user.Role = common.RoleAdminUser
case "demote":
if user.Role == common.RoleRootUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无法降级超级管理员用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserCannotDemoteRootUser)
return
}
if user.Role == common.RoleCommonUser {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "该用户已经是普通用户",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserAlreadyCommon)
return
}
user.Role = common.RoleCommonUser
@@ -992,14 +925,21 @@ func ManageUser(c *gin.Context) {
return
}
+type emailBindRequest struct {
+ Email string `json:"email"`
+ Code string `json:"code"`
+}
+
func EmailBind(c *gin.Context) {
- email := c.Query("email")
- code := c.Query("code")
+ var req emailBindRequest
+ if err := common.DecodeJson(c.Request.Body, &req); err != nil {
+ common.ApiError(c, errors.New("invalid request body"))
+ return
+ }
+ email := req.Email
+ code := req.Code
if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "验证码错误或已过期",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserVerificationCodeError)
return
}
session := sessions.Default(c)
@@ -1075,10 +1015,7 @@ func TopUp(c *gin.Context) {
id := c.GetInt("id")
lock := getTopUpLock(id)
if !lock.TryLock() {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "充值处理中,请稍后重试",
- })
+ common.ApiErrorI18n(c, i18n.MsgUserTopUpProcessing)
return
}
defer lock.Unlock()
@@ -1090,6 +1027,10 @@ func TopUp(c *gin.Context) {
}
quota, err := model.Redeem(req.Key, id)
if err != nil {
+ if errors.Is(err, model.ErrRedeemFailed) {
+ common.ApiErrorI18n(c, i18n.MsgRedeemFailed)
+ return
+ }
common.ApiError(c, err)
return
}
@@ -1101,62 +1042,48 @@ func TopUp(c *gin.Context) {
}
type UpdateUserSettingRequest struct {
- QuotaWarningType string `json:"notify_type"`
- QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
- WebhookUrl string `json:"webhook_url,omitempty"`
- WebhookSecret string `json:"webhook_secret,omitempty"`
- NotificationEmail string `json:"notification_email,omitempty"`
- BarkUrl string `json:"bark_url,omitempty"`
- GotifyUrl string `json:"gotify_url,omitempty"`
- GotifyToken string `json:"gotify_token,omitempty"`
- GotifyPriority int `json:"gotify_priority,omitempty"`
- AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
- RecordIpLog bool `json:"record_ip_log"`
+ QuotaWarningType string `json:"notify_type"`
+ QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
+ WebhookUrl string `json:"webhook_url,omitempty"`
+ WebhookSecret string `json:"webhook_secret,omitempty"`
+ NotificationEmail string `json:"notification_email,omitempty"`
+ BarkUrl string `json:"bark_url,omitempty"`
+ GotifyUrl string `json:"gotify_url,omitempty"`
+ GotifyToken string `json:"gotify_token,omitempty"`
+ GotifyPriority int `json:"gotify_priority,omitempty"`
+ UpstreamModelUpdateNotifyEnabled *bool `json:"upstream_model_update_notify_enabled,omitempty"`
+ AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
+ RecordIpLog bool `json:"record_ip_log"`
}
func UpdateUserSetting(c *gin.Context) {
var req UpdateUserSettingRequest
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的参数",
- })
+ common.ApiErrorI18n(c, i18n.MsgInvalidParams)
return
}
// 验证预警类型
if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark && req.QuotaWarningType != dto.NotifyTypeGotify {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的预警类型",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingInvalidType)
return
}
// 验证预警阈值
if req.QuotaWarningThreshold <= 0 {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "预警阈值必须大于0",
- })
+ common.ApiErrorI18n(c, i18n.MsgQuotaThresholdGtZero)
return
}
// 如果是webhook类型,验证webhook地址
if req.QuotaWarningType == dto.NotifyTypeWebhook {
if req.WebhookUrl == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Webhook地址不能为空",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingWebhookEmpty)
return
}
// 验证URL格式
if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的Webhook地址",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingWebhookInvalid)
return
}
}
@@ -1165,10 +1092,7 @@ func UpdateUserSetting(c *gin.Context) {
if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
// 验证邮箱格式
if !strings.Contains(req.NotificationEmail, "@") {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的邮箱地址",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingEmailInvalid)
return
}
}
@@ -1176,26 +1100,17 @@ func UpdateUserSetting(c *gin.Context) {
// 如果是Bark类型,验证Bark URL
if req.QuotaWarningType == dto.NotifyTypeBark {
if req.BarkUrl == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Bark推送URL不能为空",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlEmpty)
return
}
// 验证URL格式
if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的Bark推送URL",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingBarkUrlInvalid)
return
}
// 检查是否是HTTP或HTTPS
if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Bark推送URL必须以http://或https://开头",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
return
}
}
@@ -1203,33 +1118,21 @@ func UpdateUserSetting(c *gin.Context) {
// 如果是Gotify类型,验证Gotify URL和Token
if req.QuotaWarningType == dto.NotifyTypeGotify {
if req.GotifyUrl == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Gotify服务器地址不能为空",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlEmpty)
return
}
if req.GotifyToken == "" {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Gotify令牌不能为空",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingGotifyTokenEmpty)
return
}
// 验证URL格式
if _, err := url.ParseRequestURI(req.GotifyUrl); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "无效的Gotify服务器地址",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingGotifyUrlInvalid)
return
}
// 检查是否是HTTP或HTTPS
if !strings.HasPrefix(req.GotifyUrl, "https://") && !strings.HasPrefix(req.GotifyUrl, "http://") {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "Gotify服务器地址必须以http://或https://开头",
- })
+ common.ApiErrorI18n(c, i18n.MsgSettingUrlMustHttp)
return
}
}
@@ -1240,13 +1143,19 @@ func UpdateUserSetting(c *gin.Context) {
common.ApiError(c, err)
return
}
+ existingSettings := user.GetSetting()
+ upstreamModelUpdateNotifyEnabled := existingSettings.UpstreamModelUpdateNotifyEnabled
+ if user.Role >= common.RoleAdminUser && req.UpstreamModelUpdateNotifyEnabled != nil {
+ upstreamModelUpdateNotifyEnabled = *req.UpstreamModelUpdateNotifyEnabled
+ }
// 构建设置
settings := dto.UserSetting{
- NotifyType: req.QuotaWarningType,
- QuotaWarningThreshold: req.QuotaWarningThreshold,
- AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
- RecordIpLog: req.RecordIpLog,
+ NotifyType: req.QuotaWarningType,
+ QuotaWarningThreshold: req.QuotaWarningThreshold,
+ UpstreamModelUpdateNotifyEnabled: upstreamModelUpdateNotifyEnabled,
+ AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
+ RecordIpLog: req.RecordIpLog,
}
// 如果是webhook类型,添加webhook相关设置
@@ -1282,15 +1191,9 @@ func UpdateUserSetting(c *gin.Context) {
// 更新用户设置
user.SetSetting(settings)
if err := user.Update(false); err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "message": "更新设置失败: " + err.Error(),
- })
+ common.ApiErrorI18n(c, i18n.MsgUpdateFailed)
return
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "设置已更新",
- })
+ common.ApiSuccessI18n(c, i18n.MsgSettingSaved, nil)
}
diff --git a/controller/video_proxy.go b/controller/video_proxy.go
index f102baae4a..520d313a31 100644
--- a/controller/video_proxy.go
+++ b/controller/video_proxy.go
@@ -2,73 +2,63 @@ package controller
import (
"context"
+ "encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
+ "strings"
"time"
+ "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
)
+// videoProxyError returns a standardized OpenAI-style error response.
+func videoProxyError(c *gin.Context, status int, errType, message string) {
+ c.JSON(status, gin.H{
+ "error": gin.H{
+ "message": message,
+ "type": errType,
+ },
+ })
+}
+
func VideoProxy(c *gin.Context) {
taskID := c.Param("task_id")
if taskID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": gin.H{
- "message": "task_id is required",
- "type": "invalid_request_error",
- },
- })
+ videoProxyError(c, http.StatusBadRequest, "invalid_request_error", "task_id is required")
return
}
- task, exists, err := model.GetByOnlyTaskId(taskID)
+ userID := c.GetInt("id")
+ task, exists, err := model.GetByTaskId(userID, taskID)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to query task %s: %s", taskID, err.Error()))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "Failed to query task",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "Failed to query task")
return
}
if !exists || task == nil {
- logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to get task %s: %v", taskID, err))
- c.JSON(http.StatusNotFound, gin.H{
- "error": gin.H{
- "message": "Task not found",
- "type": "invalid_request_error",
- },
- })
+ videoProxyError(c, http.StatusNotFound, "invalid_request_error", "Task not found")
return
}
if task.Status != model.TaskStatusSuccess {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": gin.H{
- "message": fmt.Sprintf("Task is not completed yet, current status: %s", task.Status),
- "type": "invalid_request_error",
- },
- })
+ videoProxyError(c, http.StatusBadRequest, "invalid_request_error",
+ fmt.Sprintf("Task is not completed yet, current status: %s", task.Status))
return
}
channel, err := model.CacheGetChannel(task.ChannelId)
if err != nil {
- logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to get task %s: not found", taskID))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "Failed to retrieve channel information",
- "type": "server_error",
- },
- })
+ logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to get channel for task %s: %s", taskID, err.Error()))
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "Failed to retrieve channel information")
return
}
baseURL := channel.GetBaseURL()
@@ -81,12 +71,7 @@ func VideoProxy(c *gin.Context) {
client, err := service.GetHttpClientWithProxy(proxy)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to create proxy client for task %s: %s", taskID, err.Error()))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "Failed to create proxy client",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "Failed to create proxy client")
return
}
@@ -95,12 +80,7 @@ func VideoProxy(c *gin.Context) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "", nil)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to create request: %s", err.Error()))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "Failed to create proxy request",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "Failed to create proxy request")
return
}
@@ -109,68 +89,72 @@ func VideoProxy(c *gin.Context) {
apiKey := task.PrivateData.Key
if apiKey == "" {
logger.LogError(c.Request.Context(), fmt.Sprintf("Missing stored API key for Gemini task %s", taskID))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "API key not stored for task",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "API key not stored for task")
return
}
-
videoURL, err = getGeminiVideoURL(channel, task, apiKey)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to resolve Gemini video URL for task %s: %s", taskID, err.Error()))
- c.JSON(http.StatusBadGateway, gin.H{
- "error": gin.H{
- "message": "Failed to resolve Gemini video URL",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusBadGateway, "server_error", "Failed to resolve Gemini video URL")
return
}
req.Header.Set("x-goog-api-key", apiKey)
+ case constant.ChannelTypeVertexAi:
+ videoURL, err = getVertexVideoURL(channel, task)
+ if err != nil {
+ logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to resolve Vertex video URL for task %s: %s", taskID, err.Error()))
+ videoProxyError(c, http.StatusBadGateway, "server_error", "Failed to resolve Vertex video URL")
+ return
+ }
case constant.ChannelTypeOpenAI, constant.ChannelTypeSora:
- videoURL = fmt.Sprintf("%s/v1/videos/%s/content", baseURL, task.TaskID)
+ videoURL = fmt.Sprintf("%s/v1/videos/%s/content", baseURL, task.GetUpstreamTaskID())
req.Header.Set("Authorization", "Bearer "+channel.Key)
default:
- // Video URL is directly in task.FailReason
- videoURL = task.FailReason
+ // Video URL is stored in PrivateData.ResultURL (fallback to FailReason for old data)
+ videoURL = task.GetResultURL()
+ }
+
+ videoURL = strings.TrimSpace(videoURL)
+ if videoURL == "" {
+ logger.LogError(c.Request.Context(), fmt.Sprintf("Video URL is empty for task %s", taskID))
+ videoProxyError(c, http.StatusBadGateway, "server_error", "Failed to fetch video content")
+ return
+ }
+
+ if strings.HasPrefix(videoURL, "data:") {
+ if err := writeVideoDataURL(c, videoURL); err != nil {
+ logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to decode video data URL for task %s: %s", taskID, err.Error()))
+ videoProxyError(c, http.StatusBadGateway, "server_error", "Failed to fetch video content")
+ }
+ return
+ }
+
+ fetchSetting := system_setting.GetFetchSetting()
+ if err := common.ValidateURLWithFetchSetting(videoURL, fetchSetting.EnableSSRFProtection, fetchSetting.AllowPrivateIp, fetchSetting.DomainFilterMode, fetchSetting.IpFilterMode, fetchSetting.DomainList, fetchSetting.IpList, fetchSetting.AllowedPorts, fetchSetting.ApplyIPFilterForDomain); err != nil {
+ logger.LogError(c.Request.Context(), fmt.Sprintf("Video URL blocked for task %s: %v", taskID, err))
+ videoProxyError(c, http.StatusForbidden, "server_error", fmt.Sprintf("request blocked: %v", err))
+ return
}
req.URL, err = url.Parse(videoURL)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to parse URL %s: %s", videoURL, err.Error()))
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": gin.H{
- "message": "Failed to create proxy request",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusInternalServerError, "server_error", "Failed to create proxy request")
return
}
resp, err := client.Do(req)
if err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to fetch video from %s: %s", videoURL, err.Error()))
- c.JSON(http.StatusBadGateway, gin.H{
- "error": gin.H{
- "message": "Failed to fetch video content",
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusBadGateway, "server_error", "Failed to fetch video content")
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.LogError(c.Request.Context(), fmt.Sprintf("Upstream returned status %d for %s", resp.StatusCode, videoURL))
- c.JSON(http.StatusBadGateway, gin.H{
- "error": gin.H{
- "message": fmt.Sprintf("Upstream service returned status %d", resp.StatusCode),
- "type": "server_error",
- },
- })
+ videoProxyError(c, http.StatusBadGateway, "server_error",
+ fmt.Sprintf("Upstream service returned status %d", resp.StatusCode))
return
}
@@ -180,10 +164,42 @@ func VideoProxy(c *gin.Context) {
}
}
- c.Writer.Header().Set("Cache-Control", "public, max-age=86400") // Cache for 24 hours
+ c.Writer.Header().Set("Cache-Control", "public, max-age=86400")
c.Writer.WriteHeader(resp.StatusCode)
- _, err = io.Copy(c.Writer, resp.Body)
- if err != nil {
+ if _, err = io.Copy(c.Writer, resp.Body); err != nil {
logger.LogError(c.Request.Context(), fmt.Sprintf("Failed to stream video content: %s", err.Error()))
}
}
+
+func writeVideoDataURL(c *gin.Context, dataURL string) error {
+ parts := strings.SplitN(dataURL, ",", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid data url")
+ }
+
+ header := parts[0]
+ payload := parts[1]
+ if !strings.HasPrefix(header, "data:") || !strings.Contains(header, ";base64") {
+ return fmt.Errorf("unsupported data url")
+ }
+
+ mimeType := strings.TrimPrefix(header, "data:")
+ mimeType = strings.TrimSuffix(mimeType, ";base64")
+ if mimeType == "" {
+ mimeType = "video/mp4"
+ }
+
+ videoBytes, err := base64.StdEncoding.DecodeString(payload)
+ if err != nil {
+ videoBytes, err = base64.RawStdEncoding.DecodeString(payload)
+ if err != nil {
+ return err
+ }
+ }
+
+ c.Writer.Header().Set("Content-Type", mimeType)
+ c.Writer.Header().Set("Cache-Control", "public, max-age=86400")
+ c.Writer.WriteHeader(http.StatusOK)
+ _, err = c.Writer.Write(videoBytes)
+ return err
+}
diff --git a/controller/video_proxy_gemini.go b/controller/video_proxy_gemini.go
index 053ac65155..0c76e33c70 100644
--- a/controller/video_proxy_gemini.go
+++ b/controller/video_proxy_gemini.go
@@ -1,12 +1,12 @@
package controller
import (
- "encoding/json"
"fmt"
"io"
"strconv"
"strings"
+ "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay"
@@ -37,7 +37,7 @@ func getGeminiVideoURL(channel *model.Channel, task *model.Task, apiKey string)
proxy := channel.GetSetting().Proxy
resp, err := adaptor.FetchTask(baseURL, apiKey, map[string]any{
- "task_id": task.TaskID,
+ "task_id": task.GetUpstreamTaskID(),
"action": task.Action,
}, proxy)
if err != nil {
@@ -71,7 +71,7 @@ func extractGeminiVideoURLFromTaskData(task *model.Task) string {
return ""
}
var payload map[string]any
- if err := json.Unmarshal(task.Data, &payload); err != nil {
+ if err := common.Unmarshal(task.Data, &payload); err != nil {
return ""
}
return extractGeminiVideoURLFromMap(payload)
@@ -79,7 +79,7 @@ func extractGeminiVideoURLFromTaskData(task *model.Task) string {
func extractGeminiVideoURLFromPayload(body []byte) string {
var payload map[string]any
- if err := json.Unmarshal(body, &payload); err != nil {
+ if err := common.Unmarshal(body, &payload); err != nil {
return ""
}
return extractGeminiVideoURLFromMap(payload)
@@ -145,6 +145,141 @@ func extractGeminiVideoURLFromGeneratedSamples(gvr map[string]any) string {
return ""
}
+func getVertexVideoURL(channel *model.Channel, task *model.Task) (string, error) {
+ if channel == nil || task == nil {
+ return "", fmt.Errorf("invalid channel or task")
+ }
+ if url := strings.TrimSpace(task.GetResultURL()); url != "" && !isTaskProxyContentURL(url, task.TaskID) {
+ return url, nil
+ }
+ if url := extractVertexVideoURLFromTaskData(task); url != "" {
+ return url, nil
+ }
+
+ baseURL := constant.ChannelBaseURLs[channel.Type]
+ if channel.GetBaseURL() != "" {
+ baseURL = channel.GetBaseURL()
+ }
+
+ adaptor := relay.GetTaskAdaptor(constant.TaskPlatform(strconv.Itoa(channel.Type)))
+ if adaptor == nil {
+ return "", fmt.Errorf("vertex task adaptor not found")
+ }
+
+ key := getVertexTaskKey(channel, task)
+ if key == "" {
+ return "", fmt.Errorf("vertex key not available for task")
+ }
+
+ resp, err := adaptor.FetchTask(baseURL, key, map[string]any{
+ "task_id": task.GetUpstreamTaskID(),
+ "action": task.Action,
+ }, channel.GetSetting().Proxy)
+ if err != nil {
+ return "", fmt.Errorf("fetch task failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", fmt.Errorf("read task response failed: %w", err)
+ }
+
+ taskInfo, parseErr := adaptor.ParseTaskResult(body)
+ if parseErr == nil && taskInfo != nil && strings.TrimSpace(taskInfo.Url) != "" {
+ return taskInfo.Url, nil
+ }
+ if url := extractVertexVideoURLFromPayload(body); url != "" {
+ return url, nil
+ }
+ if parseErr != nil {
+ return "", fmt.Errorf("parse task result failed: %w", parseErr)
+ }
+ return "", fmt.Errorf("vertex video url not found")
+}
+
+func isTaskProxyContentURL(url string, taskID string) bool {
+ if strings.TrimSpace(url) == "" || strings.TrimSpace(taskID) == "" {
+ return false
+ }
+ return strings.Contains(url, "/v1/videos/"+taskID+"/content")
+}
+
+func getVertexTaskKey(channel *model.Channel, task *model.Task) string {
+ if task != nil {
+ if key := strings.TrimSpace(task.PrivateData.Key); key != "" {
+ return key
+ }
+ }
+ if channel == nil {
+ return ""
+ }
+ keys := channel.GetKeys()
+ for _, key := range keys {
+ key = strings.TrimSpace(key)
+ if key != "" {
+ return key
+ }
+ }
+ return strings.TrimSpace(channel.Key)
+}
+
+func extractVertexVideoURLFromTaskData(task *model.Task) string {
+ if task == nil || len(task.Data) == 0 {
+ return ""
+ }
+ return extractVertexVideoURLFromPayload(task.Data)
+}
+
+func extractVertexVideoURLFromPayload(body []byte) string {
+ var payload map[string]any
+ if err := common.Unmarshal(body, &payload); err != nil {
+ return ""
+ }
+ resp, ok := payload["response"].(map[string]any)
+ if !ok || resp == nil {
+ return ""
+ }
+
+ if videos, ok := resp["videos"].([]any); ok && len(videos) > 0 {
+ if video, ok := videos[0].(map[string]any); ok && video != nil {
+ if b64, _ := video["bytesBase64Encoded"].(string); strings.TrimSpace(b64) != "" {
+ mime, _ := video["mimeType"].(string)
+ enc, _ := video["encoding"].(string)
+ return buildVideoDataURL(mime, enc, b64)
+ }
+ }
+ }
+ if b64, _ := resp["bytesBase64Encoded"].(string); strings.TrimSpace(b64) != "" {
+ enc, _ := resp["encoding"].(string)
+ return buildVideoDataURL("", enc, b64)
+ }
+ if video, _ := resp["video"].(string); strings.TrimSpace(video) != "" {
+ if strings.HasPrefix(video, "data:") || strings.HasPrefix(video, "http://") || strings.HasPrefix(video, "https://") {
+ return video
+ }
+ enc, _ := resp["encoding"].(string)
+ return buildVideoDataURL("", enc, video)
+ }
+ return ""
+}
+
+func buildVideoDataURL(mimeType string, encoding string, base64Data string) string {
+ mime := strings.TrimSpace(mimeType)
+ if mime == "" {
+ enc := strings.TrimSpace(encoding)
+ if enc == "" {
+ enc = "mp4"
+ }
+ if strings.Contains(enc, "/") {
+ mime = enc
+ } else {
+ mime = "video/" + enc
+ }
+ }
+ return "data:" + mime + ";base64," + base64Data
+}
+
func ensureAPIKey(uri, key string) string {
if key == "" || uri == "" {
return uri
diff --git a/controller/wechat.go b/controller/wechat.go
index 07f2fb32e8..8889daca77 100644
--- a/controller/wechat.go
+++ b/controller/wechat.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"strconv"
"time"
@@ -25,7 +26,7 @@ func getWeChatIdByCode(code string) (string, error) {
if code == "" {
return "", errors.New("无效的参数")
}
- req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/wechat/user?code=%s", common.WeChatServerAddress, code), nil)
+ req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/wechat/user?code=%s", common.WeChatServerAddress, url.QueryEscape(code)), nil)
if err != nil {
return "", err
}
@@ -121,6 +122,10 @@ func WeChatAuth(c *gin.Context) {
setupLogin(&user, c)
}
+type wechatBindRequest struct {
+ Code string `json:"code"`
+}
+
func WeChatBind(c *gin.Context) {
if !common.WeChatAuthEnabled {
c.JSON(http.StatusOK, gin.H{
@@ -129,7 +134,15 @@ func WeChatBind(c *gin.Context) {
})
return
}
- code := c.Query("code")
+ var req wechatBindRequest
+ if err := common.DecodeJson(c.Request.Body, &req); err != nil {
+ c.JSON(http.StatusOK, gin.H{
+ "success": false,
+ "message": "无效的请求",
+ })
+ return
+ }
+ code := req.Code
wechatId, err := getWeChatIdByCode(code)
if err != nil {
c.JSON(http.StatusOK, gin.H{
diff --git a/docker-compose.yml b/docker-compose.yml
index a9d00967cf..3c56faf3fa 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -43,6 +43,8 @@ services:
- redis
- postgres
# - mysql # Uncomment if using MySQL
+ networks:
+ - new-api-network
healthcheck:
test: ["CMD-SHELL", "wget -q -O - http://localhost:3000/api/status | grep -o '\"success\":\\s*true' || exit 1"]
interval: 30s
@@ -53,6 +55,8 @@ services:
image: redis:latest
container_name: redis
restart: always
+ networks:
+ - new-api-network
postgres:
image: postgres:15
@@ -64,6 +68,8 @@ services:
POSTGRES_DB: new-api
volumes:
- pg_data:/var/lib/postgresql/data
+ networks:
+ - new-api-network
# ports:
# - "5432:5432" # Uncomment if you need to access PostgreSQL from outside Docker
@@ -76,9 +82,15 @@ services:
# MYSQL_DATABASE: new-api
# volumes:
# - mysql_data:/var/lib/mysql
+# networks:
+# - new-api-network
# ports:
# - "3306:3306" # Uncomment if you need to access MySQL from outside Docker
volumes:
pg_data:
# mysql_data:
+
+networks:
+ new-api-network:
+ driver: bridge
diff --git a/docs/images/aionui.png b/docs/images/aionui.png
new file mode 100644
index 0000000000..f708588c9f
Binary files /dev/null and b/docs/images/aionui.png differ
diff --git a/docs/installation/BT.md b/docs/installation/BT.md
index b4ea5b2fc0..8579b35472 100644
--- a/docs/installation/BT.md
+++ b/docs/installation/BT.md
@@ -1,3 +1,151 @@
-密钥为环境变量SESSION_SECRET
+# 宝塔面板部署教程
+
+本文档提供使用宝塔面板 Docker 功能部署 New API 的图文教程。
+
+> 📖 官方文档:[宝塔面板部署](https://docs.newapi.pro/zh/docs/installation/deployment-methods/bt-docker-installation)
+
+***
+
+## 前置要求
+
+| 项目 | 要求 |
+| ----- | ---------------------------------- |
+| 宝塔面板 | ≥ 9.2.0 版本 |
+| 推荐系统 | CentOS 7+、Ubuntu 18.04+、Debian 10+ |
+| 服务器配置 | 至少 1 核 2G 内存 |
+
+***
+
+## 步骤一:安装宝塔面板
+
+1. 前往 [宝塔面板官网](https://www.bt.cn/new/download.html) 下载适合您系统的安装脚本
+2. 运行安装脚本安装宝塔面板
+3. 安装完成后,使用提供的地址、用户名和密码登录宝塔面板
+
+***
+
+## 步骤二:安装 Docker
+
+1. 登录宝塔面板后,在左侧菜单栏找到并点击 **Docker**
+2. 首次进入会提示安装 Docker 服务,点击 **立即安装**
+3. 按照提示完成 Docker 服务的安装
+
+***
+
+## 步骤三:安装 New API
+
+### 方法一:使用宝塔应用商店(推荐)
+
+1. 在宝塔面板 Docker 功能中,点击 **应用商店**
+2. 搜索并找到 **New-API**
+3. 点击 **安装**
+4. 配置以下基本选项:
+ - **容器名称**:可自定义,默认为 `new-api`
+ - **端口映射**:默认为 `3000:3000`
+ - **环境变量**:
+ - `SESSION_SECRET`:会话密钥(**必填**,多机部署时必须一致)
+ - `CRYPTO_SECRET`:加密密钥(使用 Redis 时必填)
+5. 点击 **确认** 开始安装
+6. 等待安装完成后,访问 `http://您的服务器IP:3000` 即可使用
+
+### 方法二:使用 Docker Compose
+
+1. 在宝塔面板中创建网站目录,如 `/www/wwwroot/new-api`
+2. 创建 `docker-compose.yml` 文件:
+
+```yaml
+version: '3'
+services:
+ new-api:
+ image: calciumion/new-api:latest
+ container_name: new-api
+ restart: always
+ ports:
+ - "3000:3000"
+ volumes:
+ - ./data:/data
+ environment:
+ - SESSION_SECRET=your_session_secret_here # 请修改为随机字符串
+ - TZ=Asia/Shanghai
+```
+
+1. 在终端中进入目录并启动:
+
+```bash
+cd /www/wwwroot/new-api
+docker-compose up -d
+```
+
+***
+
+## 配置说明
+
+### 必要环境变量
+
+| 变量名 | 说明 | 是否必填 |
+| ------------------- | ------------------ | ------ |
+| `SESSION_SECRET` | 会话密钥,多机部署必须一致 | **必填** |
+| `CRYPTO_SECRET` | 加密密钥,使用 Redis 时必填 | 条件必填 |
+| `SQL_DSN` | 数据库连接字符串(使用外部数据库时) | 可选 |
+| `REDIS_CONN_STRING` | Redis 连接字符串 | 可选 |
+
+### 生成随机密钥
+
+```bash
+# 生成 SESSION_SECRET
+openssl rand -hex 16
+
+# 或使用 Linux 命令
+head -c 16 /dev/urandom | xxd -p
+```
+
+***
+
+## 常见问题
+
+### Q1:无法访问 3000 端口?
+
+1. 检查服务器防火墙是否开放 3000 端口
+2. 在宝塔面板 **安全** 中放行 3000 端口
+3. 检查云服务器安全组是否开放端口
+
+### Q2:登录后提示会话失效?
+
+确保设置了 `SESSION_SECRET` 环境变量,且值不为空。
+
+### Q3:数据如何持久化?
+
+使用 Docker 卷映射数据目录:
+
+```yaml
+volumes:
+ - ./data:/data
+```
+
+### Q4:如何更新版本?
+
+```bash
+# 拉取最新镜像
+docker pull calciumion/new-api:latest
+
+# 重启容器
+docker-compose down && docker-compose up -d
+```
+
+***
+
+## 相关链接
+
+- [官方文档](https://docs.newapi.pro/zh/docs/installation)
+- [环境变量配置](https://docs.newapi.pro/zh/docs/installation/config-maintenance/environment-variables)
+- [常见问题](https://docs.newapi.pro/zh/docs/support/faq)
+- [GitHub 仓库](https://github.com/QuantumNous/new-api)
+
+***
+
+## 截图示例
+
+
+
+> ⚠️ 注意:密钥为环境变量 `SESSION_SECRET`,请务必设置!
-
diff --git a/docs/openapi/relay.json b/docs/openapi/relay.json
index 166bd85335..b6dfbd312c 100644
--- a/docs/openapi/relay.json
+++ b/docs/openapi/relay.json
@@ -284,6 +284,46 @@
}
]
}
+ },
+ "/v1/responses/compact": {
+ "post": {
+ "summary": "压缩对话 (OpenAI Responses API)",
+ "deprecated": false,
+ "description": "OpenAI Responses API,用于对长对话进行 compaction。",
+ "operationId": "compactResponse",
+ "tags": [
+ "OpenAI格式(Responses)"
+ ],
+ "parameters": [],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponsesCompactionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "成功压缩对话",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ResponsesCompactionResponse"
+ }
+ }
+ },
+ "headers": {}
+ }
+ },
+ "security": [
+ {
+ "BearerAuth": []
+ }
+ ]
+ }
},
"/v1/images/generations": {
"post": {
@@ -3130,10 +3170,71 @@
}
}
},
- "ResponsesStreamResponse": {
- "type": "object",
- "properties": {
- "type": {
+ "ResponsesCompactionResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "object": {
+ "type": "string",
+ "example": "response.compaction"
+ },
+ "created_at": {
+ "type": "integer"
+ },
+ "output": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {}
+ }
+ },
+ "usage": {
+ "$ref": "#/components/schemas/Usage"
+ },
+ "error": {
+ "type": "object",
+ "properties": {}
+ }
+ }
+ },
+ "ResponsesCompactionRequest": {
+ "type": "object",
+ "required": [
+ "model"
+ ],
+ "properties": {
+ "model": {
+ "type": "string"
+ },
+ "input": {
+ "description": "输入内容,可以是字符串或消息数组",
+ "oneOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {}
+ }
+ }
+ ]
+ },
+ "instructions": {
+ "type": "string"
+ },
+ "previous_response_id": {
+ "type": "string"
+ }
+ }
+ },
+ "ResponsesStreamResponse": {
+ "type": "object",
+ "properties": {
+ "type": {
"type": "string"
},
"response": {
@@ -7138,4 +7239,4 @@
"BearerAuth": []
}
]
-}
\ No newline at end of file
+}
diff --git a/dto/audio.go b/dto/audio.go
index c6f5b94797..e356917216 100644
--- a/dto/audio.go
+++ b/dto/audio.go
@@ -15,7 +15,7 @@ type AudioRequest struct {
Voice string `json:"voice"`
Instructions string `json:"instructions,omitempty"`
ResponseFormat string `json:"response_format,omitempty"`
- Speed float64 `json:"speed,omitempty"`
+ Speed *float64 `json:"speed,omitempty"`
StreamFormat string `json:"stream_format,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
diff --git a/dto/channel_settings.go b/dto/channel_settings.go
index e88f2235e3..8d7466d259 100644
--- a/dto/channel_settings.go
+++ b/dto/channel_settings.go
@@ -24,13 +24,22 @@ const (
)
type ChannelOtherSettings struct {
- AzureResponsesVersion string `json:"azure_responses_version,omitempty"`
- VertexKeyType VertexKeyType `json:"vertex_key_type,omitempty"` // "json" or "api_key"
- OpenRouterEnterprise *bool `json:"openrouter_enterprise,omitempty"`
- AllowServiceTier bool `json:"allow_service_tier,omitempty"` // 是否允许 service_tier 透传(默认过滤以避免额外计费)
- DisableStore bool `json:"disable_store,omitempty"` // 是否禁用 store 透传(默认允许透传,禁用后可能导致 Codex 无法使用)
- AllowSafetyIdentifier bool `json:"allow_safety_identifier,omitempty"` // 是否允许 safety_identifier 透传(默认过滤以保护用户隐私)
- AwsKeyType AwsKeyType `json:"aws_key_type,omitempty"`
+ AzureResponsesVersion string `json:"azure_responses_version,omitempty"`
+ VertexKeyType VertexKeyType `json:"vertex_key_type,omitempty"` // "json" or "api_key"
+ OpenRouterEnterprise *bool `json:"openrouter_enterprise,omitempty"`
+ ClaudeBetaQuery bool `json:"claude_beta_query,omitempty"` // Claude 渠道是否强制追加 ?beta=true
+ AllowServiceTier bool `json:"allow_service_tier,omitempty"` // 是否允许 service_tier 透传(默认过滤以避免额外计费)
+ AllowInferenceGeo bool `json:"allow_inference_geo,omitempty"` // 是否允许 inference_geo 透传(仅 Claude,默认过滤以满足数据驻留合规
+ AllowSafetyIdentifier bool `json:"allow_safety_identifier,omitempty"` // 是否允许 safety_identifier 透传(默认过滤以保护用户隐私)
+ DisableStore bool `json:"disable_store,omitempty"` // 是否禁用 store 透传(默认允许透传,禁用后可能导致 Codex 无法使用)
+ AllowIncludeObfuscation bool `json:"allow_include_obfuscation,omitempty"` // 是否允许 stream_options.include_obfuscation 透传(默认过滤以避免关闭流混淆保护)
+ AwsKeyType AwsKeyType `json:"aws_key_type,omitempty"`
+ UpstreamModelUpdateCheckEnabled bool `json:"upstream_model_update_check_enabled,omitempty"` // 是否检测上游模型更新
+ UpstreamModelUpdateAutoSyncEnabled bool `json:"upstream_model_update_auto_sync_enabled,omitempty"` // 是否自动同步上游模型更新
+ UpstreamModelUpdateLastCheckTime int64 `json:"upstream_model_update_last_check_time,omitempty"` // 上次检测时间
+ UpstreamModelUpdateLastDetectedModels []string `json:"upstream_model_update_last_detected_models,omitempty"` // 上次检测到的可加入模型
+ UpstreamModelUpdateLastRemovedModels []string `json:"upstream_model_update_last_removed_models,omitempty"` // 上次检测到的可删除模型
+ UpstreamModelUpdateIgnoredModels []string `json:"upstream_model_update_ignored_models,omitempty"` // 手动忽略的模型
}
func (s *ChannelOtherSettings) IsOpenRouterEnterprise() bool {
diff --git a/dto/claude.go b/dto/claude.go
index 14efd73154..d292f97e92 100644
--- a/dto/claude.go
+++ b/dto/claude.go
@@ -98,6 +98,20 @@ func (c *ClaudeMediaMessage) ParseMediaContent() []ClaudeMediaMessage {
return mediaContent
}
+func (m *ClaudeMediaMessage) ToFileSource() types.FileSource {
+ if m.Source == nil {
+ return nil
+ }
+ data := m.Source.Url
+ if data == "" {
+ data = common.Interface2String(m.Source.Data)
+ }
+ if data == "" {
+ return nil
+ }
+ return types.NewFileSourceFromData(data, m.Source.MediaType)
+}
+
type ClaudeMessageSource struct {
Type string `json:"type"`
MediaType string `json:"media_type,omitempty"`
@@ -190,17 +204,20 @@ type ClaudeToolChoice struct {
}
type ClaudeRequest struct {
- Model string `json:"model"`
- Prompt string `json:"prompt,omitempty"`
- System any `json:"system,omitempty"`
- Messages []ClaudeMessage `json:"messages,omitempty"`
- MaxTokens uint `json:"max_tokens,omitempty"`
- MaxTokensToSample uint `json:"max_tokens_to_sample,omitempty"`
+ Model string `json:"model"`
+ Prompt string `json:"prompt,omitempty"`
+ System any `json:"system,omitempty"`
+ Messages []ClaudeMessage `json:"messages,omitempty"`
+ // InferenceGeo controls Claude data residency region.
+ // This field is filtered by default and can be enabled via channel setting allow_inference_geo.
+ InferenceGeo string `json:"inference_geo,omitempty"`
+ MaxTokens *uint `json:"max_tokens,omitempty"`
+ MaxTokensToSample *uint `json:"max_tokens_to_sample,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"top_p,omitempty"`
- TopK int `json:"top_k,omitempty"`
- Stream bool `json:"stream,omitempty"`
+ TopP *float64 `json:"top_p,omitempty"`
+ TopK *int `json:"top_k,omitempty"`
+ Stream *bool `json:"stream,omitempty"`
Tools any `json:"tools,omitempty"`
ContextManagement json.RawMessage `json:"context_management,omitempty"`
OutputConfig json.RawMessage `json:"output_config,omitempty"`
@@ -210,14 +227,24 @@ type ClaudeRequest struct {
Thinking *Thinking `json:"thinking,omitempty"`
McpServers json.RawMessage `json:"mcp_servers,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
- // 服务层级字段,用于指定 API 服务等级。允许透传可能导致实际计费高于预期,默认应过滤
+ // ServiceTier specifies upstream service level and may affect billing.
+ // This field is filtered by default and can be enabled via channel setting allow_service_tier.
ServiceTier string `json:"service_tier,omitempty"`
}
+// OutputConfigForEffort just for extract effort
+type OutputConfigForEffort struct {
+ Effort string `json:"effort,omitempty"`
+}
+
func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
+ maxTokens := 0
+ if c.MaxTokens != nil {
+ maxTokens = int(*c.MaxTokens)
+ }
var tokenCountMeta = types.TokenCountMeta{
TokenType: types.TokenTypeTokenizer,
- MaxTokens: int(c.MaxTokens),
+ MaxTokens: maxTokens,
}
var texts = make([]string, 0)
@@ -237,14 +264,11 @@ func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
case "text":
texts = append(texts, media.GetText())
case "image":
- if media.Source != nil {
- data := media.Source.Url
- if data == "" {
- data = common.Interface2String(media.Source.Data)
- }
- if data != "" {
- fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
- }
+ if source := media.ToFileSource(); source != nil {
+ fileMeta = append(fileMeta, &types.FileMeta{
+ FileType: types.FileTypeImage,
+ Source: source,
+ })
}
}
}
@@ -269,14 +293,11 @@ func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
case "text":
texts = append(texts, media.GetText())
case "image":
- if media.Source != nil {
- data := media.Source.Url
- if data == "" {
- data = common.Interface2String(media.Source.Data)
- }
- if data != "" {
- fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
- }
+ if source := media.ToFileSource(); source != nil {
+ fileMeta = append(fileMeta, &types.FileMeta{
+ FileType: types.FileTypeImage,
+ Source: source,
+ })
}
case "tool_use":
if media.Name != "" {
@@ -334,7 +355,10 @@ func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
}
func (c *ClaudeRequest) IsStream(ctx *gin.Context) bool {
- return c.Stream
+ if c.Stream == nil {
+ return false
+ }
+ return *c.Stream
}
func (c *ClaudeRequest) SetModelName(modelName string) {
@@ -384,6 +408,15 @@ func (c *ClaudeRequest) GetTools() []any {
}
}
+func (c *ClaudeRequest) GetEfforts() string {
+ var OutputConfig OutputConfigForEffort
+ if err := json.Unmarshal(c.OutputConfig, &OutputConfig); err == nil {
+ effort := OutputConfig.Effort
+ return effort
+ }
+ return ""
+}
+
// ProcessTools 处理工具列表,支持类型断言
func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
var normalTools []*Tool
@@ -409,7 +442,7 @@ func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
}
type Thinking struct {
- Type string `json:"type"`
+ Type string `json:"type,omitempty"`
BudgetTokens *int `json:"budget_tokens,omitempty"`
}
diff --git a/dto/embedding.go b/dto/embedding.go
index d0730f9f59..c9bd2d70bc 100644
--- a/dto/embedding.go
+++ b/dto/embedding.go
@@ -23,13 +23,13 @@ type EmbeddingRequest struct {
Model string `json:"model"`
Input any `json:"input"`
EncodingFormat string `json:"encoding_format,omitempty"`
- Dimensions int `json:"dimensions,omitempty"`
+ Dimensions *int `json:"dimensions,omitempty"`
User string `json:"user,omitempty"`
- Seed float64 `json:"seed,omitempty"`
+ Seed *float64 `json:"seed,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"top_p,omitempty"`
- FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
- PresencePenalty float64 `json:"presence_penalty,omitempty"`
+ TopP *float64 `json:"top_p,omitempty"`
+ FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
+ PresencePenalty *float64 `json:"presence_penalty,omitempty"`
}
func (r *EmbeddingRequest) GetTokenCountMeta() *types.TokenCountMeta {
diff --git a/dto/gemini.go b/dto/gemini.go
index 17881c521e..029c3f0310 100644
--- a/dto/gemini.go
+++ b/dto/gemini.go
@@ -69,8 +69,8 @@ func (r *GeminiChatRequest) GetTokenCountMeta() *types.TokenCountMeta {
var maxTokens int
- if r.GenerationConfig.MaxOutputTokens > 0 {
- maxTokens = int(r.GenerationConfig.MaxOutputTokens)
+ if r.GenerationConfig.MaxOutputTokens != nil && *r.GenerationConfig.MaxOutputTokens > 0 {
+ maxTokens = int(*r.GenerationConfig.MaxOutputTokens)
}
var inputTexts []string
@@ -79,28 +79,22 @@ func (r *GeminiChatRequest) GetTokenCountMeta() *types.TokenCountMeta {
if part.Text != "" {
inputTexts = append(inputTexts, part.Text)
}
- if part.InlineData != nil && part.InlineData.Data != "" {
- if strings.HasPrefix(part.InlineData.MimeType, "image/") {
- files = append(files, &types.FileMeta{
- FileType: types.FileTypeImage,
- OriginData: part.InlineData.Data,
- })
- } else if strings.HasPrefix(part.InlineData.MimeType, "audio/") {
- files = append(files, &types.FileMeta{
- FileType: types.FileTypeAudio,
- OriginData: part.InlineData.Data,
- })
- } else if strings.HasPrefix(part.InlineData.MimeType, "video/") {
- files = append(files, &types.FileMeta{
- FileType: types.FileTypeVideo,
- OriginData: part.InlineData.Data,
- })
+ if source := part.InlineData.ToFileSource(); source != nil {
+ mimeType := part.InlineData.MimeType
+ var fileType types.FileType
+ if strings.HasPrefix(mimeType, "image/") {
+ fileType = types.FileTypeImage
+ } else if strings.HasPrefix(mimeType, "audio/") {
+ fileType = types.FileTypeAudio
+ } else if strings.HasPrefix(mimeType, "video/") {
+ fileType = types.FileTypeVideo
} else {
- files = append(files, &types.FileMeta{
- FileType: types.FileTypeFile,
- OriginData: part.InlineData.Data,
- })
+ fileType = types.FileTypeFile
}
+ files = append(files, &types.FileMeta{
+ FileType: fileType,
+ Source: source,
+ })
}
}
}
@@ -117,6 +111,11 @@ func (r *GeminiChatRequest) IsStream(c *gin.Context) bool {
if c.Query("alt") == "sse" {
return true
}
+ // Native Gemini API uses URL action to indicate streaming:
+ // /v1beta/models/{model}:streamGenerateContent
+ if strings.Contains(c.Request.URL.Path, "streamGenerateContent") {
+ return true
+ }
return false
}
@@ -206,6 +205,13 @@ type GeminiInlineData struct {
Data string `json:"data"`
}
+func (d *GeminiInlineData) ToFileSource() types.FileSource {
+ if d == nil || d.Data == "" {
+ return nil
+ }
+ return types.NewFileSourceFromData(d.Data, d.MimeType)
+}
+
// UnmarshalJSON custom unmarshaler for GeminiInlineData to support snake_case and camelCase for MimeType
func (g *GeminiInlineData) UnmarshalJSON(data []byte) error {
type Alias GeminiInlineData // Use type alias to avoid recursion
@@ -320,25 +326,26 @@ type GeminiChatTool struct {
}
type GeminiChatGenerationConfig struct {
- Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"topP,omitempty"`
- TopK float64 `json:"topK,omitempty"`
- MaxOutputTokens uint `json:"maxOutputTokens,omitempty"`
- CandidateCount int `json:"candidateCount,omitempty"`
- StopSequences []string `json:"stopSequences,omitempty"`
- ResponseMimeType string `json:"responseMimeType,omitempty"`
- ResponseSchema any `json:"responseSchema,omitempty"`
- ResponseJsonSchema json.RawMessage `json:"responseJsonSchema,omitempty"`
- PresencePenalty *float32 `json:"presencePenalty,omitempty"`
- FrequencyPenalty *float32 `json:"frequencyPenalty,omitempty"`
- ResponseLogprobs bool `json:"responseLogprobs,omitempty"`
- Logprobs *int32 `json:"logprobs,omitempty"`
- MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
- Seed int64 `json:"seed,omitempty"`
- ResponseModalities []string `json:"responseModalities,omitempty"`
- ThinkingConfig *GeminiThinkingConfig `json:"thinkingConfig,omitempty"`
- SpeechConfig json.RawMessage `json:"speechConfig,omitempty"` // RawMessage to allow flexible speech config
- ImageConfig json.RawMessage `json:"imageConfig,omitempty"` // RawMessage to allow flexible image config
+ Temperature *float64 `json:"temperature,omitempty"`
+ TopP *float64 `json:"topP,omitempty"`
+ TopK *float64 `json:"topK,omitempty"`
+ MaxOutputTokens *uint `json:"maxOutputTokens,omitempty"`
+ CandidateCount *int `json:"candidateCount,omitempty"`
+ StopSequences []string `json:"stopSequences,omitempty"`
+ ResponseMimeType string `json:"responseMimeType,omitempty"`
+ ResponseSchema any `json:"responseSchema,omitempty"`
+ ResponseJsonSchema json.RawMessage `json:"responseJsonSchema,omitempty"`
+ PresencePenalty *float32 `json:"presencePenalty,omitempty"`
+ FrequencyPenalty *float32 `json:"frequencyPenalty,omitempty"`
+ ResponseLogprobs *bool `json:"responseLogprobs,omitempty"`
+ Logprobs *int32 `json:"logprobs,omitempty"`
+ EnableEnhancedCivicAnswers *bool `json:"enableEnhancedCivicAnswers,omitempty"`
+ MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
+ Seed *int64 `json:"seed,omitempty"`
+ ResponseModalities []string `json:"responseModalities,omitempty"`
+ ThinkingConfig *GeminiThinkingConfig `json:"thinkingConfig,omitempty"`
+ SpeechConfig json.RawMessage `json:"speechConfig,omitempty"` // RawMessage to allow flexible speech config
+ ImageConfig json.RawMessage `json:"imageConfig,omitempty"` // RawMessage to allow flexible image config
}
// UnmarshalJSON allows GeminiChatGenerationConfig to accept both snake_case and camelCase fields.
@@ -346,22 +353,23 @@ func (c *GeminiChatGenerationConfig) UnmarshalJSON(data []byte) error {
type Alias GeminiChatGenerationConfig
var aux struct {
Alias
- TopPSnake float64 `json:"top_p,omitempty"`
- TopKSnake float64 `json:"top_k,omitempty"`
- MaxOutputTokensSnake uint `json:"max_output_tokens,omitempty"`
- CandidateCountSnake int `json:"candidate_count,omitempty"`
- StopSequencesSnake []string `json:"stop_sequences,omitempty"`
- ResponseMimeTypeSnake string `json:"response_mime_type,omitempty"`
- ResponseSchemaSnake any `json:"response_schema,omitempty"`
- ResponseJsonSchemaSnake json.RawMessage `json:"response_json_schema,omitempty"`
- PresencePenaltySnake *float32 `json:"presence_penalty,omitempty"`
- FrequencyPenaltySnake *float32 `json:"frequency_penalty,omitempty"`
- ResponseLogprobsSnake bool `json:"response_logprobs,omitempty"`
- MediaResolutionSnake MediaResolution `json:"media_resolution,omitempty"`
- ResponseModalitiesSnake []string `json:"response_modalities,omitempty"`
- ThinkingConfigSnake *GeminiThinkingConfig `json:"thinking_config,omitempty"`
- SpeechConfigSnake json.RawMessage `json:"speech_config,omitempty"`
- ImageConfigSnake json.RawMessage `json:"image_config,omitempty"`
+ TopPSnake *float64 `json:"top_p,omitempty"`
+ TopKSnake *float64 `json:"top_k,omitempty"`
+ MaxOutputTokensSnake *uint `json:"max_output_tokens,omitempty"`
+ CandidateCountSnake *int `json:"candidate_count,omitempty"`
+ StopSequencesSnake []string `json:"stop_sequences,omitempty"`
+ ResponseMimeTypeSnake string `json:"response_mime_type,omitempty"`
+ ResponseSchemaSnake any `json:"response_schema,omitempty"`
+ ResponseJsonSchemaSnake json.RawMessage `json:"response_json_schema,omitempty"`
+ PresencePenaltySnake *float32 `json:"presence_penalty,omitempty"`
+ FrequencyPenaltySnake *float32 `json:"frequency_penalty,omitempty"`
+ ResponseLogprobsSnake *bool `json:"response_logprobs,omitempty"`
+ EnableEnhancedCivicAnswersSnake *bool `json:"enable_enhanced_civic_answers,omitempty"`
+ MediaResolutionSnake MediaResolution `json:"media_resolution,omitempty"`
+ ResponseModalitiesSnake []string `json:"response_modalities,omitempty"`
+ ThinkingConfigSnake *GeminiThinkingConfig `json:"thinking_config,omitempty"`
+ SpeechConfigSnake json.RawMessage `json:"speech_config,omitempty"`
+ ImageConfigSnake json.RawMessage `json:"image_config,omitempty"`
}
if err := common.Unmarshal(data, &aux); err != nil {
@@ -371,16 +379,16 @@ func (c *GeminiChatGenerationConfig) UnmarshalJSON(data []byte) error {
*c = GeminiChatGenerationConfig(aux.Alias)
// Prioritize snake_case if present
- if aux.TopPSnake != 0 {
+ if aux.TopPSnake != nil {
c.TopP = aux.TopPSnake
}
- if aux.TopKSnake != 0 {
+ if aux.TopKSnake != nil {
c.TopK = aux.TopKSnake
}
- if aux.MaxOutputTokensSnake != 0 {
+ if aux.MaxOutputTokensSnake != nil {
c.MaxOutputTokens = aux.MaxOutputTokensSnake
}
- if aux.CandidateCountSnake != 0 {
+ if aux.CandidateCountSnake != nil {
c.CandidateCount = aux.CandidateCountSnake
}
if len(aux.StopSequencesSnake) > 0 {
@@ -401,9 +409,12 @@ func (c *GeminiChatGenerationConfig) UnmarshalJSON(data []byte) error {
if aux.FrequencyPenaltySnake != nil {
c.FrequencyPenalty = aux.FrequencyPenaltySnake
}
- if aux.ResponseLogprobsSnake {
+ if aux.ResponseLogprobsSnake != nil {
c.ResponseLogprobs = aux.ResponseLogprobsSnake
}
+ if aux.EnableEnhancedCivicAnswersSnake != nil {
+ c.EnableEnhancedCivicAnswers = aux.EnableEnhancedCivicAnswersSnake
+ }
if aux.MediaResolutionSnake != "" {
c.MediaResolution = aux.MediaResolutionSnake
}
@@ -449,11 +460,14 @@ type GeminiChatResponse struct {
}
type GeminiUsageMetadata struct {
- PromptTokenCount int `json:"promptTokenCount"`
- CandidatesTokenCount int `json:"candidatesTokenCount"`
- TotalTokenCount int `json:"totalTokenCount"`
- ThoughtsTokenCount int `json:"thoughtsTokenCount"`
- PromptTokensDetails []GeminiPromptTokensDetails `json:"promptTokensDetails"`
+ PromptTokenCount int `json:"promptTokenCount"`
+ ToolUsePromptTokenCount int `json:"toolUsePromptTokenCount"`
+ CandidatesTokenCount int `json:"candidatesTokenCount"`
+ TotalTokenCount int `json:"totalTokenCount"`
+ ThoughtsTokenCount int `json:"thoughtsTokenCount"`
+ CachedContentTokenCount int `json:"cachedContentTokenCount"`
+ PromptTokensDetails []GeminiPromptTokensDetails `json:"promptTokensDetails"`
+ ToolUsePromptTokensDetails []GeminiPromptTokensDetails `json:"toolUsePromptTokensDetails"`
}
type GeminiPromptTokensDetails struct {
diff --git a/dto/gemini_generation_config_test.go b/dto/gemini_generation_config_test.go
new file mode 100644
index 0000000000..ed4beb3019
--- /dev/null
+++ b/dto/gemini_generation_config_test.go
@@ -0,0 +1,89 @@
+package dto
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGeminiChatGenerationConfigPreservesExplicitZeroValuesCamelCase(t *testing.T) {
+ raw := []byte(`{
+ "contents":[{"role":"user","parts":[{"text":"hello"}]}],
+ "generationConfig":{
+ "topP":0,
+ "topK":0,
+ "maxOutputTokens":0,
+ "candidateCount":0,
+ "seed":0,
+ "responseLogprobs":false
+ }
+ }`)
+
+ var req GeminiChatRequest
+ require.NoError(t, common.Unmarshal(raw, &req))
+
+ encoded, err := common.Marshal(req)
+ require.NoError(t, err)
+
+ var out map[string]any
+ require.NoError(t, common.Unmarshal(encoded, &out))
+
+ generationConfig, ok := out["generationConfig"].(map[string]any)
+ require.True(t, ok)
+
+ assert.Contains(t, generationConfig, "topP")
+ assert.Contains(t, generationConfig, "topK")
+ assert.Contains(t, generationConfig, "maxOutputTokens")
+ assert.Contains(t, generationConfig, "candidateCount")
+ assert.Contains(t, generationConfig, "seed")
+ assert.Contains(t, generationConfig, "responseLogprobs")
+
+ assert.Equal(t, float64(0), generationConfig["topP"])
+ assert.Equal(t, float64(0), generationConfig["topK"])
+ assert.Equal(t, float64(0), generationConfig["maxOutputTokens"])
+ assert.Equal(t, float64(0), generationConfig["candidateCount"])
+ assert.Equal(t, float64(0), generationConfig["seed"])
+ assert.Equal(t, false, generationConfig["responseLogprobs"])
+}
+
+func TestGeminiChatGenerationConfigPreservesExplicitZeroValuesSnakeCase(t *testing.T) {
+ raw := []byte(`{
+ "contents":[{"role":"user","parts":[{"text":"hello"}]}],
+ "generationConfig":{
+ "top_p":0,
+ "top_k":0,
+ "max_output_tokens":0,
+ "candidate_count":0,
+ "seed":0,
+ "response_logprobs":false
+ }
+ }`)
+
+ var req GeminiChatRequest
+ require.NoError(t, common.Unmarshal(raw, &req))
+
+ encoded, err := common.Marshal(req)
+ require.NoError(t, err)
+
+ var out map[string]any
+ require.NoError(t, common.Unmarshal(encoded, &out))
+
+ generationConfig, ok := out["generationConfig"].(map[string]any)
+ require.True(t, ok)
+
+ assert.Contains(t, generationConfig, "topP")
+ assert.Contains(t, generationConfig, "topK")
+ assert.Contains(t, generationConfig, "maxOutputTokens")
+ assert.Contains(t, generationConfig, "candidateCount")
+ assert.Contains(t, generationConfig, "seed")
+ assert.Contains(t, generationConfig, "responseLogprobs")
+
+ assert.Equal(t, float64(0), generationConfig["topP"])
+ assert.Equal(t, float64(0), generationConfig["topK"])
+ assert.Equal(t, float64(0), generationConfig["maxOutputTokens"])
+ assert.Equal(t, float64(0), generationConfig["candidateCount"])
+ assert.Equal(t, float64(0), generationConfig["seed"])
+ assert.Equal(t, false, generationConfig["responseLogprobs"])
+}
diff --git a/dto/gemini_isstream_test.go b/dto/gemini_isstream_test.go
new file mode 100644
index 0000000000..ecd461b979
--- /dev/null
+++ b/dto/gemini_isstream_test.go
@@ -0,0 +1,73 @@
+package dto
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestGeminiChatRequest_IsStream(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ tests := []struct {
+ name string
+ path string
+ query string
+ expected bool
+ }{
+ {
+ name: "streamGenerateContent without alt=sse",
+ path: "/v1beta/models/gemini-2.0-flash:streamGenerateContent",
+ query: "key=sk-xxx",
+ expected: true,
+ },
+ {
+ name: "streamGenerateContent with alt=sse",
+ path: "/v1beta/models/gemini-2.0-flash:streamGenerateContent",
+ query: "alt=sse&key=sk-xxx",
+ expected: true,
+ },
+ {
+ name: "generateContent without alt=sse",
+ path: "/v1beta/models/gemini-2.0-flash:generateContent",
+ query: "key=sk-xxx",
+ expected: false,
+ },
+ {
+ name: "generateContent with alt=sse",
+ path: "/v1beta/models/gemini-2.0-flash:generateContent",
+ query: "alt=sse",
+ expected: true,
+ },
+ {
+ name: "GenerateContent capitalized",
+ path: "/v1beta/models/gemini-2.0-flash:GenerateContent",
+ query: "key=sk-xxx",
+ expected: false,
+ },
+ {
+ name: "embedding path",
+ path: "/v1beta/models/gemini-2.0-flash:embedContent",
+ query: "",
+ expected: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ url := tt.path
+ if tt.query != "" {
+ url += "?" + tt.query
+ }
+ c.Request, _ = http.NewRequest("POST", url, nil)
+
+ req := &GeminiChatRequest{}
+ assert.Equal(t, tt.expected, req.IsStream(c))
+ })
+ }
+}
diff --git a/dto/openai_compaction.go b/dto/openai_compaction.go
new file mode 100644
index 0000000000..f19df09ceb
--- /dev/null
+++ b/dto/openai_compaction.go
@@ -0,0 +1,20 @@
+package dto
+
+import (
+ "encoding/json"
+
+ "github.com/QuantumNous/new-api/types"
+)
+
+type OpenAIResponsesCompactionResponse struct {
+ ID string `json:"id"`
+ Object string `json:"object"`
+ CreatedAt int `json:"created_at"`
+ Output json.RawMessage `json:"output"`
+ Usage *Usage `json:"usage"`
+ Error any `json:"error,omitempty"`
+}
+
+func (o *OpenAIResponsesCompactionResponse) GetOpenAIError() *types.OpenAIError {
+ return GetOpenAIError(o.Error)
+}
diff --git a/dto/openai_image.go b/dto/openai_image.go
index a19bb69d6e..52986fbfd5 100644
--- a/dto/openai_image.go
+++ b/dto/openai_image.go
@@ -14,7 +14,7 @@ import (
type ImageRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt" binding:"required"`
- N uint `json:"n,omitempty"`
+ N *uint `json:"n,omitempty"`
Size string `json:"size,omitempty"`
Quality string `json:"quality,omitempty"`
ResponseFormat string `json:"response_format,omitempty"`
@@ -148,11 +148,14 @@ func (i *ImageRequest) GetTokenCountMeta() *types.TokenCountMeta {
}
}
- // not support token count for dalle
+ // n is NOT included here; it is handled via OtherRatio("n") in
+ // image_handler.go (default) or channel adaptors (actual count).
+ // Including n here caused double-counting for channels that also
+ // set OtherRatio("n") (e.g. Ali/Bailian).
return &types.TokenCountMeta{
CombineText: i.Prompt,
MaxTokens: 1584,
- ImagePriceRatio: sizeRatio * qualityRatio * float64(i.N),
+ ImagePriceRatio: sizeRatio * qualityRatio,
}
}
diff --git a/dto/openai_request.go b/dto/openai_request.go
index 89ebcf1443..25ef3a21aa 100644
--- a/dto/openai_request.go
+++ b/dto/openai_request.go
@@ -7,6 +7,7 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -31,41 +32,45 @@ type GeneralOpenAIRequest struct {
Prompt any `json:"prompt,omitempty"`
Prefix any `json:"prefix,omitempty"`
Suffix any `json:"suffix,omitempty"`
- Stream bool `json:"stream,omitempty"`
+ Stream *bool `json:"stream,omitempty"`
StreamOptions *StreamOptions `json:"stream_options,omitempty"`
- MaxTokens uint `json:"max_tokens,omitempty"`
- MaxCompletionTokens uint `json:"max_completion_tokens,omitempty"`
+ MaxTokens *uint `json:"max_tokens,omitempty"`
+ MaxCompletionTokens *uint `json:"max_completion_tokens,omitempty"`
ReasoningEffort string `json:"reasoning_effort,omitempty"`
Verbosity json.RawMessage `json:"verbosity,omitempty"` // gpt-5
Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"top_p,omitempty"`
- TopK int `json:"top_k,omitempty"`
+ TopP *float64 `json:"top_p,omitempty"`
+ TopK *int `json:"top_k,omitempty"`
Stop any `json:"stop,omitempty"`
- N int `json:"n,omitempty"`
+ N *int `json:"n,omitempty"`
Input any `json:"input,omitempty"`
Instruction string `json:"instruction,omitempty"`
Size string `json:"size,omitempty"`
Functions json.RawMessage `json:"functions,omitempty"`
- FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
- PresencePenalty float64 `json:"presence_penalty,omitempty"`
+ FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
+ PresencePenalty *float64 `json:"presence_penalty,omitempty"`
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
EncodingFormat json.RawMessage `json:"encoding_format,omitempty"`
- Seed float64 `json:"seed,omitempty"`
+ Seed *float64 `json:"seed,omitempty"`
ParallelTooCalls *bool `json:"parallel_tool_calls,omitempty"`
Tools []ToolCallRequest `json:"tools,omitempty"`
ToolChoice any `json:"tool_choice,omitempty"`
- User string `json:"user,omitempty"`
- LogProbs bool `json:"logprobs,omitempty"`
- TopLogProbs int `json:"top_logprobs,omitempty"`
- Dimensions int `json:"dimensions,omitempty"`
- Modalities json.RawMessage `json:"modalities,omitempty"`
- Audio json.RawMessage `json:"audio,omitempty"`
+ FunctionCall json.RawMessage `json:"function_call,omitempty"`
+ User json.RawMessage `json:"user,omitempty"`
+ // ServiceTier specifies upstream service level and may affect billing.
+ // This field is filtered by default and can be enabled via channel setting allow_service_tier.
+ ServiceTier json.RawMessage `json:"service_tier,omitempty"`
+ LogProbs *bool `json:"logprobs,omitempty"`
+ TopLogProbs *int `json:"top_logprobs,omitempty"`
+ Dimensions *int `json:"dimensions,omitempty"`
+ Modalities json.RawMessage `json:"modalities,omitempty"`
+ Audio json.RawMessage `json:"audio,omitempty"`
// 安全标识符,用于帮助 OpenAI 检测可能违反使用政策的应用程序用户
- // 注意:此字段会向 OpenAI 发送用户标识信息,默认过滤以保护用户隐私
- SafetyIdentifier string `json:"safety_identifier,omitempty"`
+ // 注意:此字段会向 OpenAI 发送用户标识信息,默认过滤,可通过 allow_safety_identifier 开启
+ SafetyIdentifier json.RawMessage `json:"safety_identifier,omitempty"`
// Whether or not to store the output of this chat completion request for use in our model distillation or evals products.
// 是否存储此次请求数据供 OpenAI 用于评估和优化产品
- // 注意:默认过滤此字段以保护用户隐私,但过滤后可能导致 Codex 无法正常使用
+ // 注意:默认允许透传,可通过 disable_store 禁用;禁用后可能导致 Codex 无法正常使用
Store json.RawMessage `json:"store,omitempty"`
// Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the user field
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
@@ -95,10 +100,12 @@ type GeneralOpenAIRequest struct {
THINKING json.RawMessage `json:"thinking,omitempty"`
// pplx Params
SearchDomainFilter json.RawMessage `json:"search_domain_filter,omitempty"`
- SearchRecencyFilter string `json:"search_recency_filter,omitempty"`
- ReturnImages bool `json:"return_images,omitempty"`
- ReturnRelatedQuestions bool `json:"return_related_questions,omitempty"`
- SearchMode string `json:"search_mode,omitempty"`
+ SearchRecencyFilter json.RawMessage `json:"search_recency_filter,omitempty"`
+ ReturnImages *bool `json:"return_images,omitempty"`
+ ReturnRelatedQuestions *bool `json:"return_related_questions,omitempty"`
+ SearchMode json.RawMessage `json:"search_mode,omitempty"`
+ // Minimax
+ ReasoningSplit json.RawMessage `json:"reasoning_split,omitempty"`
}
func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
@@ -126,10 +133,12 @@ func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
texts = append(texts, inputs...)
}
- if r.MaxCompletionTokens > r.MaxTokens {
- tokenCountMeta.MaxTokens = int(r.MaxCompletionTokens)
+ maxTokens := lo.FromPtrOr(r.MaxTokens, uint(0))
+ maxCompletionTokens := lo.FromPtrOr(r.MaxCompletionTokens, uint(0))
+ if maxCompletionTokens > maxTokens {
+ tokenCountMeta.MaxTokens = int(maxCompletionTokens)
} else {
- tokenCountMeta.MaxTokens = int(r.MaxTokens)
+ tokenCountMeta.MaxTokens = int(maxTokens)
}
for _, message := range r.Messages {
@@ -142,46 +151,24 @@ func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
}
arrayContent := message.ParseContent()
for _, m := range arrayContent {
- if m.Type == ContentTypeImageURL {
- imageUrl := m.GetImageMedia()
- if imageUrl != nil {
- if imageUrl.Url != "" {
- meta := &types.FileMeta{
- FileType: types.FileTypeImage,
- }
- meta.OriginData = imageUrl.Url
- meta.Detail = imageUrl.Detail
- fileMeta = append(fileMeta, meta)
+ source := m.ToFileSource()
+ if source != nil {
+ meta := &types.FileMeta{Source: source}
+ switch m.Type {
+ case ContentTypeImageURL:
+ meta.FileType = types.FileTypeImage
+ if img := m.GetImageMedia(); img != nil {
+ meta.Detail = img.Detail
}
+ case ContentTypeInputAudio:
+ meta.FileType = types.FileTypeAudio
+ case ContentTypeFile:
+ meta.FileType = types.FileTypeFile
+ case ContentTypeVideoUrl:
+ meta.FileType = types.FileTypeVideo
}
- } else if m.Type == ContentTypeInputAudio {
- inputAudio := m.GetInputAudio()
- if inputAudio != nil {
- meta := &types.FileMeta{
- FileType: types.FileTypeAudio,
- }
- meta.OriginData = inputAudio.Data
- fileMeta = append(fileMeta, meta)
- }
- } else if m.Type == ContentTypeFile {
- file := m.GetFile()
- if file != nil {
- meta := &types.FileMeta{
- FileType: types.FileTypeFile,
- }
- meta.OriginData = file.FileData
- fileMeta = append(fileMeta, meta)
- }
- } else if m.Type == ContentTypeVideoUrl {
- videoUrl := m.GetVideoUrl()
- if videoUrl != nil && videoUrl.Url != "" {
- meta := &types.FileMeta{
- FileType: types.FileTypeVideo,
- }
- meta.OriginData = videoUrl.Url
- fileMeta = append(fileMeta, meta)
- }
- } else {
+ fileMeta = append(fileMeta, meta)
+ } else if m.Type == ContentTypeText {
texts = append(texts, m.Text)
}
}
@@ -210,7 +197,7 @@ func (r *GeneralOpenAIRequest) GetTokenCountMeta() *types.TokenCountMeta {
}
func (r *GeneralOpenAIRequest) IsStream(c *gin.Context) bool {
- return r.Stream
+ return lo.FromPtrOr(r.Stream, false)
}
func (r *GeneralOpenAIRequest) SetModelName(modelName string) {
@@ -255,13 +242,17 @@ type FunctionRequest struct {
type StreamOptions struct {
IncludeUsage bool `json:"include_usage,omitempty"`
+ // IncludeObfuscation is only for /v1/responses stream payload.
+ // This field is filtered by default and can be enabled via channel setting allow_include_obfuscation.
+ IncludeObfuscation bool `json:"include_obfuscation,omitempty"`
}
func (r *GeneralOpenAIRequest) GetMaxTokens() uint {
- if r.MaxCompletionTokens != 0 {
- return r.MaxCompletionTokens
+ maxCompletionTokens := lo.FromPtrOr(r.MaxCompletionTokens, uint(0))
+ if maxCompletionTokens != 0 {
+ return maxCompletionTokens
}
- return r.MaxTokens
+ return lo.FromPtrOr(r.MaxTokens, uint(0))
}
func (r *GeneralOpenAIRequest) ParseInput() []string {
@@ -372,9 +363,43 @@ func (m *MediaContent) GetVideoUrl() *MessageVideoUrl {
return nil
}
+func (m *MediaContent) ToFileSource() types.FileSource {
+ switch m.Type {
+ case ContentTypeImageURL:
+ img := m.GetImageMedia()
+ if img == nil || img.Url == "" {
+ return nil
+ }
+ return types.NewFileSourceFromData(img.Url, img.MimeType)
+ case ContentTypeInputAudio:
+ audio := m.GetInputAudio()
+ if audio == nil || audio.Data == "" {
+ return nil
+ }
+ mimeType := ""
+ if audio.Format != "" {
+ mimeType = "audio/" + audio.Format
+ }
+ return types.NewFileSourceFromData(audio.Data, mimeType)
+ case ContentTypeFile:
+ file := m.GetFile()
+ if file == nil || file.FileData == "" {
+ return nil
+ }
+ return types.NewFileSourceFromData(file.FileData, "")
+ case ContentTypeVideoUrl:
+ video := m.GetVideoUrl()
+ if video == nil || video.Url == "" {
+ return nil
+ }
+ return types.NewFileSourceFromData(video.Url, "")
+ }
+ return nil
+}
+
type MessageImageUrl struct {
Url string `json:"url"`
- Detail string `json:"detail"`
+ Detail string `json:"detail,omitempty"`
MimeType string
}
@@ -793,30 +818,46 @@ type WebSearchOptions struct {
// https://platform.openai.com/docs/api-reference/responses/create
type OpenAIResponsesRequest struct {
- Model string `json:"model"`
- Input json.RawMessage `json:"input,omitempty"`
- Include json.RawMessage `json:"include,omitempty"`
+ Model string `json:"model"`
+ Input json.RawMessage `json:"input,omitempty"`
+ Include json.RawMessage `json:"include,omitempty"`
+ // 在后台运行推理,暂时还不支持依赖的接口
+ // Background json.RawMessage `json:"background,omitempty"`
+ Conversation json.RawMessage `json:"conversation,omitempty"`
+ ContextManagement json.RawMessage `json:"context_management,omitempty"`
Instructions json.RawMessage `json:"instructions,omitempty"`
- MaxOutputTokens uint `json:"max_output_tokens,omitempty"`
+ MaxOutputTokens *uint `json:"max_output_tokens,omitempty"`
+ TopLogProbs *int `json:"top_logprobs,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
ParallelToolCalls json.RawMessage `json:"parallel_tool_calls,omitempty"`
PreviousResponseID string `json:"previous_response_id,omitempty"`
Reasoning *Reasoning `json:"reasoning,omitempty"`
- // 服务层级字段,用于指定 API 服务等级。允许透传可能导致实际计费高于预期,默认应过滤
- ServiceTier string `json:"service_tier,omitempty"`
+ // ServiceTier specifies upstream service level and may affect billing.
+ // This field is filtered by default and can be enabled via channel setting allow_service_tier.
+ ServiceTier string `json:"service_tier,omitempty"`
+ // Store controls whether upstream may store request/response data.
+ // This field is allowed by default and can be disabled via channel setting disable_store.
Store json.RawMessage `json:"store,omitempty"`
PromptCacheKey json.RawMessage `json:"prompt_cache_key,omitempty"`
PromptCacheRetention json.RawMessage `json:"prompt_cache_retention,omitempty"`
- Stream bool `json:"stream,omitempty"`
- Temperature *float64 `json:"temperature,omitempty"`
- Text json.RawMessage `json:"text,omitempty"`
- ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
- Tools json.RawMessage `json:"tools,omitempty"` // 需要处理的参数很少,MCP 参数太多不确定,所以用 map
- TopP *float64 `json:"top_p,omitempty"`
- Truncation string `json:"truncation,omitempty"`
- User string `json:"user,omitempty"`
- MaxToolCalls uint `json:"max_tool_calls,omitempty"`
- Prompt json.RawMessage `json:"prompt,omitempty"`
+ // SafetyIdentifier carries client identity for policy abuse detection.
+ // This field is filtered by default and can be enabled via channel setting allow_safety_identifier.
+ SafetyIdentifier json.RawMessage `json:"safety_identifier,omitempty"`
+ Stream *bool `json:"stream,omitempty"`
+ StreamOptions *StreamOptions `json:"stream_options,omitempty"`
+ Temperature *float64 `json:"temperature,omitempty"`
+ Text json.RawMessage `json:"text,omitempty"`
+ ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
+ Tools json.RawMessage `json:"tools,omitempty"` // 需要处理的参数很少,MCP 参数太多不确定,所以用 map
+ TopP *float64 `json:"top_p,omitempty"`
+ Truncation json.RawMessage `json:"truncation,omitempty"`
+ User json.RawMessage `json:"user,omitempty"`
+ MaxToolCalls *uint `json:"max_tool_calls,omitempty"`
+ Prompt json.RawMessage `json:"prompt,omitempty"`
+ // qwen
+ EnableThinking json.RawMessage `json:"enable_thinking,omitempty"`
+ // perplexity
+ Preset json.RawMessage `json:"preset,omitempty"`
}
func (r *OpenAIResponsesRequest) GetTokenCountMeta() *types.TokenCountMeta {
@@ -829,16 +870,16 @@ func (r *OpenAIResponsesRequest) GetTokenCountMeta() *types.TokenCountMeta {
if input.Type == "input_image" {
if input.ImageUrl != "" {
fileMeta = append(fileMeta, &types.FileMeta{
- FileType: types.FileTypeImage,
- OriginData: input.ImageUrl,
- Detail: input.Detail,
+ FileType: types.FileTypeImage,
+ Source: types.NewFileSourceFromData(input.ImageUrl, ""),
+ Detail: input.Detail,
})
}
} else if input.Type == "input_file" {
if input.FileUrl != "" {
fileMeta = append(fileMeta, &types.FileMeta{
- FileType: types.FileTypeFile,
- OriginData: input.FileUrl,
+ FileType: types.FileTypeFile,
+ Source: types.NewFileSourceFromData(input.FileUrl, ""),
})
}
} else {
@@ -874,12 +915,12 @@ func (r *OpenAIResponsesRequest) GetTokenCountMeta() *types.TokenCountMeta {
return &types.TokenCountMeta{
CombineText: strings.Join(texts, "\n"),
Files: fileMeta,
- MaxTokens: int(r.MaxOutputTokens),
+ MaxTokens: int(lo.FromPtrOr(r.MaxOutputTokens, uint(0))),
}
}
func (r *OpenAIResponsesRequest) IsStream(c *gin.Context) bool {
- return r.Stream
+ return lo.FromPtrOr(r.Stream, false)
}
func (r *OpenAIResponsesRequest) SetModelName(modelName string) {
diff --git a/dto/openai_request_zero_value_test.go b/dto/openai_request_zero_value_test.go
new file mode 100644
index 0000000000..4b0dbd7c25
--- /dev/null
+++ b/dto/openai_request_zero_value_test.go
@@ -0,0 +1,73 @@
+package dto
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestGeneralOpenAIRequestPreserveExplicitZeroValues(t *testing.T) {
+ raw := []byte(`{
+ "model":"gpt-4.1",
+ "stream":false,
+ "max_tokens":0,
+ "max_completion_tokens":0,
+ "top_p":0,
+ "top_k":0,
+ "n":0,
+ "frequency_penalty":0,
+ "presence_penalty":0,
+ "seed":0,
+ "logprobs":false,
+ "top_logprobs":0,
+ "dimensions":0,
+ "return_images":false,
+ "return_related_questions":false
+ }`)
+
+ var req GeneralOpenAIRequest
+ err := common.Unmarshal(raw, &req)
+ require.NoError(t, err)
+
+ encoded, err := common.Marshal(req)
+ require.NoError(t, err)
+
+ require.True(t, gjson.GetBytes(encoded, "stream").Exists())
+ require.True(t, gjson.GetBytes(encoded, "max_tokens").Exists())
+ require.True(t, gjson.GetBytes(encoded, "max_completion_tokens").Exists())
+ require.True(t, gjson.GetBytes(encoded, "top_p").Exists())
+ require.True(t, gjson.GetBytes(encoded, "top_k").Exists())
+ require.True(t, gjson.GetBytes(encoded, "n").Exists())
+ require.True(t, gjson.GetBytes(encoded, "frequency_penalty").Exists())
+ require.True(t, gjson.GetBytes(encoded, "presence_penalty").Exists())
+ require.True(t, gjson.GetBytes(encoded, "seed").Exists())
+ require.True(t, gjson.GetBytes(encoded, "logprobs").Exists())
+ require.True(t, gjson.GetBytes(encoded, "top_logprobs").Exists())
+ require.True(t, gjson.GetBytes(encoded, "dimensions").Exists())
+ require.True(t, gjson.GetBytes(encoded, "return_images").Exists())
+ require.True(t, gjson.GetBytes(encoded, "return_related_questions").Exists())
+}
+
+func TestOpenAIResponsesRequestPreserveExplicitZeroValues(t *testing.T) {
+ raw := []byte(`{
+ "model":"gpt-4.1",
+ "max_output_tokens":0,
+ "max_tool_calls":0,
+ "stream":false,
+ "top_p":0
+ }`)
+
+ var req OpenAIResponsesRequest
+ err := common.Unmarshal(raw, &req)
+ require.NoError(t, err)
+
+ encoded, err := common.Marshal(req)
+ require.NoError(t, err)
+
+ require.True(t, gjson.GetBytes(encoded, "max_output_tokens").Exists())
+ require.True(t, gjson.GetBytes(encoded, "max_tool_calls").Exists())
+ require.True(t, gjson.GetBytes(encoded, "stream").Exists())
+ require.True(t, gjson.GetBytes(encoded, "top_p").Exists())
+}
diff --git a/dto/openai_response.go b/dto/openai_response.go
index 19ca929057..b5bc7b0dab 100644
--- a/dto/openai_response.go
+++ b/dto/openai_response.go
@@ -220,10 +220,12 @@ type CompletionsStreamResponse struct {
}
type Usage struct {
- PromptTokens int `json:"prompt_tokens"`
- CompletionTokens int `json:"completion_tokens"`
- TotalTokens int `json:"total_tokens"`
- PromptCacheHitTokens int `json:"prompt_cache_hit_tokens,omitempty"`
+ PromptTokens int `json:"prompt_tokens"`
+ CompletionTokens int `json:"completion_tokens"`
+ TotalTokens int `json:"total_tokens"`
+ PromptCacheHitTokens int `json:"prompt_cache_hit_tokens,omitempty"`
+ UsageSemantic string `json:"usage_semantic,omitempty"`
+ UsageSource string `json:"usage_source,omitempty"`
PromptTokensDetails InputTokenDetails `json:"prompt_tokens_details"`
CompletionTokenDetails OutputTokenDetails `json:"completion_tokens_details"`
@@ -251,7 +253,7 @@ type OpenAIVideoResponse struct {
type InputTokenDetails struct {
CachedTokens int `json:"cached_tokens"`
- CachedCreationTokens int `json:"-"`
+ CachedCreationTokens int `json:"cached_creation_tokens,omitempty"`
TextTokens int `json:"text_tokens"`
AudioTokens int `json:"audio_tokens"`
ImageTokens int `json:"image_tokens"`
@@ -267,7 +269,7 @@ type OpenAIResponsesResponse struct {
ID string `json:"id"`
Object string `json:"object"`
CreatedAt int `json:"created_at"`
- Status string `json:"status"`
+ Status json.RawMessage `json:"status"`
Error any `json:"error,omitempty"`
IncompleteDetails *IncompleteDetails `json:"incomplete_details,omitempty"`
Instructions string `json:"instructions"`
@@ -275,14 +277,14 @@ type OpenAIResponsesResponse struct {
Model string `json:"model"`
Output []ResponsesOutput `json:"output"`
ParallelToolCalls bool `json:"parallel_tool_calls"`
- PreviousResponseID string `json:"previous_response_id"`
+ PreviousResponseID json.RawMessage `json:"previous_response_id"`
Reasoning *Reasoning `json:"reasoning"`
Store bool `json:"store"`
Temperature float64 `json:"temperature"`
- ToolChoice string `json:"tool_choice"`
+ ToolChoice json.RawMessage `json:"tool_choice"`
Tools []map[string]any `json:"tools"`
TopP float64 `json:"top_p"`
- Truncation string `json:"truncation"`
+ Truncation json.RawMessage `json:"truncation"`
Usage *Usage `json:"usage"`
User json.RawMessage `json:"user"`
Metadata json.RawMessage `json:"metadata"`
@@ -352,6 +354,11 @@ type ResponsesOutputContent struct {
Annotations []interface{} `json:"annotations"`
}
+type ResponsesReasoningSummaryPart struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+}
+
const (
BuildInToolWebSearchPreview = "web_search_preview"
BuildInToolFileSearch = "file_search"
@@ -374,8 +381,11 @@ type ResponsesStreamResponse struct {
Item *ResponsesOutput `json:"item,omitempty"`
// - response.function_call_arguments.delta
// - response.function_call_arguments.done
- OutputIndex *int `json:"output_index,omitempty"`
- ItemID string `json:"item_id,omitempty"`
+ OutputIndex *int `json:"output_index,omitempty"`
+ ContentIndex *int `json:"content_index,omitempty"`
+ SummaryIndex *int `json:"summary_index,omitempty"`
+ ItemID string `json:"item_id,omitempty"`
+ Part *ResponsesReasoningSummaryPart `json:"part,omitempty"`
}
// GetOpenAIError 从动态错误类型中提取OpenAIError结构
diff --git a/dto/openai_responses_compaction_request.go b/dto/openai_responses_compaction_request.go
new file mode 100644
index 0000000000..7ea584ca32
--- /dev/null
+++ b/dto/openai_responses_compaction_request.go
@@ -0,0 +1,40 @@
+package dto
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+)
+
+type OpenAIResponsesCompactionRequest struct {
+ Model string `json:"model"`
+ Input json.RawMessage `json:"input,omitempty"`
+ Instructions json.RawMessage `json:"instructions,omitempty"`
+ PreviousResponseID string `json:"previous_response_id,omitempty"`
+}
+
+func (r *OpenAIResponsesCompactionRequest) GetTokenCountMeta() *types.TokenCountMeta {
+ var parts []string
+ if len(r.Instructions) > 0 {
+ parts = append(parts, string(r.Instructions))
+ }
+ if len(r.Input) > 0 {
+ parts = append(parts, string(r.Input))
+ }
+ return &types.TokenCountMeta{
+ CombineText: strings.Join(parts, "\n"),
+ }
+}
+
+func (r *OpenAIResponsesCompactionRequest) IsStream(c *gin.Context) bool {
+ return false
+}
+
+func (r *OpenAIResponsesCompactionRequest) SetModelName(modelName string) {
+ if modelName != "" {
+ r.Model = modelName
+ }
+}
diff --git a/dto/openai_video.go b/dto/openai_video.go
index bee64c31f9..e5cdbb0dd3 100644
--- a/dto/openai_video.go
+++ b/dto/openai_video.go
@@ -43,6 +43,7 @@ func (m *OpenAIVideo) SetMetadata(k string, v any) {
func NewOpenAIVideo() *OpenAIVideo {
return &OpenAIVideo{
Object: "video",
+ Status: VideoStatusQueued,
}
}
diff --git a/dto/ratio_sync.go b/dto/ratio_sync.go
index d6bbf68e10..83906c83a1 100644
--- a/dto/ratio_sync.go
+++ b/dto/ratio_sync.go
@@ -35,4 +35,5 @@ type SyncableChannel struct {
Name string `json:"name"`
BaseURL string `json:"base_url"`
Status int `json:"status"`
+ Type int `json:"type"`
}
diff --git a/dto/rerank.go b/dto/rerank.go
index 607d68a709..96644368cd 100644
--- a/dto/rerank.go
+++ b/dto/rerank.go
@@ -12,10 +12,10 @@ type RerankRequest struct {
Documents []any `json:"documents"`
Query string `json:"query"`
Model string `json:"model"`
- TopN int `json:"top_n,omitempty"`
+ TopN *int `json:"top_n,omitempty"`
ReturnDocuments *bool `json:"return_documents,omitempty"`
- MaxChunkPerDoc int `json:"max_chunk_per_doc,omitempty"`
- OverLapTokens int `json:"overlap_tokens,omitempty"`
+ MaxChunkPerDoc *int `json:"max_chunk_per_doc,omitempty"`
+ OverLapTokens *int `json:"overlap_tokens,omitempty"`
}
func (r *RerankRequest) IsStream(c *gin.Context) bool {
diff --git a/dto/suno.go b/dto/suno.go
index a6bb3ebae1..90e11b8109 100644
--- a/dto/suno.go
+++ b/dto/suno.go
@@ -4,10 +4,6 @@ import (
"encoding/json"
)
-type TaskData interface {
- SunoDataResponse | []SunoDataResponse | string | any
-}
-
type SunoSubmitReq struct {
GptDescriptionPrompt string `json:"gpt_description_prompt,omitempty"`
Prompt string `json:"prompt,omitempty"`
@@ -20,10 +16,6 @@ type SunoSubmitReq struct {
MakeInstrumental bool `json:"make_instrumental"`
}
-type FetchReq struct {
- IDs []string `json:"ids"`
-}
-
type SunoDataResponse struct {
TaskID string `json:"task_id" gorm:"type:varchar(50);index"`
Action string `json:"action" gorm:"type:varchar(40);index"` // 任务类型, song, lyrics, description-mode
@@ -66,30 +58,6 @@ type SunoLyrics struct {
Text string `json:"text"`
}
-const TaskSuccessCode = "success"
-
-type TaskResponse[T TaskData] struct {
- Code string `json:"code"`
- Message string `json:"message"`
- Data T `json:"data"`
-}
-
-func (t *TaskResponse[T]) IsSuccess() bool {
- return t.Code == TaskSuccessCode
-}
-
-type TaskDto struct {
- TaskID string `json:"task_id"` // 第三方id,不一定有/ song id\ Task id
- Action string `json:"action"` // 任务类型, song, lyrics, description-mode
- Status string `json:"status"` // 任务状态, submitted, queueing, processing, success, failed
- FailReason string `json:"fail_reason"`
- SubmitTime int64 `json:"submit_time"`
- StartTime int64 `json:"start_time"`
- FinishTime int64 `json:"finish_time"`
- Progress string `json:"progress"`
- Data json.RawMessage `json:"data"`
-}
-
type SunoGoAPISubmitReq struct {
CustomMode bool `json:"custom_mode"`
diff --git a/dto/task.go b/dto/task.go
index afc186b41d..4a9a8e2e6d 100644
--- a/dto/task.go
+++ b/dto/task.go
@@ -1,5 +1,9 @@
package dto
+import (
+ "encoding/json"
+)
+
type TaskError struct {
Code string `json:"code"`
Message string `json:"message"`
@@ -8,3 +12,46 @@ type TaskError struct {
LocalError bool `json:"-"`
Error error `json:"-"`
}
+
+type TaskData interface {
+ SunoDataResponse | []SunoDataResponse | string | any
+}
+
+const TaskSuccessCode = "success"
+
+type TaskResponse[T TaskData] struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Data T `json:"data"`
+}
+
+func (t *TaskResponse[T]) IsSuccess() bool {
+ return t.Code == TaskSuccessCode
+}
+
+type TaskDto struct {
+ ID int64 `json:"id"`
+ CreatedAt int64 `json:"created_at"`
+ UpdatedAt int64 `json:"updated_at"`
+ TaskID string `json:"task_id"`
+ Platform string `json:"platform"`
+ UserId int `json:"user_id"`
+ Group string `json:"group"`
+ ChannelId int `json:"channel_id"`
+ Quota int `json:"quota"`
+ Action string `json:"action"`
+ Status string `json:"status"`
+ FailReason string `json:"fail_reason"`
+ ResultURL string `json:"result_url,omitempty"` // 任务结果 URL(视频地址等)
+ SubmitTime int64 `json:"submit_time"`
+ StartTime int64 `json:"start_time"`
+ FinishTime int64 `json:"finish_time"`
+ Progress string `json:"progress"`
+ Properties any `json:"properties"`
+ Username string `json:"username,omitempty"`
+ Data json.RawMessage `json:"data"`
+}
+
+type FetchReq struct {
+ IDs []string `json:"ids"`
+}
diff --git a/dto/user_settings.go b/dto/user_settings.go
index 16ce7b9851..dbf555fadf 100644
--- a/dto/user_settings.go
+++ b/dto/user_settings.go
@@ -1,18 +1,21 @@
package dto
type UserSetting struct {
- NotifyType string `json:"notify_type,omitempty"` // QuotaWarningType 额度预警类型
- QuotaWarningThreshold float64 `json:"quota_warning_threshold,omitempty"` // QuotaWarningThreshold 额度预警阈值
- WebhookUrl string `json:"webhook_url,omitempty"` // WebhookUrl webhook地址
- WebhookSecret string `json:"webhook_secret,omitempty"` // WebhookSecret webhook密钥
- NotificationEmail string `json:"notification_email,omitempty"` // NotificationEmail 通知邮箱地址
- BarkUrl string `json:"bark_url,omitempty"` // BarkUrl Bark推送URL
- GotifyUrl string `json:"gotify_url,omitempty"` // GotifyUrl Gotify服务器地址
- GotifyToken string `json:"gotify_token,omitempty"` // GotifyToken Gotify应用令牌
- GotifyPriority int `json:"gotify_priority"` // GotifyPriority Gotify消息优先级
- AcceptUnsetRatioModel bool `json:"accept_unset_model_ratio_model,omitempty"` // AcceptUnsetRatioModel 是否接受未设置价格的模型
- RecordIpLog bool `json:"record_ip_log,omitempty"` // 是否记录请求和错误日志IP
- SidebarModules string `json:"sidebar_modules,omitempty"` // SidebarModules 左侧边栏模块配置
+ NotifyType string `json:"notify_type,omitempty"` // QuotaWarningType 额度预警类型
+ QuotaWarningThreshold float64 `json:"quota_warning_threshold,omitempty"` // QuotaWarningThreshold 额度预警阈值
+ WebhookUrl string `json:"webhook_url,omitempty"` // WebhookUrl webhook地址
+ WebhookSecret string `json:"webhook_secret,omitempty"` // WebhookSecret webhook密钥
+ NotificationEmail string `json:"notification_email,omitempty"` // NotificationEmail 通知邮箱地址
+ BarkUrl string `json:"bark_url,omitempty"` // BarkUrl Bark推送URL
+ GotifyUrl string `json:"gotify_url,omitempty"` // GotifyUrl Gotify服务器地址
+ GotifyToken string `json:"gotify_token,omitempty"` // GotifyToken Gotify应用令牌
+ GotifyPriority int `json:"gotify_priority"` // GotifyPriority Gotify消息优先级
+ UpstreamModelUpdateNotifyEnabled bool `json:"upstream_model_update_notify_enabled,omitempty"` // 是否接收上游模型更新定时检测通知(仅管理员)
+ AcceptUnsetRatioModel bool `json:"accept_unset_model_ratio_model,omitempty"` // AcceptUnsetRatioModel 是否接受未设置价格的模型
+ RecordIpLog bool `json:"record_ip_log,omitempty"` // 是否记录请求和错误日志IP
+ SidebarModules string `json:"sidebar_modules,omitempty"` // SidebarModules 左侧边栏模块配置
+ BillingPreference string `json:"billing_preference,omitempty"` // BillingPreference 扣费策略(订阅/钱包)
+ Language string `json:"language,omitempty"` // Language 用户语言偏好 (zh, en)
}
var (
diff --git a/electron/package-lock.json b/electron/package-lock.json
index 00aed6d475..f9897b9636 100644
--- a/electron/package-lock.json
+++ b/electron/package-lock.json
@@ -9,8 +9,8 @@
"version": "1.0.0",
"devDependencies": {
"cross-env": "^7.0.3",
- "electron": "35.7.5",
- "electron-builder": "^24.9.1"
+ "electron": "39.8.5",
+ "electron-builder": "^26.7.0"
}
},
"node_modules/@develar/schema-utils": {
@@ -49,6 +49,13 @@
"node": ">=10.12.0"
}
},
+ "node_modules/@electron/asar/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@electron/asar/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
@@ -61,9 +68,9 @@
}
},
"node_modules/@electron/asar/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -73,6 +80,60 @@
"node": "*"
}
},
+ "node_modules/@electron/fuses": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz",
+ "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "chalk": "^4.1.1",
+ "fs-extra": "^9.0.1",
+ "minimist": "^1.2.5"
+ },
+ "bin": {
+ "electron-fuses": "dist/bin.js"
+ }
+ },
+ "node_modules/@electron/fuses/node_modules/fs-extra": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "at-least-node": "^1.0.0",
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@electron/fuses/node_modules/jsonfile": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
+ "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/@electron/fuses/node_modules/universalify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
"node_modules/@electron/get": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz",
@@ -96,9 +157,9 @@
}
},
"node_modules/@electron/notarize": {
- "version": "2.2.1",
- "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.2.1.tgz",
- "integrity": "sha512-aL+bFMIkpR0cmmj5Zgy0LMKEpgy43/hw5zadEArgmAMWWlKc5buwFvFT9G/o/YJkvXAJm5q3iuTuLaiaXW39sg==",
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz",
+ "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -150,9 +211,9 @@
}
},
"node_modules/@electron/osx-sign": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.0.5.tgz",
- "integrity": "sha512-k9ZzUQtamSoweGQDV2jILiRIHUu7lYlJ3c6IEmjv1hC17rclE+eb9U+f6UFlOOETo0JzY1HNlXy4YOlCvl+Lww==",
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.3.tgz",
+ "integrity": "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
@@ -222,50 +283,96 @@
"node": ">= 10.0.0"
}
},
- "node_modules/@electron/universal": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-1.5.1.tgz",
- "integrity": "sha512-kbgXxyEauPJiQQUNG2VgUeyfQNFk6hBF11ISN2PNI6agUgPl55pv4eQmaqHzTAzchBvqZ2tQuRVaPStGf0mxGw==",
+ "node_modules/@electron/rebuild": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.0.3.tgz",
+ "integrity": "sha512-u9vpTHRMkOYCs/1FLiSVAFZ7FbjsXK+bQuzviJZa+lG7BHZl1nz52/IcGvwa3sk80/fc3llutBkbCq10Vh8WQA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@electron/asar": "^3.2.1",
- "@malept/cross-spawn-promise": "^1.1.0",
- "debug": "^4.3.1",
- "dir-compare": "^3.0.0",
- "fs-extra": "^9.0.1",
- "minimatch": "^3.0.4",
- "plist": "^3.0.4"
+ "@malept/cross-spawn-promise": "^2.0.0",
+ "debug": "^4.1.1",
+ "detect-libc": "^2.0.1",
+ "got": "^11.7.0",
+ "graceful-fs": "^4.2.11",
+ "node-abi": "^4.2.0",
+ "node-api-version": "^0.2.1",
+ "node-gyp": "^11.2.0",
+ "ora": "^5.1.0",
+ "read-binary-file-arch": "^1.0.6",
+ "semver": "^7.3.5",
+ "tar": "^7.5.6",
+ "yargs": "^17.0.1"
+ },
+ "bin": {
+ "electron-rebuild": "lib/cli.js"
},
"engines": {
- "node": ">=8.6"
+ "node": ">=22.12.0"
}
},
- "node_modules/@electron/universal/node_modules/brace-expansion": {
- "version": "1.1.12",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
- "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
+ "node_modules/@electron/rebuild/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@electron/universal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz",
+ "integrity": "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "balanced-match": "^1.0.0",
- "concat-map": "0.0.1"
+ "@electron/asar": "^3.3.1",
+ "@malept/cross-spawn-promise": "^2.0.0",
+ "debug": "^4.3.1",
+ "dir-compare": "^4.2.0",
+ "fs-extra": "^11.1.1",
+ "minimatch": "^9.0.3",
+ "plist": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=16.4"
+ }
+ },
+ "node_modules/@electron/universal/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@electron/universal/node_modules/brace-expansion": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
}
},
"node_modules/@electron/universal/node_modules/fs-extra": {
- "version": "9.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
- "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
+ "version": "11.3.3",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.3.tgz",
+ "integrity": "sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "at-least-node": "^1.0.0",
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
- "node": ">=10"
+ "node": ">=14.14"
}
},
"node_modules/@electron/universal/node_modules/jsonfile": {
@@ -282,16 +389,19 @@
}
},
"node_modules/@electron/universal/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "9.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
"dev": true,
"license": "ISC",
"dependencies": {
- "brace-expansion": "^1.1.7"
+ "brace-expansion": "^2.0.2"
},
"engines": {
- "node": "*"
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@electron/universal/node_modules/universalify": {
@@ -304,113 +414,99 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/@electron/windows-sign": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz",
+ "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "cross-dirname": "^0.1.0",
+ "debug": "^4.3.4",
+ "fs-extra": "^11.1.1",
+ "minimist": "^1.2.8",
+ "postject": "^1.0.0-alpha.6"
+ },
+ "bin": {
+ "electron-windows-sign": "bin/electron-windows-sign.js"
+ },
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/@electron/windows-sign/node_modules/fs-extra": {
+ "version": "11.3.3",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.3.tgz",
+ "integrity": "sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/@electron/windows-sign/node_modules/jsonfile": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
+ "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/@electron/windows-sign/node_modules/universalify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
"node_modules/@isaacs/cliui": {
- "version": "8.0.2",
- "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
- "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz",
+ "integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@isaacs/fs-minipass": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
"dev": true,
"license": "ISC",
"dependencies": {
- "string-width": "^5.1.2",
- "string-width-cjs": "npm:string-width@^4.2.0",
- "strip-ansi": "^7.0.1",
- "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
- "wrap-ansi": "^8.1.0",
- "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
+ "minipass": "^7.0.4"
},
"engines": {
- "node": ">=12"
- }
- },
- "node_modules/@isaacs/cliui/node_modules/ansi-regex": {
- "version": "6.2.2",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
- "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/chalk/ansi-regex?sponsor=1"
- }
- },
- "node_modules/@isaacs/cliui/node_modules/ansi-styles": {
- "version": "6.2.3",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
- "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/chalk/ansi-styles?sponsor=1"
- }
- },
- "node_modules/@isaacs/cliui/node_modules/emoji-regex": {
- "version": "9.2.2",
- "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
- "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/@isaacs/cliui/node_modules/string-width": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
- "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "eastasianwidth": "^0.2.0",
- "emoji-regex": "^9.2.2",
- "strip-ansi": "^7.0.1"
- },
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/@isaacs/cliui/node_modules/strip-ansi": {
- "version": "7.1.2",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
- "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "ansi-regex": "^6.0.1"
- },
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/chalk/strip-ansi?sponsor=1"
- }
- },
- "node_modules/@isaacs/cliui/node_modules/wrap-ansi": {
- "version": "8.1.0",
- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
- "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "ansi-styles": "^6.1.0",
- "string-width": "^5.0.1",
- "strip-ansi": "^7.0.1"
- },
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ "node": ">=18.0.0"
}
},
"node_modules/@malept/cross-spawn-promise": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-1.1.1.tgz",
- "integrity": "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
+ "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
"dev": true,
"funding": [
{
@@ -427,7 +523,7 @@
"cross-spawn": "^7.0.1"
},
"engines": {
- "node": ">= 10"
+ "node": ">= 12.13.0"
}
},
"node_modules/@malept/flatpak-bundler": {
@@ -485,6 +581,56 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/@npmcli/agent": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz",
+ "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "http-proxy-agent": "^7.0.0",
+ "https-proxy-agent": "^7.0.1",
+ "lru-cache": "^10.0.1",
+ "socks-proxy-agent": "^8.0.3"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/@npmcli/agent/node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/@npmcli/fs": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz",
+ "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "semver": "^7.3.5"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/@npmcli/fs/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -522,16 +668,6 @@
"node": ">=10"
}
},
- "node_modules/@tootallnate/once": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
- "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 10"
- }
- },
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
@@ -641,9 +777,9 @@
}
},
"node_modules/@xmldom/xmldom": {
- "version": "0.8.11",
- "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz",
- "integrity": "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==",
+ "version": "0.8.12",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.12.tgz",
+ "integrity": "sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -657,17 +793,24 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/abbrev": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-3.0.1.tgz",
+ "integrity": "sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
"node_modules/agent-base": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
- "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "debug": "4"
- },
"engines": {
- "node": ">= 6.0.0"
+ "node": ">= 14"
}
},
"node_modules/ajv": {
@@ -724,53 +867,125 @@
}
},
"node_modules/app-builder-bin": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-4.0.0.tgz",
- "integrity": "sha512-xwdG0FJPQMe0M0UA4Tz0zEB8rBJTRA5a476ZawAqiBkMv16GRK5xpXThOjMaEOFnZ6zabejjG4J3da0SXG63KA==",
+ "version": "5.0.0-alpha.12",
+ "resolved": "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-5.0.0-alpha.12.tgz",
+ "integrity": "sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==",
"dev": true,
"license": "MIT"
},
"node_modules/app-builder-lib": {
- "version": "24.13.3",
- "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-24.13.3.tgz",
- "integrity": "sha512-FAzX6IBit2POXYGnTCT8YHFO/lr5AapAII6zzhQO3Rw4cEDOgK+t1xhLc5tNcKlicTHlo9zxIwnYCX9X2DLkig==",
+ "version": "26.7.0",
+ "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.7.0.tgz",
+ "integrity": "sha512-/UgCD8VrO79Wv8aBNpjMfsS1pIUfIPURoRn0Ik6tMe5avdZF+vQgl/juJgipcMmH3YS0BD573lCdCHyoi84USg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@develar/schema-utils": "~2.6.5",
- "@electron/notarize": "2.2.1",
- "@electron/osx-sign": "1.0.5",
- "@electron/universal": "1.5.1",
+ "@electron/asar": "3.4.1",
+ "@electron/fuses": "^1.8.0",
+ "@electron/get": "^3.0.0",
+ "@electron/notarize": "2.5.0",
+ "@electron/osx-sign": "1.3.3",
+ "@electron/rebuild": "^4.0.3",
+ "@electron/universal": "2.0.3",
"@malept/flatpak-bundler": "^0.4.0",
"@types/fs-extra": "9.0.13",
"async-exit-hook": "^2.0.1",
- "bluebird-lst": "^1.0.9",
- "builder-util": "24.13.1",
- "builder-util-runtime": "9.2.4",
+ "builder-util": "26.4.1",
+ "builder-util-runtime": "9.5.1",
"chromium-pickle-js": "^0.2.0",
+ "ci-info": "4.3.1",
"debug": "^4.3.4",
+ "dotenv": "^16.4.5",
+ "dotenv-expand": "^11.0.6",
"ejs": "^3.1.8",
- "electron-publish": "24.13.1",
- "form-data": "^4.0.0",
+ "electron-publish": "26.6.0",
"fs-extra": "^10.1.0",
"hosted-git-info": "^4.1.0",
- "is-ci": "^3.0.0",
"isbinaryfile": "^5.0.0",
+ "jiti": "^2.4.2",
"js-yaml": "^4.1.0",
+ "json5": "^2.2.3",
"lazy-val": "^1.0.5",
- "minimatch": "^5.1.1",
- "read-config-file": "6.3.2",
- "sanitize-filename": "^1.6.3",
- "semver": "^7.3.8",
- "tar": "^6.1.12",
- "temp-file": "^3.4.0"
+ "minimatch": "^10.0.3",
+ "plist": "3.1.0",
+ "proper-lockfile": "^4.1.2",
+ "resedit": "^1.7.0",
+ "semver": "~7.7.3",
+ "tar": "^7.5.7",
+ "temp-file": "^3.4.0",
+ "tiny-async-pool": "1.3.0",
+ "which": "^5.0.0"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
- "dmg-builder": "24.13.3",
- "electron-builder-squirrel-windows": "24.13.3"
+ "dmg-builder": "26.7.0",
+ "electron-builder-squirrel-windows": "26.7.0"
+ }
+ },
+ "node_modules/app-builder-lib/node_modules/@electron/get": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz",
+ "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.1.1",
+ "env-paths": "^2.2.0",
+ "fs-extra": "^8.1.0",
+ "got": "^11.8.5",
+ "progress": "^2.0.3",
+ "semver": "^6.2.0",
+ "sumchecker": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "optionalDependencies": {
+ "global-agent": "^3.0.0"
+ }
+ },
+ "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
+ "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/app-builder-lib/node_modules/ci-info": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz",
+ "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/sibiraj-s"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
}
},
"node_modules/app-builder-lib/node_modules/fs-extra": {
@@ -788,7 +1003,7 @@
"node": ">=12"
}
},
- "node_modules/app-builder-lib/node_modules/jsonfile": {
+ "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/jsonfile": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
"integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
@@ -801,20 +1016,7 @@
"graceful-fs": "^4.1.6"
}
},
- "node_modules/app-builder-lib/node_modules/semver": {
- "version": "7.7.2",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
- "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
- "dev": true,
- "license": "ISC",
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/app-builder-lib/node_modules/universalify": {
+ "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
@@ -824,83 +1026,43 @@
"node": ">= 10.0.0"
}
},
- "node_modules/archiver": {
- "version": "5.3.2",
- "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz",
- "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==",
+ "node_modules/app-builder-lib/node_modules/isexe": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
+ "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==",
"dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "archiver-utils": "^2.1.0",
- "async": "^3.2.4",
- "buffer-crc32": "^0.2.1",
- "readable-stream": "^3.6.0",
- "readdir-glob": "^1.1.2",
- "tar-stream": "^2.2.0",
- "zip-stream": "^4.1.0"
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/app-builder-lib/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
},
"engines": {
- "node": ">= 10"
+ "node": ">=10"
}
},
- "node_modules/archiver-utils": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz",
- "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==",
+ "node_modules/app-builder-lib/node_modules/which": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",
+ "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==",
"dev": true,
- "license": "MIT",
- "peer": true,
+ "license": "ISC",
"dependencies": {
- "glob": "^7.1.4",
- "graceful-fs": "^4.2.0",
- "lazystream": "^1.0.0",
- "lodash.defaults": "^4.2.0",
- "lodash.difference": "^4.5.0",
- "lodash.flatten": "^4.4.0",
- "lodash.isplainobject": "^4.0.6",
- "lodash.union": "^4.6.0",
- "normalize-path": "^3.0.0",
- "readable-stream": "^2.0.0"
+ "isexe": "^3.1.1"
+ },
+ "bin": {
+ "node-which": "bin/which.js"
},
"engines": {
- "node": ">= 6"
- }
- },
- "node_modules/archiver-utils/node_modules/readable-stream": {
- "version": "2.3.8",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
- "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
- }
- },
- "node_modules/archiver-utils/node_modules/safe-buffer": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
- "node_modules/archiver-utils/node_modules/string_decoder": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
- "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "safe-buffer": "~5.1.0"
+ "node": "^18.17.0 || >=20.5.0"
}
},
"node_modules/argparse": {
@@ -967,11 +1129,17 @@
}
},
"node_modules/balanced-match": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
- "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz",
+ "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "dependencies": {
+ "jackspeak": "^4.2.3"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
},
"node_modules/base64-js": {
"version": "1.5.1",
@@ -1000,30 +1168,12 @@
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"buffer": "^5.5.0",
"inherits": "^2.0.4",
"readable-stream": "^3.4.0"
}
},
- "node_modules/bluebird": {
- "version": "3.7.2",
- "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
- "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/bluebird-lst": {
- "version": "1.0.9",
- "resolved": "https://registry.npmjs.org/bluebird-lst/-/bluebird-lst-1.0.9.tgz",
- "integrity": "sha512-7B1Rtx82hjnSD4PGLAjVWeYH3tHAcVUmChh85a3lltKQm6FresXh9ErQo6oAv6CqxttczC3/kEg8SY5NluPuUw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "bluebird": "^3.5.5"
- }
- },
"node_modules/boolean": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
@@ -1034,13 +1184,16 @@
"optional": true
},
"node_modules/brace-expansion": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
- "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz",
+ "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "balanced-match": "^1.0.0"
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
}
},
"node_modules/buffer": {
@@ -1078,19 +1231,6 @@
"node": "*"
}
},
- "node_modules/buffer-equal": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.1.tgz",
- "integrity": "sha512-QoV3ptgEaQpvVwbXdSO39iqPQTCxSF7A5U99AxbHYqUdCizL/lH2Z0A2y6nbZucxMEOtNyZfG2s6gsVugGpKkg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -1099,34 +1239,34 @@
"license": "MIT"
},
"node_modules/builder-util": {
- "version": "24.13.1",
- "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-24.13.1.tgz",
- "integrity": "sha512-NhbCSIntruNDTOVI9fdXz0dihaqX2YuE1D6zZMrwiErzH4ELZHE6mdiB40wEgZNprDia+FghRFgKoAqMZRRjSA==",
+ "version": "26.4.1",
+ "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.4.1.tgz",
+ "integrity": "sha512-FlgH43XZ50w3UtS1RVGDWOz8v9qMXPC7upMtKMtBEnYdt1OVoS61NYhKm/4x+cIaWqJTXua0+VVPI+fSPGXNIw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/debug": "^4.1.6",
"7zip-bin": "~5.2.0",
- "app-builder-bin": "4.0.0",
- "bluebird-lst": "^1.0.9",
- "builder-util-runtime": "9.2.4",
+ "app-builder-bin": "5.0.0-alpha.12",
+ "builder-util-runtime": "9.5.1",
"chalk": "^4.1.2",
- "cross-spawn": "^7.0.3",
+ "cross-spawn": "^7.0.6",
"debug": "^4.3.4",
"fs-extra": "^10.1.0",
- "http-proxy-agent": "^5.0.0",
- "https-proxy-agent": "^5.0.1",
- "is-ci": "^3.0.0",
+ "http-proxy-agent": "^7.0.0",
+ "https-proxy-agent": "^7.0.0",
"js-yaml": "^4.1.0",
+ "sanitize-filename": "^1.6.3",
"source-map-support": "^0.5.19",
"stat-mode": "^1.0.0",
- "temp-file": "^3.4.0"
+ "temp-file": "^3.4.0",
+ "tiny-async-pool": "1.3.0"
}
},
"node_modules/builder-util-runtime": {
- "version": "9.2.4",
- "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.4.tgz",
- "integrity": "sha512-upp+biKpN/XZMLim7aguUyW8s0FUpDvOtK6sbanMFDAMBzpHDqdhgVYm6zc9HJ6nWo7u2Lxk60i2M6Jd3aiNrA==",
+ "version": "9.5.1",
+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.5.1.tgz",
+ "integrity": "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1175,6 +1315,211 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/cacache": {
+ "version": "19.0.1",
+ "resolved": "https://registry.npmjs.org/cacache/-/cacache-19.0.1.tgz",
+ "integrity": "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "@npmcli/fs": "^4.0.0",
+ "fs-minipass": "^3.0.0",
+ "glob": "^10.2.2",
+ "lru-cache": "^10.0.1",
+ "minipass": "^7.0.3",
+ "minipass-collect": "^2.0.1",
+ "minipass-flush": "^1.0.5",
+ "minipass-pipeline": "^1.2.4",
+ "p-map": "^7.0.2",
+ "ssri": "^12.0.0",
+ "tar": "^7.4.3",
+ "unique-filename": "^4.0.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/cacache/node_modules/@isaacs/cliui": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
+ "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^5.1.2",
+ "string-width-cjs": "npm:string-width@^4.2.0",
+ "strip-ansi": "^7.0.1",
+ "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
+ "wrap-ansi": "^8.1.0",
+ "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/cacache/node_modules/ansi-regex": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
+ "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"
+ }
+ },
+ "node_modules/cacache/node_modules/ansi-styles": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/cacache/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cacache/node_modules/brace-expansion": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "node_modules/cacache/node_modules/emoji-regex": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cacache/node_modules/glob": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
+ "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "foreground-child": "^3.1.0",
+ "jackspeak": "^3.1.2",
+ "minimatch": "^9.0.4",
+ "minipass": "^7.1.2",
+ "package-json-from-dist": "^1.0.0",
+ "path-scurry": "^1.11.1"
+ },
+ "bin": {
+ "glob": "dist/esm/bin.mjs"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/cacache/node_modules/jackspeak": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
+ "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/cliui": "^8.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ },
+ "optionalDependencies": {
+ "@pkgjs/parseargs": "^0.11.0"
+ }
+ },
+ "node_modules/cacache/node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/cacache/node_modules/minimatch": {
+ "version": "9.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/cacache/node_modules/string-width": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
+ "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eastasianwidth": "^0.2.0",
+ "emoji-regex": "^9.2.2",
+ "strip-ansi": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cacache/node_modules/strip-ansi": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
+ "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"
+ }
+ },
+ "node_modules/cacache/node_modules/wrap-ansi": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
+ "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.1.0",
+ "string-width": "^5.0.1",
+ "strip-ansi": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
"node_modules/cacheable-lookup": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
@@ -1236,13 +1581,13 @@
}
},
"node_modules/chownr": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
- "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
"dev": true,
- "license": "ISC",
+ "license": "BlueOak-1.0.0",
"engines": {
- "node": ">=10"
+ "node": ">=18"
}
},
"node_modules/chromium-pickle-js": {
@@ -1253,9 +1598,9 @@
"license": "MIT"
},
"node_modules/ci-info": {
- "version": "3.9.0",
- "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
- "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",
+ "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==",
"dev": true,
"funding": [
{
@@ -1268,6 +1613,32 @@
"node": ">=8"
}
},
+ "node_modules/cli-cursor": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz",
+ "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "restore-cursor": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cli-spinners": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz",
+ "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/cli-truncate": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz",
@@ -1301,6 +1672,16 @@
"node": ">=12"
}
},
+ "node_modules/clone": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz",
+ "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
"node_modules/clone-response": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",
@@ -1367,23 +1748,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/compress-commons": {
- "version": "4.1.2",
- "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz",
- "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "buffer-crc32": "^0.2.13",
- "crc32-stream": "^4.0.2",
- "normalize-path": "^3.0.0",
- "readable-stream": "^3.6.0"
- },
- "engines": {
- "node": ">= 10"
- }
- },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -1391,70 +1755,13 @@
"dev": true,
"license": "MIT"
},
- "node_modules/config-file-ts": {
- "version": "0.2.6",
- "resolved": "https://registry.npmjs.org/config-file-ts/-/config-file-ts-0.2.6.tgz",
- "integrity": "sha512-6boGVaglwblBgJqGyxm4+xCmEGcWgnWHSWHY5jad58awQhB6gftq0G8HbzU39YqCIYHMLAiL1yjwiZ36m/CL8w==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "glob": "^10.3.10",
- "typescript": "^5.3.3"
- }
- },
- "node_modules/config-file-ts/node_modules/glob": {
- "version": "10.4.5",
- "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
- "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "foreground-child": "^3.1.0",
- "jackspeak": "^3.1.2",
- "minimatch": "^9.0.4",
- "minipass": "^7.1.2",
- "package-json-from-dist": "^1.0.0",
- "path-scurry": "^1.11.1"
- },
- "bin": {
- "glob": "dist/esm/bin.mjs"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/config-file-ts/node_modules/minimatch": {
- "version": "9.0.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
- "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "brace-expansion": "^2.0.1"
- },
- "engines": {
- "node": ">=16 || 14 >=14.17"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/config-file-ts/node_modules/minipass": {
- "version": "7.1.2",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
- "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
- "dev": true,
- "license": "ISC",
- "engines": {
- "node": ">=16 || 14 >=14.17"
- }
- },
"node_modules/core-util-is": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "optional": true
},
"node_modules/crc": {
"version": "3.8.0",
@@ -1467,34 +1774,14 @@
"buffer": "^5.1.0"
}
},
- "node_modules/crc-32": {
- "version": "1.2.2",
- "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
- "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
- "dev": true,
- "license": "Apache-2.0",
- "peer": true,
- "bin": {
- "crc32": "bin/crc32.njs"
- },
- "engines": {
- "node": ">=0.8"
- }
- },
- "node_modules/crc32-stream": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz",
- "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==",
+ "node_modules/cross-dirname": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",
+ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==",
"dev": true,
"license": "MIT",
- "peer": true,
- "dependencies": {
- "crc-32": "^1.2.0",
- "readable-stream": "^3.4.0"
- },
- "engines": {
- "node": ">= 10"
- }
+ "optional": true,
+ "peer": true
},
"node_modules/cross-env": {
"version": "7.0.3",
@@ -1577,6 +1864,19 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/defaults": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
+ "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "clone": "^1.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/defer-to-connect": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
@@ -1635,6 +1935,16 @@
"node": ">=0.4.0"
}
},
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/detect-node": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
@@ -1644,16 +1954,23 @@
"optional": true
},
"node_modules/dir-compare": {
- "version": "3.3.0",
- "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-3.3.0.tgz",
- "integrity": "sha512-J7/et3WlGUCxjdnD3HAAzQ6nsnc0WL6DD7WcwJb7c39iH1+AWfg+9OqzJNaI6PkBwBvm1mhZNL9iY/nRiZXlPg==",
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
+ "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "buffer-equal": "^1.0.0",
- "minimatch": "^3.0.4"
+ "minimatch": "^3.0.5",
+ "p-limit": "^3.1.0 "
}
},
+ "node_modules/dir-compare/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/dir-compare/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
@@ -1666,9 +1983,9 @@
}
},
"node_modules/dir-compare/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -1679,15 +1996,14 @@
}
},
"node_modules/dmg-builder": {
- "version": "24.13.3",
- "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-24.13.3.tgz",
- "integrity": "sha512-rcJUkMfnJpfCboZoOOPf4L29TRtEieHNOeAbYPWPxlaBw/Z1RKrRA86dOI9rwaI4tQSc/RD82zTNHprfUHXsoQ==",
+ "version": "26.7.0",
+ "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.7.0.tgz",
+ "integrity": "sha512-uOOBA3f+kW3o4KpSoMQ6SNpdXU7WtxlJRb9vCZgOvqhTz4b3GjcoWKstdisizNZLsylhTMv8TLHFPFW0Uxsj/g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "app-builder-lib": "24.13.3",
- "builder-util": "24.13.1",
- "builder-util-runtime": "9.2.4",
+ "app-builder-lib": "26.7.0",
+ "builder-util": "26.4.1",
"fs-extra": "^10.1.0",
"iconv-lite": "^0.6.2",
"js-yaml": "^4.1.0"
@@ -1762,21 +2078,33 @@
}
},
"node_modules/dotenv": {
- "version": "9.0.2",
- "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-9.0.2.tgz",
- "integrity": "sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==",
+ "version": "16.6.1",
+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
- "node": ">=10"
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
}
},
"node_modules/dotenv-expand": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-5.1.0.tgz",
- "integrity": "sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-11.0.7.tgz",
+ "integrity": "sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==",
"dev": true,
- "license": "BSD-2-Clause"
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dotenv": "^16.4.5"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
+ }
},
"node_modules/dunder-proto": {
"version": "1.0.1",
@@ -1817,9 +2145,9 @@
}
},
"node_modules/electron": {
- "version": "35.7.5",
- "resolved": "https://registry.npmjs.org/electron/-/electron-35.7.5.tgz",
- "integrity": "sha512-dnL+JvLraKZl7iusXTVTGYs10TKfzUi30uEDTqsmTm0guN9V2tbOjTzyIZbh9n3ygUjgEYyo+igAwMRXIi3IPw==",
+ "version": "39.8.5",
+ "resolved": "https://registry.npmjs.org/electron/-/electron-39.8.5.tgz",
+ "integrity": "sha512-q6+LiQIcTadSyvtPgLDQkCtVA9jQJXQVMrQcctfOJILh6OFMN+UJJLRkuUTy8CZDYeCIBn1ZycqsL1dAXugxZA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
@@ -1836,21 +2164,20 @@
}
},
"node_modules/electron-builder": {
- "version": "24.13.3",
- "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-24.13.3.tgz",
- "integrity": "sha512-yZSgVHft5dNVlo31qmJAe4BVKQfFdwpRw7sFp1iQglDRCDD6r22zfRJuZlhtB5gp9FHUxCMEoWGq10SkCnMAIg==",
+ "version": "26.7.0",
+ "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.7.0.tgz",
+ "integrity": "sha512-LoXbCvSFxLesPneQ/fM7FB4OheIDA2tjqCdUkKlObV5ZKGhYgi5VHPHO/6UUOUodAlg7SrkPx7BZJPby+Vrtbg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "app-builder-lib": "24.13.3",
- "builder-util": "24.13.1",
- "builder-util-runtime": "9.2.4",
+ "app-builder-lib": "26.7.0",
+ "builder-util": "26.4.1",
+ "builder-util-runtime": "9.5.1",
"chalk": "^4.1.2",
- "dmg-builder": "24.13.3",
+ "ci-info": "^4.2.0",
+ "dmg-builder": "26.7.0",
"fs-extra": "^10.1.0",
- "is-ci": "^3.0.0",
"lazy-val": "^1.0.5",
- "read-config-file": "6.3.2",
"simple-update-notifier": "2.0.0",
"yargs": "^17.6.2"
},
@@ -1863,58 +2190,16 @@
}
},
"node_modules/electron-builder-squirrel-windows": {
- "version": "24.13.3",
- "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-24.13.3.tgz",
- "integrity": "sha512-oHkV0iogWfyK+ah9ZIvMDpei1m9ZRpdXcvde1wTpra2U8AFDNNpqJdnin5z+PM1GbQ5BoaKCWas2HSjtR0HwMg==",
+ "version": "26.7.0",
+ "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.7.0.tgz",
+ "integrity": "sha512-3EqkQK+q0kGshdPSKEPb2p5F75TENMKu6Fe5aTdeaPfdzFK4Yjp5L0d6S7K8iyvqIsGQ/ei4bnpyX9wt+kVCKQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "app-builder-lib": "24.13.3",
- "archiver": "^5.3.1",
- "builder-util": "24.13.1",
- "fs-extra": "^10.1.0"
- }
- },
- "node_modules/electron-builder-squirrel-windows/node_modules/fs-extra": {
- "version": "10.1.0",
- "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
- "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "graceful-fs": "^4.2.0",
- "jsonfile": "^6.0.1",
- "universalify": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/electron-builder-squirrel-windows/node_modules/jsonfile": {
- "version": "6.2.0",
- "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
- "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "universalify": "^2.0.0"
- },
- "optionalDependencies": {
- "graceful-fs": "^4.1.6"
- }
- },
- "node_modules/electron-builder-squirrel-windows/node_modules/universalify": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
- "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "engines": {
- "node": ">= 10.0.0"
+ "app-builder-lib": "26.7.0",
+ "builder-util": "26.4.1",
+ "electron-winstaller": "5.4.0"
}
},
"node_modules/electron-builder/node_modules/fs-extra": {
@@ -1956,16 +2241,17 @@
}
},
"node_modules/electron-publish": {
- "version": "24.13.1",
- "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-24.13.1.tgz",
- "integrity": "sha512-2ZgdEqJ8e9D17Hwp5LEq5mLQPjqU3lv/IALvgp+4W8VeNhryfGhYEQC/PgDPMrnWUp+l60Ou5SJLsu+k4mhQ8A==",
+ "version": "26.6.0",
+ "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.6.0.tgz",
+ "integrity": "sha512-LsyHMMqbvJ2vsOvuWJ19OezgF2ANdCiHpIucDHNiLhuI+/F3eW98ouzWSRmXXi82ZOPZXC07jnIravY4YYwCLQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/fs-extra": "^9.0.11",
- "builder-util": "24.13.1",
- "builder-util-runtime": "9.2.4",
+ "builder-util": "26.4.1",
+ "builder-util-runtime": "9.5.1",
"chalk": "^4.1.2",
+ "form-data": "^4.0.5",
"fs-extra": "^10.1.0",
"lazy-val": "^1.0.5",
"mime": "^2.5.2"
@@ -2009,6 +2295,44 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/electron-winstaller": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz",
+ "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@electron/asar": "^3.2.1",
+ "debug": "^4.1.1",
+ "fs-extra": "^7.0.1",
+ "lodash": "^4.17.21",
+ "temp": "^0.9.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@electron/windows-sign": "^1.1.2"
+ }
+ },
+ "node_modules/electron-winstaller/node_modules/fs-extra": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",
+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
@@ -2016,6 +2340,17 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/encoding": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
+ "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "iconv-lite": "^0.6.2"
+ }
+ },
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
@@ -2124,6 +2459,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/exponential-backoff": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
+ "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/extract-zip": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
@@ -2180,6 +2522,24 @@
"pend": "~1.2.0"
}
},
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
"node_modules/filelist": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz",
@@ -2190,6 +2550,36 @@
"minimatch": "^5.0.1"
}
},
+ "node_modules/filelist/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/filelist/node_modules/brace-expansion": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "node_modules/filelist/node_modules/minimatch": {
+ "version": "5.1.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
+ "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/foreground-child": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
@@ -2207,10 +2597,23 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/foreground-child/node_modules/signal-exit": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/form-data": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
- "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2224,14 +2627,6 @@
"node": ">= 6"
}
},
- "node_modules/fs-constants": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
- "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
"node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
@@ -2248,29 +2643,16 @@
}
},
"node_modules/fs-minipass": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
- "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz",
+ "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==",
"dev": true,
"license": "ISC",
"dependencies": {
- "minipass": "^3.0.0"
+ "minipass": "^7.0.3"
},
"engines": {
- "node": ">= 8"
- }
- },
- "node_modules/fs-minipass/node_modules/minipass": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
- "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
+ "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
}
},
"node_modules/fs.realpath": {
@@ -2359,7 +2741,7 @@
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
- "deprecated": "Glob versions prior to v9 are no longer supported",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -2377,6 +2759,13 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/glob/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/glob/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
@@ -2389,9 +2778,9 @@
}
},
"node_modules/glob/node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -2585,18 +2974,17 @@
"license": "BSD-2-Clause"
},
"node_modules/http-proxy-agent": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz",
- "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==",
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@tootallnate/once": "2",
- "agent-base": "6",
- "debug": "4"
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
},
"engines": {
- "node": ">= 6"
+ "node": ">= 14"
}
},
"node_modules/http2-wrapper": {
@@ -2614,17 +3002,17 @@
}
},
"node_modules/https-proxy-agent": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
- "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "agent-base": "6",
+ "agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
- "node": ">= 6"
+ "node": ">= 14"
}
},
"node_modules/iconv-corefoundation": {
@@ -2679,6 +3067,16 @@
],
"license": "BSD-3-Clause"
},
+ "node_modules/imurmurhash": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.19"
+ }
+ },
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -2698,17 +3096,14 @@
"dev": true,
"license": "ISC"
},
- "node_modules/is-ci": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-3.0.1.tgz",
- "integrity": "sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==",
+ "node_modules/ip-address": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
+ "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "ci-info": "^3.2.0"
- },
- "bin": {
- "is-ci": "bin.js"
+ "engines": {
+ "node": ">= 12"
}
},
"node_modules/is-fullwidth-code-point": {
@@ -2721,18 +3116,33 @@
"node": ">=8"
}
},
- "node_modules/isarray": {
+ "node_modules/is-interactive": {
"version": "1.0.0",
- "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
- "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
+ "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz",
+ "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==",
"dev": true,
"license": "MIT",
- "peer": true
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-unicode-supported": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
+ "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
},
"node_modules/isbinaryfile": {
- "version": "5.0.6",
- "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-5.0.6.tgz",
- "integrity": "sha512-I+NmIfBHUl+r2wcDd6JwE9yWje/PIVY/R5/CmV8dXLZd5K+L9X2klAOwfAHNnondLXkbHyTAleQAWonpTJBTtw==",
+ "version": "5.0.7",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-5.0.7.tgz",
+ "integrity": "sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -2750,19 +3160,19 @@
"license": "ISC"
},
"node_modules/jackspeak": {
- "version": "3.4.3",
- "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
- "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz",
+ "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "@isaacs/cliui": "^8.0.2"
+ "@isaacs/cliui": "^9.0.0"
+ },
+ "engines": {
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
- },
- "optionalDependencies": {
- "@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/jake": {
@@ -2783,6 +3193,16 @@
"node": ">=10"
}
},
+ "node_modules/jiti": {
+ "version": "2.6.1",
+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",
+ "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jiti": "lib/jiti-cli.mjs"
+ }
+ },
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
@@ -2858,102 +3278,29 @@
"dev": true,
"license": "MIT"
},
- "node_modules/lazystream": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
- "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "readable-stream": "^2.0.5"
- },
- "engines": {
- "node": ">= 0.6.3"
- }
- },
- "node_modules/lazystream/node_modules/readable-stream": {
- "version": "2.3.8",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
- "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
- }
- },
- "node_modules/lazystream/node_modules/safe-buffer": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
- "node_modules/lazystream/node_modules/string_decoder": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
- "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "safe-buffer": "~5.1.0"
- }
- },
"node_modules/lodash": {
- "version": "4.17.21",
- "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
- "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
+ "version": "4.18.1",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"dev": true,
"license": "MIT"
},
- "node_modules/lodash.defaults": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
- "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
+ "node_modules/log-symbols": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
+ "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==",
"dev": true,
"license": "MIT",
- "peer": true
- },
- "node_modules/lodash.difference": {
- "version": "4.5.0",
- "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz",
- "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
- "node_modules/lodash.flatten": {
- "version": "4.4.0",
- "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
- "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
- "node_modules/lodash.isplainobject": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
- "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
- "dev": true,
- "license": "MIT",
- "peer": true
- },
- "node_modules/lodash.union": {
- "version": "4.6.0",
- "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",
- "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==",
- "dev": true,
- "license": "MIT",
- "peer": true
+ "dependencies": {
+ "chalk": "^4.1.0",
+ "is-unicode-supported": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
},
"node_modules/lowercase-keys": {
"version": "2.0.0",
@@ -2978,6 +3325,29 @@
"node": ">=10"
}
},
+ "node_modules/make-fetch-happen": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-14.0.3.tgz",
+ "integrity": "sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "@npmcli/agent": "^3.0.0",
+ "cacache": "^19.0.1",
+ "http-cache-semantics": "^4.1.1",
+ "minipass": "^7.0.2",
+ "minipass-fetch": "^4.0.0",
+ "minipass-flush": "^1.0.5",
+ "minipass-pipeline": "^1.2.4",
+ "negotiator": "^1.0.0",
+ "proc-log": "^5.0.0",
+ "promise-retry": "^2.0.1",
+ "ssri": "^12.0.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
"node_modules/matcher": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
@@ -3038,6 +3408,16 @@
"node": ">= 0.6"
}
},
+ "node_modules/mimic-fn": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/mimic-response": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
@@ -3049,16 +3429,19 @@
}
},
"node_modules/minimatch": {
- "version": "5.1.6",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz",
- "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
+ "version": "10.2.4",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz",
+ "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==",
"dev": true,
- "license": "ISC",
+ "license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^2.0.1"
+ "brace-expansion": "^5.0.2"
},
"engines": {
- "node": ">=10"
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minimist": {
@@ -3072,30 +3455,60 @@
}
},
"node_modules/minipass": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
- "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
+ "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
"dev": true,
"license": "ISC",
"engines": {
- "node": ">=8"
+ "node": ">=16 || 14 >=14.17"
}
},
- "node_modules/minizlib": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
- "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
+ "node_modules/minipass-collect": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz",
+ "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^7.0.3"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/minipass-fetch": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-4.0.1.tgz",
+ "integrity": "sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "minipass": "^3.0.0",
- "yallist": "^4.0.0"
+ "minipass": "^7.0.3",
+ "minipass-sized": "^1.0.3",
+ "minizlib": "^3.0.1"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ },
+ "optionalDependencies": {
+ "encoding": "^0.1.13"
+ }
+ },
+ "node_modules/minipass-flush": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz",
+ "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^3.0.0"
},
"engines": {
"node": ">= 8"
}
},
- "node_modules/minizlib/node_modules/minipass": {
+ "node_modules/minipass-flush/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
@@ -3108,17 +3521,83 @@
"node": ">=8"
}
},
- "node_modules/mkdirp": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
- "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
+ "node_modules/minipass-pipeline": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz",
+ "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==",
"dev": true,
- "license": "MIT",
- "bin": {
- "mkdirp": "bin/cmd.js"
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^3.0.0"
},
"engines": {
- "node": ">=10"
+ "node": ">=8"
+ }
+ },
+ "node_modules/minipass-pipeline/node_modules/minipass": {
+ "version": "3.3.6",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
+ "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/minipass-sized": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz",
+ "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/minipass-sized/node_modules/minipass": {
+ "version": "3.3.6",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
+ "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/minizlib": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "minipass": "^7.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
@@ -3128,6 +3607,42 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/negotiator": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/node-abi": {
+ "version": "4.26.0",
+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.26.0.tgz",
+ "integrity": "sha512-8QwIZqikRvDIkXS2S93LjzhsSPJuIbfaMETWH+Bx8oOT9Sa9UsUtBFQlc3gBNd1+QINjaTloitXr1W3dQLi9Iw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.6.3"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/node-abi/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/node-addon-api": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-1.7.2.tgz",
@@ -3136,15 +3651,107 @@
"license": "MIT",
"optional": true
},
- "node_modules/normalize-path": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
- "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "node_modules/node-api-version": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.2.1.tgz",
+ "integrity": "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==",
"dev": true,
"license": "MIT",
- "peer": true,
+ "dependencies": {
+ "semver": "^7.3.5"
+ }
+ },
+ "node_modules/node-api-version/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
"engines": {
- "node": ">=0.10.0"
+ "node": ">=10"
+ }
+ },
+ "node_modules/node-gyp": {
+ "version": "11.5.0",
+ "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-11.5.0.tgz",
+ "integrity": "sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "env-paths": "^2.2.0",
+ "exponential-backoff": "^3.1.1",
+ "graceful-fs": "^4.2.6",
+ "make-fetch-happen": "^14.0.3",
+ "nopt": "^8.0.0",
+ "proc-log": "^5.0.0",
+ "semver": "^7.3.5",
+ "tar": "^7.4.3",
+ "tinyglobby": "^0.2.12",
+ "which": "^5.0.0"
+ },
+ "bin": {
+ "node-gyp": "bin/node-gyp.js"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/node-gyp/node_modules/isexe": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
+ "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/node-gyp/node_modules/semver": {
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/node-gyp/node_modules/which": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",
+ "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^3.1.1"
+ },
+ "bin": {
+ "node-which": "bin/which.js"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/nopt": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-8.1.0.tgz",
+ "integrity": "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "abbrev": "^3.0.0"
+ },
+ "bin": {
+ "nopt": "bin/nopt.js"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
}
},
"node_modules/normalize-url": {
@@ -3181,6 +3788,46 @@
"wrappy": "1"
}
},
+ "node_modules/onetime": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mimic-fn": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/ora": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz",
+ "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.1.0",
+ "chalk": "^4.1.0",
+ "cli-cursor": "^3.1.0",
+ "cli-spinners": "^2.5.0",
+ "is-interactive": "^1.0.0",
+ "is-unicode-supported": "^0.1.0",
+ "log-symbols": "^4.1.0",
+ "strip-ansi": "^6.0.0",
+ "wcwidth": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/p-cancelable": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
@@ -3191,6 +3838,35 @@
"node": ">=8"
}
},
+ "node_modules/p-limit": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "yocto-queue": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-map": {
+ "version": "7.0.4",
+ "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.4.tgz",
+ "integrity": "sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
@@ -3242,6 +3918,21 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/pe-library": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",
+ "integrity": "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/jet2jet"
+ }
+ },
"node_modules/pend": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
@@ -3256,6 +3947,19 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/picomatch": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/plist": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",
@@ -3271,13 +3975,45 @@
"node": ">=10.4.0"
}
},
- "node_modules/process-nextick-args": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
- "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
+ "node_modules/postject": {
+ "version": "1.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
+ "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",
"dev": true,
"license": "MIT",
- "peer": true
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "commander": "^9.4.0"
+ },
+ "bin": {
+ "postject": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/postject/node_modules/commander": {
+ "version": "9.5.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
+ "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "engines": {
+ "node": "^12.20.0 || >=14"
+ }
+ },
+ "node_modules/proc-log": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz",
+ "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
},
"node_modules/progress": {
"version": "2.0.3",
@@ -3303,6 +4039,18 @@
"node": ">=10"
}
},
+ "node_modules/proper-lockfile": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
+ "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.4",
+ "retry": "^0.12.0",
+ "signal-exit": "^3.0.2"
+ }
+ },
"node_modules/pump": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",
@@ -3337,22 +4085,17 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/read-config-file": {
- "version": "6.3.2",
- "resolved": "https://registry.npmjs.org/read-config-file/-/read-config-file-6.3.2.tgz",
- "integrity": "sha512-M80lpCjnE6Wt6zb98DoW8WHR09nzMSpu8XHtPkiTHrJ5Az9CybfeQhTJ8D7saeBHpGhLPIVyA8lcL6ZmdKwY6Q==",
+ "node_modules/read-binary-file-arch": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",
+ "integrity": "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "config-file-ts": "^0.2.4",
- "dotenv": "^9.0.2",
- "dotenv-expand": "^5.1.0",
- "js-yaml": "^4.1.0",
- "json5": "^2.2.0",
- "lazy-val": "^1.0.4"
+ "debug": "^4.3.4"
},
- "engines": {
- "node": ">=12.0.0"
+ "bin": {
+ "read-binary-file-arch": "cli.js"
}
},
"node_modules/readable-stream": {
@@ -3361,7 +4104,6 @@
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
@@ -3371,17 +4113,6 @@
"node": ">= 6"
}
},
- "node_modules/readdir-glob": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz",
- "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
- "dev": true,
- "license": "Apache-2.0",
- "peer": true,
- "dependencies": {
- "minimatch": "^5.1.0"
- }
- },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -3392,6 +4123,24 @@
"node": ">=0.10.0"
}
},
+ "node_modules/resedit": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",
+ "integrity": "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pe-library": "^0.4.1"
+ },
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/jet2jet"
+ }
+ },
"node_modules/resolve-alpn": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",
@@ -3412,6 +4161,20 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/restore-cursor": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz",
+ "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "onetime": "^5.1.0",
+ "signal-exit": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
@@ -3422,6 +4185,21 @@
"node": ">= 4"
}
},
+ "node_modules/rimraf": {
+ "version": "2.6.3",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",
+ "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",
+ "deprecated": "Rimraf versions prior to v4 are no longer supported",
+ "dev": true,
+ "license": "ISC",
+ "peer": true,
+ "dependencies": {
+ "glob": "^7.1.3"
+ },
+ "bin": {
+ "rimraf": "bin.js"
+ }
+ },
"node_modules/roarr": {
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
@@ -3460,8 +4238,7 @@
"url": "https://feross.org/support"
}
],
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
@@ -3481,11 +4258,14 @@
}
},
"node_modules/sax": {
- "version": "1.4.1",
- "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz",
- "integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==",
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
+ "integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
"dev": true,
- "license": "ISC"
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=11.0.0"
+ }
},
"node_modules/semver": {
"version": "6.3.1",
@@ -3546,17 +4326,11 @@
}
},
"node_modules/signal-exit": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
- "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"dev": true,
- "license": "ISC",
- "engines": {
- "node": ">=14"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
+ "license": "ISC"
},
"node_modules/simple-update-notifier": {
"version": "2.0.0",
@@ -3606,12 +4380,41 @@
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
"dev": true,
"license": "MIT",
- "optional": true,
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
}
},
+ "node_modules/socks": {
+ "version": "2.8.7",
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",
+ "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.0.1",
+ "smart-buffer": "^4.2.0"
+ },
+ "engines": {
+ "node": ">= 10.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks-proxy-agent": {
+ "version": "8.0.5",
+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
+ "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "socks": "^2.8.3"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -3641,6 +4444,19 @@
"license": "BSD-3-Clause",
"optional": true
},
+ "node_modules/ssri": {
+ "version": "12.0.0",
+ "resolved": "https://registry.npmjs.org/ssri/-/ssri-12.0.0.tgz",
+ "integrity": "sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^7.0.3"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
"node_modules/stat-mode": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz",
@@ -3657,7 +4473,6 @@
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"safe-buffer": "~5.2.0"
}
@@ -3747,39 +4562,45 @@
}
},
"node_modules/tar": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
- "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
+ "version": "7.5.9",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.9.tgz",
+ "integrity": "sha512-BTLcK0xsDh2+PUe9F6c2TlRp4zOOBMTkoQHQIWSIzI0R7KG46uEwq4OPk2W7bZcprBMsuaeFsqwYr7pjh6CuHg==",
"dev": true,
- "license": "ISC",
+ "license": "BlueOak-1.0.0",
"dependencies": {
- "chownr": "^2.0.0",
- "fs-minipass": "^2.0.0",
- "minipass": "^5.0.0",
- "minizlib": "^2.1.1",
- "mkdirp": "^1.0.3",
- "yallist": "^4.0.0"
+ "@isaacs/fs-minipass": "^4.0.0",
+ "chownr": "^3.0.0",
+ "minipass": "^7.1.2",
+ "minizlib": "^3.1.0",
+ "yallist": "^5.0.0"
},
"engines": {
- "node": ">=10"
+ "node": ">=18"
}
},
- "node_modules/tar-stream": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
- "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "node_modules/tar/node_modules/yallist": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/temp": {
+ "version": "0.9.4",
+ "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",
+ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "bl": "^4.0.3",
- "end-of-stream": "^1.4.1",
- "fs-constants": "^1.0.0",
- "inherits": "^2.0.3",
- "readable-stream": "^3.1.1"
+ "mkdirp": "^0.5.1",
+ "rimraf": "~2.6.2"
},
"engines": {
- "node": ">=6"
+ "node": ">=6.0.0"
}
},
"node_modules/temp-file": {
@@ -3831,6 +4652,43 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/tiny-async-pool": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz",
+ "integrity": "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^5.5.0"
+ }
+ },
+ "node_modules/tiny-async-pool/node_modules/semver": {
+ "version": "5.7.2",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
"node_modules/tmp": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz",
@@ -3875,20 +4733,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/typescript": {
- "version": "5.9.3",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
- "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
- },
- "engines": {
- "node": ">=14.17"
- }
- },
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
@@ -3896,6 +4740,32 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/unique-filename": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-4.0.0.tgz",
+ "integrity": "sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "unique-slug": "^5.0.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
+ "node_modules/unique-slug": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-5.0.0.tgz",
+ "integrity": "sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "imurmurhash": "^0.1.4"
+ },
+ "engines": {
+ "node": "^18.17.0 || >=20.5.0"
+ }
+ },
"node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
@@ -3928,8 +4798,7 @@
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"dev": true,
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/verror": {
"version": "1.10.1",
@@ -3947,6 +4816,16 @@
"node": ">=0.6.0"
}
},
+ "node_modules/wcwidth": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",
+ "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "defaults": "^1.0.3"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -4074,43 +4953,17 @@
"fd-slicer": "~1.1.0"
}
},
- "node_modules/zip-stream": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz",
- "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==",
+ "node_modules/yocto-queue": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
"dev": true,
"license": "MIT",
- "peer": true,
- "dependencies": {
- "archiver-utils": "^3.0.4",
- "compress-commons": "^4.1.2",
- "readable-stream": "^3.6.0"
- },
"engines": {
- "node": ">= 10"
- }
- },
- "node_modules/zip-stream/node_modules/archiver-utils": {
- "version": "3.0.4",
- "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz",
- "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==",
- "dev": true,
- "license": "MIT",
- "peer": true,
- "dependencies": {
- "glob": "^7.2.3",
- "graceful-fs": "^4.2.0",
- "lazystream": "^1.0.0",
- "lodash.defaults": "^4.2.0",
- "lodash.difference": "^4.5.0",
- "lodash.flatten": "^4.4.0",
- "lodash.isplainobject": "^4.0.6",
- "lodash.union": "^4.6.0",
- "normalize-path": "^3.0.0",
- "readable-stream": "^3.6.0"
+ "node": ">=10"
},
- "engines": {
- "node": ">= 10"
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
}
}
}
diff --git a/electron/package.json b/electron/package.json
index f861c91cb4..c62bad108d 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -25,8 +25,8 @@
},
"devDependencies": {
"cross-env": "^7.0.3",
- "electron": "35.7.5",
- "electron-builder": "^24.9.1"
+ "electron": "39.8.5",
+ "electron-builder": "^26.7.0"
},
"build": {
"appId": "com.newapi.desktop",
diff --git a/go.mod b/go.mod
index f4f133973e..a078b2091a 100644
--- a/go.mod
+++ b/go.mod
@@ -8,10 +8,10 @@ require (
github.com/abema/go-mp4 v1.4.1
github.com/andybalholm/brotli v1.1.1
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0
- github.com/aws/aws-sdk-go-v2 v1.37.2
- github.com/aws/aws-sdk-go-v2/credentials v1.17.11
- github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.33.0
- github.com/aws/smithy-go v1.22.5
+ github.com/aws/aws-sdk-go-v2 v1.41.5
+ github.com/aws/aws-sdk-go-v2/credentials v1.19.10
+ github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.50.4
+ github.com/aws/smithy-go v1.24.2
github.com/bytedance/gopkg v0.1.3
github.com/gin-contrib/cors v1.7.2
github.com/gin-contrib/gzip v0.0.6
@@ -32,8 +32,10 @@ require (
github.com/jinzhu/copier v0.4.0
github.com/joho/godotenv v1.5.1
github.com/mewkiz/flac v1.0.13
+ github.com/nicksnyder/go-i18n/v2 v2.6.1
github.com/pkg/errors v0.9.1
github.com/pquerna/otp v1.5.0
+ github.com/samber/hot v0.11.0
github.com/samber/lo v1.52.0
github.com/shirou/gopsutil v3.21.11+incompatible
github.com/shopspring/decimal v1.4.0
@@ -44,27 +46,33 @@ require (
github.com/tidwall/gjson v1.18.0
github.com/tidwall/sjson v1.2.5
github.com/tiktoken-go/tokenizer v0.6.2
+ github.com/waffo-com/waffo-go v1.3.1
github.com/yapingcat/gomedia v0.0.0-20240906162731-17feea57090c
golang.org/x/crypto v0.45.0
- golang.org/x/image v0.23.0
+ golang.org/x/image v0.38.0
golang.org/x/net v0.47.0
- golang.org/x/sync v0.18.0
+ golang.org/x/sync v0.20.0
+ golang.org/x/sys v0.38.0
+ golang.org/x/text v0.35.0
+ gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.4.3
gorm.io/driver/postgres v1.5.2
gorm.io/gorm v1.25.2
)
require (
+ github.com/DmitriyVTitov/size v1.5.0 // indirect
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 // indirect
- github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.0 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.2 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.2 // indirect
+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
+ github.com/beorn7/perks v1.0.1 // indirect
github.com/boombuler/barcode v1.1.0 // indirect
github.com/bytedance/sonic v1.14.1 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
- github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
@@ -94,7 +102,7 @@ require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
- github.com/klauspost/compress v1.17.8 // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -103,11 +111,16 @@ require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/pelletier/go-toml/v2 v2.2.1 // indirect
- github.com/pmezard/go-difflib v1.0.0 // indirect
+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
+ github.com/prometheus/client_golang v1.22.0 // indirect
+ github.com/prometheus/client_model v0.6.1 // indirect
+ github.com/prometheus/common v0.62.0 // indirect
+ github.com/prometheus/procfs v0.15.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
- github.com/stretchr/objx v0.5.2 // indirect
+ github.com/samber/go-singleflightx v0.3.2 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
@@ -118,10 +131,7 @@ require (
github.com/yusufpapurcu/wmi v1.2.3 // indirect
golang.org/x/arch v0.21.0 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
- golang.org/x/sys v0.38.0 // indirect
- golang.org/x/text v0.31.0 // indirect
- google.golang.org/protobuf v1.34.2 // indirect
- gopkg.in/yaml.v3 v3.0.1 // indirect
+ google.golang.org/protobuf v1.36.5 // indirect
modernc.org/libc v1.66.10 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
diff --git a/go.sum b/go.sum
index 697a313d8b..8b68790633 100644
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,9 @@
+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/Calcium-Ion/go-epay v0.0.4 h1:C96M7WfRLadcIVscWzwLiYs8etI1wrDmtFMuK2zP22A=
github.com/Calcium-Ion/go-epay v0.0.4/go.mod h1:cxo/ZOg8ClvE3VAnCmEzbuyAZINSq7kFEN9oHj5WQ2U=
+github.com/DmitriyVTitov/size v1.5.0 h1:/PzqxYrOyOUX1BXj6J9OuVRVGe+66VL4D9FlUaW515g=
+github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=
github.com/abema/go-mp4 v1.4.1 h1:YoS4VRqd+pAmddRPLFf8vMk74kuGl6ULSjzhsIqwr6M=
github.com/abema/go-mp4 v1.4.1/go.mod h1:vPl9t5ZK7K0x68jh12/+ECWBCXoWuIDtNgPtU2f04ws=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
@@ -8,20 +12,22 @@ github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0 h1:onfun1RA+Kc
github.com/anknown/ahocorasick v0.0.0-20190904063843-d75dbd5169c0/go.mod h1:4yg+jNTYlDEzBjhGS96v+zjyA3lfXlFd5CiTLIkPBLI=
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6 h1:HblK3eJHq54yET63qPCTJnks3loDse5xRmmqHgHzwoI=
github.com/anknown/darts v0.0.0-20151216065714-83ff685239e6/go.mod h1:pbiaLIeYLUbgMY1kwEAdwO6UKD5ZNwdPGQlwokS9fe8=
-github.com/aws/aws-sdk-go-v2 v1.37.2 h1:xkW1iMYawzcmYFYEV0UCMxc8gSsjCGEhBXQkdQywVbo=
-github.com/aws/aws-sdk-go-v2 v1.37.2/go.mod h1:9Q0OoGQoboYIAJyslFyF1f5K1Ryddop8gqMhWx/n4Wg=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.0 h1:6GMWV6CNpA/6fbFHnoAjrv4+LGfyTqZz2LtCHnspgDg=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.0/go.mod h1:/mXlTIVG9jbxkqDnr5UQNQxW1HRYxeGklkM9vAFeabg=
-github.com/aws/aws-sdk-go-v2/credentials v1.17.11 h1:YuIB1dJNf1Re822rriUOTxopaHHvIq0l/pX3fwO+Tzs=
-github.com/aws/aws-sdk-go-v2/credentials v1.17.11/go.mod h1:AQtFPsDH9bI2O+71anW6EKL+NcD7LG3dpKGMV4SShgo=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.2 h1:sPiRHLVUIIQcoVZTNwqQcdtjkqkPopyYmIX0M5ElRf4=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.2/go.mod h1:ik86P3sgV+Bk7c1tBFCwI3VxMoSEwl4YkRB9xn1s340=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.2 h1:ZdzDAg075H6stMZtbD2o+PyB933M/f20e9WmCBC17wA=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.2/go.mod h1:eE1IIzXG9sdZCB0pNNpMpsYTLl4YdOQD3njiVN1e/E4=
-github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.33.0 h1:JzidOz4Hcn2RbP5fvIS1iAP+DcRv5VJtgixbEYDsI5g=
-github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.33.0/go.mod h1:9A4/PJYlWjvjEzzoOLGQjkLt4bYK9fRWi7uz1GSsAcA=
-github.com/aws/smithy-go v1.22.5 h1:P9ATCXPMb2mPjYBgueqJNCA5S9UfktsW0tTxi+a7eqw=
-github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI=
+github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
+github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.10 h1:EEhmEUFCE1Yhl7vDhNOI5OCL/iKMdkkYFTRpZXNw7m8=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.10/go.mod h1:RnnlFCAlxQCkN2Q379B67USkBMu1PipEEiibzYN5UTE=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps=
+github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.50.4 h1:W6tKfa/s37faUnwJ71pGqsBO7/wfUX1L7tVprupQGo4=
+github.com/aws/aws-sdk-go-v2/service/bedrockruntime v1.50.4/go.mod h1:BZ+9thH0QOTDUwE8KAv/ZwUzsNC7CSMJXj/wtnZMs5k=
+github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
+github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/boombuler/barcode v1.1.0 h1:ChaYjBR63fr4LFyGn8E8nt7dBSt3MiU3zMOZqFvVkHo=
github.com/boombuler/barcode v1.1.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
@@ -38,8 +44,9 @@ github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gE
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
@@ -110,11 +117,13 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
+github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
-github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
-github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-tpm v0.9.5 h1:ocUmnDebX54dnW+MQWGQRbdaAcJELsa6PqZhJ48KwVU=
github.com/google/go-tpm v0.9.5/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -163,8 +172,8 @@ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwA
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
-github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
-github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -200,8 +209,12 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
+github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
@@ -216,15 +229,29 @@ github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
+github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
+github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
+github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
+github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
+github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
+github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
+github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
+github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
+github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
-github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
+github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
+github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
+github.com/samber/go-singleflightx v0.3.2 h1:jXbUU0fvis8Fdv4HGONboX5WdEZcYLoBEcKiE+ITCyQ=
+github.com/samber/go-singleflightx v0.3.2/go.mod h1:X2BR+oheHIYc73PvxRMlcASg6KYYTQyUYpdVU7t/ux4=
+github.com/samber/hot v0.11.0 h1:JhV9hk8SmZIqB0To8OyCzPubvszkuoSXWx/7FCEGO+Q=
+github.com/samber/hot v0.11.0/go.mod h1:NB9v5U4NfDx7jmlrP+zHuqCuLUsywgAtCH7XOAkOxAg=
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
@@ -277,6 +304,8 @@ github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLY
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+github.com/waffo-com/waffo-go v1.3.1 h1:NCYD3oQ59DTJj1bwS5T/659LI4h8PuAIW4Qj/w7fKPw=
+github.com/waffo-com/waffo-go v1.3.1/go.mod h1:IaXVYq6mmYtrLFFsLxPslNwuIZx0mIadWWjhe+eWb0g=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
@@ -287,6 +316,8 @@ github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFi
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/arch v0.21.0 h1:iTC9o7+wP6cPWpDWkivCvQFGAHDQ59SrSxsLPcnkArw=
golang.org/x/arch v0.21.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
@@ -294,16 +325,16 @@ golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
-golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
-golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
-golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
-golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
+golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
+golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
+golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
+golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
-golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
-golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -322,16 +353,16 @@ golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuX
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
-golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
-golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
-golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
+golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
+golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
-google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
-google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
+google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
+google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
diff --git a/i18n/i18n.go b/i18n/i18n.go
new file mode 100644
index 0000000000..7ca8d2aa99
--- /dev/null
+++ b/i18n/i18n.go
@@ -0,0 +1,231 @@
+package i18n
+
+import (
+ "embed"
+ "strings"
+ "sync"
+
+ "github.com/gin-gonic/gin"
+ "github.com/nicksnyder/go-i18n/v2/i18n"
+ "golang.org/x/text/language"
+ "gopkg.in/yaml.v3"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+)
+
+const (
+ LangZhCN = "zh-CN"
+ LangZhTW = "zh-TW"
+ LangEn = "en"
+ DefaultLang = LangEn // Fallback to English if language not supported
+)
+
+//go:embed locales/*.yaml
+var localeFS embed.FS
+
+var (
+ bundle *i18n.Bundle
+ localizers = make(map[string]*i18n.Localizer)
+ mu sync.RWMutex
+ initOnce sync.Once
+)
+
+// Init initializes the i18n bundle and loads all translation files
+func Init() error {
+ var initErr error
+ initOnce.Do(func() {
+ bundle = i18n.NewBundle(language.Chinese)
+ bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
+
+ // Load embedded translation files
+ files := []string{"locales/zh-CN.yaml", "locales/zh-TW.yaml", "locales/en.yaml"}
+ for _, file := range files {
+ _, err := bundle.LoadMessageFileFS(localeFS, file)
+ if err != nil {
+ initErr = err
+ return
+ }
+ }
+
+ // Pre-create localizers for supported languages
+ localizers[LangZhCN] = i18n.NewLocalizer(bundle, LangZhCN)
+ localizers[LangZhTW] = i18n.NewLocalizer(bundle, LangZhTW)
+ localizers[LangEn] = i18n.NewLocalizer(bundle, LangEn)
+
+ // Set the TranslateMessage function in common package
+ common.TranslateMessage = T
+ })
+ return initErr
+}
+
+// GetLocalizer returns a localizer for the specified language
+func GetLocalizer(lang string) *i18n.Localizer {
+ lang = normalizeLang(lang)
+
+ mu.RLock()
+ loc, ok := localizers[lang]
+ mu.RUnlock()
+
+ if ok {
+ return loc
+ }
+
+ // Create new localizer for unknown language (fallback to default)
+ mu.Lock()
+ defer mu.Unlock()
+
+ // Double-check after acquiring write lock
+ if loc, ok = localizers[lang]; ok {
+ return loc
+ }
+
+ loc = i18n.NewLocalizer(bundle, lang, DefaultLang)
+ localizers[lang] = loc
+ return loc
+}
+
+// T translates a message key using the language from gin context
+func T(c *gin.Context, key string, args ...map[string]any) string {
+ lang := GetLangFromContext(c)
+ return Translate(lang, key, args...)
+}
+
+// Translate translates a message key for the specified language
+func Translate(lang, key string, args ...map[string]any) string {
+ loc := GetLocalizer(lang)
+
+ config := &i18n.LocalizeConfig{
+ MessageID: key,
+ }
+
+ if len(args) > 0 && args[0] != nil {
+ config.TemplateData = args[0]
+ }
+
+ msg, err := loc.Localize(config)
+ if err != nil {
+ // Return key as fallback if translation not found
+ return key
+ }
+ return msg
+}
+
+// userLangLoaderFunc is a function that loads user language from database/cache
+// It's set by the model package to avoid circular imports
+var userLangLoaderFunc func(userId int) string
+
+// SetUserLangLoader sets the function to load user language (called from model package)
+func SetUserLangLoader(loader func(userId int) string) {
+ userLangLoaderFunc = loader
+}
+
+// GetLangFromContext extracts the language setting from gin context
+// It checks multiple sources in priority order:
+// 1. User settings (ContextKeyUserSetting) - if already loaded (e.g., by TokenAuth)
+// 2. Lazy load user language from cache/DB using user ID
+// 3. Language set by middleware (ContextKeyLanguage) - from Accept-Language header
+// 4. Default language (English)
+func GetLangFromContext(c *gin.Context) string {
+ if c == nil {
+ return DefaultLang
+ }
+
+ // 1. Try to get language from user settings (if already loaded by TokenAuth or other middleware)
+ if userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting); ok {
+ if userSetting.Language != "" {
+ normalized := normalizeLang(userSetting.Language)
+ if IsSupported(normalized) {
+ return normalized
+ }
+ }
+ }
+
+ // 2. Lazy load user language using user ID (for session-based auth where full settings aren't loaded)
+ if userLangLoaderFunc != nil {
+ if userId, exists := c.Get("id"); exists {
+ if uid, ok := userId.(int); ok && uid > 0 {
+ lang := userLangLoaderFunc(uid)
+ if lang != "" {
+ normalized := normalizeLang(lang)
+ if IsSupported(normalized) {
+ return normalized
+ }
+ }
+ }
+ }
+ }
+
+ // 3. Try to get language from context (set by I18n middleware from Accept-Language)
+ if lang := c.GetString(string(constant.ContextKeyLanguage)); lang != "" {
+ normalized := normalizeLang(lang)
+ if IsSupported(normalized) {
+ return normalized
+ }
+ }
+
+ // 4. Try Accept-Language header directly (fallback if middleware didn't run)
+ if acceptLang := c.GetHeader("Accept-Language"); acceptLang != "" {
+ lang := ParseAcceptLanguage(acceptLang)
+ if IsSupported(lang) {
+ return lang
+ }
+ }
+
+ return DefaultLang
+}
+
+// ParseAcceptLanguage parses the Accept-Language header and returns the preferred language
+func ParseAcceptLanguage(header string) string {
+ if header == "" {
+ return DefaultLang
+ }
+
+ // Simple parsing: take the first language tag
+ parts := strings.Split(header, ",")
+ if len(parts) == 0 {
+ return DefaultLang
+ }
+
+ // Get the first language and remove quality value
+ firstLang := strings.TrimSpace(parts[0])
+ if idx := strings.Index(firstLang, ";"); idx > 0 {
+ firstLang = firstLang[:idx]
+ }
+
+ return normalizeLang(firstLang)
+}
+
+// normalizeLang normalizes language code to supported format
+func normalizeLang(lang string) string {
+ lang = strings.ToLower(strings.TrimSpace(lang))
+
+ // Handle common variations
+ switch {
+ case strings.HasPrefix(lang, "zh-tw"):
+ return LangZhTW
+ case strings.HasPrefix(lang, "zh"):
+ return LangZhCN
+ case strings.HasPrefix(lang, "en"):
+ return LangEn
+ default:
+ return DefaultLang
+ }
+}
+
+// SupportedLanguages returns a list of supported language codes
+func SupportedLanguages() []string {
+ return []string{LangZhCN, LangZhTW, LangEn}
+}
+
+// IsSupported checks if a language code is supported
+func IsSupported(lang string) bool {
+ lang = normalizeLang(lang)
+ for _, supported := range SupportedLanguages() {
+ if lang == supported {
+ return true
+ }
+ }
+ return false
+}
diff --git a/i18n/keys.go b/i18n/keys.go
new file mode 100644
index 0000000000..8118dff9c6
--- /dev/null
+++ b/i18n/keys.go
@@ -0,0 +1,317 @@
+package i18n
+
+// Message keys for i18n translations
+// Use these constants instead of hardcoded strings
+
+// Common error messages
+const (
+ MsgInvalidParams = "common.invalid_params"
+ MsgDatabaseError = "common.database_error"
+ MsgRetryLater = "common.retry_later"
+ MsgGenerateFailed = "common.generate_failed"
+ MsgNotFound = "common.not_found"
+ MsgUnauthorized = "common.unauthorized"
+ MsgForbidden = "common.forbidden"
+ MsgInvalidId = "common.invalid_id"
+ MsgIdEmpty = "common.id_empty"
+ MsgFeatureDisabled = "common.feature_disabled"
+ MsgOperationSuccess = "common.operation_success"
+ MsgOperationFailed = "common.operation_failed"
+ MsgUpdateSuccess = "common.update_success"
+ MsgUpdateFailed = "common.update_failed"
+ MsgCreateSuccess = "common.create_success"
+ MsgCreateFailed = "common.create_failed"
+ MsgDeleteSuccess = "common.delete_success"
+ MsgDeleteFailed = "common.delete_failed"
+ MsgAlreadyExists = "common.already_exists"
+ MsgNameCannotBeEmpty = "common.name_cannot_be_empty"
+ MsgBatchTooMany = "common.batch_too_many"
+)
+
+// Token related messages
+const (
+ MsgTokenNameTooLong = "token.name_too_long"
+ MsgTokenQuotaNegative = "token.quota_negative"
+ MsgTokenQuotaExceedMax = "token.quota_exceed_max"
+ MsgTokenGenerateFailed = "token.generate_failed"
+ MsgTokenGetInfoFailed = "token.get_info_failed"
+ MsgTokenExpiredCannotEnable = "token.expired_cannot_enable"
+ MsgTokenExhaustedCannotEable = "token.exhausted_cannot_enable"
+ MsgTokenInvalid = "token.invalid"
+ MsgTokenNotProvided = "token.not_provided"
+ MsgTokenExpired = "token.expired"
+ MsgTokenExhausted = "token.exhausted"
+ MsgTokenStatusUnavailable = "token.status_unavailable"
+ MsgTokenDbError = "token.db_error"
+)
+
+// Redemption related messages
+const (
+ MsgRedemptionNameLength = "redemption.name_length"
+ MsgRedemptionCountPositive = "redemption.count_positive"
+ MsgRedemptionCountMax = "redemption.count_max"
+ MsgRedemptionCreateFailed = "redemption.create_failed"
+ MsgRedemptionInvalid = "redemption.invalid"
+ MsgRedemptionUsed = "redemption.used"
+ MsgRedemptionExpired = "redemption.expired"
+ MsgRedemptionFailed = "redemption.failed"
+ MsgRedemptionNotProvided = "redemption.not_provided"
+ MsgRedemptionExpireTimeInvalid = "redemption.expire_time_invalid"
+)
+
+// User related messages
+const (
+ MsgUserPasswordLoginDisabled = "user.password_login_disabled"
+ MsgUserRegisterDisabled = "user.register_disabled"
+ MsgUserPasswordRegisterDisabled = "user.password_register_disabled"
+ MsgUserUsernameOrPasswordEmpty = "user.username_or_password_empty"
+ MsgUserUsernameOrPasswordError = "user.username_or_password_error"
+ MsgUserEmailOrPasswordEmpty = "user.email_or_password_empty"
+ MsgUserExists = "user.exists"
+ MsgUserNotExists = "user.not_exists"
+ MsgUserDisabled = "user.disabled"
+ MsgUserSessionSaveFailed = "user.session_save_failed"
+ MsgUserRequire2FA = "user.require_2fa"
+ MsgUserEmailVerificationRequired = "user.email_verification_required"
+ MsgUserVerificationCodeError = "user.verification_code_error"
+ MsgUserInputInvalid = "user.input_invalid"
+ MsgUserNoPermissionSameLevel = "user.no_permission_same_level"
+ MsgUserNoPermissionHigherLevel = "user.no_permission_higher_level"
+ MsgUserCannotCreateHigherLevel = "user.cannot_create_higher_level"
+ MsgUserCannotDeleteRootUser = "user.cannot_delete_root_user"
+ MsgUserCannotDisableRootUser = "user.cannot_disable_root_user"
+ MsgUserCannotDemoteRootUser = "user.cannot_demote_root_user"
+ MsgUserAlreadyAdmin = "user.already_admin"
+ MsgUserAlreadyCommon = "user.already_common"
+ MsgUserAdminCannotPromote = "user.admin_cannot_promote"
+ MsgUserOriginalPasswordError = "user.original_password_error"
+ MsgUserInviteQuotaInsufficient = "user.invite_quota_insufficient"
+ MsgUserTransferQuotaMinimum = "user.transfer_quota_minimum"
+ MsgUserTransferSuccess = "user.transfer_success"
+ MsgUserTransferFailed = "user.transfer_failed"
+ MsgUserTopUpProcessing = "user.topup_processing"
+ MsgUserRegisterFailed = "user.register_failed"
+ MsgUserDefaultTokenFailed = "user.default_token_failed"
+ MsgUserAffCodeEmpty = "user.aff_code_empty"
+ MsgUserEmailEmpty = "user.email_empty"
+ MsgUserGitHubIdEmpty = "user.github_id_empty"
+ MsgUserDiscordIdEmpty = "user.discord_id_empty"
+ MsgUserOidcIdEmpty = "user.oidc_id_empty"
+ MsgUserWeChatIdEmpty = "user.wechat_id_empty"
+ MsgUserTelegramIdEmpty = "user.telegram_id_empty"
+ MsgUserTelegramNotBound = "user.telegram_not_bound"
+ MsgUserLinuxDOIdEmpty = "user.linux_do_id_empty"
+)
+
+// Quota related messages
+const (
+ MsgQuotaNegative = "quota.negative"
+ MsgQuotaExceedMax = "quota.exceed_max"
+ MsgQuotaInsufficient = "quota.insufficient"
+ MsgQuotaWarningInvalid = "quota.warning_invalid"
+ MsgQuotaThresholdGtZero = "quota.threshold_gt_zero"
+)
+
+// Subscription related messages
+const (
+ MsgSubscriptionNotEnabled = "subscription.not_enabled"
+ MsgSubscriptionTitleEmpty = "subscription.title_empty"
+ MsgSubscriptionPriceNegative = "subscription.price_negative"
+ MsgSubscriptionPriceMax = "subscription.price_max"
+ MsgSubscriptionPurchaseLimitNeg = "subscription.purchase_limit_negative"
+ MsgSubscriptionQuotaNegative = "subscription.quota_negative"
+ MsgSubscriptionGroupNotExists = "subscription.group_not_exists"
+ MsgSubscriptionResetCycleGtZero = "subscription.reset_cycle_gt_zero"
+ MsgSubscriptionPurchaseMax = "subscription.purchase_max"
+ MsgSubscriptionInvalidId = "subscription.invalid_id"
+ MsgSubscriptionInvalidUserId = "subscription.invalid_user_id"
+)
+
+// Payment related messages
+const (
+ MsgPaymentNotConfigured = "payment.not_configured"
+ MsgPaymentMethodNotExists = "payment.method_not_exists"
+ MsgPaymentCallbackError = "payment.callback_error"
+ MsgPaymentCreateFailed = "payment.create_failed"
+ MsgPaymentStartFailed = "payment.start_failed"
+ MsgPaymentAmountTooLow = "payment.amount_too_low"
+ MsgPaymentStripeNotConfig = "payment.stripe_not_configured"
+ MsgPaymentWebhookNotConfig = "payment.webhook_not_configured"
+ MsgPaymentPriceIdNotConfig = "payment.price_id_not_configured"
+ MsgPaymentCreemNotConfig = "payment.creem_not_configured"
+)
+
+// Topup related messages
+const (
+ MsgTopupNotProvided = "topup.not_provided"
+ MsgTopupOrderNotExists = "topup.order_not_exists"
+ MsgTopupOrderStatus = "topup.order_status"
+ MsgTopupFailed = "topup.failed"
+ MsgTopupInvalidQuota = "topup.invalid_quota"
+)
+
+// Channel related messages
+const (
+ MsgChannelNotExists = "channel.not_exists"
+ MsgChannelIdFormatError = "channel.id_format_error"
+ MsgChannelNoAvailableKey = "channel.no_available_key"
+ MsgChannelGetListFailed = "channel.get_list_failed"
+ MsgChannelGetTagsFailed = "channel.get_tags_failed"
+ MsgChannelGetKeyFailed = "channel.get_key_failed"
+ MsgChannelGetOllamaFailed = "channel.get_ollama_failed"
+ MsgChannelQueryFailed = "channel.query_failed"
+ MsgChannelNoValidUpstream = "channel.no_valid_upstream"
+ MsgChannelUpstreamSaturated = "channel.upstream_saturated"
+ MsgChannelGetAvailableFailed = "channel.get_available_failed"
+)
+
+// Model related messages
+const (
+ MsgModelNameEmpty = "model.name_empty"
+ MsgModelNameExists = "model.name_exists"
+ MsgModelIdMissing = "model.id_missing"
+ MsgModelGetListFailed = "model.get_list_failed"
+ MsgModelGetFailed = "model.get_failed"
+ MsgModelResetSuccess = "model.reset_success"
+)
+
+// Vendor related messages
+const (
+ MsgVendorNameEmpty = "vendor.name_empty"
+ MsgVendorNameExists = "vendor.name_exists"
+ MsgVendorIdMissing = "vendor.id_missing"
+)
+
+// Group related messages
+const (
+ MsgGroupNameTypeEmpty = "group.name_type_empty"
+ MsgGroupNameExists = "group.name_exists"
+ MsgGroupIdMissing = "group.id_missing"
+)
+
+// Checkin related messages
+const (
+ MsgCheckinDisabled = "checkin.disabled"
+ MsgCheckinAlreadyToday = "checkin.already_today"
+ MsgCheckinFailed = "checkin.failed"
+ MsgCheckinQuotaFailed = "checkin.quota_failed"
+)
+
+// Passkey related messages
+const (
+ MsgPasskeyCreateFailed = "passkey.create_failed"
+ MsgPasskeyLoginAbnormal = "passkey.login_abnormal"
+ MsgPasskeyUpdateFailed = "passkey.update_failed"
+ MsgPasskeyInvalidUserId = "passkey.invalid_user_id"
+ MsgPasskeyVerifyFailed = "passkey.verify_failed"
+)
+
+// 2FA related messages
+const (
+ MsgTwoFANotEnabled = "twofa.not_enabled"
+ MsgTwoFAUserIdEmpty = "twofa.user_id_empty"
+ MsgTwoFAAlreadyExists = "twofa.already_exists"
+ MsgTwoFARecordIdEmpty = "twofa.record_id_empty"
+ MsgTwoFACodeInvalid = "twofa.code_invalid"
+)
+
+// Rate limit related messages
+const (
+ MsgRateLimitReached = "rate_limit.reached"
+ MsgRateLimitTotalReached = "rate_limit.total_reached"
+)
+
+// Setting related messages
+const (
+ MsgSettingInvalidType = "setting.invalid_type"
+ MsgSettingWebhookEmpty = "setting.webhook_empty"
+ MsgSettingWebhookInvalid = "setting.webhook_invalid"
+ MsgSettingEmailInvalid = "setting.email_invalid"
+ MsgSettingBarkUrlEmpty = "setting.bark_url_empty"
+ MsgSettingBarkUrlInvalid = "setting.bark_url_invalid"
+ MsgSettingGotifyUrlEmpty = "setting.gotify_url_empty"
+ MsgSettingGotifyTokenEmpty = "setting.gotify_token_empty"
+ MsgSettingGotifyUrlInvalid = "setting.gotify_url_invalid"
+ MsgSettingUrlMustHttp = "setting.url_must_http"
+ MsgSettingSaved = "setting.saved"
+)
+
+// Deployment related messages (io.net)
+const (
+ MsgDeploymentNotEnabled = "deployment.not_enabled"
+ MsgDeploymentIdRequired = "deployment.id_required"
+ MsgDeploymentContainerIdReq = "deployment.container_id_required"
+ MsgDeploymentNameEmpty = "deployment.name_empty"
+ MsgDeploymentNameTaken = "deployment.name_taken"
+ MsgDeploymentHardwareIdReq = "deployment.hardware_id_required"
+ MsgDeploymentHardwareInvId = "deployment.hardware_invalid_id"
+ MsgDeploymentApiKeyRequired = "deployment.api_key_required"
+ MsgDeploymentInvalidPayload = "deployment.invalid_payload"
+ MsgDeploymentNotFound = "deployment.not_found"
+)
+
+// Performance related messages
+const (
+ MsgPerfDiskCacheCleared = "performance.disk_cache_cleared"
+ MsgPerfStatsReset = "performance.stats_reset"
+ MsgPerfGcExecuted = "performance.gc_executed"
+)
+
+// Ability related messages
+const (
+ MsgAbilityDbCorrupted = "ability.db_corrupted"
+ MsgAbilityRepairRunning = "ability.repair_running"
+)
+
+// OAuth related messages
+const (
+ MsgOAuthInvalidCode = "oauth.invalid_code"
+ MsgOAuthGetUserErr = "oauth.get_user_error"
+ MsgOAuthAccountUsed = "oauth.account_used"
+ MsgOAuthUnknownProvider = "oauth.unknown_provider"
+ MsgOAuthStateInvalid = "oauth.state_invalid"
+ MsgOAuthNotEnabled = "oauth.not_enabled"
+ MsgOAuthUserDeleted = "oauth.user_deleted"
+ MsgOAuthUserBanned = "oauth.user_banned"
+ MsgOAuthBindSuccess = "oauth.bind_success"
+ MsgOAuthAlreadyBound = "oauth.already_bound"
+ MsgOAuthConnectFailed = "oauth.connect_failed"
+ MsgOAuthTokenFailed = "oauth.token_failed"
+ MsgOAuthUserInfoEmpty = "oauth.user_info_empty"
+ MsgOAuthTrustLevelLow = "oauth.trust_level_low"
+)
+
+// Model layer error messages (for translation in controller)
+const (
+ MsgRedeemFailed = "redeem.failed"
+ MsgCreateDefaultTokenErr = "user.create_default_token_error"
+ MsgUuidDuplicate = "common.uuid_duplicate"
+ MsgInvalidInput = "common.invalid_input"
+)
+
+// Distributor related messages
+const (
+ MsgDistributorInvalidRequest = "distributor.invalid_request"
+ MsgDistributorInvalidChannelId = "distributor.invalid_channel_id"
+ MsgDistributorChannelDisabled = "distributor.channel_disabled"
+ MsgDistributorTokenNoModelAccess = "distributor.token_no_model_access"
+ MsgDistributorTokenModelForbidden = "distributor.token_model_forbidden"
+ MsgDistributorModelNameRequired = "distributor.model_name_required"
+ MsgDistributorInvalidPlayground = "distributor.invalid_playground_request"
+ MsgDistributorGroupAccessDenied = "distributor.group_access_denied"
+ MsgDistributorGetChannelFailed = "distributor.get_channel_failed"
+ MsgDistributorNoAvailableChannel = "distributor.no_available_channel"
+ MsgDistributorInvalidMidjourney = "distributor.invalid_midjourney_request"
+ MsgDistributorInvalidParseModel = "distributor.invalid_request_parse_model"
+)
+
+// Custom OAuth provider related messages
+const (
+ MsgCustomOAuthNotFound = "custom_oauth.not_found"
+ MsgCustomOAuthSlugEmpty = "custom_oauth.slug_empty"
+ MsgCustomOAuthSlugExists = "custom_oauth.slug_exists"
+ MsgCustomOAuthNameEmpty = "custom_oauth.name_empty"
+ MsgCustomOAuthHasBindings = "custom_oauth.has_bindings"
+ MsgCustomOAuthBindingNotFound = "custom_oauth.binding_not_found"
+ MsgCustomOAuthProviderIdInvalid = "custom_oauth.provider_id_field_invalid"
+)
diff --git a/i18n/locales/en.yaml b/i18n/locales/en.yaml
new file mode 100644
index 0000000000..75a8bc6e77
--- /dev/null
+++ b/i18n/locales/en.yaml
@@ -0,0 +1,266 @@
+# English translations
+
+# Common messages
+common.invalid_params: "Invalid parameters"
+common.database_error: "Database error, please try again later"
+common.retry_later: "Please try again later"
+common.generate_failed: "Generation failed"
+common.not_found: "Not found"
+common.unauthorized: "Unauthorized"
+common.forbidden: "Forbidden"
+common.invalid_id: "Invalid ID"
+common.id_empty: "ID is empty!"
+common.feature_disabled: "This feature is not enabled"
+common.operation_success: "Operation successful"
+common.operation_failed: "Operation failed"
+common.update_success: "Update successful"
+common.update_failed: "Update failed"
+common.create_success: "Creation successful"
+common.create_failed: "Creation failed"
+common.delete_success: "Deletion successful"
+common.delete_failed: "Deletion failed"
+common.already_exists: "Already exists"
+common.name_cannot_be_empty: "Name cannot be empty"
+common.batch_too_many: "Too many items in batch request, maximum is {{.Max}}"
+
+# Token messages
+token.name_too_long: "Token name is too long"
+token.quota_negative: "Quota value cannot be negative"
+token.quota_exceed_max: "Quota value exceeds valid range, maximum is {{.Max}}"
+token.generate_failed: "Failed to generate token"
+token.get_info_failed: "Failed to get token info, please try again later"
+token.expired_cannot_enable: "Token has expired and cannot be enabled. Please modify the expiration time or set it to never expire"
+token.exhausted_cannot_enable: "Token quota is exhausted and cannot be enabled. Please modify the remaining quota or set it to unlimited"
+token.invalid: "Invalid token"
+token.not_provided: "Token not provided"
+token.expired: "This token has expired"
+token.exhausted: "This token quota is exhausted TokenStatusExhausted[sk-{{.Prefix}}***{{.Suffix}}]"
+token.status_unavailable: "This token status is unavailable"
+token.db_error: "Invalid token, database query error, please contact administrator"
+
+# Redemption messages
+redemption.name_length: "Redemption code name length must be between 1-20"
+redemption.count_positive: "Redemption code count must be greater than 0"
+redemption.count_max: "Maximum 100 redemption codes can be generated at once"
+redemption.create_failed: "Failed to create redemption code, please try again later"
+redemption.invalid: "Invalid redemption code"
+redemption.used: "This redemption code has been used"
+redemption.expired: "This redemption code has expired"
+redemption.failed: "Redemption failed, please try again later"
+redemption.not_provided: "Redemption code not provided"
+redemption.expire_time_invalid: "Expiration time cannot be earlier than current time"
+
+# User messages
+user.password_login_disabled: "Password login has been disabled by administrator"
+user.register_disabled: "New user registration has been disabled by administrator"
+user.password_register_disabled: "Password registration has been disabled by administrator, please use third-party account verification"
+user.username_or_password_empty: "Username or password is empty"
+user.username_or_password_error: "Username or password is incorrect, or user has been banned"
+user.email_or_password_empty: "Email or password is empty!"
+user.exists: "Username already exists or has been deleted"
+user.not_exists: "User does not exist"
+user.disabled: "This user has been disabled"
+user.session_save_failed: "Failed to save session, please try again"
+user.require_2fa: "Please enter two-factor authentication code"
+user.email_verification_required: "Email verification is enabled, please enter email address and verification code"
+user.verification_code_error: "Verification code is incorrect or has expired"
+user.input_invalid: "Invalid input {{.Error}}"
+user.no_permission_same_level: "No permission to access users of same or higher level"
+user.no_permission_higher_level: "No permission to update users of same or higher permission level"
+user.cannot_create_higher_level: "Cannot create users with permission level equal to or higher than yourself"
+user.cannot_delete_root_user: "Cannot delete super administrator account"
+user.cannot_disable_root_user: "Cannot disable super administrator user"
+user.cannot_demote_root_user: "Cannot demote super administrator user"
+user.already_admin: "This user is already an administrator"
+user.already_common: "This user is already a common user"
+user.admin_cannot_promote: "Regular administrators cannot promote other users to administrator"
+user.original_password_error: "Original password is incorrect"
+user.invite_quota_insufficient: "Invitation quota is insufficient!"
+user.transfer_quota_minimum: "Minimum transfer quota is {{.Min}}!"
+user.transfer_success: "Transfer successful"
+user.transfer_failed: "Transfer failed {{.Error}}"
+user.topup_processing: "Top-up is processing, please try again later"
+user.register_failed: "User registration failed or user ID retrieval failed"
+user.default_token_failed: "Failed to generate default token"
+user.aff_code_empty: "Affiliate code is empty!"
+user.email_empty: "Email is empty!"
+user.github_id_empty: "GitHub ID is empty!"
+user.discord_id_empty: "Discord ID is empty!"
+user.oidc_id_empty: "OIDC ID is empty!"
+user.wechat_id_empty: "WeChat ID is empty!"
+user.telegram_id_empty: "Telegram ID is empty!"
+user.telegram_not_bound: "This Telegram account is not bound"
+user.linux_do_id_empty: "Linux DO ID is empty!"
+
+# Quota messages
+quota.negative: "Quota cannot be negative!"
+quota.exceed_max: "Quota value exceeds valid range"
+quota.insufficient: "Insufficient quota"
+quota.warning_invalid: "Invalid warning type"
+quota.threshold_gt_zero: "Warning threshold must be greater than 0"
+
+# Subscription messages
+subscription.not_enabled: "Subscription plan is not enabled"
+subscription.title_empty: "Subscription plan title cannot be empty"
+subscription.price_negative: "Price cannot be negative"
+subscription.price_max: "Price cannot exceed 9999"
+subscription.purchase_limit_negative: "Purchase limit cannot be negative"
+subscription.quota_negative: "Total quota cannot be negative"
+subscription.group_not_exists: "Upgrade group does not exist"
+subscription.reset_cycle_gt_zero: "Custom reset cycle must be greater than 0 seconds"
+subscription.purchase_max: "Purchase limit for this plan has been reached"
+subscription.invalid_id: "Invalid subscription ID"
+subscription.invalid_user_id: "Invalid user ID"
+
+# Payment messages
+payment.not_configured: "Payment information has not been configured by administrator"
+payment.method_not_exists: "Payment method does not exist"
+payment.callback_error: "Callback URL configuration error"
+payment.create_failed: "Failed to create order"
+payment.start_failed: "Failed to start payment"
+payment.amount_too_low: "Plan amount is too low"
+payment.stripe_not_configured: "Stripe is not configured or key is invalid"
+payment.webhook_not_configured: "Webhook is not configured"
+payment.price_id_not_configured: "StripePriceId is not configured for this plan"
+payment.creem_not_configured: "CreemProductId is not configured for this plan"
+
+# Topup messages
+topup.not_provided: "Payment order number not provided"
+topup.order_not_exists: "Top-up order does not exist"
+topup.order_status: "Top-up order status error"
+topup.failed: "Top-up failed, please try again later"
+topup.invalid_quota: "Invalid top-up quota"
+
+# Channel messages
+channel.not_exists: "Channel does not exist"
+channel.id_format_error: "Channel ID format error"
+channel.no_available_key: "No available channel keys"
+channel.get_list_failed: "Failed to get channel list, please try again later"
+channel.get_tags_failed: "Failed to get tags, please try again later"
+channel.get_key_failed: "Failed to get channel key"
+channel.get_ollama_failed: "Failed to get Ollama models"
+channel.query_failed: "Failed to query channel"
+channel.no_valid_upstream: "No valid upstream channel"
+channel.upstream_saturated: "Current group upstream load is saturated, please try again later"
+channel.get_available_failed: "Failed to get available channels for model {{.Model}} under group {{.Group}}"
+
+# Model messages
+model.name_empty: "Model name cannot be empty"
+model.name_exists: "Model name already exists"
+model.id_missing: "Model ID is missing"
+model.get_list_failed: "Failed to get model list, please try again later"
+model.get_failed: "Failed to get upstream models"
+model.reset_success: "Model ratio reset successful"
+
+# Vendor messages
+vendor.name_empty: "Vendor name cannot be empty"
+vendor.name_exists: "Vendor name already exists"
+vendor.id_missing: "Vendor ID is missing"
+
+# Group messages
+group.name_type_empty: "Group name and type cannot be empty"
+group.name_exists: "Group name already exists"
+group.id_missing: "Group ID is missing"
+
+# Checkin messages
+checkin.disabled: "Check-in feature is not enabled"
+checkin.already_today: "Already checked in today"
+checkin.failed: "Check-in failed, please try again later"
+checkin.quota_failed: "Check-in failed: quota update error"
+
+# Passkey messages
+passkey.create_failed: "Unable to create Passkey credential"
+passkey.login_abnormal: "Passkey login status is abnormal"
+passkey.update_failed: "Passkey credential update failed"
+passkey.invalid_user_id: "Invalid user ID"
+passkey.verify_failed: "Passkey verification failed, please try again or contact administrator"
+
+# 2FA messages
+twofa.not_enabled: "User has not enabled 2FA"
+twofa.user_id_empty: "User ID cannot be empty"
+twofa.already_exists: "User already has 2FA configured"
+twofa.record_id_empty: "2FA record ID cannot be empty"
+twofa.code_invalid: "Verification code or backup code is incorrect"
+
+# Rate limit messages
+rate_limit.reached: "You have reached the request limit: maximum {{.Max}} requests in {{.Minutes}} minutes"
+rate_limit.total_reached: "You have reached the total request limit: maximum {{.Max}} requests in {{.Minutes}} minutes, including failed attempts"
+
+# Setting messages
+setting.invalid_type: "Invalid warning type"
+setting.webhook_empty: "Webhook URL cannot be empty"
+setting.webhook_invalid: "Invalid Webhook URL"
+setting.email_invalid: "Invalid email address"
+setting.bark_url_empty: "Bark push URL cannot be empty"
+setting.bark_url_invalid: "Invalid Bark push URL"
+setting.gotify_url_empty: "Gotify server URL cannot be empty"
+setting.gotify_token_empty: "Gotify token cannot be empty"
+setting.gotify_url_invalid: "Invalid Gotify server URL"
+setting.url_must_http: "URL must start with http:// or https://"
+setting.saved: "Settings updated"
+
+# Deployment messages (io.net)
+deployment.not_enabled: "io.net model deployment is not enabled or API key is missing"
+deployment.id_required: "Deployment ID is required"
+deployment.container_id_required: "Container ID is required"
+deployment.name_empty: "Deployment name cannot be empty"
+deployment.name_taken: "Deployment name is not available, please choose a different name"
+deployment.hardware_id_required: "hardware_id parameter is required"
+deployment.hardware_invalid_id: "Invalid hardware_id parameter"
+deployment.api_key_required: "api_key is required"
+deployment.invalid_payload: "Invalid request payload"
+deployment.not_found: "Container details not found"
+
+# Performance messages
+performance.disk_cache_cleared: "Inactive disk cache has been cleared"
+performance.stats_reset: "Statistics have been reset"
+performance.gc_executed: "GC has been executed"
+
+# Ability messages
+ability.db_corrupted: "Database consistency has been compromised"
+ability.repair_running: "A repair task is already running, please try again later"
+
+# OAuth messages
+oauth.invalid_code: "Invalid authorization code"
+oauth.get_user_error: "Failed to get user information"
+oauth.account_used: "This account has been bound to another user"
+oauth.unknown_provider: "Unknown OAuth provider"
+oauth.state_invalid: "State parameter is empty or mismatched"
+oauth.not_enabled: "{{.Provider}} login and registration has not been enabled by administrator"
+oauth.user_deleted: "User has been deleted"
+oauth.user_banned: "User has been banned"
+oauth.bind_success: "Binding successful"
+oauth.already_bound: "This {{.Provider}} account has already been bound"
+oauth.connect_failed: "Unable to connect to {{.Provider}} server, please try again later"
+oauth.token_failed: "Failed to get token from {{.Provider}}, please check settings"
+oauth.user_info_empty: "{{.Provider}} returned empty user info, please check settings"
+oauth.trust_level_low: "Linux DO trust level does not meet the minimum required by administrator"
+
+# Model layer error messages
+redeem.failed: "Redemption failed, please try again later"
+user.create_default_token_error: "Failed to create default token"
+common.uuid_duplicate: "Please retry, the system generated a duplicate UUID!"
+common.invalid_input: "Invalid input"
+
+# Distributor messages
+distributor.invalid_request: "Invalid request: {{.Error}}"
+distributor.invalid_channel_id: "Invalid channel ID"
+distributor.channel_disabled: "This channel has been disabled"
+distributor.token_no_model_access: "This token has no access to any models"
+distributor.token_model_forbidden: "This token has no access to model {{.Model}}"
+distributor.model_name_required: "Model name not specified, model name cannot be empty"
+distributor.invalid_playground_request: "Invalid playground request: {{.Error}}"
+distributor.group_access_denied: "No permission to access this group"
+distributor.get_channel_failed: "Failed to get available channel for model {{.Model}} under group {{.Group}} (distributor): {{.Error}}"
+distributor.no_available_channel: "No available channel for model {{.Model}} under group {{.Group}} (distributor)"
+distributor.invalid_midjourney_request: "Invalid Midjourney request: {{.Error}}"
+distributor.invalid_request_parse_model: "Invalid request, unable to parse model"
+
+# Custom OAuth provider messages
+custom_oauth.not_found: "Custom OAuth provider not found"
+custom_oauth.slug_empty: "Slug cannot be empty"
+custom_oauth.slug_exists: "Slug already exists"
+custom_oauth.name_empty: "Provider name cannot be empty"
+custom_oauth.has_bindings: "Cannot delete provider with existing user bindings"
+custom_oauth.binding_not_found: "OAuth binding not found"
+custom_oauth.provider_id_field_invalid: "Could not extract user ID from provider response"
diff --git a/i18n/locales/zh-CN.yaml b/i18n/locales/zh-CN.yaml
new file mode 100644
index 0000000000..1f3b5a7b4b
--- /dev/null
+++ b/i18n/locales/zh-CN.yaml
@@ -0,0 +1,267 @@
+# Chinese (Simplified) translations
+# 中文(简体)翻译文件
+
+# Common messages
+common.invalid_params: "无效的参数"
+common.database_error: "数据库错误,请稍后重试"
+common.retry_later: "请稍后重试"
+common.generate_failed: "生成失败"
+common.not_found: "未找到"
+common.unauthorized: "未授权"
+common.forbidden: "无权限"
+common.invalid_id: "无效的ID"
+common.id_empty: "ID 为空!"
+common.feature_disabled: "该功能未启用"
+common.operation_success: "操作成功"
+common.operation_failed: "操作失败"
+common.update_success: "更新成功"
+common.update_failed: "更新失败"
+common.create_success: "创建成功"
+common.create_failed: "创建失败"
+common.delete_success: "删除成功"
+common.delete_failed: "删除失败"
+common.already_exists: "已存在"
+common.name_cannot_be_empty: "名称不能为空"
+common.batch_too_many: "批量请求数量过多,最多 {{.Max}} 条"
+
+# Token messages
+token.name_too_long: "令牌名称过长"
+token.quota_negative: "额度值不能为负数"
+token.quota_exceed_max: "额度值超出有效范围,最大值为 {{.Max}}"
+token.generate_failed: "生成令牌失败"
+token.get_info_failed: "获取令牌信息失败,请稍后重试"
+token.expired_cannot_enable: "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期"
+token.exhausted_cannot_enable: "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度"
+token.invalid: "无效的令牌"
+token.not_provided: "未提供令牌"
+token.expired: "该令牌已过期"
+token.exhausted: "该令牌额度已用尽 TokenStatusExhausted[sk-{{.Prefix}}***{{.Suffix}}]"
+token.status_unavailable: "该令牌状态不可用"
+token.db_error: "无效的令牌,数据库查询出错,请联系管理员"
+
+# Redemption messages
+redemption.name_length: "兑换码名称长度必须在1-20之间"
+redemption.count_positive: "兑换码个数必须大于0"
+redemption.count_max: "一次兑换码批量生成的个数不能大于 100"
+redemption.create_failed: "创建兑换码失败,请稍后重试"
+redemption.invalid: "无效的兑换码"
+redemption.used: "该兑换码已被使用"
+redemption.expired: "该兑换码已过期"
+redemption.failed: "兑换失败,请稍后重试"
+redemption.not_provided: "未提供兑换码"
+redemption.expire_time_invalid: "过期时间不能早于当前时间"
+
+# User messages
+user.password_login_disabled: "管理员关闭了密码登录"
+user.register_disabled: "管理员关闭了新用户注册"
+user.password_register_disabled: "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册"
+user.username_or_password_empty: "用户名或密码为空"
+user.username_or_password_error: "用户名或密码错误,或用户已被封禁"
+user.email_or_password_empty: "邮箱地址或密码为空!"
+user.exists: "用户名已存在,或已注销"
+user.not_exists: "用户不存在"
+user.disabled: "该用户已被禁用"
+user.session_save_failed: "无法保存会话信息,请重试"
+user.require_2fa: "请输入两步验证码"
+user.email_verification_required: "管理员开启了邮箱验证,请输入邮箱地址和验证码"
+user.verification_code_error: "验证码错误或已过期"
+user.input_invalid: "输入不合法 {{.Error}}"
+user.no_permission_same_level: "无权获取同级或更高等级用户的信息"
+user.no_permission_higher_level: "无权更新同权限等级或更高权限等级的用户信息"
+user.cannot_create_higher_level: "无法创建权限大于等于自己的用户"
+user.cannot_delete_root_user: "不能删除超级管理员账户"
+user.cannot_disable_root_user: "无法禁用超级管理员用户"
+user.cannot_demote_root_user: "无法降级超级管理员用户"
+user.already_admin: "该用户已经是管理员"
+user.already_common: "该用户已经是普通用户"
+user.admin_cannot_promote: "普通管理员用户无法提升其他用户为管理员"
+user.original_password_error: "原密码错误"
+user.invite_quota_insufficient: "邀请额度不足!"
+user.transfer_quota_minimum: "转移额度最小为{{.Min}}!"
+user.transfer_success: "划转成功"
+user.transfer_failed: "划转失败 {{.Error}}"
+user.topup_processing: "充值处理中,请稍后重试"
+user.register_failed: "用户注册失败或用户ID获取失败"
+user.default_token_failed: "生成默认令牌失败"
+user.aff_code_empty: "affCode 为空!"
+user.email_empty: "email 为空!"
+user.github_id_empty: "GitHub id 为空!"
+user.discord_id_empty: "discord id 为空!"
+user.oidc_id_empty: "oidc id 为空!"
+user.wechat_id_empty: "WeChat id 为空!"
+user.telegram_id_empty: "Telegram id 为空!"
+user.telegram_not_bound: "该 Telegram 账户未绑定"
+user.linux_do_id_empty: "Linux DO id 为空!"
+
+# Quota messages
+quota.negative: "额度不能为负数!"
+quota.exceed_max: "额度值超出有效范围"
+quota.insufficient: "额度不足"
+quota.warning_invalid: "无效的预警类型"
+quota.threshold_gt_zero: "预警阈值必须大于0"
+
+# Subscription messages
+subscription.not_enabled: "套餐未启用"
+subscription.title_empty: "套餐标题不能为空"
+subscription.price_negative: "价格不能为负数"
+subscription.price_max: "价格不能超过9999"
+subscription.purchase_limit_negative: "购买上限不能为负数"
+subscription.quota_negative: "总额度不能为负数"
+subscription.group_not_exists: "升级分组不存在"
+subscription.reset_cycle_gt_zero: "自定义重置周期需大于0秒"
+subscription.purchase_max: "已达到该套餐购买上限"
+subscription.invalid_id: "无效的订阅ID"
+subscription.invalid_user_id: "无效的用户ID"
+
+# Payment messages
+payment.not_configured: "当前管理员未配置支付信息"
+payment.method_not_exists: "支付方式不存在"
+payment.callback_error: "回调地址配置错误"
+payment.create_failed: "创建订单失败"
+payment.start_failed: "拉起支付失败"
+payment.amount_too_low: "套餐金额过低"
+payment.stripe_not_configured: "Stripe 未配置或密钥无效"
+payment.webhook_not_configured: "Webhook 未配置"
+payment.price_id_not_configured: "该套餐未配置 StripePriceId"
+payment.creem_not_configured: "该套餐未配置 CreemProductId"
+
+# Topup messages
+topup.not_provided: "未提供支付单号"
+topup.order_not_exists: "充值订单不存在"
+topup.order_status: "充值订单状态错误"
+topup.failed: "充值失败,请稍后重试"
+topup.invalid_quota: "无效的充值额度"
+
+# Channel messages
+channel.not_exists: "渠道不存在"
+channel.id_format_error: "渠道ID格式错误"
+channel.no_available_key: "没有可用的渠道密钥"
+channel.get_list_failed: "获取渠道列表失败,请稍后重试"
+channel.get_tags_failed: "获取标签失败,请稍后重试"
+channel.get_key_failed: "获取渠道密钥失败"
+channel.get_ollama_failed: "获取Ollama模型失败"
+channel.query_failed: "查询渠道失败"
+channel.no_valid_upstream: "无有效上游渠道"
+channel.upstream_saturated: "当前分组上游负载已饱和,请稍后再试"
+channel.get_available_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败"
+
+# Model messages
+model.name_empty: "模型名称不能为空"
+model.name_exists: "模型名称已存在"
+model.id_missing: "缺少模型 ID"
+model.get_list_failed: "获取模型列表失败,请稍后重试"
+model.get_failed: "获取上游模型失败"
+model.reset_success: "重置模型倍率成功"
+
+# Vendor messages
+vendor.name_empty: "供应商名称不能为空"
+vendor.name_exists: "供应商名称已存在"
+vendor.id_missing: "缺少供应商 ID"
+
+# Group messages
+group.name_type_empty: "组名称和类型不能为空"
+group.name_exists: "组名称已存在"
+group.id_missing: "缺少组 ID"
+
+# Checkin messages
+checkin.disabled: "签到功能未启用"
+checkin.already_today: "今日已签到"
+checkin.failed: "签到失败,请稍后重试"
+checkin.quota_failed: "签到失败:更新额度出错"
+
+# Passkey messages
+passkey.create_failed: "无法创建 Passkey 凭证"
+passkey.login_abnormal: "Passkey 登录状态异常"
+passkey.update_failed: "Passkey 凭证更新失败"
+passkey.invalid_user_id: "无效的用户 ID"
+passkey.verify_failed: "Passkey 验证失败,请重试或联系管理员"
+
+# 2FA messages
+twofa.not_enabled: "用户未启用2FA"
+twofa.user_id_empty: "用户ID不能为空"
+twofa.already_exists: "用户已存在2FA设置"
+twofa.record_id_empty: "2FA记录ID不能为空"
+twofa.code_invalid: "验证码或备用码不正确"
+
+# Rate limit messages
+rate_limit.reached: "您已达到请求数限制:{{.Minutes}}分钟内最多请求{{.Max}}次"
+rate_limit.total_reached: "您已达到总请求数限制:{{.Minutes}}分钟内最多请求{{.Max}}次,包括失败次数"
+
+# Setting messages
+setting.invalid_type: "无效的预警类型"
+setting.webhook_empty: "Webhook地址不能为空"
+setting.webhook_invalid: "无效的Webhook地址"
+setting.email_invalid: "无效的邮箱地址"
+setting.bark_url_empty: "Bark推送URL不能为空"
+setting.bark_url_invalid: "无效的Bark推送URL"
+setting.gotify_url_empty: "Gotify服务器地址不能为空"
+setting.gotify_token_empty: "Gotify令牌不能为空"
+setting.gotify_url_invalid: "无效的Gotify服务器地址"
+setting.url_must_http: "URL必须以http://或https://开头"
+setting.saved: "设置已更新"
+
+# Deployment messages (io.net)
+deployment.not_enabled: "io.net 模型部署功能未启用或 API 密钥缺失"
+deployment.id_required: "deployment ID 为必填项"
+deployment.container_id_required: "container ID 为必填项"
+deployment.name_empty: "deployment 名称不能为空"
+deployment.name_taken: "deployment 名称已被使用,请选择其他名称"
+deployment.hardware_id_required: "hardware_id 参数为必填项"
+deployment.hardware_invalid_id: "无效的 hardware_id 参数"
+deployment.api_key_required: "api_key 为必填项"
+deployment.invalid_payload: "无效的请求内容"
+deployment.not_found: "未找到容器详情"
+
+# Performance messages
+performance.disk_cache_cleared: "不活跃的磁盘缓存已清理"
+performance.stats_reset: "统计信息已重置"
+performance.gc_executed: "GC 已执行"
+
+# Ability messages
+ability.db_corrupted: "数据库一致性被破坏"
+ability.repair_running: "已经有一个修复任务在运行中,请稍后再试"
+
+# OAuth messages
+oauth.invalid_code: "无效的授权码"
+oauth.get_user_error: "获取用户信息失败"
+oauth.account_used: "该账户已被其他用户绑定"
+oauth.unknown_provider: "未知的 OAuth 提供商"
+oauth.state_invalid: "state 参数为空或不匹配"
+oauth.not_enabled: "管理员未开启通过 {{.Provider}} 登录以及注册"
+oauth.user_deleted: "用户已注销"
+oauth.user_banned: "用户已被封禁"
+oauth.bind_success: "绑定成功"
+oauth.already_bound: "该 {{.Provider}} 账户已被绑定"
+oauth.connect_failed: "无法连接至 {{.Provider}} 服务器,请稍后重试"
+oauth.token_failed: "{{.Provider}} 获取 Token 失败,请检查设置"
+oauth.user_info_empty: "{{.Provider}} 获取用户信息为空,请检查设置"
+oauth.trust_level_low: "Linux DO 信任等级未达到管理员设置的最低信任等级"
+
+# Model layer error messages
+redeem.failed: "兑换失败,请稍后重试"
+user.create_default_token_error: "创建默认令牌失败"
+common.uuid_duplicate: "请重试,系统生成的 UUID 竟然重复了!"
+common.invalid_input: "输入不合法"
+
+# Distributor messages
+distributor.invalid_request: "无效的请求,{{.Error}}"
+distributor.invalid_channel_id: "无效的渠道 Id"
+distributor.channel_disabled: "该渠道已被禁用"
+distributor.token_no_model_access: "该令牌无权访问任何模型"
+distributor.token_model_forbidden: "该令牌无权访问模型 {{.Model}}"
+distributor.model_name_required: "未指定模型名称,模型名称不能为空"
+distributor.invalid_playground_request: "无效的playground请求,{{.Error}}"
+distributor.group_access_denied: "无权访问该分组"
+distributor.get_channel_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败(distributor):{{.Error}}"
+distributor.no_available_channel: "分组 {{.Group}} 下模型 {{.Model}} 无可用渠道(distributor)"
+distributor.invalid_midjourney_request: "无效的midjourney请求,{{.Error}}"
+distributor.invalid_request_parse_model: "无效的请求,无法解析模型"
+
+# Custom OAuth provider messages
+custom_oauth.not_found: "自定义 OAuth 提供商不存在"
+custom_oauth.slug_empty: "标识符不能为空"
+custom_oauth.slug_exists: "标识符已存在"
+custom_oauth.name_empty: "提供商名称不能为空"
+custom_oauth.has_bindings: "无法删除已有用户绑定的提供商"
+custom_oauth.binding_not_found: "OAuth 绑定不存在"
+custom_oauth.provider_id_field_invalid: "无法从提供商响应中提取用户 ID"
diff --git a/i18n/locales/zh-TW.yaml b/i18n/locales/zh-TW.yaml
new file mode 100644
index 0000000000..1231c0e248
--- /dev/null
+++ b/i18n/locales/zh-TW.yaml
@@ -0,0 +1,267 @@
+# Chinese (Traditional) translations
+# 中文(繁體)翻譯檔案
+
+# Common messages
+common.invalid_params: "無效的參數"
+common.database_error: "資料庫錯誤,請稍後重試"
+common.retry_later: "請稍後重試"
+common.generate_failed: "生成失敗"
+common.not_found: "未找到"
+common.unauthorized: "未授權"
+common.forbidden: "無權限"
+common.invalid_id: "無效的ID"
+common.id_empty: "ID 為空!"
+common.feature_disabled: "該功能未啟用"
+common.operation_success: "操作成功"
+common.operation_failed: "操作失敗"
+common.update_success: "更新成功"
+common.update_failed: "更新失敗"
+common.create_success: "建立成功"
+common.create_failed: "建立失敗"
+common.delete_success: "刪除成功"
+common.delete_failed: "刪除失敗"
+common.already_exists: "已存在"
+common.name_cannot_be_empty: "名稱不能為空"
+common.batch_too_many: "批次請求數量過多,最多 {{.Max}} 條"
+
+# Token messages
+token.name_too_long: "令牌名稱過長"
+token.quota_negative: "額度值不能為負數"
+token.quota_exceed_max: "額度值超出有效範圍,最大值為 {{.Max}}"
+token.generate_failed: "生成令牌失敗"
+token.get_info_failed: "獲取令牌資訊失敗,請稍後重試"
+token.expired_cannot_enable: "令牌已過期,無法啟用,請先修改令牌過期時間,或者設定為永不過期"
+token.exhausted_cannot_enable: "令牌可用額度已用盡,無法啟用,請先修改令牌剩餘額度,或者設定為無限額度"
+token.invalid: "無效的令牌"
+token.not_provided: "未提供令牌"
+token.expired: "該令牌已過期"
+token.exhausted: "該令牌額度已用盡 TokenStatusExhausted[sk-{{.Prefix}}***{{.Suffix}}]"
+token.status_unavailable: "該令牌狀態不可用"
+token.db_error: "無效的令牌,資料庫查詢出錯,請聯繫管理員"
+
+# Redemption messages
+redemption.name_length: "兌換碼名稱長度必須在1-20之間"
+redemption.count_positive: "兌換碼個數必須大於0"
+redemption.count_max: "一次兌換碼批量生成的個數不能大於 100"
+redemption.create_failed: "建立兌換碼失敗,請稍後重試"
+redemption.invalid: "無效的兌換碼"
+redemption.used: "該兌換碼已被使用"
+redemption.expired: "該兌換碼已過期"
+redemption.failed: "兌換失敗,請稍後重試"
+redemption.not_provided: "未提供兌換碼"
+redemption.expire_time_invalid: "過期時間不能早於當前時間"
+
+# User messages
+user.password_login_disabled: "管理員關閉了密碼登錄"
+user.register_disabled: "管理員關閉了新使用者註冊"
+user.password_register_disabled: "管理員關閉了通過密碼進行註冊,請使用第三方帳號驗證的形式進行註冊"
+user.username_or_password_empty: "使用者名或密碼為空"
+user.username_or_password_error: "使用者名或密碼錯誤,或使用者已被封禁"
+user.email_or_password_empty: "信箱位址或密碼為空!"
+user.exists: "使用者名已存在,或已註銷"
+user.not_exists: "使用者不存在"
+user.disabled: "該使用者已被禁用"
+user.session_save_failed: "無法保存對話,請重試"
+user.require_2fa: "請輸入雙重驗證碼"
+user.email_verification_required: "管理員開啟了信箱驗證,請輸入信箱位址和驗證碼"
+user.verification_code_error: "驗證碼錯誤或已過期"
+user.input_invalid: "輸入不合法 {{.Error}}"
+user.no_permission_same_level: "無權獲取同級或更高等級使用者的資訊"
+user.no_permission_higher_level: "無權更新同權限等級或更高權限等級的使用者資訊"
+user.cannot_create_higher_level: "無法建立權限大於等於自己的使用者"
+user.cannot_delete_root_user: "不能刪除超級管理員帳號"
+user.cannot_disable_root_user: "無法禁用超級管理員使用者"
+user.cannot_demote_root_user: "無法降級超級管理員使用者"
+user.already_admin: "該使用者已經是管理員"
+user.already_common: "該使用者已經是普通使用者"
+user.admin_cannot_promote: "普通管理員使用者無法提升其他使用者為管理員"
+user.original_password_error: "原密碼錯誤"
+user.invite_quota_insufficient: "邀請額度不足!"
+user.transfer_quota_minimum: "轉移額度最小為{{.Min}}!"
+user.transfer_success: "劃轉成功"
+user.transfer_failed: "劃轉失敗 {{.Error}}"
+user.topup_processing: "充值處理中,請稍後重試"
+user.register_failed: "使用者註冊失敗或使用者ID獲取失敗"
+user.default_token_failed: "生成預設令牌失敗"
+user.aff_code_empty: "affCode 為空!"
+user.email_empty: "email 為空!"
+user.github_id_empty: "GitHub id 為空!"
+user.discord_id_empty: "discord id 為空!"
+user.oidc_id_empty: "oidc id 為空!"
+user.wechat_id_empty: "WeChat id 為空!"
+user.telegram_id_empty: "Telegram id 為空!"
+user.telegram_not_bound: "該 Telegram 帳號未綁定"
+user.linux_do_id_empty: "Linux DO id 為空!"
+
+# Quota messages
+quota.negative: "額度不能為負數!"
+quota.exceed_max: "額度值超出有效範圍"
+quota.insufficient: "額度不足"
+quota.warning_invalid: "無效的預警類型"
+quota.threshold_gt_zero: "預警閾值必須大於0"
+
+# Subscription messages
+subscription.not_enabled: "訂閱方案未啟用"
+subscription.title_empty: "訂閱方案標題不能為空"
+subscription.price_negative: "價格不能為負數"
+subscription.price_max: "價格不能超過9999"
+subscription.purchase_limit_negative: "購買上限不能為負數"
+subscription.quota_negative: "總額度不能為負數"
+subscription.group_not_exists: "升級分組不存在"
+subscription.reset_cycle_gt_zero: "自訂重置週期需大於0秒"
+subscription.purchase_max: "已達到該訂閱方案購買上限"
+subscription.invalid_id: "無效的訂閱ID"
+subscription.invalid_user_id: "無效的使用者ID"
+
+# Payment messages
+payment.not_configured: "當前管理員未設定支付資訊"
+payment.method_not_exists: "不存在此支付方式"
+payment.callback_error: "回調位址設定錯誤"
+payment.create_failed: "建立訂單失敗"
+payment.start_failed: "啟用支付失敗"
+payment.amount_too_low: "訂閱方案金額過低"
+payment.stripe_not_configured: "Stripe 未設定或密鑰無效"
+payment.webhook_not_configured: "Webhook 未設定"
+payment.price_id_not_configured: "該訂閱方案未設定 StripePriceId"
+payment.creem_not_configured: "該訂閱方案未設定 CreemProductId"
+
+# Topup messages
+topup.not_provided: "未提供支付單號"
+topup.order_not_exists: "充值訂單不存在"
+topup.order_status: "充值訂單狀態錯誤"
+topup.failed: "充值失敗,請稍後重試"
+topup.invalid_quota: "無效的充值額度"
+
+# Channel messages
+channel.not_exists: "管道不存在"
+channel.id_format_error: "管道ID格式錯誤"
+channel.no_available_key: "沒有可用的管道密鑰"
+channel.get_list_failed: "獲取管道列表失敗,請稍後重試"
+channel.get_tags_failed: "獲取標籤失敗,請稍後重試"
+channel.get_key_failed: "獲取管道密鑰失敗"
+channel.get_ollama_failed: "獲取Ollama模型失敗"
+channel.query_failed: "查詢管道失敗"
+channel.no_valid_upstream: "無有效上游管道"
+channel.upstream_saturated: "當前分組上游負載已飽和,請稍後再試"
+channel.get_available_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗"
+
+# Model messages
+model.name_empty: "模型名稱不能為空"
+model.name_exists: "模型名稱已存在"
+model.id_missing: "缺少模型 ID"
+model.get_list_failed: "獲取模型列表失敗,請稍後重試"
+model.get_failed: "獲取上游模型失敗"
+model.reset_success: "重置模型倍率成功"
+
+# Vendor messages
+vendor.name_empty: "供應商名稱不能為空"
+vendor.name_exists: "供應商名稱已存在"
+vendor.id_missing: "缺少供應商 ID"
+
+# Group messages
+group.name_type_empty: "組名稱和類型不能為空"
+group.name_exists: "組名稱已存在"
+group.id_missing: "缺少組 ID"
+
+# Checkin messages
+checkin.disabled: "簽到功能未啟用"
+checkin.already_today: "今日已簽到"
+checkin.failed: "簽到失敗,請稍後重試"
+checkin.quota_failed: "簽到失敗:更新額度出錯"
+
+# Passkey messages
+passkey.create_failed: "無法建立 Passkey 憑證"
+passkey.login_abnormal: "Passkey 登錄狀態異常"
+passkey.update_failed: "Passkey 憑證更新失敗"
+passkey.invalid_user_id: "無效的使用者 ID"
+passkey.verify_failed: "Passkey 驗證失敗,請重試或聯繫管理員"
+
+# 2FA messages
+twofa.not_enabled: "使用者未啟用2FA"
+twofa.user_id_empty: "使用者ID不能為空"
+twofa.already_exists: "使用者已存在2FA設定"
+twofa.record_id_empty: "2FA記錄ID不能為空"
+twofa.code_invalid: "驗證碼或備用碼不正確"
+
+# Rate limit messages
+rate_limit.reached: "您已達到請求數限制:{{.Minutes}}分鐘內最多請求{{.Max}}次"
+rate_limit.total_reached: "您已達到總請求數限制:{{.Minutes}}分鐘內最多請求{{.Max}}次,包括失敗次數"
+
+# Setting messages
+setting.invalid_type: "無效的預警類型"
+setting.webhook_empty: "Webhook位址不能為空"
+setting.webhook_invalid: "無效的Webhook位址"
+setting.email_invalid: "無效的信箱位址"
+setting.bark_url_empty: "Bark推送URL不能為空"
+setting.bark_url_invalid: "無效的Bark推送URL"
+setting.gotify_url_empty: "Gotify伺服器位址不能為空"
+setting.gotify_token_empty: "Gotify令牌不能為空"
+setting.gotify_url_invalid: "無效的Gotify伺服器位址"
+setting.url_must_http: "URL必須以http://或https://開頭"
+setting.saved: "設定已更新"
+
+# Deployment messages (io.net)
+deployment.not_enabled: "io.net 模型部署功能未啟用或 API 密鑰缺失"
+deployment.id_required: "deployment ID 為必填項"
+deployment.container_id_required: "container ID 為必填項"
+deployment.name_empty: "deployment 名稱不能為空"
+deployment.name_taken: "deployment 名稱已被使用,請選擇其他名稱"
+deployment.hardware_id_required: "hardware_id 參數為必填項"
+deployment.hardware_invalid_id: "無效的 hardware_id 參數"
+deployment.api_key_required: "api_key 為必填項"
+deployment.invalid_payload: "無效的請求內容"
+deployment.not_found: "未找到容器詳情"
+
+# Performance messages
+performance.disk_cache_cleared: "不活躍的磁碟快取已清理"
+performance.stats_reset: "統計資訊已重置"
+performance.gc_executed: "GC 已執行"
+
+# Ability messages
+ability.db_corrupted: "資料庫一致性被破壞"
+ability.repair_running: "已經有一個修復任務在運行中,請稍後再試"
+
+# OAuth messages
+oauth.invalid_code: "無效的授權碼"
+oauth.get_user_error: "獲取使用者資訊失敗"
+oauth.account_used: "該帳號已被其他使用者綁定"
+oauth.unknown_provider: "未知的 OAuth 供應者"
+oauth.state_invalid: "state 參數為空或不匹配"
+oauth.not_enabled: "管理員未開啟通過 {{.Provider}} 登錄以及註冊"
+oauth.user_deleted: "使用者已註銷"
+oauth.user_banned: "使用者已被封禁"
+oauth.bind_success: "綁定成功"
+oauth.already_bound: "該 {{.Provider}} 帳號已被綁定"
+oauth.connect_failed: "無法連接至 {{.Provider}} 伺服器,請稍後重試"
+oauth.token_failed: "{{.Provider}} 獲取 Token 失敗,請檢查設定"
+oauth.user_info_empty: "{{.Provider}} 獲取使用者資訊為空,請檢查設定"
+oauth.trust_level_low: "Linux DO 信任等級未達到管理員設定的最低信任等級"
+
+# Model layer error messages
+redeem.failed: "兌換失敗,請稍後重試"
+user.create_default_token_error: "建立預設令牌失敗"
+common.uuid_duplicate: "請重試,系統生成的 UUID 竟然重複了!"
+common.invalid_input: "輸入不合法"
+
+# Distributor messages
+distributor.invalid_request: "無效的請求,{{.Error}}"
+distributor.invalid_channel_id: "無效的管道 Id"
+distributor.channel_disabled: "該管道已被禁用"
+distributor.token_no_model_access: "該令牌無權存取任何模型"
+distributor.token_model_forbidden: "該令牌無權存取模型 {{.Model}}"
+distributor.model_name_required: "未指定模型名稱,模型名稱不能為空"
+distributor.invalid_playground_request: "無效的playground請求,{{.Error}}"
+distributor.group_access_denied: "無權存取該分組"
+distributor.get_channel_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗(distributor):{{.Error}}"
+distributor.no_available_channel: "分組 {{.Group}} 下模型 {{.Model}} 無可用管道(distributor)"
+distributor.invalid_midjourney_request: "無效的midjourney請求,{{.Error}}"
+distributor.invalid_request_parse_model: "無效的請求,無法解析模型"
+
+# Custom OAuth provider messages
+custom_oauth.not_found: "自訂 OAuth 供應者不存在"
+custom_oauth.slug_empty: "標識符不能為空"
+custom_oauth.slug_exists: "標識符已存在"
+custom_oauth.name_empty: "供應者名稱不能為空"
+custom_oauth.has_bindings: "無法刪除已有使用者綁定的供應者"
+custom_oauth.binding_not_found: "OAuth 綁定不存在"
+custom_oauth.provider_id_field_invalid: "無法從供應者響應中提取使用者 ID"
diff --git a/logger/logger.go b/logger/logger.go
index 61b1d49d8e..7b0c82de50 100644
--- a/logger/logger.go
+++ b/logger/logger.go
@@ -2,7 +2,6 @@ package logger
import (
"context"
- "encoding/json"
"fmt"
"io"
"log"
@@ -30,6 +29,15 @@ const maxLogCount = 1000000
var logCount int
var setupLogLock sync.Mutex
var setupLogWorking bool
+var currentLogPath string
+var currentLogPathMu sync.RWMutex
+var currentLogFile *os.File
+
+func GetCurrentLogPath() string {
+ currentLogPathMu.RLock()
+ defer currentLogPathMu.RUnlock()
+ return currentLogPath
+}
func SetupLogger() {
defer func() {
@@ -49,8 +57,19 @@ func SetupLogger() {
if err != nil {
log.Fatal("failed to open log file")
}
+ currentLogPathMu.Lock()
+ oldFile := currentLogFile
+ currentLogPath = logPath
+ currentLogFile = fd
+ currentLogPathMu.Unlock()
+
+ common.LogWriterMu.Lock()
gin.DefaultWriter = io.MultiWriter(os.Stdout, fd)
gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, fd)
+ if oldFile != nil {
+ _ = oldFile.Close()
+ }
+ common.LogWriterMu.Unlock()
}
}
@@ -76,16 +95,18 @@ func LogDebug(ctx context.Context, msg string, args ...any) {
}
func logHelper(ctx context.Context, level string, msg string) {
- writer := gin.DefaultErrorWriter
- if level == loggerINFO {
- writer = gin.DefaultWriter
- }
id := ctx.Value(common.RequestIdKey)
if id == nil {
id = "SYSTEM"
}
now := time.Now()
+ common.LogWriterMu.RLock()
+ writer := gin.DefaultErrorWriter
+ if level == loggerINFO {
+ writer = gin.DefaultWriter
+ }
_, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
+ common.LogWriterMu.RUnlock()
logCount++ // we don't need accurate count, so no lock here
if logCount > maxLogCount && !setupLogWorking {
logCount = 0
@@ -151,7 +172,7 @@ func FormatQuota(quota int) string {
// LogJson 仅供测试使用 only for test
func LogJson(ctx context.Context, msg string, obj any) {
- jsonStr, err := json.Marshal(obj)
+ jsonStr, err := common.Marshal(obj)
if err != nil {
LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error()))
return
diff --git a/main.go b/main.go
index 1326b12275..dbbf44a182 100644
--- a/main.go
+++ b/main.go
@@ -14,11 +14,15 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/controller"
+ "github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/oauth"
+ "github.com/QuantumNous/new-api/relay"
"github.com/QuantumNous/new-api/router"
"github.com/QuantumNous/new-api/service"
+ _ "github.com/QuantumNous/new-api/setting/performance_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/bytedance/gopkg/util/gopool"
@@ -105,6 +109,21 @@ func main() {
// Codex credential auto-refresh check every 10 minutes, refresh when expires within 1 day
service.StartCodexCredentialAutoRefreshTask()
+ // Subscription quota reset task (daily/weekly/monthly/custom)
+ service.StartSubscriptionQuotaResetTask()
+
+ // Wire task polling adaptor factory (breaks service -> relay import cycle)
+ service.GetTaskAdaptorFunc = func(platform constant.TaskPlatform) service.TaskPollingAdaptor {
+ a := relay.GetTaskAdaptor(platform)
+ if a == nil {
+ return nil
+ }
+ return a
+ }
+
+ // Channel upstream model update check task
+ controller.StartChannelUpstreamModelUpdateTask()
+
if common.IsMasterNode && constant.UpdateTask {
gopool.Go(func() {
controller.UpdateMidjourneyTaskBulk()
@@ -146,6 +165,8 @@ func main() {
// This will cause SSE not to work!!!
//server.Use(gzip.Gzip(gzip.DefaultCompression))
server.Use(middleware.RequestId())
+ server.Use(middleware.PoweredBy())
+ server.Use(middleware.I18n())
middleware.SetUpLogger(server)
// Initialize session store
store := cookie.NewStore([]byte(common.SessionSecret))
@@ -252,6 +273,9 @@ func InitResources() error {
// Initialize options, should after model.InitDB()
model.InitOptionMap()
+ // 清理旧的磁盘缓存文件
+ common.CleanupOldCacheFiles()
+
// 初始化模型
model.GetPricing()
@@ -266,5 +290,27 @@ func InitResources() error {
if err != nil {
return err
}
+
+ // 启动系统监控
+ common.StartSystemMonitor()
+
+ // Initialize i18n
+ err = i18n.Init()
+ if err != nil {
+ common.SysError("failed to initialize i18n: " + err.Error())
+ // Don't return error, i18n is not critical
+ } else {
+ common.SysLog("i18n initialized with languages: " + strings.Join(i18n.SupportedLanguages(), ", "))
+ }
+ // Register user language loader for lazy loading
+ i18n.SetUserLangLoader(model.GetUserLanguage)
+
+ // Load custom OAuth providers from database
+ err = oauth.LoadCustomProviders()
+ if err != nil {
+ common.SysError("failed to load custom OAuth providers: " + err.Error())
+ // Don't return error, custom OAuth is not critical
+ }
+
return nil
}
diff --git a/middleware/auth.go b/middleware/auth.go
index a5d283d26d..342e7f4981 100644
--- a/middleware/auth.go
+++ b/middleware/auth.go
@@ -125,6 +125,8 @@ func authHelper(c *gin.Context, minRole int) {
c.Abort()
return
}
+ // 防止不同newapi版本冲突,导致数据不通用
+ c.Header("Auth-Version", "864b7076dbcd0a3c01b5520316720ebf")
c.Set("username", username)
c.Set("role", role)
c.Set("id", id)
@@ -132,17 +134,6 @@ func authHelper(c *gin.Context, minRole int) {
c.Set("user_group", session.Get("group"))
c.Set("use_access_token", useAccessToken)
- //userCache, err := model.GetUserCache(id.(int))
- //if err != nil {
- // c.JSON(http.StatusOK, gin.H{
- // "success": false,
- // "message": err.Error(),
- // })
- // c.Abort()
- // return
- //}
- //userCache.WriteContext(c)
-
c.Next()
}
@@ -179,6 +170,81 @@ func WssAuth(c *gin.Context) {
}
+// TokenOrUserAuth allows either session-based user auth or API token auth.
+// Used for endpoints that need to be accessible from both the dashboard and API clients.
+func TokenOrUserAuth() func(c *gin.Context) {
+ return func(c *gin.Context) {
+ // Try session auth first (dashboard users)
+ session := sessions.Default(c)
+ if id := session.Get("id"); id != nil {
+ if status, ok := session.Get("status").(int); ok && status == common.UserStatusEnabled {
+ c.Set("id", id)
+ c.Next()
+ return
+ }
+ }
+ // Fall back to token auth (API clients)
+ TokenAuth()(c)
+ }
+}
+
+// TokenAuthReadOnly 宽松版本的令牌认证中间件,用于只读查询接口。
+// 只验证令牌 key 是否存在,不检查令牌状态、过期时间和额度。
+// 即使令牌已过期、已耗尽或已禁用,也允许访问。
+// 仍然检查用户是否被封禁。
+func TokenAuthReadOnly() func(c *gin.Context) {
+ return func(c *gin.Context) {
+ key := c.Request.Header.Get("Authorization")
+ if key == "" {
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "message": "未提供 Authorization 请求头",
+ })
+ c.Abort()
+ return
+ }
+ if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
+ key = strings.TrimSpace(key[7:])
+ }
+ key = strings.TrimPrefix(key, "sk-")
+ parts := strings.Split(key, "-")
+ key = parts[0]
+
+ token, err := model.GetTokenByKey(key, false)
+ if err != nil {
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "message": "无效的令牌",
+ })
+ c.Abort()
+ return
+ }
+
+ userCache, err := model.GetUserCache(token.UserId)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "message": err.Error(),
+ })
+ c.Abort()
+ return
+ }
+ if userCache.Status != common.UserStatusEnabled {
+ c.JSON(http.StatusForbidden, gin.H{
+ "success": false,
+ "message": "用户已被封禁",
+ })
+ c.Abort()
+ return
+ }
+
+ c.Set("id", token.UserId)
+ c.Set("token_id", token.Id)
+ c.Set("token_key", token.Key)
+ c.Next()
+ }
+}
+
func TokenAuth() func(c *gin.Context) {
return func(c *gin.Context) {
// 先检测是否为ws
@@ -327,6 +393,7 @@ func SetupContextForToken(c *gin.Context, token *model.Token, parts ...string) e
if model.IsAdmin(token.UserId) {
c.Set("specific_channel_id", parts[1])
} else {
+ c.Header("specific_channel_version", "701e3ae1dc3f7975556d354e0675168d004891c8")
abortWithOpenAiMessage(c, http.StatusForbidden, "普通用户不支持指定渠道")
return fmt.Errorf("普通用户不支持指定渠道")
}
diff --git a/middleware/body_cleanup.go b/middleware/body_cleanup.go
new file mode 100644
index 0000000000..f7b7ab51a0
--- /dev/null
+++ b/middleware/body_cleanup.go
@@ -0,0 +1,22 @@
+package middleware
+
+import (
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/gin-gonic/gin"
+)
+
+// BodyStorageCleanup 请求体存储清理中间件
+// 在请求处理完成后自动清理磁盘/内存缓存
+func BodyStorageCleanup() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ // 处理请求
+ c.Next()
+
+ // 请求结束后清理存储
+ common.CleanupBodyStorage(c)
+
+ // 清理文件缓存(URL 下载的文件等)
+ service.CleanupFileSources(c)
+ }
+}
diff --git a/middleware/cache.go b/middleware/cache.go
index 979734ab2f..1a9dff877d 100644
--- a/middleware/cache.go
+++ b/middleware/cache.go
@@ -11,6 +11,7 @@ func Cache() func(c *gin.Context) {
} else {
c.Header("Cache-Control", "max-age=604800") // one week
}
+ c.Header("Cache-Version", "b688f2fb5be447c25e5aa3bd063087a83db32a288bf6a4f35f2d8db310e40b14")
c.Next()
}
}
diff --git a/middleware/cors.go b/middleware/cors.go
index d2a109abec..6aaa15d739 100644
--- a/middleware/cors.go
+++ b/middleware/cors.go
@@ -1,6 +1,7 @@
package middleware
import (
+ "github.com/QuantumNous/new-api/common"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
@@ -13,3 +14,10 @@ func CORS() gin.HandlerFunc {
config.AllowHeaders = []string{"*"}
return cors.New(config)
}
+
+func PoweredBy() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ c.Header("X-New-Api-Version", common.Version)
+ c.Next()
+ }
+}
diff --git a/middleware/distributor.go b/middleware/distributor.go
index 95fa64a306..d626941456 100644
--- a/middleware/distributor.go
+++ b/middleware/distributor.go
@@ -12,6 +12,7 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/service"
@@ -32,22 +33,22 @@ func Distribute() func(c *gin.Context) {
channelId, ok := common.GetContextKey(c, constant.ContextKeyTokenSpecificChannelId)
modelRequest, shouldSelectChannel, err := getModelRequest(c)
if err != nil {
- abortWithOpenAiMessage(c, http.StatusBadRequest, "Invalid request, "+err.Error())
+ abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
return
}
if ok {
id, err := strconv.Atoi(channelId.(string))
if err != nil {
- abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
+ abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidChannelId))
return
}
channel, err = model.GetChannelById(id, true)
if err != nil {
- abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
+ abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidChannelId))
return
}
if channel.Status != common.ChannelStatusEnabled {
- abortWithOpenAiMessage(c, http.StatusForbidden, "该渠道已被禁用")
+ abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorChannelDisabled))
return
}
} else {
@@ -58,7 +59,7 @@ func Distribute() func(c *gin.Context) {
s, ok := common.GetContextKey(c, constant.ContextKeyTokenModelLimit)
if !ok {
// token model limit is empty, all models are not allowed
- abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问任何模型")
+ abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorTokenNoModelAccess))
return
}
var tokenModelLimit map[string]bool
@@ -68,14 +69,14 @@ func Distribute() func(c *gin.Context) {
}
matchName := ratio_setting.FormatMatchingModelName(modelRequest.Model) // match gpts & thinking-*
if _, ok := tokenModelLimit[matchName]; !ok {
- abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问模型 "+modelRequest.Model)
+ abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorTokenModelForbidden, map[string]any{"Model": modelRequest.Model}))
return
}
}
if shouldSelectChannel {
if modelRequest.Model == "" {
- abortWithOpenAiMessage(c, http.StatusBadRequest, "未指定模型名称,模型名称不能为空")
+ abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorModelNameRequired))
return
}
var selectGroup string
@@ -85,47 +86,81 @@ func Distribute() func(c *gin.Context) {
playgroundRequest := &dto.PlayGroundRequest{}
err = common.UnmarshalBodyReusable(c, playgroundRequest)
if err != nil {
- abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的playground请求, "+err.Error())
+ abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidPlayground, map[string]any{"Error": err.Error()}))
return
}
if playgroundRequest.Group != "" {
if !service.GroupInUserUsableGroups(usingGroup, playgroundRequest.Group) && playgroundRequest.Group != usingGroup {
- abortWithOpenAiMessage(c, http.StatusForbidden, "无权访问该分组")
+ abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorGroupAccessDenied))
return
}
usingGroup = playgroundRequest.Group
common.SetContextKey(c, constant.ContextKeyUsingGroup, usingGroup)
}
}
- channel, selectGroup, err = service.CacheGetRandomSatisfiedChannel(&service.RetryParam{
- Ctx: c,
- ModelName: modelRequest.Model,
- TokenGroup: usingGroup,
- Retry: common.GetPointer(0),
- })
- if err != nil {
- showGroup := usingGroup
- if usingGroup == "auto" {
- showGroup = fmt.Sprintf("auto(%s)", selectGroup)
+
+ if preferredChannelID, found := service.GetPreferredChannelByAffinity(c, modelRequest.Model, usingGroup); found {
+ preferred, err := model.CacheGetChannel(preferredChannelID)
+ if err == nil && preferred != nil {
+ if preferred.Status != common.ChannelStatusEnabled {
+ if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
+ abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorChannelDisabled))
+ return
+ }
+ } else if usingGroup == "auto" {
+ userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
+ autoGroups := service.GetUserAutoGroup(userGroup)
+ for _, g := range autoGroups {
+ if model.IsChannelEnabledForGroupModel(g, modelRequest.Model, preferred.Id) {
+ selectGroup = g
+ common.SetContextKey(c, constant.ContextKeyAutoGroup, g)
+ channel = preferred
+ service.MarkChannelAffinityUsed(c, g, preferred.Id)
+ break
+ }
+ }
+ } else if model.IsChannelEnabledForGroupModel(usingGroup, modelRequest.Model, preferred.Id) {
+ channel = preferred
+ selectGroup = usingGroup
+ service.MarkChannelAffinityUsed(c, usingGroup, preferred.Id)
+ }
}
- message := fmt.Sprintf("获取分组 %s 下模型 %s 的可用渠道失败(distributor): %s", showGroup, modelRequest.Model, err.Error())
- // 如果错误,但是渠道不为空,说明是数据库一致性问题
- //if channel != nil {
- // common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
- // message = "数据库一致性已被破坏,请联系管理员"
- //}
- abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message, types.ErrorCodeModelNotFound)
- return
}
+
if channel == nil {
- abortWithOpenAiMessage(c, http.StatusServiceUnavailable, fmt.Sprintf("分组 %s 下模型 %s 无可用渠道(distributor)", usingGroup, modelRequest.Model), types.ErrorCodeModelNotFound)
- return
+ channel, selectGroup, err = service.CacheGetRandomSatisfiedChannel(&service.RetryParam{
+ Ctx: c,
+ ModelName: modelRequest.Model,
+ TokenGroup: usingGroup,
+ Retry: common.GetPointer(0),
+ })
+ if err != nil {
+ showGroup := usingGroup
+ if usingGroup == "auto" {
+ showGroup = fmt.Sprintf("auto(%s)", selectGroup)
+ }
+ message := i18n.T(c, i18n.MsgDistributorGetChannelFailed, map[string]any{"Group": showGroup, "Model": modelRequest.Model, "Error": err.Error()})
+ // 如果错误,但是渠道不为空,说明是数据库一致性问题
+ //if channel != nil {
+ // common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
+ // message = "数据库一致性已被破坏,请联系管理员"
+ //}
+ abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message, types.ErrorCodeModelNotFound)
+ return
+ }
+ if channel == nil {
+ abortWithOpenAiMessage(c, http.StatusServiceUnavailable, i18n.T(c, i18n.MsgDistributorNoAvailableChannel, map[string]any{"Group": usingGroup, "Model": modelRequest.Model}), types.ErrorCodeModelNotFound)
+ return
+ }
}
}
}
common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
SetupContextForSelectedChannel(c, channel, modelRequest.Model)
c.Next()
+ if channel != nil && c.Writer != nil && c.Writer.Status() < http.StatusBadRequest {
+ service.RecordChannelAffinity(c, channel.Id)
+ }
}
}
@@ -138,7 +173,7 @@ func getModelFromRequest(c *gin.Context) (*ModelRequest, error) {
var modelRequest ModelRequest
err := common.UnmarshalBodyReusable(c, &modelRequest)
if err != nil {
- return nil, errors.New("无效的请求, " + err.Error())
+ return nil, errors.New(i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
}
return &modelRequest, nil
}
@@ -158,7 +193,7 @@ func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
midjourneyRequest := dto.MidjourneyRequest{}
err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
if err != nil {
- return nil, false, errors.New("无效的midjourney请求, " + err.Error())
+ return nil, false, errors.New(i18n.T(c, i18n.MsgDistributorInvalidMidjourney, map[string]any{"Error": err.Error()}))
}
midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
if mjErr != nil {
@@ -166,7 +201,7 @@ func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
}
if midjourneyModel == "" {
if !success {
- return nil, false, fmt.Errorf("无效的请求, 无法解析模型")
+ return nil, false, fmt.Errorf("%s", i18n.T(c, i18n.MsgDistributorInvalidParseModel))
} else {
// task fetch, task fetch by condition, notify
shouldSelectChannel = false
@@ -300,6 +335,10 @@ func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
modelRequest.Group = req.Group
common.SetContextKey(c, constant.ContextKeyTokenGroup, modelRequest.Group)
}
+
+ if strings.HasPrefix(c.Request.URL.Path, "/v1/responses/compact") && modelRequest.Model != "" {
+ modelRequest.Model = ratio_setting.WithCompactModelSuffix(modelRequest.Model)
+ }
return &modelRequest, shouldSelectChannel, nil
}
@@ -314,8 +353,13 @@ func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, mode
common.SetContextKey(c, constant.ContextKeyChannelCreateTime, channel.CreatedTime)
common.SetContextKey(c, constant.ContextKeyChannelSetting, channel.GetSetting())
common.SetContextKey(c, constant.ContextKeyChannelOtherSetting, channel.GetOtherSettings())
- common.SetContextKey(c, constant.ContextKeyChannelParamOverride, channel.GetParamOverride())
- common.SetContextKey(c, constant.ContextKeyChannelHeaderOverride, channel.GetHeaderOverride())
+ paramOverride := channel.GetParamOverride()
+ headerOverride := channel.GetHeaderOverride()
+ if mergedParam, applied := service.ApplyChannelAffinityOverrideTemplate(c, paramOverride); applied {
+ paramOverride = mergedParam
+ }
+ common.SetContextKey(c, constant.ContextKeyChannelParamOverride, paramOverride)
+ common.SetContextKey(c, constant.ContextKeyChannelHeaderOverride, headerOverride)
if nil != channel.OpenAIOrganization && *channel.OpenAIOrganization != "" {
common.SetContextKey(c, constant.ContextKeyChannelOrganization, *channel.OpenAIOrganization)
}
diff --git a/middleware/i18n.go b/middleware/i18n.go
new file mode 100644
index 0000000000..279a738a3e
--- /dev/null
+++ b/middleware/i18n.go
@@ -0,0 +1,50 @@
+package middleware
+
+import (
+ "github.com/gin-gonic/gin"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/i18n"
+)
+
+// I18n middleware detects and sets the language preference for the request
+func I18n() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ lang := detectLanguage(c)
+ c.Set(string(constant.ContextKeyLanguage), lang)
+ c.Next()
+ }
+}
+
+// detectLanguage determines the language preference for the request
+// Priority: 1. User setting (if logged in) -> 2. Accept-Language header -> 3. Default language
+func detectLanguage(c *gin.Context) string {
+ // 1. Try to get language from user setting (set by auth middleware)
+ if userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting); ok {
+ if userSetting.Language != "" && i18n.IsSupported(userSetting.Language) {
+ return userSetting.Language
+ }
+ }
+
+ // 2. Parse Accept-Language header
+ acceptLang := c.GetHeader("Accept-Language")
+ if acceptLang != "" {
+ lang := i18n.ParseAcceptLanguage(acceptLang)
+ if i18n.IsSupported(lang) {
+ return lang
+ }
+ }
+
+ // 3. Return default language
+ return i18n.DefaultLang
+}
+
+// GetLanguage returns the current language from gin context
+func GetLanguage(c *gin.Context) string {
+ if lang := c.GetString(string(constant.ContextKeyLanguage)); lang != "" {
+ return lang
+ }
+ return i18n.DefaultLang
+}
diff --git a/middleware/logger.go b/middleware/logger.go
index b4ed8c89d7..151008d9f2 100644
--- a/middleware/logger.go
+++ b/middleware/logger.go
@@ -7,14 +7,28 @@ import (
"github.com/gin-gonic/gin"
)
+const RouteTagKey = "route_tag"
+
+func RouteTag(tag string) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ c.Set(RouteTagKey, tag)
+ c.Next()
+ }
+}
+
func SetUpLogger(server *gin.Engine) {
server.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
var requestID string
if param.Keys != nil {
- requestID = param.Keys[common.RequestIdKey].(string)
+ requestID, _ = param.Keys[common.RequestIdKey].(string)
}
- return fmt.Sprintf("[GIN] %s | %s | %3d | %13v | %15s | %7s %s\n",
+ tag, _ := param.Keys[RouteTagKey].(string)
+ if tag == "" {
+ tag = "web"
+ }
+ return fmt.Sprintf("[GIN] %s | %s | %s | %3d | %13v | %15s | %7s %s\n",
param.TimeStamp.Format("2006/01/02 - 15:04:05"),
+ tag,
requestID,
param.StatusCode,
param.Latency,
diff --git a/middleware/performance.go b/middleware/performance.go
new file mode 100644
index 0000000000..8668bb9546
--- /dev/null
+++ b/middleware/performance.go
@@ -0,0 +1,71 @@
+package middleware
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/gin-gonic/gin"
+)
+
+// SystemPerformanceCheck 检查系统性能中间件
+func SystemPerformanceCheck() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ // 仅检查 Relay 接口 (/v1, /v1beta 等)
+ // 这里简单判断路径前缀,可以根据实际路由调整
+ path := c.Request.URL.Path
+ if strings.HasPrefix(path, "/v1/messages") {
+ if err := checkSystemPerformance(); err != nil {
+ c.JSON(err.StatusCode, gin.H{
+ "error": err.ToClaudeError(),
+ })
+ c.Abort()
+ return
+ }
+ } else {
+ if err := checkSystemPerformance(); err != nil {
+ c.JSON(err.StatusCode, gin.H{
+ "error": err.ToOpenAIError(),
+ })
+ c.Abort()
+ return
+ }
+ }
+ c.Next()
+ }
+}
+
+// checkSystemPerformance 检查系统性能是否超过阈值
+func checkSystemPerformance() *types.NewAPIError {
+ config := common.GetPerformanceMonitorConfig()
+ if !config.Enabled {
+ return nil
+ }
+
+ status := common.GetSystemStatus()
+
+ // 检查 CPU
+ if config.CPUThreshold > 0 && int(status.CPUUsage) > config.CPUThreshold {
+ return types.NewErrorWithStatusCode(
+ fmt.Errorf("system cpu overloaded (current: %.1f%%, threshold: %d%%)", status.CPUUsage, config.CPUThreshold),
+ "system_cpu_overloaded", http.StatusServiceUnavailable)
+ }
+
+ // 检查内存
+ if config.MemoryThreshold > 0 && int(status.MemoryUsage) > config.MemoryThreshold {
+ return types.NewErrorWithStatusCode(
+ fmt.Errorf("system memory overloaded (current: %.1f%%, threshold: %d%%)", status.MemoryUsage, config.MemoryThreshold),
+ "system_memory_overloaded", http.StatusServiceUnavailable)
+ }
+
+ // 检查磁盘
+ if config.DiskThreshold > 0 && int(status.DiskUsage) > config.DiskThreshold {
+ return types.NewErrorWithStatusCode(
+ fmt.Errorf("system disk overloaded (current: %.1f%%, threshold: %d%%)", status.DiskUsage, config.DiskThreshold),
+ "system_disk_overloaded", http.StatusServiceUnavailable)
+ }
+
+ return nil
+}
diff --git a/middleware/rate-limit.go b/middleware/rate-limit.go
index 866542e17e..d8dd15d9c5 100644
--- a/middleware/rate-limit.go
+++ b/middleware/rate-limit.go
@@ -115,3 +115,91 @@ func DownloadRateLimit() func(c *gin.Context) {
func UploadRateLimit() func(c *gin.Context) {
return rateLimitFactory(common.UploadRateLimitNum, common.UploadRateLimitDuration, "UP")
}
+
+// userRateLimitFactory creates a rate limiter keyed by authenticated user ID
+// instead of client IP, making it resistant to proxy rotation attacks.
+// Must be used AFTER authentication middleware (UserAuth).
+func userRateLimitFactory(maxRequestNum int, duration int64, mark string) func(c *gin.Context) {
+ if common.RedisEnabled {
+ return func(c *gin.Context) {
+ userId := c.GetInt("id")
+ if userId == 0 {
+ c.Status(http.StatusUnauthorized)
+ c.Abort()
+ return
+ }
+ key := fmt.Sprintf("rateLimit:%s:user:%d", mark, userId)
+ userRedisRateLimiter(c, maxRequestNum, duration, key)
+ }
+ }
+ // It's safe to call multi times.
+ inMemoryRateLimiter.Init(common.RateLimitKeyExpirationDuration)
+ return func(c *gin.Context) {
+ userId := c.GetInt("id")
+ if userId == 0 {
+ c.Status(http.StatusUnauthorized)
+ c.Abort()
+ return
+ }
+ key := fmt.Sprintf("%s:user:%d", mark, userId)
+ if !inMemoryRateLimiter.Request(key, maxRequestNum, duration) {
+ c.Status(http.StatusTooManyRequests)
+ c.Abort()
+ return
+ }
+ }
+}
+
+// userRedisRateLimiter is like redisRateLimiter but accepts a pre-built key
+// (to support user-ID-based keys).
+func userRedisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, key string) {
+ ctx := context.Background()
+ rdb := common.RDB
+ listLength, err := rdb.LLen(ctx, key).Result()
+ if err != nil {
+ fmt.Println(err.Error())
+ c.Status(http.StatusInternalServerError)
+ c.Abort()
+ return
+ }
+ if listLength < int64(maxRequestNum) {
+ rdb.LPush(ctx, key, time.Now().Format(timeFormat))
+ rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
+ } else {
+ oldTimeStr, _ := rdb.LIndex(ctx, key, -1).Result()
+ oldTime, err := time.Parse(timeFormat, oldTimeStr)
+ if err != nil {
+ fmt.Println(err)
+ c.Status(http.StatusInternalServerError)
+ c.Abort()
+ return
+ }
+ nowTimeStr := time.Now().Format(timeFormat)
+ nowTime, err := time.Parse(timeFormat, nowTimeStr)
+ if err != nil {
+ fmt.Println(err)
+ c.Status(http.StatusInternalServerError)
+ c.Abort()
+ return
+ }
+ if int64(nowTime.Sub(oldTime).Seconds()) < duration {
+ rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
+ c.Status(http.StatusTooManyRequests)
+ c.Abort()
+ return
+ } else {
+ rdb.LPush(ctx, key, time.Now().Format(timeFormat))
+ rdb.LTrim(ctx, key, 0, int64(maxRequestNum-1))
+ rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration)
+ }
+ }
+}
+
+// SearchRateLimit returns a per-user rate limiter for search endpoints.
+// Configurable via SEARCH_RATE_LIMIT_ENABLE / SEARCH_RATE_LIMIT / SEARCH_RATE_LIMIT_DURATION.
+func SearchRateLimit() func(c *gin.Context) {
+ if !common.SearchRateLimitEnable {
+ return defNext
+ }
+ return userRateLimitFactory(common.SearchRateLimitNum, common.SearchRateLimitDuration, "SR")
+}
diff --git a/middleware/request-id.go b/middleware/request-id.go
index 2b3e5ddc1b..241c2a867f 100644
--- a/middleware/request-id.go
+++ b/middleware/request-id.go
@@ -2,14 +2,25 @@ package middleware
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
+ "runtime/debug"
"github.com/QuantumNous/new-api/common"
"github.com/gin-gonic/gin"
)
+var _bp = func() string {
+ if bi, ok := debug.ReadBuildInfo(); ok && bi.Main.Path != "" {
+ h := sha256.Sum256([]byte(bi.Main.Path))
+ return hex.EncodeToString(h[:4])
+ }
+ return common.GetRandomString(8)
+}()
+
func RequestId() func(c *gin.Context) {
return func(c *gin.Context) {
- id := common.GetTimeString() + common.GetRandomString(8)
+ id := common.GetTimeString() + _bp + common.GetRandomString(8)
c.Set(common.RequestIdKey, id)
ctx := context.WithValue(c.Request.Context(), common.RequestIdKey, id)
c.Request = c.Request.WithContext(ctx)
diff --git a/model/channel_satisfy.go b/model/channel_satisfy.go
new file mode 100644
index 0000000000..681f1e69bb
--- /dev/null
+++ b/model/channel_satisfy.go
@@ -0,0 +1,71 @@
+package model
+
+import (
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
+)
+
+func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool {
+ if group == "" || modelName == "" || channelID <= 0 {
+ return false
+ }
+ if !common.MemoryCacheEnabled {
+ return isChannelEnabledForGroupModelDB(group, modelName, channelID)
+ }
+
+ channelSyncLock.RLock()
+ defer channelSyncLock.RUnlock()
+
+ if group2model2channels == nil {
+ return false
+ }
+
+ if isChannelIDInList(group2model2channels[group][modelName], channelID) {
+ return true
+ }
+ normalized := ratio_setting.FormatMatchingModelName(modelName)
+ if normalized != "" && normalized != modelName {
+ return isChannelIDInList(group2model2channels[group][normalized], channelID)
+ }
+ return false
+}
+
+func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool {
+ if len(groups) == 0 {
+ return false
+ }
+ for _, g := range groups {
+ if IsChannelEnabledForGroupModel(g, modelName, channelID) {
+ return true
+ }
+ }
+ return false
+}
+
+func isChannelEnabledForGroupModelDB(group string, modelName string, channelID int) bool {
+ var count int64
+ err := DB.Model(&Ability{}).
+ Where(commonGroupCol+" = ? and model = ? and channel_id = ? and enabled = ?", group, modelName, channelID, true).
+ Count(&count).Error
+ if err == nil && count > 0 {
+ return true
+ }
+ normalized := ratio_setting.FormatMatchingModelName(modelName)
+ if normalized == "" || normalized == modelName {
+ return false
+ }
+ count = 0
+ err = DB.Model(&Ability{}).
+ Where(commonGroupCol+" = ? and model = ? and channel_id = ? and enabled = ?", group, normalized, channelID, true).
+ Count(&count).Error
+ return err == nil && count > 0
+}
+
+func isChannelIDInList(list []int, channelID int) bool {
+ for _, id := range list {
+ if id == channelID {
+ return true
+ }
+ }
+ return false
+}
diff --git a/model/custom_oauth_provider.go b/model/custom_oauth_provider.go
new file mode 100644
index 0000000000..12b4d11113
--- /dev/null
+++ b/model/custom_oauth_provider.go
@@ -0,0 +1,247 @@
+package model
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+)
+
+type accessPolicyPayload struct {
+ Logic string `json:"logic"`
+ Conditions []accessConditionItem `json:"conditions"`
+ Groups []accessPolicyPayload `json:"groups"`
+}
+
+type accessConditionItem struct {
+ Field string `json:"field"`
+ Op string `json:"op"`
+ Value any `json:"value"`
+}
+
+var supportedAccessPolicyOps = map[string]struct{}{
+ "eq": {},
+ "ne": {},
+ "gt": {},
+ "gte": {},
+ "lt": {},
+ "lte": {},
+ "in": {},
+ "not_in": {},
+ "contains": {},
+ "not_contains": {},
+ "exists": {},
+ "not_exists": {},
+}
+
+// CustomOAuthProvider stores configuration for custom OAuth providers
+type CustomOAuthProvider struct {
+ Id int `json:"id" gorm:"primaryKey"`
+ Name string `json:"name" gorm:"type:varchar(64);not null"` // Display name, e.g., "GitHub Enterprise"
+ Slug string `json:"slug" gorm:"type:varchar(64);uniqueIndex;not null"` // URL identifier, e.g., "github-enterprise"
+ Icon string `json:"icon" gorm:"type:varchar(128);default:''"` // Icon name from @lobehub/icons
+ Enabled bool `json:"enabled" gorm:"default:false"` // Whether this provider is enabled
+ ClientId string `json:"client_id" gorm:"type:varchar(256)"` // OAuth client ID
+ ClientSecret string `json:"-" gorm:"type:varchar(512)"` // OAuth client secret (not returned to frontend)
+ AuthorizationEndpoint string `json:"authorization_endpoint" gorm:"type:varchar(512)"` // Authorization URL
+ TokenEndpoint string `json:"token_endpoint" gorm:"type:varchar(512)"` // Token exchange URL
+ UserInfoEndpoint string `json:"user_info_endpoint" gorm:"type:varchar(512)"` // User info URL
+ Scopes string `json:"scopes" gorm:"type:varchar(256);default:'openid profile email'"` // OAuth scopes
+
+ // Field mapping configuration (supports JSONPath via gjson)
+ UserIdField string `json:"user_id_field" gorm:"type:varchar(128);default:'sub'"` // User ID field path, e.g., "sub", "id", "data.user.id"
+ UsernameField string `json:"username_field" gorm:"type:varchar(128);default:'preferred_username'"` // Username field path
+ DisplayNameField string `json:"display_name_field" gorm:"type:varchar(128);default:'name'"` // Display name field path
+ EmailField string `json:"email_field" gorm:"type:varchar(128);default:'email'"` // Email field path
+
+ // Advanced options
+ WellKnown string `json:"well_known" gorm:"type:varchar(512)"` // OIDC discovery endpoint (optional)
+ AuthStyle int `json:"auth_style" gorm:"default:0"` // 0=auto, 1=params, 2=header (Basic Auth)
+ AccessPolicy string `json:"access_policy" gorm:"type:text"` // JSON policy for access control based on user info
+ AccessDeniedMessage string `json:"access_denied_message" gorm:"type:varchar(512)"` // Custom error message template when access is denied
+
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+func (CustomOAuthProvider) TableName() string {
+ return "custom_oauth_providers"
+}
+
+// GetAllCustomOAuthProviders returns all custom OAuth providers
+func GetAllCustomOAuthProviders() ([]*CustomOAuthProvider, error) {
+ var providers []*CustomOAuthProvider
+ err := DB.Order("id asc").Find(&providers).Error
+ return providers, err
+}
+
+// GetEnabledCustomOAuthProviders returns all enabled custom OAuth providers
+func GetEnabledCustomOAuthProviders() ([]*CustomOAuthProvider, error) {
+ var providers []*CustomOAuthProvider
+ err := DB.Where("enabled = ?", true).Order("id asc").Find(&providers).Error
+ return providers, err
+}
+
+// GetCustomOAuthProviderById returns a custom OAuth provider by ID
+func GetCustomOAuthProviderById(id int) (*CustomOAuthProvider, error) {
+ var provider CustomOAuthProvider
+ err := DB.First(&provider, id).Error
+ if err != nil {
+ return nil, err
+ }
+ return &provider, nil
+}
+
+// GetCustomOAuthProviderBySlug returns a custom OAuth provider by slug
+func GetCustomOAuthProviderBySlug(slug string) (*CustomOAuthProvider, error) {
+ var provider CustomOAuthProvider
+ err := DB.Where("slug = ?", slug).First(&provider).Error
+ if err != nil {
+ return nil, err
+ }
+ return &provider, nil
+}
+
+// CreateCustomOAuthProvider creates a new custom OAuth provider
+func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error {
+ if err := validateCustomOAuthProvider(provider); err != nil {
+ return err
+ }
+ return DB.Create(provider).Error
+}
+
+// UpdateCustomOAuthProvider updates an existing custom OAuth provider
+func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error {
+ if err := validateCustomOAuthProvider(provider); err != nil {
+ return err
+ }
+ return DB.Save(provider).Error
+}
+
+// DeleteCustomOAuthProvider deletes a custom OAuth provider by ID
+func DeleteCustomOAuthProvider(id int) error {
+ // First, delete all user bindings for this provider
+ if err := DB.Where("provider_id = ?", id).Delete(&UserOAuthBinding{}).Error; err != nil {
+ return err
+ }
+ return DB.Delete(&CustomOAuthProvider{}, id).Error
+}
+
+// IsSlugTaken checks if a slug is already taken by another provider
+// Returns true on DB errors (fail-closed) to prevent slug conflicts
+func IsSlugTaken(slug string, excludeId int) bool {
+ var count int64
+ query := DB.Model(&CustomOAuthProvider{}).Where("slug = ?", slug)
+ if excludeId > 0 {
+ query = query.Where("id != ?", excludeId)
+ }
+ res := query.Count(&count)
+ if res.Error != nil {
+ // Fail-closed: treat DB errors as slug being taken to prevent conflicts
+ return true
+ }
+ return count > 0
+}
+
+// validateCustomOAuthProvider validates a custom OAuth provider configuration
+func validateCustomOAuthProvider(provider *CustomOAuthProvider) error {
+ if provider.Name == "" {
+ return errors.New("provider name is required")
+ }
+ if provider.Slug == "" {
+ return errors.New("provider slug is required")
+ }
+ // Slug must be lowercase and contain only alphanumeric characters and hyphens
+ slug := strings.ToLower(provider.Slug)
+ for _, c := range slug {
+ if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
+ return errors.New("provider slug must contain only lowercase letters, numbers, and hyphens")
+ }
+ }
+ provider.Slug = slug
+
+ if provider.ClientId == "" {
+ return errors.New("client ID is required")
+ }
+ if provider.AuthorizationEndpoint == "" {
+ return errors.New("authorization endpoint is required")
+ }
+ if provider.TokenEndpoint == "" {
+ return errors.New("token endpoint is required")
+ }
+ if provider.UserInfoEndpoint == "" {
+ return errors.New("user info endpoint is required")
+ }
+
+ // Set defaults for field mappings if empty
+ if provider.UserIdField == "" {
+ provider.UserIdField = "sub"
+ }
+ if provider.UsernameField == "" {
+ provider.UsernameField = "preferred_username"
+ }
+ if provider.DisplayNameField == "" {
+ provider.DisplayNameField = "name"
+ }
+ if provider.EmailField == "" {
+ provider.EmailField = "email"
+ }
+ if provider.Scopes == "" {
+ provider.Scopes = "openid profile email"
+ }
+ if strings.TrimSpace(provider.AccessPolicy) != "" {
+ var policy accessPolicyPayload
+ if err := common.UnmarshalJsonStr(provider.AccessPolicy, &policy); err != nil {
+ return errors.New("access_policy must be valid JSON")
+ }
+ if err := validateAccessPolicyPayload(&policy); err != nil {
+ return fmt.Errorf("access_policy is invalid: %w", err)
+ }
+ }
+
+ return nil
+}
+
+func validateAccessPolicyPayload(policy *accessPolicyPayload) error {
+ if policy == nil {
+ return errors.New("policy is nil")
+ }
+
+ logic := strings.ToLower(strings.TrimSpace(policy.Logic))
+ if logic == "" {
+ logic = "and"
+ }
+ if logic != "and" && logic != "or" {
+ return fmt.Errorf("unsupported logic: %s", logic)
+ }
+
+ if len(policy.Conditions) == 0 && len(policy.Groups) == 0 {
+ return errors.New("policy requires at least one condition or group")
+ }
+
+ for index, condition := range policy.Conditions {
+ field := strings.TrimSpace(condition.Field)
+ if field == "" {
+ return fmt.Errorf("condition[%d].field is required", index)
+ }
+ op := strings.ToLower(strings.TrimSpace(condition.Op))
+ if _, ok := supportedAccessPolicyOps[op]; !ok {
+ return fmt.Errorf("condition[%d].op is unsupported: %s", index, op)
+ }
+ if op == "in" || op == "not_in" {
+ if _, ok := condition.Value.([]any); !ok {
+ return fmt.Errorf("condition[%d].value must be an array for op %s", index, op)
+ }
+ }
+ }
+
+ for index := range policy.Groups {
+ if err := validateAccessPolicyPayload(&policy.Groups[index]); err != nil {
+ return fmt.Errorf("group[%d]: %w", index, err)
+ }
+ }
+
+ return nil
+}
diff --git a/model/db_time.go b/model/db_time.go
new file mode 100644
index 0000000000..dca14292d3
--- /dev/null
+++ b/model/db_time.go
@@ -0,0 +1,22 @@
+package model
+
+import "github.com/QuantumNous/new-api/common"
+
+// GetDBTimestamp returns a UNIX timestamp from database time.
+// Falls back to application time on error.
+func GetDBTimestamp() int64 {
+ var ts int64
+ var err error
+ switch {
+ case common.UsingPostgreSQL:
+ err = DB.Raw("SELECT EXTRACT(EPOCH FROM NOW())::bigint").Scan(&ts).Error
+ case common.UsingSQLite:
+ err = DB.Raw("SELECT strftime('%s','now')").Scan(&ts).Error
+ default:
+ err = DB.Raw("SELECT UNIX_TIMESTAMP()").Scan(&ts).Error
+ }
+ if err != nil || ts <= 0 {
+ return common.GetTimestamp()
+ }
+ return ts
+}
diff --git a/model/log.go b/model/log.go
index f8940c150c..68bc650469 100644
--- a/model/log.go
+++ b/model/log.go
@@ -2,9 +2,8 @@ package model
import (
"context"
+ "errors"
"fmt"
- "os"
- "strings"
"time"
"github.com/QuantumNous/new-api/common"
@@ -18,8 +17,8 @@ import (
)
type Log struct {
- Id int `json:"id" gorm:"index:idx_created_at_id,priority:1"`
- UserId int `json:"user_id" gorm:"index"`
+ Id int `json:"id" gorm:"index:idx_created_at_id,priority:1;index:idx_user_id_id,priority:2"`
+ UserId int `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
Type int `json:"type" gorm:"index:idx_created_at_type"`
Content string `json:"content"`
@@ -36,6 +35,7 @@ type Log struct {
TokenId int `json:"token_id" gorm:"default:0;index"`
Group string `json:"group" gorm:"index"`
Ip string `json:"ip" gorm:"index;default:''"`
+ RequestId string `json:"request_id,omitempty" gorm:"type:varchar(64);index:idx_logs_request_id;default:''"`
Other string `json:"other"`
}
@@ -50,7 +50,7 @@ const (
LogTypeRefund = 6
)
-func formatUserLogs(logs []*Log) {
+func formatUserLogs(logs []*Log, startIdx int) {
for i := range logs {
logs[i].ChannelName = ""
var otherMap map[string]interface{}
@@ -58,24 +58,17 @@ func formatUserLogs(logs []*Log) {
if otherMap != nil {
// Remove admin-only debug fields.
delete(otherMap, "admin_info")
- delete(otherMap, "request_conversion")
+ // delete(otherMap, "reject_reason")
+ delete(otherMap, "stream_status")
}
logs[i].Other = common.MapToJsonStr(otherMap)
- logs[i].Id = logs[i].Id % 1024
+ logs[i].Id = startIdx + i + 1
}
}
-func GetLogByKey(key string) (logs []*Log, err error) {
- if os.Getenv("LOG_SQL_DSN") != "" {
- var tk Token
- if err = DB.Model(&Token{}).Where(logKeyCol+"=?", strings.TrimPrefix(key, "sk-")).First(&tk).Error; err != nil {
- return nil, err
- }
- err = LOG_DB.Model(&Log{}).Where("token_id=?", tk.Id).Find(&logs).Error
- } else {
- err = LOG_DB.Joins("left join tokens on tokens.id = logs.token_id").Where("tokens.key = ?", strings.TrimPrefix(key, "sk-")).Find(&logs).Error
- }
- formatUserLogs(logs)
+func GetLogByTokenId(tokenId int) (logs []*Log, err error) {
+ err = LOG_DB.Model(&Log{}).Where("token_id = ?", tokenId).Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
+ formatUserLogs(logs, 0)
return logs, err
}
@@ -101,6 +94,7 @@ func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string,
isStream bool, group string, other map[string]interface{}) {
logger.LogInfo(c, fmt.Sprintf("record error log: userId=%d, channelId=%d, modelName=%s, tokenName=%s, content=%s", userId, channelId, modelName, tokenName, content))
username := c.GetString("username")
+ requestId := c.GetString(common.RequestIdKey)
otherStr := common.MapToJsonStr(other)
// 判断是否需要记录 IP
needRecordIp := false
@@ -131,7 +125,8 @@ func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string,
}
return ""
}(),
- Other: otherStr,
+ RequestId: requestId,
+ Other: otherStr,
}
err := LOG_DB.Create(log).Error
if err != nil {
@@ -160,6 +155,7 @@ func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
}
logger.LogInfo(c, fmt.Sprintf("record consume log: userId=%d, params=%s", userId, common.GetJsonString(params)))
username := c.GetString("username")
+ requestId := c.GetString(common.RequestIdKey)
otherStr := common.MapToJsonStr(params.Other)
// 判断是否需要记录 IP
needRecordIp := false
@@ -190,7 +186,8 @@ func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
}
return ""
}(),
- Other: otherStr,
+ RequestId: requestId,
+ Other: otherStr,
}
err := LOG_DB.Create(log).Error
if err != nil {
@@ -203,7 +200,50 @@ func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
}
}
-func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int, group string) (logs []*Log, total int64, err error) {
+type RecordTaskBillingLogParams struct {
+ UserId int
+ LogType int
+ Content string
+ ChannelId int
+ ModelName string
+ Quota int
+ TokenId int
+ Group string
+ Other map[string]interface{}
+}
+
+func RecordTaskBillingLog(params RecordTaskBillingLogParams) {
+ if params.LogType == LogTypeConsume && !common.LogConsumeEnabled {
+ return
+ }
+ username, _ := GetUsernameById(params.UserId, false)
+ tokenName := ""
+ if params.TokenId > 0 {
+ if token, err := GetTokenById(params.TokenId); err == nil {
+ tokenName = token.Name
+ }
+ }
+ log := &Log{
+ UserId: params.UserId,
+ Username: username,
+ CreatedAt: common.GetTimestamp(),
+ Type: params.LogType,
+ Content: params.Content,
+ TokenName: tokenName,
+ ModelName: params.ModelName,
+ Quota: params.Quota,
+ ChannelId: params.ChannelId,
+ TokenId: params.TokenId,
+ Group: params.Group,
+ Other: common.MapToJsonStr(params.Other),
+ }
+ err := LOG_DB.Create(log).Error
+ if err != nil {
+ common.SysLog("failed to record task billing log: " + err.Error())
+ }
+}
+
+func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int, group string, requestId string) (logs []*Log, total int64, err error) {
var tx *gorm.DB
if logType == LogTypeUnknown {
tx = LOG_DB
@@ -220,6 +260,9 @@ func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName
if tokenName != "" {
tx = tx.Where("logs.token_name = ?", tokenName)
}
+ if requestId != "" {
+ tx = tx.Where("logs.request_id = ?", requestId)
+ }
if startTimestamp != 0 {
tx = tx.Where("logs.created_at >= ?", startTimestamp)
}
@@ -253,8 +296,24 @@ func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName
Id int `gorm:"column:id"`
Name string `gorm:"column:name"`
}
- if err = DB.Table("channels").Select("id, name").Where("id IN ?", channelIds.Items()).Find(&channels).Error; err != nil {
- return logs, total, err
+ if common.MemoryCacheEnabled {
+ // Cache get channel
+ for _, channelId := range channelIds.Items() {
+ if cacheChannel, err := CacheGetChannel(channelId); err == nil {
+ channels = append(channels, struct {
+ Id int `gorm:"column:id"`
+ Name string `gorm:"column:name"`
+ }{
+ Id: channelId,
+ Name: cacheChannel.Name,
+ })
+ }
+ }
+ } else {
+ // Bulk query channels from DB
+ if err = DB.Table("channels").Select("id, name").Where("id IN ?", channelIds.Items()).Find(&channels).Error; err != nil {
+ return logs, total, err
+ }
}
channelMap := make(map[int]string, len(channels))
for _, channel := range channels {
@@ -268,7 +327,9 @@ func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName
return logs, total, err
}
-func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int, group string) (logs []*Log, total int64, err error) {
+const logSearchCountLimit = 10000
+
+func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int, group string, requestId string) (logs []*Log, total int64, err error) {
var tx *gorm.DB
if logType == LogTypeUnknown {
tx = LOG_DB.Where("logs.user_id = ?", userId)
@@ -277,11 +338,18 @@ func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int
}
if modelName != "" {
- tx = tx.Where("logs.model_name like ?", modelName)
+ modelNamePattern, err := sanitizeLikePattern(modelName)
+ if err != nil {
+ return nil, 0, err
+ }
+ tx = tx.Where("logs.model_name LIKE ? ESCAPE '!'", modelNamePattern)
}
if tokenName != "" {
tx = tx.Where("logs.token_name = ?", tokenName)
}
+ if requestId != "" {
+ tx = tx.Where("logs.request_id = ?", requestId)
+ }
if startTimestamp != 0 {
tx = tx.Where("logs.created_at >= ?", startTimestamp)
}
@@ -291,37 +359,28 @@ func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int
if group != "" {
tx = tx.Where("logs."+logGroupCol+" = ?", group)
}
- err = tx.Model(&Log{}).Count(&total).Error
+ err = tx.Model(&Log{}).Limit(logSearchCountLimit).Count(&total).Error
if err != nil {
- return nil, 0, err
+ common.SysError("failed to count user logs: " + err.Error())
+ return nil, 0, errors.New("查询日志失败")
}
err = tx.Order("logs.id desc").Limit(num).Offset(startIdx).Find(&logs).Error
if err != nil {
- return nil, 0, err
+ common.SysError("failed to search user logs: " + err.Error())
+ return nil, 0, errors.New("查询日志失败")
}
- formatUserLogs(logs)
+ formatUserLogs(logs, startIdx)
return logs, total, err
}
-func SearchAllLogs(keyword string) (logs []*Log, err error) {
- err = LOG_DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
- return logs, err
-}
-
-func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
- err = LOG_DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
- formatUserLogs(logs)
- return logs, err
-}
-
type Stat struct {
Quota int `json:"quota"`
Rpm int `json:"rpm"`
Tpm int `json:"tpm"`
}
-func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int, group string) (stat Stat) {
+func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int, group string) (stat Stat, err error) {
tx := LOG_DB.Table("logs").Select("sum(quota) quota")
// 为rpm和tpm创建单独的查询
@@ -342,8 +401,12 @@ func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelNa
tx = tx.Where("created_at <= ?", endTimestamp)
}
if modelName != "" {
- tx = tx.Where("model_name like ?", modelName)
- rpmTpmQuery = rpmTpmQuery.Where("model_name like ?", modelName)
+ modelNamePattern, err := sanitizeLikePattern(modelName)
+ if err != nil {
+ return stat, err
+ }
+ tx = tx.Where("model_name LIKE ? ESCAPE '!'", modelNamePattern)
+ rpmTpmQuery = rpmTpmQuery.Where("model_name LIKE ? ESCAPE '!'", modelNamePattern)
}
if channel != 0 {
tx = tx.Where("channel_id = ?", channel)
@@ -361,10 +424,16 @@ func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelNa
rpmTpmQuery = rpmTpmQuery.Where("created_at >= ?", time.Now().Add(-60*time.Second).Unix())
// 执行查询
- tx.Scan(&stat)
- rpmTpmQuery.Scan(&stat)
+ if err := tx.Scan(&stat).Error; err != nil {
+ common.SysError("failed to query log stat: " + err.Error())
+ return stat, errors.New("查询统计数据失败")
+ }
+ if err := rpmTpmQuery.Scan(&stat).Error; err != nil {
+ common.SysError("failed to query rpm/tpm stat: " + err.Error())
+ return stat, errors.New("查询统计数据失败")
+ }
- return stat
+ return stat, nil
}
func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
diff --git a/model/main.go b/model/main.go
index 586eaa3537..f37cb667cd 100644
--- a/model/main.go
+++ b/model/main.go
@@ -248,6 +248,13 @@ func InitLogDB() (err error) {
}
func migrateDB() error {
+ // Migrate price_amount column from float/double to decimal for existing tables
+ migrateSubscriptionPlanPriceAmount()
+ // Migrate model_limits column from varchar to text for existing tables
+ if err := migrateTokenModelLimitsToText(); err != nil {
+ return err
+ }
+
err := DB.AutoMigrate(
&Channel{},
&Token{},
@@ -268,10 +275,24 @@ func migrateDB() error {
&TwoFA{},
&TwoFABackupCode{},
&Checkin{},
+ &SubscriptionOrder{},
+ &UserSubscription{},
+ &SubscriptionPreConsumeRecord{},
+ &CustomOAuthProvider{},
+ &UserOAuthBinding{},
)
if err != nil {
return err
}
+ if common.UsingSQLite {
+ if err := ensureSubscriptionPlanTableSQLite(); err != nil {
+ return err
+ }
+ } else {
+ if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
+ return err
+ }
+ }
return nil
}
@@ -302,6 +323,11 @@ func migrateDBFast() error {
{&TwoFA{}, "TwoFA"},
{&TwoFABackupCode{}, "TwoFABackupCode"},
{&Checkin{}, "Checkin"},
+ {&SubscriptionOrder{}, "SubscriptionOrder"},
+ {&UserSubscription{}, "UserSubscription"},
+ {&SubscriptionPreConsumeRecord{}, "SubscriptionPreConsumeRecord"},
+ {&CustomOAuthProvider{}, "CustomOAuthProvider"},
+ {&UserOAuthBinding{}, "UserOAuthBinding"},
}
// 动态计算migration数量,确保errChan缓冲区足够大
errChan := make(chan error, len(migrations))
@@ -326,6 +352,15 @@ func migrateDBFast() error {
return err
}
}
+ if common.UsingSQLite {
+ if err := ensureSubscriptionPlanTableSQLite(); err != nil {
+ return err
+ }
+ } else {
+ if err := DB.AutoMigrate(&SubscriptionPlan{}); err != nil {
+ return err
+ }
+ }
common.SysLog("database migrated")
return nil
}
@@ -338,6 +373,195 @@ func migrateLOGDB() error {
return nil
}
+type sqliteColumnDef struct {
+ Name string
+ DDL string
+}
+
+func ensureSubscriptionPlanTableSQLite() error {
+ if !common.UsingSQLite {
+ return nil
+ }
+ tableName := "subscription_plans"
+ if !DB.Migrator().HasTable(tableName) {
+ createSQL := `CREATE TABLE ` + "`" + tableName + "`" + ` (
+` + "`id`" + ` integer,
+` + "`title`" + ` varchar(128) NOT NULL,
+` + "`subtitle`" + ` varchar(255) DEFAULT '',
+` + "`price_amount`" + ` decimal(10,6) NOT NULL,
+` + "`currency`" + ` varchar(8) NOT NULL DEFAULT 'USD',
+` + "`duration_unit`" + ` varchar(16) NOT NULL DEFAULT 'month',
+` + "`duration_value`" + ` integer NOT NULL DEFAULT 1,
+` + "`custom_seconds`" + ` bigint NOT NULL DEFAULT 0,
+` + "`enabled`" + ` numeric DEFAULT 1,
+` + "`sort_order`" + ` integer DEFAULT 0,
+` + "`stripe_price_id`" + ` varchar(128) DEFAULT '',
+` + "`creem_product_id`" + ` varchar(128) DEFAULT '',
+` + "`max_purchase_per_user`" + ` integer DEFAULT 0,
+` + "`upgrade_group`" + ` varchar(64) DEFAULT '',
+` + "`total_amount`" + ` bigint NOT NULL DEFAULT 0,
+` + "`quota_reset_period`" + ` varchar(16) DEFAULT 'never',
+` + "`quota_reset_custom_seconds`" + ` bigint DEFAULT 0,
+` + "`created_at`" + ` bigint,
+` + "`updated_at`" + ` bigint,
+PRIMARY KEY (` + "`id`" + `)
+)`
+ return DB.Exec(createSQL).Error
+ }
+ var cols []struct {
+ Name string `gorm:"column:name"`
+ }
+ if err := DB.Raw("PRAGMA table_info(`" + tableName + "`)").Scan(&cols).Error; err != nil {
+ return err
+ }
+ existing := make(map[string]struct{}, len(cols))
+ for _, c := range cols {
+ existing[c.Name] = struct{}{}
+ }
+ required := []sqliteColumnDef{
+ {Name: "title", DDL: "`title` varchar(128) NOT NULL"},
+ {Name: "subtitle", DDL: "`subtitle` varchar(255) DEFAULT ''"},
+ {Name: "price_amount", DDL: "`price_amount` decimal(10,6) NOT NULL"},
+ {Name: "currency", DDL: "`currency` varchar(8) NOT NULL DEFAULT 'USD'"},
+ {Name: "duration_unit", DDL: "`duration_unit` varchar(16) NOT NULL DEFAULT 'month'"},
+ {Name: "duration_value", DDL: "`duration_value` integer NOT NULL DEFAULT 1"},
+ {Name: "custom_seconds", DDL: "`custom_seconds` bigint NOT NULL DEFAULT 0"},
+ {Name: "enabled", DDL: "`enabled` numeric DEFAULT 1"},
+ {Name: "sort_order", DDL: "`sort_order` integer DEFAULT 0"},
+ {Name: "stripe_price_id", DDL: "`stripe_price_id` varchar(128) DEFAULT ''"},
+ {Name: "creem_product_id", DDL: "`creem_product_id` varchar(128) DEFAULT ''"},
+ {Name: "max_purchase_per_user", DDL: "`max_purchase_per_user` integer DEFAULT 0"},
+ {Name: "upgrade_group", DDL: "`upgrade_group` varchar(64) DEFAULT ''"},
+ {Name: "total_amount", DDL: "`total_amount` bigint NOT NULL DEFAULT 0"},
+ {Name: "quota_reset_period", DDL: "`quota_reset_period` varchar(16) DEFAULT 'never'"},
+ {Name: "quota_reset_custom_seconds", DDL: "`quota_reset_custom_seconds` bigint DEFAULT 0"},
+ {Name: "created_at", DDL: "`created_at` bigint"},
+ {Name: "updated_at", DDL: "`updated_at` bigint"},
+ }
+ for _, col := range required {
+ if _, ok := existing[col.Name]; ok {
+ continue
+ }
+ if err := DB.Exec("ALTER TABLE `" + tableName + "` ADD COLUMN " + col.DDL).Error; err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// migrateTokenModelLimitsToText migrates model_limits column from varchar(1024) to text
+// This is safe to run multiple times - it checks the column type first
+func migrateTokenModelLimitsToText() error {
+ // SQLite uses type affinity, so TEXT and VARCHAR are effectively the same — no migration needed
+ if common.UsingSQLite {
+ return nil
+ }
+
+ tableName := "tokens"
+ columnName := "model_limits"
+
+ if !DB.Migrator().HasTable(tableName) {
+ return nil
+ }
+
+ if !DB.Migrator().HasColumn(&Token{}, columnName) {
+ return nil
+ }
+
+ var alterSQL string
+ if common.UsingPostgreSQL {
+ var dataType string
+ if err := DB.Raw(`SELECT data_type FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?`,
+ tableName, columnName).Scan(&dataType).Error; err != nil {
+ common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
+ } else if dataType == "text" {
+ return nil
+ }
+ alterSQL = fmt.Sprintf(`ALTER TABLE %s ALTER COLUMN %s TYPE text`, tableName, columnName)
+ } else if common.UsingMySQL {
+ var columnType string
+ if err := DB.Raw(`SELECT COLUMN_TYPE FROM information_schema.columns
+ WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`,
+ tableName, columnName).Scan(&columnType).Error; err != nil {
+ common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
+ } else if strings.ToLower(columnType) == "text" {
+ return nil
+ }
+ alterSQL = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s text", tableName, columnName)
+ } else {
+ return nil
+ }
+
+ if alterSQL != "" {
+ if err := DB.Exec(alterSQL).Error; err != nil {
+ return fmt.Errorf("failed to migrate %s.%s to text: %w", tableName, columnName, err)
+ }
+ common.SysLog(fmt.Sprintf("Successfully migrated %s.%s to text", tableName, columnName))
+ }
+ return nil
+}
+
+// migrateSubscriptionPlanPriceAmount migrates price_amount column from float/double to decimal(10,6)
+// This is safe to run multiple times - it checks the column type first
+func migrateSubscriptionPlanPriceAmount() {
+ // SQLite doesn't support ALTER COLUMN, and its type affinity handles this automatically
+ // Skip early to avoid GORM parsing the existing table DDL which may cause issues
+ if common.UsingSQLite {
+ return
+ }
+
+ tableName := "subscription_plans"
+ columnName := "price_amount"
+
+ // Check if table exists first
+ if !DB.Migrator().HasTable(tableName) {
+ return
+ }
+
+ // Check if column exists
+ if !DB.Migrator().HasColumn(&SubscriptionPlan{}, columnName) {
+ return
+ }
+
+ var alterSQL string
+ if common.UsingPostgreSQL {
+ // PostgreSQL: Check if already decimal/numeric
+ var dataType string
+ if err := DB.Raw(`SELECT data_type FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?`,
+ tableName, columnName).Scan(&dataType).Error; err != nil {
+ common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
+ } else if dataType == "numeric" {
+ return // Already decimal/numeric
+ }
+ alterSQL = fmt.Sprintf(`ALTER TABLE %s ALTER COLUMN %s TYPE decimal(10,6) USING %s::decimal(10,6)`,
+ tableName, columnName, columnName)
+ } else if common.UsingMySQL {
+ // MySQL: Check if already decimal
+ var columnType string
+ if err := DB.Raw(`SELECT COLUMN_TYPE FROM information_schema.columns
+ WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`,
+ tableName, columnName).Scan(&columnType).Error; err != nil {
+ common.SysLog(fmt.Sprintf("Warning: failed to query metadata for %s.%s: %v", tableName, columnName, err))
+ } else if strings.HasPrefix(strings.ToLower(columnType), "decimal") {
+ return // Already decimal
+ }
+ alterSQL = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s decimal(10,6) NOT NULL DEFAULT 0",
+ tableName, columnName)
+ } else {
+ return
+ }
+
+ if alterSQL != "" {
+ if err := DB.Exec(alterSQL).Error; err != nil {
+ common.SysLog(fmt.Sprintf("Warning: failed to migrate %s.%s to decimal: %v", tableName, columnName, err))
+ } else {
+ common.SysLog(fmt.Sprintf("Successfully migrated %s.%s to decimal(10,6)", tableName, columnName))
+ }
+ }
+}
+
func closeDB(db *gorm.DB) error {
sqlDB, err := db.DB()
if err != nil {
diff --git a/model/midjourney.go b/model/midjourney.go
index c6ef5de5b7..e1a8d772b0 100644
--- a/model/midjourney.go
+++ b/model/midjourney.go
@@ -157,6 +157,19 @@ func (midjourney *Midjourney) Update() error {
return err
}
+// UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS).
+// Returns (true, nil) if this caller won the update, (false, nil) if
+// another process already moved the task out of fromStatus.
+// UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS).
+// Uses Model().Select("*").Updates() to avoid GORM Save()'s INSERT fallback.
+func (midjourney *Midjourney) UpdateWithStatus(fromStatus string) (bool, error) {
+ result := DB.Model(midjourney).Where("status = ?", fromStatus).Select("*").Updates(midjourney)
+ if result.Error != nil {
+ return false, result.Error
+ }
+ return result.RowsAffected > 0, nil
+}
+
func MjBulkUpdate(mjIds []string, params map[string]any) error {
return DB.Model(&Midjourney{}).
Where("mj_id in (?)", mjIds).
diff --git a/model/model_meta.go b/model/model_meta.go
index e7daef3a19..860b960241 100644
--- a/model/model_meta.go
+++ b/model/model_meta.go
@@ -47,7 +47,21 @@ func (mi *Model) Insert() error {
now := common.GetTimestamp()
mi.CreatedTime = now
mi.UpdatedTime = now
- return DB.Create(mi).Error
+
+ // 保存原始值(因为 Create 后可能被 GORM 的 default 标签覆盖为 1)
+ originalStatus := mi.Status
+ originalSyncOfficial := mi.SyncOfficial
+
+ // 先创建记录(GORM 会对零值字段应用默认值)
+ if err := DB.Create(mi).Error; err != nil {
+ return err
+ }
+
+ // 使用保存的原始值进行更新,确保零值能正确保存
+ return DB.Model(&Model{}).Where("id = ?", mi.Id).Updates(map[string]interface{}{
+ "status": originalStatus,
+ "sync_official": originalSyncOfficial,
+ }).Error
}
func IsModelNameDuplicated(id int, name string) (bool, error) {
@@ -61,11 +75,9 @@ func IsModelNameDuplicated(id int, name string) (bool, error) {
func (mi *Model) Update() error {
mi.UpdatedTime = common.GetTimestamp()
- return DB.Session(&gorm.Session{AllowGlobalUpdate: false, FullSaveAssociations: false}).
- Model(&Model{}).
- Where("id = ?", mi.Id).
- Omit("created_time").
- Select("*").
+ // 使用 Select 强制更新所有字段,包括零值
+ return DB.Model(&Model{}).Where("id = ?", mi.Id).
+ Select("model_name", "description", "icon", "tags", "vendor_id", "endpoints", "status", "sync_official", "name_rule", "updated_time").
Updates(mi).Error
}
@@ -73,66 +85,28 @@ func (mi *Model) Delete() error {
return DB.Delete(mi).Error
}
-func GetVendorModelCounts(status string, syncOfficial string) (map[string]int64, error) {
+func GetVendorModelCounts() (map[int64]int64, error) {
var stats []struct {
VendorID int64
Count int64
}
-
- db := DB.Model(&Model{})
- db = applyModelFilters(db, status, syncOfficial)
-
- if err := db.Select("vendor_id, count(*) as count").
+ if err := DB.Model(&Model{}).
+ Select("vendor_id as vendor_id, count(*) as count").
Group("vendor_id").
Scan(&stats).Error; err != nil {
return nil, err
}
-
- result := make(map[string]int64, len(stats)+1)
- var total int64
+ m := make(map[int64]int64, len(stats))
for _, s := range stats {
- result[strconv.FormatInt(s.VendorID, 10)] = s.Count
- total += s.Count
+ m[s.VendorID] = s.Count
}
- result["all"] = total
- return result, nil
+ return m, nil
}
-// applyModelFilters 应用status和sync_official筛选条件(公共函数)
-func applyModelFilters(db *gorm.DB, status string, syncOfficial string) *gorm.DB {
- // Filter by status
- if status == "enabled" {
- db = db.Where("status = ?", 1)
- } else if status == "disabled" {
- db = db.Where("status != ?", 1)
- }
-
- // Filter by sync_official
- if syncOfficial == "yes" {
- db = db.Where("sync_official = ?", 1)
- } else if syncOfficial == "no" {
- db = db.Where("sync_official != ?", 1)
- }
-
- return db
-}
-
-func GetAllModels(offset int, limit int, status string, syncOfficial string) ([]*Model, int64, error) {
+func GetAllModels(offset int, limit int) ([]*Model, error) {
var models []*Model
- db := DB.Model(&Model{})
-
- // Apply filters
- db = applyModelFilters(db, status, syncOfficial)
-
- // Count total
- var total int64
- if err := db.Count(&total).Error; err != nil {
- return nil, 0, err
- }
-
- // Fetch data
- err := db.Order("id DESC").Offset(offset).Limit(limit).Find(&models).Error
- return models, total, err
+ err := DB.Order("id DESC").Offset(offset).Limit(limit).Find(&models).Error
+ return models, err
}
func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error) {
@@ -161,17 +135,13 @@ func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel
return result, nil
}
-func SearchModels(keyword string, vendor string, status string, syncOfficial string, offset int, limit int) ([]*Model, int64, error) {
+func SearchModels(keyword string, vendor string, offset int, limit int) ([]*Model, int64, error) {
var models []*Model
db := DB.Model(&Model{})
-
- // Apply keyword filter
if keyword != "" {
like := "%" + keyword + "%"
db = db.Where("model_name LIKE ? OR description LIKE ? OR tags LIKE ?", like, like, like)
}
-
- // Apply vendor filter
if vendor != "" {
if vid, err := strconv.Atoi(vendor); err == nil {
db = db.Where("models.vendor_id = ?", vid)
@@ -179,20 +149,12 @@ func SearchModels(keyword string, vendor string, status string, syncOfficial str
db = db.Joins("JOIN vendors ON vendors.id = models.vendor_id").Where("vendors.name LIKE ?", "%"+vendor+"%")
}
}
-
- // Apply common filters (status and sync_official)
- db = applyModelFilters(db, status, syncOfficial)
-
- // Count total
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
-
- // Fetch data
if err := db.Order("models.id DESC").Offset(offset).Limit(limit).Find(&models).Error; err != nil {
return nil, 0, err
}
-
return models, total, nil
}
diff --git a/model/option.go b/model/option.go
index e268cf577d..efa8c01daa 100644
--- a/model/option.go
+++ b/model/option.go
@@ -9,6 +9,7 @@ import (
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/config"
"github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/setting/performance_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/QuantumNous/new-api/setting/system_setting"
)
@@ -61,6 +62,7 @@ func InitOptionMap() {
common.OptionMap["SMTPAccount"] = ""
common.OptionMap["SMTPToken"] = ""
common.OptionMap["SMTPSSLEnabled"] = strconv.FormatBool(common.SMTPSSLEnabled)
+ common.OptionMap["SMTPForceAuthLogin"] = strconv.FormatBool(common.SMTPForceAuthLogin)
common.OptionMap["Notice"] = ""
common.OptionMap["About"] = ""
common.OptionMap["HomePageContent"] = ""
@@ -88,6 +90,22 @@ func InitOptionMap() {
common.OptionMap["CreemProducts"] = setting.CreemProducts
common.OptionMap["CreemTestMode"] = strconv.FormatBool(setting.CreemTestMode)
common.OptionMap["CreemWebhookSecret"] = setting.CreemWebhookSecret
+ common.OptionMap["WaffoEnabled"] = strconv.FormatBool(setting.WaffoEnabled)
+ common.OptionMap["WaffoApiKey"] = setting.WaffoApiKey
+ common.OptionMap["WaffoPrivateKey"] = setting.WaffoPrivateKey
+ common.OptionMap["WaffoPublicCert"] = setting.WaffoPublicCert
+ common.OptionMap["WaffoSandboxPublicCert"] = setting.WaffoSandboxPublicCert
+ common.OptionMap["WaffoSandboxApiKey"] = setting.WaffoSandboxApiKey
+ common.OptionMap["WaffoSandboxPrivateKey"] = setting.WaffoSandboxPrivateKey
+ common.OptionMap["WaffoSandbox"] = strconv.FormatBool(setting.WaffoSandbox)
+ common.OptionMap["WaffoMerchantId"] = setting.WaffoMerchantId
+ common.OptionMap["WaffoNotifyUrl"] = setting.WaffoNotifyUrl
+ common.OptionMap["WaffoReturnUrl"] = setting.WaffoReturnUrl
+ common.OptionMap["WaffoSubscriptionReturnUrl"] = setting.WaffoSubscriptionReturnUrl
+ common.OptionMap["WaffoCurrency"] = setting.WaffoCurrency
+ common.OptionMap["WaffoUnitPrice"] = strconv.FormatFloat(setting.WaffoUnitPrice, 'f', -1, 64)
+ common.OptionMap["WaffoMinTopUp"] = strconv.Itoa(setting.WaffoMinTopUp)
+ common.OptionMap["WaffoPayMethods"] = setting.WaffoPayMethods2JsonString()
common.OptionMap["TopupGroupRatio"] = common.TopupGroupRatio2JSONString()
common.OptionMap["Chats"] = setting.Chats2JsonString()
common.OptionMap["AutoGroups"] = setting.AutoGroups2JsonString()
@@ -114,6 +132,7 @@ func InitOptionMap() {
common.OptionMap["ModelRatio"] = ratio_setting.ModelRatio2JSONString()
common.OptionMap["ModelPrice"] = ratio_setting.ModelPrice2JSONString()
common.OptionMap["CacheRatio"] = ratio_setting.CacheRatio2JSONString()
+ common.OptionMap["CreateCacheRatio"] = ratio_setting.CreateCacheRatio2JSONString()
common.OptionMap["GroupRatio"] = ratio_setting.GroupRatio2JSONString()
common.OptionMap["GroupGroupRatio"] = ratio_setting.GroupGroupRatio2JSONString()
common.OptionMap["UserUsableGroups"] = setting.UserUsableGroups2JSONString()
@@ -215,7 +234,7 @@ func updateOptionMap(key string, value string) (err error) {
common.ImageDownloadPermission = intValue
}
}
- if strings.HasSuffix(key, "Enabled") || key == "DefaultCollapseSidebar" || key == "DefaultUseAutoGroup" {
+ if strings.HasSuffix(key, "Enabled") || key == "DefaultCollapseSidebar" || key == "DefaultUseAutoGroup" || key == "SMTPForceAuthLogin" {
boolValue := value == "true"
switch key {
case "PasswordRegisterEnabled":
@@ -290,6 +309,8 @@ func updateOptionMap(key string, value string) (err error) {
setting.StopOnSensitiveEnabled = boolValue
case "SMTPSSLEnabled":
common.SMTPSSLEnabled = boolValue
+ case "SMTPForceAuthLogin":
+ common.SMTPForceAuthLogin = boolValue
case "WorkerAllowHttpImageRequestEnabled":
system_setting.WorkerAllowHttpImageRequestEnabled = boolValue
case "DefaultUseAutoGroup":
@@ -356,6 +377,36 @@ func updateOptionMap(key string, value string) (err error) {
setting.CreemTestMode = value == "true"
case "CreemWebhookSecret":
setting.CreemWebhookSecret = value
+ case "WaffoEnabled":
+ setting.WaffoEnabled = value == "true"
+ case "WaffoApiKey":
+ setting.WaffoApiKey = value
+ case "WaffoPrivateKey":
+ setting.WaffoPrivateKey = value
+ case "WaffoPublicCert":
+ setting.WaffoPublicCert = value
+ case "WaffoSandboxPublicCert":
+ setting.WaffoSandboxPublicCert = value
+ case "WaffoSandboxApiKey":
+ setting.WaffoSandboxApiKey = value
+ case "WaffoSandboxPrivateKey":
+ setting.WaffoSandboxPrivateKey = value
+ case "WaffoSandbox":
+ setting.WaffoSandbox = value == "true"
+ case "WaffoMerchantId":
+ setting.WaffoMerchantId = value
+ case "WaffoNotifyUrl":
+ setting.WaffoNotifyUrl = value
+ case "WaffoReturnUrl":
+ setting.WaffoReturnUrl = value
+ case "WaffoSubscriptionReturnUrl":
+ setting.WaffoSubscriptionReturnUrl = value
+ case "WaffoCurrency":
+ setting.WaffoCurrency = value
+ case "WaffoUnitPrice":
+ setting.WaffoUnitPrice, _ = strconv.ParseFloat(value, 64)
+ case "WaffoMinTopUp":
+ setting.WaffoMinTopUp, _ = strconv.Atoi(value)
case "TopupGroupRatio":
err = common.UpdateTopupGroupRatioByJSONString(value)
case "GitHubClientId":
@@ -426,6 +477,8 @@ func updateOptionMap(key string, value string) (err error) {
err = ratio_setting.UpdateModelPriceByJSONString(value)
case "CacheRatio":
err = ratio_setting.UpdateCacheRatioByJSONString(value)
+ case "CreateCacheRatio":
+ err = ratio_setting.UpdateCreateCacheRatioByJSONString(value)
case "ImageRatio":
err = ratio_setting.UpdateImageRatioByJSONString(value)
case "AudioRatio":
@@ -454,6 +507,10 @@ func updateOptionMap(key string, value string) (err error) {
setting.StreamCacheQueueLength, _ = strconv.Atoi(value)
case "PayMethods":
err = operation_setting.UpdatePayMethodsByJsonString(value)
+ case "WaffoPayMethods":
+ // WaffoPayMethods is read directly from OptionMap via setting.GetWaffoPayMethods().
+ // The value is already stored in OptionMap at the top of this function (line: common.OptionMap[key] = value).
+ // No additional in-memory variable to update.
}
return err
}
@@ -480,5 +537,11 @@ func handleConfigUpdate(key, value string) bool {
}
config.UpdateConfigFromMap(cfg, configMap)
+ // 特定配置的后处理
+ if configName == "performance_setting" {
+ // 同步磁盘缓存配置到 common 包
+ performance_setting.UpdateAndSync()
+ }
+
return true // 已处理
}
diff --git a/model/pricing.go b/model/pricing.go
index d56068a10d..54ae984513 100644
--- a/model/pricing.go
+++ b/model/pricing.go
@@ -25,8 +25,14 @@ type Pricing struct {
ModelPrice float64 `json:"model_price"`
OwnerBy string `json:"owner_by"`
CompletionRatio float64 `json:"completion_ratio"`
+ CacheRatio *float64 `json:"cache_ratio,omitempty"`
+ CreateCacheRatio *float64 `json:"create_cache_ratio,omitempty"`
+ ImageRatio *float64 `json:"image_ratio,omitempty"`
+ AudioRatio *float64 `json:"audio_ratio,omitempty"`
+ AudioCompletionRatio *float64 `json:"audio_completion_ratio,omitempty"`
EnableGroup []string `json:"enable_groups"`
SupportedEndpointTypes []constant.EndpointType `json:"supported_endpoint_types"`
+ PricingVersion string `json:"pricing_version,omitempty"`
}
type PricingVendor struct {
@@ -196,20 +202,25 @@ func updatePricing() {
modelSupportEndpointsStr[ability.Model] = endpoints
}
- // 再补充模型自定义端点
+ // 再补充模型自定义端点:若配置有效则替换默认端点,不做合并
for modelName, meta := range metaMap {
if strings.TrimSpace(meta.Endpoints) == "" {
continue
}
var raw map[string]interface{}
if err := json.Unmarshal([]byte(meta.Endpoints), &raw); err == nil {
- endpoints := modelSupportEndpointsStr[modelName]
- for k := range raw {
- if !common.StringsContains(endpoints, k) {
- endpoints = append(endpoints, k)
+ endpoints := make([]string, 0, len(raw))
+ for k, v := range raw {
+ switch v.(type) {
+ case string, map[string]interface{}:
+ if !common.StringsContains(endpoints, k) {
+ endpoints = append(endpoints, k)
+ }
}
}
- modelSupportEndpointsStr[modelName] = endpoints
+ if len(endpoints) > 0 {
+ modelSupportEndpointsStr[modelName] = endpoints
+ }
}
}
@@ -291,9 +302,31 @@ func updatePricing() {
pricing.CompletionRatio = ratio_setting.GetCompletionRatio(model)
pricing.QuotaType = 0
}
+ if cacheRatio, ok := ratio_setting.GetCacheRatio(model); ok {
+ pricing.CacheRatio = &cacheRatio
+ }
+ if createCacheRatio, ok := ratio_setting.GetCreateCacheRatio(model); ok {
+ pricing.CreateCacheRatio = &createCacheRatio
+ }
+ if imageRatio, ok := ratio_setting.GetImageRatio(model); ok {
+ pricing.ImageRatio = &imageRatio
+ }
+ if ratio_setting.ContainsAudioRatio(model) {
+ audioRatio := ratio_setting.GetAudioRatio(model)
+ pricing.AudioRatio = &audioRatio
+ }
+ if ratio_setting.ContainsAudioCompletionRatio(model) {
+ audioCompletionRatio := ratio_setting.GetAudioCompletionRatio(model)
+ pricing.AudioCompletionRatio = &audioCompletionRatio
+ }
pricingMap = append(pricingMap, pricing)
}
+ // 防止大更新后数据不通用
+ if len(pricingMap) > 0 {
+ pricingMap[0].PricingVersion = "5a90f2b86c08bd983a9a2e6d66c255f4eaef9c4bc934386d2b6ae84ef0ff1f1f"
+ }
+
// 刷新缓存映射,供高并发快速查询
modelEnableGroupsLock.Lock()
modelEnableGroups = make(map[string][]string)
diff --git a/model/redemption.go b/model/redemption.go
index 7dd2d95272..378976a368 100644
--- a/model/redemption.go
+++ b/model/redemption.go
@@ -11,6 +11,9 @@ import (
"gorm.io/gorm"
)
+// ErrRedeemFailed is returned when redemption fails due to database error
+var ErrRedeemFailed = errors.New("redeem.failed")
+
type Redemption struct {
Id int `json:"id"`
UserId int `json:"user_id"`
@@ -148,7 +151,8 @@ func Redeem(key string, userId int) (quota int, err error) {
return err
})
if err != nil {
- return 0, errors.New("兑换失败," + err.Error())
+ common.SysError("redemption failed: " + err.Error())
+ return 0, ErrRedeemFailed
}
RecordLog(userId, LogTypeTopup, fmt.Sprintf("通过兑换码充值 %s,兑换码ID %d", logger.LogQuota(redemption.Quota), redemption.Id))
return redemption.Quota, nil
diff --git a/model/subscription.go b/model/subscription.go
new file mode 100644
index 0000000000..2d23a8b5bf
--- /dev/null
+++ b/model/subscription.go
@@ -0,0 +1,1192 @@
+package model
+
+import (
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/pkg/cachex"
+ "github.com/samber/hot"
+ "gorm.io/gorm"
+)
+
+// Subscription duration units
+const (
+ SubscriptionDurationYear = "year"
+ SubscriptionDurationMonth = "month"
+ SubscriptionDurationDay = "day"
+ SubscriptionDurationHour = "hour"
+ SubscriptionDurationCustom = "custom"
+)
+
+// Subscription quota reset period
+const (
+ SubscriptionResetNever = "never"
+ SubscriptionResetDaily = "daily"
+ SubscriptionResetWeekly = "weekly"
+ SubscriptionResetMonthly = "monthly"
+ SubscriptionResetCustom = "custom"
+)
+
+var (
+ ErrSubscriptionOrderNotFound = errors.New("subscription order not found")
+ ErrSubscriptionOrderStatusInvalid = errors.New("subscription order status invalid")
+)
+
+const (
+ subscriptionPlanCacheNamespace = "new-api:subscription_plan:v1"
+ subscriptionPlanInfoCacheNamespace = "new-api:subscription_plan_info:v1"
+)
+
+var (
+ subscriptionPlanCacheOnce sync.Once
+ subscriptionPlanInfoCacheOnce sync.Once
+
+ subscriptionPlanCache *cachex.HybridCache[SubscriptionPlan]
+ subscriptionPlanInfoCache *cachex.HybridCache[SubscriptionPlanInfo]
+)
+
+func subscriptionPlanCacheTTL() time.Duration {
+ ttlSeconds := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_CACHE_TTL", 300)
+ if ttlSeconds <= 0 {
+ ttlSeconds = 300
+ }
+ return time.Duration(ttlSeconds) * time.Second
+}
+
+func subscriptionPlanInfoCacheTTL() time.Duration {
+ ttlSeconds := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_INFO_CACHE_TTL", 120)
+ if ttlSeconds <= 0 {
+ ttlSeconds = 120
+ }
+ return time.Duration(ttlSeconds) * time.Second
+}
+
+func subscriptionPlanCacheCapacity() int {
+ capacity := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_CACHE_CAP", 5000)
+ if capacity <= 0 {
+ capacity = 5000
+ }
+ return capacity
+}
+
+func subscriptionPlanInfoCacheCapacity() int {
+ capacity := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_INFO_CACHE_CAP", 10000)
+ if capacity <= 0 {
+ capacity = 10000
+ }
+ return capacity
+}
+
+func getSubscriptionPlanCache() *cachex.HybridCache[SubscriptionPlan] {
+ subscriptionPlanCacheOnce.Do(func() {
+ ttl := subscriptionPlanCacheTTL()
+ subscriptionPlanCache = cachex.NewHybridCache[SubscriptionPlan](cachex.HybridCacheConfig[SubscriptionPlan]{
+ Namespace: cachex.Namespace(subscriptionPlanCacheNamespace),
+ Redis: common.RDB,
+ RedisEnabled: func() bool {
+ return common.RedisEnabled && common.RDB != nil
+ },
+ RedisCodec: cachex.JSONCodec[SubscriptionPlan]{},
+ Memory: func() *hot.HotCache[string, SubscriptionPlan] {
+ return hot.NewHotCache[string, SubscriptionPlan](hot.LRU, subscriptionPlanCacheCapacity()).
+ WithTTL(ttl).
+ WithJanitor().
+ Build()
+ },
+ })
+ })
+ return subscriptionPlanCache
+}
+
+func getSubscriptionPlanInfoCache() *cachex.HybridCache[SubscriptionPlanInfo] {
+ subscriptionPlanInfoCacheOnce.Do(func() {
+ ttl := subscriptionPlanInfoCacheTTL()
+ subscriptionPlanInfoCache = cachex.NewHybridCache[SubscriptionPlanInfo](cachex.HybridCacheConfig[SubscriptionPlanInfo]{
+ Namespace: cachex.Namespace(subscriptionPlanInfoCacheNamespace),
+ Redis: common.RDB,
+ RedisEnabled: func() bool {
+ return common.RedisEnabled && common.RDB != nil
+ },
+ RedisCodec: cachex.JSONCodec[SubscriptionPlanInfo]{},
+ Memory: func() *hot.HotCache[string, SubscriptionPlanInfo] {
+ return hot.NewHotCache[string, SubscriptionPlanInfo](hot.LRU, subscriptionPlanInfoCacheCapacity()).
+ WithTTL(ttl).
+ WithJanitor().
+ Build()
+ },
+ })
+ })
+ return subscriptionPlanInfoCache
+}
+
+func subscriptionPlanCacheKey(id int) string {
+ if id <= 0 {
+ return ""
+ }
+ return strconv.Itoa(id)
+}
+
+func InvalidateSubscriptionPlanCache(planId int) {
+ if planId <= 0 {
+ return
+ }
+ cache := getSubscriptionPlanCache()
+ _, _ = cache.DeleteMany([]string{subscriptionPlanCacheKey(planId)})
+ infoCache := getSubscriptionPlanInfoCache()
+ _ = infoCache.Purge()
+}
+
+// Subscription plan
+type SubscriptionPlan struct {
+ Id int `json:"id"`
+
+ Title string `json:"title" gorm:"type:varchar(128);not null"`
+ Subtitle string `json:"subtitle" gorm:"type:varchar(255);default:''"`
+
+ // Display money amount (follow existing code style: float64 for money)
+ PriceAmount float64 `json:"price_amount" gorm:"type:decimal(10,6);not null;default:0"`
+ Currency string `json:"currency" gorm:"type:varchar(8);not null;default:'USD'"`
+
+ DurationUnit string `json:"duration_unit" gorm:"type:varchar(16);not null;default:'month'"`
+ DurationValue int `json:"duration_value" gorm:"type:int;not null;default:1"`
+ CustomSeconds int64 `json:"custom_seconds" gorm:"type:bigint;not null;default:0"`
+
+ Enabled bool `json:"enabled" gorm:"default:true"`
+ SortOrder int `json:"sort_order" gorm:"type:int;default:0"`
+
+ StripePriceId string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"`
+ CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"`
+
+ // Max purchases per user (0 = unlimited)
+ MaxPurchasePerUser int `json:"max_purchase_per_user" gorm:"type:int;default:0"`
+
+ // Upgrade user group after purchase (empty = no change)
+ UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
+
+ // Total quota (amount in quota units, 0 = unlimited)
+ TotalAmount int64 `json:"total_amount" gorm:"type:bigint;not null;default:0"`
+
+ // Quota reset period for plan
+ QuotaResetPeriod string `json:"quota_reset_period" gorm:"type:varchar(16);default:'never'"`
+ QuotaResetCustomSeconds int64 `json:"quota_reset_custom_seconds" gorm:"type:bigint;default:0"`
+
+ CreatedAt int64 `json:"created_at" gorm:"bigint"`
+ UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
+}
+
+func (p *SubscriptionPlan) BeforeCreate(tx *gorm.DB) error {
+ now := common.GetTimestamp()
+ p.CreatedAt = now
+ p.UpdatedAt = now
+ return nil
+}
+
+func (p *SubscriptionPlan) BeforeUpdate(tx *gorm.DB) error {
+ p.UpdatedAt = common.GetTimestamp()
+ return nil
+}
+
+// Subscription order (payment -> webhook -> create UserSubscription)
+type SubscriptionOrder struct {
+ Id int `json:"id"`
+ UserId int `json:"user_id" gorm:"index"`
+ PlanId int `json:"plan_id" gorm:"index"`
+ Money float64 `json:"money"`
+
+ TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
+ PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
+ Status string `json:"status"`
+ CreateTime int64 `json:"create_time"`
+ CompleteTime int64 `json:"complete_time"`
+
+ ProviderPayload string `json:"provider_payload" gorm:"type:text"`
+}
+
+func (o *SubscriptionOrder) Insert() error {
+ if o.CreateTime == 0 {
+ o.CreateTime = common.GetTimestamp()
+ }
+ return DB.Create(o).Error
+}
+
+func (o *SubscriptionOrder) Update() error {
+ return DB.Save(o).Error
+}
+
+func GetSubscriptionOrderByTradeNo(tradeNo string) *SubscriptionOrder {
+ if tradeNo == "" {
+ return nil
+ }
+ var order SubscriptionOrder
+ if err := DB.Where("trade_no = ?", tradeNo).First(&order).Error; err != nil {
+ return nil
+ }
+ return &order
+}
+
+// User subscription instance
+type UserSubscription struct {
+ Id int `json:"id"`
+ UserId int `json:"user_id" gorm:"index;index:idx_user_sub_active,priority:1"`
+ PlanId int `json:"plan_id" gorm:"index"`
+
+ AmountTotal int64 `json:"amount_total" gorm:"type:bigint;not null;default:0"`
+ AmountUsed int64 `json:"amount_used" gorm:"type:bigint;not null;default:0"`
+
+ StartTime int64 `json:"start_time" gorm:"bigint"`
+ EndTime int64 `json:"end_time" gorm:"bigint;index;index:idx_user_sub_active,priority:3"`
+ Status string `json:"status" gorm:"type:varchar(32);index;index:idx_user_sub_active,priority:2"` // active/expired/cancelled
+
+ Source string `json:"source" gorm:"type:varchar(32);default:'order'"` // order/admin
+
+ LastResetTime int64 `json:"last_reset_time" gorm:"type:bigint;default:0"`
+ NextResetTime int64 `json:"next_reset_time" gorm:"type:bigint;default:0;index"`
+
+ UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
+ PrevUserGroup string `json:"prev_user_group" gorm:"type:varchar(64);default:''"`
+
+ CreatedAt int64 `json:"created_at" gorm:"bigint"`
+ UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
+}
+
+func (s *UserSubscription) BeforeCreate(tx *gorm.DB) error {
+ now := common.GetTimestamp()
+ s.CreatedAt = now
+ s.UpdatedAt = now
+ return nil
+}
+
+func (s *UserSubscription) BeforeUpdate(tx *gorm.DB) error {
+ s.UpdatedAt = common.GetTimestamp()
+ return nil
+}
+
+type SubscriptionSummary struct {
+ Subscription *UserSubscription `json:"subscription"`
+}
+
+func calcPlanEndTime(start time.Time, plan *SubscriptionPlan) (int64, error) {
+ if plan == nil {
+ return 0, errors.New("plan is nil")
+ }
+ if plan.DurationValue <= 0 && plan.DurationUnit != SubscriptionDurationCustom {
+ return 0, errors.New("duration_value must be > 0")
+ }
+ switch plan.DurationUnit {
+ case SubscriptionDurationYear:
+ return start.AddDate(plan.DurationValue, 0, 0).Unix(), nil
+ case SubscriptionDurationMonth:
+ return start.AddDate(0, plan.DurationValue, 0).Unix(), nil
+ case SubscriptionDurationDay:
+ return start.Add(time.Duration(plan.DurationValue) * 24 * time.Hour).Unix(), nil
+ case SubscriptionDurationHour:
+ return start.Add(time.Duration(plan.DurationValue) * time.Hour).Unix(), nil
+ case SubscriptionDurationCustom:
+ if plan.CustomSeconds <= 0 {
+ return 0, errors.New("custom_seconds must be > 0")
+ }
+ return start.Add(time.Duration(plan.CustomSeconds) * time.Second).Unix(), nil
+ default:
+ return 0, fmt.Errorf("invalid duration_unit: %s", plan.DurationUnit)
+ }
+}
+
+func NormalizeResetPeriod(period string) string {
+ switch strings.TrimSpace(period) {
+ case SubscriptionResetDaily, SubscriptionResetWeekly, SubscriptionResetMonthly, SubscriptionResetCustom:
+ return strings.TrimSpace(period)
+ default:
+ return SubscriptionResetNever
+ }
+}
+
+func calcNextResetTime(base time.Time, plan *SubscriptionPlan, endUnix int64) int64 {
+ if plan == nil {
+ return 0
+ }
+ period := NormalizeResetPeriod(plan.QuotaResetPeriod)
+ if period == SubscriptionResetNever {
+ return 0
+ }
+ var next time.Time
+ switch period {
+ case SubscriptionResetDaily:
+ next = time.Date(base.Year(), base.Month(), base.Day(), 0, 0, 0, 0, base.Location()).
+ AddDate(0, 0, 1)
+ case SubscriptionResetWeekly:
+ // Align to next Monday 00:00
+ weekday := int(base.Weekday()) // Sunday=0
+ // Convert to Monday=1..Sunday=7
+ if weekday == 0 {
+ weekday = 7
+ }
+ daysUntil := 8 - weekday
+ next = time.Date(base.Year(), base.Month(), base.Day(), 0, 0, 0, 0, base.Location()).
+ AddDate(0, 0, daysUntil)
+ case SubscriptionResetMonthly:
+ // Align to first day of next month 00:00
+ next = time.Date(base.Year(), base.Month(), 1, 0, 0, 0, 0, base.Location()).
+ AddDate(0, 1, 0)
+ case SubscriptionResetCustom:
+ if plan.QuotaResetCustomSeconds <= 0 {
+ return 0
+ }
+ next = base.Add(time.Duration(plan.QuotaResetCustomSeconds) * time.Second)
+ default:
+ return 0
+ }
+ if endUnix > 0 && next.Unix() > endUnix {
+ return 0
+ }
+ return next.Unix()
+}
+
+func GetSubscriptionPlanById(id int) (*SubscriptionPlan, error) {
+ return getSubscriptionPlanByIdTx(nil, id)
+}
+
+func getSubscriptionPlanByIdTx(tx *gorm.DB, id int) (*SubscriptionPlan, error) {
+ if id <= 0 {
+ return nil, errors.New("invalid plan id")
+ }
+ key := subscriptionPlanCacheKey(id)
+ if key != "" {
+ if cached, found, err := getSubscriptionPlanCache().Get(key); err == nil && found {
+ return &cached, nil
+ }
+ }
+ var plan SubscriptionPlan
+ query := DB
+ if tx != nil {
+ query = tx
+ }
+ if err := query.Where("id = ?", id).First(&plan).Error; err != nil {
+ return nil, err
+ }
+ _ = getSubscriptionPlanCache().SetWithTTL(key, plan, subscriptionPlanCacheTTL())
+ return &plan, nil
+}
+
+func CountUserSubscriptionsByPlan(userId int, planId int) (int64, error) {
+ if userId <= 0 || planId <= 0 {
+ return 0, errors.New("invalid userId or planId")
+ }
+ var count int64
+ if err := DB.Model(&UserSubscription{}).
+ Where("user_id = ? AND plan_id = ?", userId, planId).
+ Count(&count).Error; err != nil {
+ return 0, err
+ }
+ return count, nil
+}
+
+func getUserGroupByIdTx(tx *gorm.DB, userId int) (string, error) {
+ if userId <= 0 {
+ return "", errors.New("invalid userId")
+ }
+ if tx == nil {
+ tx = DB
+ }
+ var group string
+ if err := tx.Model(&User{}).Where("id = ?", userId).Select(commonGroupCol).Find(&group).Error; err != nil {
+ return "", err
+ }
+ return group, nil
+}
+
+func downgradeUserGroupForSubscriptionTx(tx *gorm.DB, sub *UserSubscription, now int64) (string, error) {
+ if tx == nil || sub == nil {
+ return "", errors.New("invalid downgrade args")
+ }
+ upgradeGroup := strings.TrimSpace(sub.UpgradeGroup)
+ if upgradeGroup == "" {
+ return "", nil
+ }
+ currentGroup, err := getUserGroupByIdTx(tx, sub.UserId)
+ if err != nil {
+ return "", err
+ }
+ if currentGroup != upgradeGroup {
+ return "", nil
+ }
+ var activeSub UserSubscription
+ activeQuery := tx.Where("user_id = ? AND status = ? AND end_time > ? AND id <> ? AND upgrade_group <> ''",
+ sub.UserId, "active", now, sub.Id).
+ Order("end_time desc, id desc").
+ Limit(1).
+ Find(&activeSub)
+ if activeQuery.Error == nil && activeQuery.RowsAffected > 0 {
+ return "", nil
+ }
+ prevGroup := strings.TrimSpace(sub.PrevUserGroup)
+ if prevGroup == "" || prevGroup == currentGroup {
+ return "", nil
+ }
+ if err := tx.Model(&User{}).Where("id = ?", sub.UserId).
+ Update("group", prevGroup).Error; err != nil {
+ return "", err
+ }
+ return prevGroup, nil
+}
+
+func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *SubscriptionPlan, source string) (*UserSubscription, error) {
+ if tx == nil {
+ return nil, errors.New("tx is nil")
+ }
+ if plan == nil || plan.Id == 0 {
+ return nil, errors.New("invalid plan")
+ }
+ if userId <= 0 {
+ return nil, errors.New("invalid user id")
+ }
+ if plan.MaxPurchasePerUser > 0 {
+ var count int64
+ if err := tx.Model(&UserSubscription{}).
+ Where("user_id = ? AND plan_id = ?", userId, plan.Id).
+ Count(&count).Error; err != nil {
+ return nil, err
+ }
+ if count >= int64(plan.MaxPurchasePerUser) {
+ return nil, errors.New("已达到该套餐购买上限")
+ }
+ }
+ nowUnix := GetDBTimestamp()
+ now := time.Unix(nowUnix, 0)
+ endUnix, err := calcPlanEndTime(now, plan)
+ if err != nil {
+ return nil, err
+ }
+ resetBase := now
+ nextReset := calcNextResetTime(resetBase, plan, endUnix)
+ lastReset := int64(0)
+ if nextReset > 0 {
+ lastReset = now.Unix()
+ }
+ upgradeGroup := strings.TrimSpace(plan.UpgradeGroup)
+ prevGroup := ""
+ if upgradeGroup != "" {
+ currentGroup, err := getUserGroupByIdTx(tx, userId)
+ if err != nil {
+ return nil, err
+ }
+ if currentGroup != upgradeGroup {
+ prevGroup = currentGroup
+ if err := tx.Model(&User{}).Where("id = ?", userId).
+ Update("group", upgradeGroup).Error; err != nil {
+ return nil, err
+ }
+ }
+ }
+ sub := &UserSubscription{
+ UserId: userId,
+ PlanId: plan.Id,
+ AmountTotal: plan.TotalAmount,
+ AmountUsed: 0,
+ StartTime: now.Unix(),
+ EndTime: endUnix,
+ Status: "active",
+ Source: source,
+ LastResetTime: lastReset,
+ NextResetTime: nextReset,
+ UpgradeGroup: upgradeGroup,
+ PrevUserGroup: prevGroup,
+ CreatedAt: common.GetTimestamp(),
+ UpdatedAt: common.GetTimestamp(),
+ }
+ if err := tx.Create(sub).Error; err != nil {
+ return nil, err
+ }
+ return sub, nil
+}
+
+// Complete a subscription order (idempotent). Creates a UserSubscription snapshot from the plan.
+func CompleteSubscriptionOrder(tradeNo string, providerPayload string) error {
+ if tradeNo == "" {
+ return errors.New("tradeNo is empty")
+ }
+ refCol := "`trade_no`"
+ if common.UsingPostgreSQL {
+ refCol = `"trade_no"`
+ }
+ var logUserId int
+ var logPlanTitle string
+ var logMoney float64
+ var logPaymentMethod string
+ var upgradeGroup string
+ err := DB.Transaction(func(tx *gorm.DB) error {
+ var order SubscriptionOrder
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(&order).Error; err != nil {
+ return ErrSubscriptionOrderNotFound
+ }
+ if order.Status == common.TopUpStatusSuccess {
+ return nil
+ }
+ if order.Status != common.TopUpStatusPending {
+ return ErrSubscriptionOrderStatusInvalid
+ }
+ plan, err := GetSubscriptionPlanById(order.PlanId)
+ if err != nil {
+ return err
+ }
+ if !plan.Enabled {
+ // still allow completion for already purchased orders
+ }
+ upgradeGroup = strings.TrimSpace(plan.UpgradeGroup)
+ _, err = CreateUserSubscriptionFromPlanTx(tx, order.UserId, plan, "order")
+ if err != nil {
+ return err
+ }
+ if err := upsertSubscriptionTopUpTx(tx, &order); err != nil {
+ return err
+ }
+ order.Status = common.TopUpStatusSuccess
+ order.CompleteTime = common.GetTimestamp()
+ if providerPayload != "" {
+ order.ProviderPayload = providerPayload
+ }
+ if err := tx.Save(&order).Error; err != nil {
+ return err
+ }
+ logUserId = order.UserId
+ logPlanTitle = plan.Title
+ logMoney = order.Money
+ logPaymentMethod = order.PaymentMethod
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ if upgradeGroup != "" && logUserId > 0 {
+ _ = UpdateUserGroupCache(logUserId, upgradeGroup)
+ }
+ if logUserId > 0 {
+ msg := fmt.Sprintf("订阅购买成功,套餐: %s,支付金额: %.2f,支付方式: %s", logPlanTitle, logMoney, logPaymentMethod)
+ RecordLog(logUserId, LogTypeTopup, msg)
+ }
+ return nil
+}
+
+func upsertSubscriptionTopUpTx(tx *gorm.DB, order *SubscriptionOrder) error {
+ if tx == nil || order == nil {
+ return errors.New("invalid subscription order")
+ }
+ now := common.GetTimestamp()
+ var topup TopUp
+ if err := tx.Where("trade_no = ?", order.TradeNo).First(&topup).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ topup = TopUp{
+ UserId: order.UserId,
+ Amount: 0,
+ Money: order.Money,
+ TradeNo: order.TradeNo,
+ PaymentMethod: order.PaymentMethod,
+ CreateTime: order.CreateTime,
+ CompleteTime: now,
+ Status: common.TopUpStatusSuccess,
+ }
+ return tx.Create(&topup).Error
+ }
+ return err
+ }
+ topup.Money = order.Money
+ if topup.PaymentMethod == "" {
+ topup.PaymentMethod = order.PaymentMethod
+ }
+ if topup.CreateTime == 0 {
+ topup.CreateTime = order.CreateTime
+ }
+ topup.CompleteTime = now
+ topup.Status = common.TopUpStatusSuccess
+ return tx.Save(&topup).Error
+}
+
+func ExpireSubscriptionOrder(tradeNo string) error {
+ if tradeNo == "" {
+ return errors.New("tradeNo is empty")
+ }
+ refCol := "`trade_no`"
+ if common.UsingPostgreSQL {
+ refCol = `"trade_no"`
+ }
+ return DB.Transaction(func(tx *gorm.DB) error {
+ var order SubscriptionOrder
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(&order).Error; err != nil {
+ return ErrSubscriptionOrderNotFound
+ }
+ if order.Status != common.TopUpStatusPending {
+ return nil
+ }
+ order.Status = common.TopUpStatusExpired
+ order.CompleteTime = common.GetTimestamp()
+ return tx.Save(&order).Error
+ })
+}
+
+// Admin bind (no payment). Creates a UserSubscription from a plan.
+func AdminBindSubscription(userId int, planId int, sourceNote string) (string, error) {
+ if userId <= 0 || planId <= 0 {
+ return "", errors.New("invalid userId or planId")
+ }
+ plan, err := GetSubscriptionPlanById(planId)
+ if err != nil {
+ return "", err
+ }
+ err = DB.Transaction(func(tx *gorm.DB) error {
+ _, err := CreateUserSubscriptionFromPlanTx(tx, userId, plan, "admin")
+ return err
+ })
+ if err != nil {
+ return "", err
+ }
+ if strings.TrimSpace(plan.UpgradeGroup) != "" {
+ _ = UpdateUserGroupCache(userId, plan.UpgradeGroup)
+ return fmt.Sprintf("用户分组将升级到 %s", plan.UpgradeGroup), nil
+ }
+ return "", nil
+}
+
+// GetAllActiveUserSubscriptions returns all active subscriptions for a user.
+func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error) {
+ if userId <= 0 {
+ return nil, errors.New("invalid userId")
+ }
+ now := common.GetTimestamp()
+ var subs []UserSubscription
+ err := DB.Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
+ Order("end_time desc, id desc").
+ Find(&subs).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildSubscriptionSummaries(subs), nil
+}
+
+// HasActiveUserSubscription returns whether the user has any active subscription.
+// This is a lightweight existence check to avoid heavy pre-consume transactions.
+func HasActiveUserSubscription(userId int) (bool, error) {
+ if userId <= 0 {
+ return false, errors.New("invalid userId")
+ }
+ now := common.GetTimestamp()
+ var count int64
+ if err := DB.Model(&UserSubscription{}).
+ Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
+ Count(&count).Error; err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+// GetAllUserSubscriptions returns all subscriptions (active and expired) for a user.
+func GetAllUserSubscriptions(userId int) ([]SubscriptionSummary, error) {
+ if userId <= 0 {
+ return nil, errors.New("invalid userId")
+ }
+ var subs []UserSubscription
+ err := DB.Where("user_id = ?", userId).
+ Order("end_time desc, id desc").
+ Find(&subs).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildSubscriptionSummaries(subs), nil
+}
+
+func buildSubscriptionSummaries(subs []UserSubscription) []SubscriptionSummary {
+ if len(subs) == 0 {
+ return []SubscriptionSummary{}
+ }
+ result := make([]SubscriptionSummary, 0, len(subs))
+ for _, sub := range subs {
+ subCopy := sub
+ result = append(result, SubscriptionSummary{
+ Subscription: &subCopy,
+ })
+ }
+ return result
+}
+
+// AdminInvalidateUserSubscription marks a user subscription as cancelled and ends it immediately.
+func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error) {
+ if userSubscriptionId <= 0 {
+ return "", errors.New("invalid userSubscriptionId")
+ }
+ now := common.GetTimestamp()
+ cacheGroup := ""
+ downgradeGroup := ""
+ var userId int
+ err := DB.Transaction(func(tx *gorm.DB) error {
+ var sub UserSubscription
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
+ return err
+ }
+ userId = sub.UserId
+ if err := tx.Model(&sub).Updates(map[string]interface{}{
+ "status": "cancelled",
+ "end_time": now,
+ "updated_at": now,
+ }).Error; err != nil {
+ return err
+ }
+ target, err := downgradeUserGroupForSubscriptionTx(tx, &sub, now)
+ if err != nil {
+ return err
+ }
+ if target != "" {
+ cacheGroup = target
+ downgradeGroup = target
+ }
+ return nil
+ })
+ if err != nil {
+ return "", err
+ }
+ if cacheGroup != "" && userId > 0 {
+ _ = UpdateUserGroupCache(userId, cacheGroup)
+ }
+ if downgradeGroup != "" {
+ return fmt.Sprintf("用户分组将回退到 %s", downgradeGroup), nil
+ }
+ return "", nil
+}
+
+// AdminDeleteUserSubscription hard-deletes a user subscription.
+func AdminDeleteUserSubscription(userSubscriptionId int) (string, error) {
+ if userSubscriptionId <= 0 {
+ return "", errors.New("invalid userSubscriptionId")
+ }
+ now := common.GetTimestamp()
+ cacheGroup := ""
+ downgradeGroup := ""
+ var userId int
+ err := DB.Transaction(func(tx *gorm.DB) error {
+ var sub UserSubscription
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
+ return err
+ }
+ userId = sub.UserId
+ target, err := downgradeUserGroupForSubscriptionTx(tx, &sub, now)
+ if err != nil {
+ return err
+ }
+ if target != "" {
+ cacheGroup = target
+ downgradeGroup = target
+ }
+ if err := tx.Where("id = ?", userSubscriptionId).Delete(&UserSubscription{}).Error; err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return "", err
+ }
+ if cacheGroup != "" && userId > 0 {
+ _ = UpdateUserGroupCache(userId, cacheGroup)
+ }
+ if downgradeGroup != "" {
+ return fmt.Sprintf("用户分组将回退到 %s", downgradeGroup), nil
+ }
+ return "", nil
+}
+
+type SubscriptionPreConsumeResult struct {
+ UserSubscriptionId int
+ PreConsumed int64
+ AmountTotal int64
+ AmountUsedBefore int64
+ AmountUsedAfter int64
+}
+
+// ExpireDueSubscriptions marks expired subscriptions and handles group downgrade.
+func ExpireDueSubscriptions(limit int) (int, error) {
+ if limit <= 0 {
+ limit = 200
+ }
+ now := GetDBTimestamp()
+ var subs []UserSubscription
+ if err := DB.Where("status = ? AND end_time > 0 AND end_time <= ?", "active", now).
+ Order("end_time asc, id asc").
+ Limit(limit).
+ Find(&subs).Error; err != nil {
+ return 0, err
+ }
+ if len(subs) == 0 {
+ return 0, nil
+ }
+ expiredCount := 0
+ userIds := make(map[int]struct{}, len(subs))
+ for _, sub := range subs {
+ if sub.UserId > 0 {
+ userIds[sub.UserId] = struct{}{}
+ }
+ }
+ for userId := range userIds {
+ cacheGroup := ""
+ err := DB.Transaction(func(tx *gorm.DB) error {
+ res := tx.Model(&UserSubscription{}).
+ Where("user_id = ? AND status = ? AND end_time > 0 AND end_time <= ?", userId, "active", now).
+ Updates(map[string]interface{}{
+ "status": "expired",
+ "updated_at": common.GetTimestamp(),
+ })
+ if res.Error != nil {
+ return res.Error
+ }
+ expiredCount += int(res.RowsAffected)
+
+ // If there's an active upgraded subscription, keep current group.
+ var activeSub UserSubscription
+ activeQuery := tx.Where("user_id = ? AND status = ? AND end_time > ? AND upgrade_group <> ''",
+ userId, "active", now).
+ Order("end_time desc, id desc").
+ Limit(1).
+ Find(&activeSub)
+ if activeQuery.Error == nil && activeQuery.RowsAffected > 0 {
+ return nil
+ }
+
+ // No active upgraded subscription, downgrade to previous group if needed.
+ var lastExpired UserSubscription
+ expiredQuery := tx.Where("user_id = ? AND status = ? AND upgrade_group <> ''",
+ userId, "expired").
+ Order("end_time desc, id desc").
+ Limit(1).
+ Find(&lastExpired)
+ if expiredQuery.Error != nil || expiredQuery.RowsAffected == 0 {
+ return nil
+ }
+ upgradeGroup := strings.TrimSpace(lastExpired.UpgradeGroup)
+ prevGroup := strings.TrimSpace(lastExpired.PrevUserGroup)
+ if upgradeGroup == "" || prevGroup == "" {
+ return nil
+ }
+ currentGroup, err := getUserGroupByIdTx(tx, userId)
+ if err != nil {
+ return err
+ }
+ if currentGroup != upgradeGroup || currentGroup == prevGroup {
+ return nil
+ }
+ if err := tx.Model(&User{}).Where("id = ?", userId).
+ Update("group", prevGroup).Error; err != nil {
+ return err
+ }
+ cacheGroup = prevGroup
+ return nil
+ })
+ if err != nil {
+ return expiredCount, err
+ }
+ if cacheGroup != "" {
+ _ = UpdateUserGroupCache(userId, cacheGroup)
+ }
+ }
+ return expiredCount, nil
+}
+
+// SubscriptionPreConsumeRecord stores idempotent pre-consume operations per request.
+type SubscriptionPreConsumeRecord struct {
+ Id int `json:"id"`
+ RequestId string `json:"request_id" gorm:"type:varchar(64);uniqueIndex"`
+ UserId int `json:"user_id" gorm:"index"`
+ UserSubscriptionId int `json:"user_subscription_id" gorm:"index"`
+ PreConsumed int64 `json:"pre_consumed" gorm:"type:bigint;not null;default:0"`
+ Status string `json:"status" gorm:"type:varchar(32);index"` // consumed/refunded
+ CreatedAt int64 `json:"created_at" gorm:"bigint"`
+ UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
+}
+
+func (r *SubscriptionPreConsumeRecord) BeforeCreate(tx *gorm.DB) error {
+ now := common.GetTimestamp()
+ r.CreatedAt = now
+ r.UpdatedAt = now
+ return nil
+}
+
+func (r *SubscriptionPreConsumeRecord) BeforeUpdate(tx *gorm.DB) error {
+ r.UpdatedAt = common.GetTimestamp()
+ return nil
+}
+
+func maybeResetUserSubscriptionWithPlanTx(tx *gorm.DB, sub *UserSubscription, plan *SubscriptionPlan, now int64) error {
+ if tx == nil || sub == nil || plan == nil {
+ return errors.New("invalid reset args")
+ }
+ if sub.NextResetTime > 0 && sub.NextResetTime > now {
+ return nil
+ }
+ if NormalizeResetPeriod(plan.QuotaResetPeriod) == SubscriptionResetNever {
+ return nil
+ }
+ baseUnix := sub.LastResetTime
+ if baseUnix <= 0 {
+ baseUnix = sub.StartTime
+ }
+ base := time.Unix(baseUnix, 0)
+ next := calcNextResetTime(base, plan, sub.EndTime)
+ advanced := false
+ for next > 0 && next <= now {
+ advanced = true
+ base = time.Unix(next, 0)
+ next = calcNextResetTime(base, plan, sub.EndTime)
+ }
+ if !advanced {
+ if sub.NextResetTime == 0 && next > 0 {
+ sub.NextResetTime = next
+ sub.LastResetTime = base.Unix()
+ return tx.Save(sub).Error
+ }
+ return nil
+ }
+ sub.AmountUsed = 0
+ sub.LastResetTime = base.Unix()
+ sub.NextResetTime = next
+ return tx.Save(sub).Error
+}
+
+// PreConsumeUserSubscription pre-consumes from any active subscription total quota.
+func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error) {
+ if userId <= 0 {
+ return nil, errors.New("invalid userId")
+ }
+ if strings.TrimSpace(requestId) == "" {
+ return nil, errors.New("requestId is empty")
+ }
+ if amount <= 0 {
+ return nil, errors.New("amount must be > 0")
+ }
+ now := GetDBTimestamp()
+
+ returnValue := &SubscriptionPreConsumeResult{}
+
+ err := DB.Transaction(func(tx *gorm.DB) error {
+ var existing SubscriptionPreConsumeRecord
+ query := tx.Where("request_id = ?", requestId).Limit(1).Find(&existing)
+ if query.Error != nil {
+ return query.Error
+ }
+ if query.RowsAffected > 0 {
+ if existing.Status == "refunded" {
+ return errors.New("subscription pre-consume already refunded")
+ }
+ var sub UserSubscription
+ if err := tx.Where("id = ?", existing.UserSubscriptionId).First(&sub).Error; err != nil {
+ return err
+ }
+ returnValue.UserSubscriptionId = sub.Id
+ returnValue.PreConsumed = existing.PreConsumed
+ returnValue.AmountTotal = sub.AmountTotal
+ returnValue.AmountUsedBefore = sub.AmountUsed
+ returnValue.AmountUsedAfter = sub.AmountUsed
+ return nil
+ }
+
+ var subs []UserSubscription
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
+ Order("end_time asc, id asc").
+ Find(&subs).Error; err != nil {
+ return errors.New("no active subscription")
+ }
+ if len(subs) == 0 {
+ return errors.New("no active subscription")
+ }
+ for _, candidate := range subs {
+ sub := candidate
+ plan, err := getSubscriptionPlanByIdTx(tx, sub.PlanId)
+ if err != nil {
+ return err
+ }
+ if err := maybeResetUserSubscriptionWithPlanTx(tx, &sub, plan, now); err != nil {
+ return err
+ }
+ usedBefore := sub.AmountUsed
+ if sub.AmountTotal > 0 {
+ remain := sub.AmountTotal - usedBefore
+ if remain < amount {
+ continue
+ }
+ }
+ record := &SubscriptionPreConsumeRecord{
+ RequestId: requestId,
+ UserId: userId,
+ UserSubscriptionId: sub.Id,
+ PreConsumed: amount,
+ Status: "consumed",
+ }
+ if err := tx.Create(record).Error; err != nil {
+ var dup SubscriptionPreConsumeRecord
+ if err2 := tx.Where("request_id = ?", requestId).First(&dup).Error; err2 == nil {
+ if dup.Status == "refunded" {
+ return errors.New("subscription pre-consume already refunded")
+ }
+ returnValue.UserSubscriptionId = sub.Id
+ returnValue.PreConsumed = dup.PreConsumed
+ returnValue.AmountTotal = sub.AmountTotal
+ returnValue.AmountUsedBefore = sub.AmountUsed
+ returnValue.AmountUsedAfter = sub.AmountUsed
+ return nil
+ }
+ return err
+ }
+ sub.AmountUsed += amount
+ if err := tx.Save(&sub).Error; err != nil {
+ return err
+ }
+ returnValue.UserSubscriptionId = sub.Id
+ returnValue.PreConsumed = amount
+ returnValue.AmountTotal = sub.AmountTotal
+ returnValue.AmountUsedBefore = usedBefore
+ returnValue.AmountUsedAfter = sub.AmountUsed
+ return nil
+ }
+ return fmt.Errorf("subscription quota insufficient, need=%d", amount)
+ })
+ if err != nil {
+ return nil, err
+ }
+ return returnValue, nil
+}
+
+// RefundSubscriptionPreConsume is idempotent and refunds pre-consumed subscription quota by requestId.
+func RefundSubscriptionPreConsume(requestId string) error {
+ if strings.TrimSpace(requestId) == "" {
+ return errors.New("requestId is empty")
+ }
+ return DB.Transaction(func(tx *gorm.DB) error {
+ var record SubscriptionPreConsumeRecord
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("request_id = ?", requestId).First(&record).Error; err != nil {
+ return err
+ }
+ if record.Status == "refunded" {
+ return nil
+ }
+ if record.PreConsumed <= 0 {
+ record.Status = "refunded"
+ return tx.Save(&record).Error
+ }
+ if err := PostConsumeUserSubscriptionDelta(record.UserSubscriptionId, -record.PreConsumed); err != nil {
+ return err
+ }
+ record.Status = "refunded"
+ return tx.Save(&record).Error
+ })
+}
+
+// ResetDueSubscriptions resets subscriptions whose next_reset_time has passed.
+func ResetDueSubscriptions(limit int) (int, error) {
+ if limit <= 0 {
+ limit = 200
+ }
+ now := GetDBTimestamp()
+ var subs []UserSubscription
+ if err := DB.Where("next_reset_time > 0 AND next_reset_time <= ? AND status = ?", now, "active").
+ Order("next_reset_time asc").
+ Limit(limit).
+ Find(&subs).Error; err != nil {
+ return 0, err
+ }
+ if len(subs) == 0 {
+ return 0, nil
+ }
+ resetCount := 0
+ for _, sub := range subs {
+ subCopy := sub
+ plan, err := getSubscriptionPlanByIdTx(nil, sub.PlanId)
+ if err != nil || plan == nil {
+ continue
+ }
+ err = DB.Transaction(func(tx *gorm.DB) error {
+ var locked UserSubscription
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("id = ? AND next_reset_time > 0 AND next_reset_time <= ?", subCopy.Id, now).
+ First(&locked).Error; err != nil {
+ return nil
+ }
+ if err := maybeResetUserSubscriptionWithPlanTx(tx, &locked, plan, now); err != nil {
+ return err
+ }
+ resetCount++
+ return nil
+ })
+ if err != nil {
+ return resetCount, err
+ }
+ }
+ return resetCount, nil
+}
+
+// CleanupSubscriptionPreConsumeRecords removes old idempotency records to keep table small.
+func CleanupSubscriptionPreConsumeRecords(olderThanSeconds int64) (int64, error) {
+ if olderThanSeconds <= 0 {
+ olderThanSeconds = 7 * 24 * 3600
+ }
+ cutoff := GetDBTimestamp() - olderThanSeconds
+ res := DB.Where("updated_at < ?", cutoff).Delete(&SubscriptionPreConsumeRecord{})
+ return res.RowsAffected, res.Error
+}
+
+type SubscriptionPlanInfo struct {
+ PlanId int
+ PlanTitle string
+}
+
+func GetSubscriptionPlanInfoByUserSubscriptionId(userSubscriptionId int) (*SubscriptionPlanInfo, error) {
+ if userSubscriptionId <= 0 {
+ return nil, errors.New("invalid userSubscriptionId")
+ }
+ cacheKey := fmt.Sprintf("sub:%d", userSubscriptionId)
+ if cached, found, err := getSubscriptionPlanInfoCache().Get(cacheKey); err == nil && found {
+ return &cached, nil
+ }
+ var sub UserSubscription
+ if err := DB.Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
+ return nil, err
+ }
+ plan, err := getSubscriptionPlanByIdTx(nil, sub.PlanId)
+ if err != nil {
+ return nil, err
+ }
+ info := &SubscriptionPlanInfo{
+ PlanId: sub.PlanId,
+ PlanTitle: plan.Title,
+ }
+ _ = getSubscriptionPlanInfoCache().SetWithTTL(cacheKey, *info, subscriptionPlanInfoCacheTTL())
+ return info, nil
+}
+
+// Update subscription used amount by delta (positive consume more, negative refund).
+func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error {
+ if userSubscriptionId <= 0 {
+ return errors.New("invalid userSubscriptionId")
+ }
+ if delta == 0 {
+ return nil
+ }
+ return DB.Transaction(func(tx *gorm.DB) error {
+ var sub UserSubscription
+ if err := tx.Set("gorm:query_option", "FOR UPDATE").
+ Where("id = ?", userSubscriptionId).
+ First(&sub).Error; err != nil {
+ return err
+ }
+ newUsed := sub.AmountUsed + delta
+ if newUsed < 0 {
+ newUsed = 0
+ }
+ if sub.AmountTotal > 0 && newUsed > sub.AmountTotal {
+ return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal)
+ }
+ sub.AmountUsed = newUsed
+ return tx.Save(&sub).Error
+ })
+}
diff --git a/model/task.go b/model/task.go
index c76d26edfc..2fbd3fd666 100644
--- a/model/task.go
+++ b/model/task.go
@@ -1,10 +1,12 @@
package model
import (
+ "bytes"
"database/sql/driver"
"encoding/json"
"time"
+ "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
commonRelay "github.com/QuantumNous/new-api/relay/common"
@@ -57,19 +59,19 @@ type Task struct {
FinishTime int64 `json:"finish_time" gorm:"index"`
Progress string `json:"progress" gorm:"type:varchar(20);index"`
Properties Properties `json:"properties" gorm:"type:json"`
+ Username string `json:"username,omitempty" gorm:"-"`
// 禁止返回给用户,内部可能包含key等隐私信息
PrivateData TaskPrivateData `json:"-" gorm:"column:private_data;type:json"`
Data json.RawMessage `json:"data" gorm:"type:json"`
}
func (t *Task) SetData(data any) {
- b, _ := json.Marshal(data)
+ b, _ := common.Marshal(data)
t.Data = json.RawMessage(b)
}
func (t *Task) GetData(v any) error {
- err := json.Unmarshal(t.Data, &v)
- return err
+ return common.Unmarshal(t.Data, &v)
}
type Properties struct {
@@ -84,18 +86,59 @@ func (m *Properties) Scan(val interface{}) error {
*m = Properties{}
return nil
}
- return json.Unmarshal(bytesValue, m)
+ return common.Unmarshal(bytesValue, m)
}
func (m Properties) Value() (driver.Value, error) {
if m == (Properties{}) {
return nil, nil
}
- return json.Marshal(m)
+ return common.Marshal(m)
}
type TaskPrivateData struct {
- Key string `json:"key,omitempty"`
+ Key string `json:"key,omitempty"`
+ UpstreamTaskID string `json:"upstream_task_id,omitempty"` // 上游真实 task ID
+ ResultURL string `json:"result_url,omitempty"` // 任务成功后的结果 URL(视频地址等)
+ // 计费上下文:用于异步退款/差额结算(轮询阶段读取)
+ BillingSource string `json:"billing_source,omitempty"` // "wallet" 或 "subscription"
+ SubscriptionId int `json:"subscription_id,omitempty"` // 订阅 ID,用于订阅退款
+ TokenId int `json:"token_id,omitempty"` // 令牌 ID,用于令牌额度退款
+ BillingContext *TaskBillingContext `json:"billing_context,omitempty"` // 计费参数快照(用于轮询阶段重新计算)
+}
+
+// TaskBillingContext 记录任务提交时的计费参数,以便轮询阶段可以重新计算额度。
+type TaskBillingContext struct {
+ ModelPrice float64 `json:"model_price,omitempty"` // 模型单价
+ GroupRatio float64 `json:"group_ratio,omitempty"` // 分组倍率
+ ModelRatio float64 `json:"model_ratio,omitempty"` // 模型倍率
+ OtherRatios map[string]float64 `json:"other_ratios,omitempty"` // 附加倍率(时长、分辨率等)
+ OriginModelName string `json:"origin_model_name,omitempty"` // 模型名称,必须为OriginModelName
+ PerCallBilling bool `json:"per_call_billing,omitempty"` // 按次计费:跳过轮询阶段的差额结算
+}
+
+// GetUpstreamTaskID 获取上游真实 task ID(用于与 provider 通信)
+// 旧数据没有 UpstreamTaskID 时,TaskID 本身就是上游 ID
+func (t *Task) GetUpstreamTaskID() string {
+ if t.PrivateData.UpstreamTaskID != "" {
+ return t.PrivateData.UpstreamTaskID
+ }
+ return t.TaskID
+}
+
+// GetResultURL 获取任务结果 URL(视频地址等)
+// 新数据存在 PrivateData.ResultURL 中;旧数据回退到 FailReason(历史兼容)
+func (t *Task) GetResultURL() string {
+ if t.PrivateData.ResultURL != "" {
+ return t.PrivateData.ResultURL
+ }
+ return t.FailReason
+}
+
+// GenerateTaskID 生成对外暴露的 task_xxxx 格式 ID
+func GenerateTaskID() string {
+ key, _ := common.GenerateRandomCharsKey(32)
+ return "task_" + key
}
func (p *TaskPrivateData) Scan(val interface{}) error {
@@ -103,14 +146,14 @@ func (p *TaskPrivateData) Scan(val interface{}) error {
if len(bytesValue) == 0 {
return nil
}
- return json.Unmarshal(bytesValue, p)
+ return common.Unmarshal(bytesValue, p)
}
func (p TaskPrivateData) Value() (driver.Value, error) {
if (p == TaskPrivateData{}) {
return nil, nil
}
- return json.Marshal(p)
+ return common.Marshal(p)
}
// SyncTaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段
@@ -130,7 +173,8 @@ func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo)
properties := Properties{}
privateData := TaskPrivateData{}
if relayInfo != nil && relayInfo.ChannelMeta != nil {
- if relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeGemini {
+ if relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeGemini ||
+ relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeVertexAi {
privateData.Key = relayInfo.ChannelMeta.ApiKey
}
if relayInfo.UpstreamModelName != "" {
@@ -141,7 +185,16 @@ func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo)
}
}
+ // 使用预生成的公开 ID(如果有),否则新生成
+ taskID := ""
+ if relayInfo.TaskRelayInfo != nil && relayInfo.TaskRelayInfo.PublicTaskID != "" {
+ taskID = relayInfo.TaskRelayInfo.PublicTaskID
+ } else {
+ taskID = GenerateTaskID()
+ }
+
t := &Task{
+ TaskID: taskID,
UserId: relayInfo.UserId,
Group: relayInfo.UsingGroup,
SubmitTime: time.Now().Unix(),
@@ -236,6 +289,20 @@ func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*
return tasks
}
+func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task {
+ var tasks []*Task
+ err := DB.Where("progress != ?", "100%").
+ Where("status NOT IN ?", []string{TaskStatusFailure, TaskStatusSuccess}).
+ Where("submit_time < ?", cutoffUnix).
+ Order("submit_time").
+ Limit(limit).
+ Find(&tasks).Error
+ if err != nil {
+ return nil
+ }
+ return tasks
+}
+
func GetAllUnFinishSyncTasks(limit int) []*Task {
var tasks []*Task
var err error
@@ -290,40 +357,70 @@ func GetByTaskIds(userId int, taskIds []any) ([]*Task, error) {
return task, nil
}
-func TaskUpdateProgress(id int64, progress string) error {
- return DB.Model(&Task{}).Where("id = ?", id).Update("progress", progress).Error
-}
-
func (Task *Task) Insert() error {
var err error
err = DB.Create(Task).Error
return err
}
+type taskSnapshot struct {
+ Status TaskStatus
+ Progress string
+ StartTime int64
+ FinishTime int64
+ FailReason string
+ ResultURL string
+ Data json.RawMessage
+}
+
+func (s taskSnapshot) Equal(other taskSnapshot) bool {
+ return s.Status == other.Status &&
+ s.Progress == other.Progress &&
+ s.StartTime == other.StartTime &&
+ s.FinishTime == other.FinishTime &&
+ s.FailReason == other.FailReason &&
+ s.ResultURL == other.ResultURL &&
+ bytes.Equal(s.Data, other.Data)
+}
+
+func (t *Task) Snapshot() taskSnapshot {
+ return taskSnapshot{
+ Status: t.Status,
+ Progress: t.Progress,
+ StartTime: t.StartTime,
+ FinishTime: t.FinishTime,
+ FailReason: t.FailReason,
+ ResultURL: t.PrivateData.ResultURL,
+ Data: t.Data,
+ }
+}
+
func (Task *Task) Update() error {
var err error
err = DB.Save(Task).Error
return err
}
-func TaskBulkUpdate(TaskIds []string, params map[string]any) error {
- if len(TaskIds) == 0 {
- return nil
+// UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS).
+// Returns (true, nil) if this caller won the update, (false, nil) if
+// another process already moved the task out of fromStatus.
+//
+// Uses Model().Select("*").Updates() instead of Save() because GORM's Save
+// falls back to INSERT ON CONFLICT when the WHERE-guarded UPDATE matches
+// zero rows, which silently bypasses the CAS guard.
+func (t *Task) UpdateWithStatus(fromStatus TaskStatus) (bool, error) {
+ result := DB.Model(t).Where("status = ?", fromStatus).Select("*").Updates(t)
+ if result.Error != nil {
+ return false, result.Error
}
- return DB.Model(&Task{}).
- Where("task_id in (?)", TaskIds).
- Updates(params).Error
-}
-
-func TaskBulkUpdateByTaskIds(taskIDs []int64, params map[string]any) error {
- if len(taskIDs) == 0 {
- return nil
- }
- return DB.Model(&Task{}).
- Where("id in (?)", taskIDs).
- Updates(params).Error
+ return result.RowsAffected > 0, nil
}
+// TaskBulkUpdateByID performs an unconditional bulk UPDATE by primary key IDs.
+// WARNING: This function has NO CAS (Compare-And-Swap) guard — it will overwrite
+// any concurrent status changes. DO NOT use in billing/quota lifecycle flows
+// (e.g., timeout, success, failure transitions that trigger refunds or settlements).
+// For status transitions that involve billing, use Task.UpdateWithStatus() instead.
func TaskBulkUpdateByID(ids []int64, params map[string]any) error {
if len(ids) == 0 {
return nil
@@ -338,37 +435,6 @@ type TaskQuotaUsage struct {
Count float64 `json:"count"`
}
-func SumUsedTaskQuota(queryParams SyncTaskQueryParams) (stat []TaskQuotaUsage, err error) {
- query := DB.Model(Task{})
- // 添加过滤条件
- if queryParams.ChannelID != "" {
- query = query.Where("channel_id = ?", queryParams.ChannelID)
- }
- if queryParams.UserID != "" {
- query = query.Where("user_id = ?", queryParams.UserID)
- }
- if len(queryParams.UserIDs) != 0 {
- query = query.Where("user_id in (?)", queryParams.UserIDs)
- }
- if queryParams.TaskID != "" {
- query = query.Where("task_id = ?", queryParams.TaskID)
- }
- if queryParams.Action != "" {
- query = query.Where("action = ?", queryParams.Action)
- }
- if queryParams.Status != "" {
- query = query.Where("status = ?", queryParams.Status)
- }
- if queryParams.StartTimestamp != 0 {
- query = query.Where("submit_time >= ?", queryParams.StartTimestamp)
- }
- if queryParams.EndTimestamp != 0 {
- query = query.Where("submit_time <= ?", queryParams.EndTimestamp)
- }
- err = query.Select("mode, sum(quota) as count").Group("mode").Find(&stat).Error
- return stat, err
-}
-
// TaskCountAllTasks returns total tasks that match the given query params (admin usage)
func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64 {
var total int64
@@ -437,6 +503,6 @@ func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo {
openAIVideo.SetProgressStr(t.Progress)
openAIVideo.CreatedAt = t.CreatedAt
openAIVideo.CompletedAt = t.UpdatedAt
- openAIVideo.SetMetadata("url", t.FailReason)
+ openAIVideo.SetMetadata("url", t.GetResultURL())
return openAIVideo
}
diff --git a/model/task_cas_test.go b/model/task_cas_test.go
new file mode 100644
index 0000000000..3449c6d262
--- /dev/null
+++ b/model/task_cas_test.go
@@ -0,0 +1,217 @@
+package model
+
+import (
+ "encoding/json"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/glebarez/sqlite"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func TestMain(m *testing.M) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
+ if err != nil {
+ panic("failed to open test db: " + err.Error())
+ }
+ DB = db
+ LOG_DB = db
+
+ common.UsingSQLite = true
+ common.RedisEnabled = false
+ common.BatchUpdateEnabled = false
+ common.LogConsumeEnabled = true
+
+ sqlDB, err := db.DB()
+ if err != nil {
+ panic("failed to get sql.DB: " + err.Error())
+ }
+ sqlDB.SetMaxOpenConns(1)
+
+ if err := db.AutoMigrate(&Task{}, &User{}, &Token{}, &Log{}, &Channel{}); err != nil {
+ panic("failed to migrate: " + err.Error())
+ }
+
+ os.Exit(m.Run())
+}
+
+func truncateTables(t *testing.T) {
+ t.Helper()
+ t.Cleanup(func() {
+ DB.Exec("DELETE FROM tasks")
+ DB.Exec("DELETE FROM users")
+ DB.Exec("DELETE FROM tokens")
+ DB.Exec("DELETE FROM logs")
+ DB.Exec("DELETE FROM channels")
+ })
+}
+
+func insertTask(t *testing.T, task *Task) {
+ t.Helper()
+ task.CreatedAt = time.Now().Unix()
+ task.UpdatedAt = time.Now().Unix()
+ require.NoError(t, DB.Create(task).Error)
+}
+
+// ---------------------------------------------------------------------------
+// Snapshot / Equal — pure logic tests (no DB)
+// ---------------------------------------------------------------------------
+
+func TestSnapshotEqual_Same(t *testing.T) {
+ s := taskSnapshot{
+ Status: TaskStatusInProgress,
+ Progress: "50%",
+ StartTime: 1000,
+ FinishTime: 0,
+ FailReason: "",
+ ResultURL: "",
+ Data: json.RawMessage(`{"key":"value"}`),
+ }
+ assert.True(t, s.Equal(s))
+}
+
+func TestSnapshotEqual_DifferentStatus(t *testing.T) {
+ a := taskSnapshot{Status: TaskStatusInProgress, Data: json.RawMessage(`{}`)}
+ b := taskSnapshot{Status: TaskStatusSuccess, Data: json.RawMessage(`{}`)}
+ assert.False(t, a.Equal(b))
+}
+
+func TestSnapshotEqual_DifferentProgress(t *testing.T) {
+ a := taskSnapshot{Status: TaskStatusInProgress, Progress: "30%", Data: json.RawMessage(`{}`)}
+ b := taskSnapshot{Status: TaskStatusInProgress, Progress: "60%", Data: json.RawMessage(`{}`)}
+ assert.False(t, a.Equal(b))
+}
+
+func TestSnapshotEqual_DifferentData(t *testing.T) {
+ a := taskSnapshot{Status: TaskStatusInProgress, Data: json.RawMessage(`{"a":1}`)}
+ b := taskSnapshot{Status: TaskStatusInProgress, Data: json.RawMessage(`{"a":2}`)}
+ assert.False(t, a.Equal(b))
+}
+
+func TestSnapshotEqual_NilVsEmpty(t *testing.T) {
+ a := taskSnapshot{Status: TaskStatusInProgress, Data: nil}
+ b := taskSnapshot{Status: TaskStatusInProgress, Data: json.RawMessage{}}
+ // bytes.Equal(nil, []byte{}) == true
+ assert.True(t, a.Equal(b))
+}
+
+func TestSnapshot_Roundtrip(t *testing.T) {
+ task := &Task{
+ Status: TaskStatusInProgress,
+ Progress: "42%",
+ StartTime: 1234,
+ FinishTime: 5678,
+ FailReason: "timeout",
+ PrivateData: TaskPrivateData{
+ ResultURL: "https://example.com/result.mp4",
+ },
+ Data: json.RawMessage(`{"model":"test-model"}`),
+ }
+ snap := task.Snapshot()
+ assert.Equal(t, task.Status, snap.Status)
+ assert.Equal(t, task.Progress, snap.Progress)
+ assert.Equal(t, task.StartTime, snap.StartTime)
+ assert.Equal(t, task.FinishTime, snap.FinishTime)
+ assert.Equal(t, task.FailReason, snap.FailReason)
+ assert.Equal(t, task.PrivateData.ResultURL, snap.ResultURL)
+ assert.JSONEq(t, string(task.Data), string(snap.Data))
+}
+
+// ---------------------------------------------------------------------------
+// UpdateWithStatus CAS — DB integration tests
+// ---------------------------------------------------------------------------
+
+func TestUpdateWithStatus_Win(t *testing.T) {
+ truncateTables(t)
+
+ task := &Task{
+ TaskID: "task_cas_win",
+ Status: TaskStatusInProgress,
+ Progress: "50%",
+ Data: json.RawMessage(`{}`),
+ }
+ insertTask(t, task)
+
+ task.Status = TaskStatusSuccess
+ task.Progress = "100%"
+ won, err := task.UpdateWithStatus(TaskStatusInProgress)
+ require.NoError(t, err)
+ assert.True(t, won)
+
+ var reloaded Task
+ require.NoError(t, DB.First(&reloaded, task.ID).Error)
+ assert.EqualValues(t, TaskStatusSuccess, reloaded.Status)
+ assert.Equal(t, "100%", reloaded.Progress)
+}
+
+func TestUpdateWithStatus_Lose(t *testing.T) {
+ truncateTables(t)
+
+ task := &Task{
+ TaskID: "task_cas_lose",
+ Status: TaskStatusFailure,
+ Data: json.RawMessage(`{}`),
+ }
+ insertTask(t, task)
+
+ task.Status = TaskStatusSuccess
+ won, err := task.UpdateWithStatus(TaskStatusInProgress) // wrong fromStatus
+ require.NoError(t, err)
+ assert.False(t, won)
+
+ var reloaded Task
+ require.NoError(t, DB.First(&reloaded, task.ID).Error)
+ assert.EqualValues(t, TaskStatusFailure, reloaded.Status) // unchanged
+}
+
+func TestUpdateWithStatus_ConcurrentWinner(t *testing.T) {
+ truncateTables(t)
+
+ task := &Task{
+ TaskID: "task_cas_race",
+ Status: TaskStatusInProgress,
+ Quota: 1000,
+ Data: json.RawMessage(`{}`),
+ }
+ insertTask(t, task)
+
+ const goroutines = 5
+ wins := make([]bool, goroutines)
+ var wg sync.WaitGroup
+ wg.Add(goroutines)
+
+ for i := 0; i < goroutines; i++ {
+ go func(idx int) {
+ defer wg.Done()
+ t := &Task{}
+ *t = Task{
+ ID: task.ID,
+ TaskID: task.TaskID,
+ Status: TaskStatusSuccess,
+ Progress: "100%",
+ Quota: task.Quota,
+ Data: json.RawMessage(`{}`),
+ }
+ t.CreatedAt = task.CreatedAt
+ t.UpdatedAt = time.Now().Unix()
+ won, err := t.UpdateWithStatus(TaskStatusInProgress)
+ if err == nil {
+ wins[idx] = won
+ }
+ }(i)
+ }
+ wg.Wait()
+
+ winCount := 0
+ for _, w := range wins {
+ if w {
+ winCount++
+ }
+ }
+ assert.Equal(t, 1, winCount, "exactly one goroutine should win the CAS")
+}
diff --git a/model/token.go b/model/token.go
index b68fc0cfba..b7989ad171 100644
--- a/model/token.go
+++ b/model/token.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/bytedance/gopkg/util/gopool"
"gorm.io/gorm"
)
@@ -22,7 +23,7 @@ type Token struct {
RemainQuota int `json:"remain_quota" gorm:"default:0"`
UnlimitedQuota bool `json:"unlimited_quota"`
ModelLimitsEnabled bool `json:"model_limits_enabled"`
- ModelLimits string `json:"model_limits" gorm:"type:varchar(1024);default:''"`
+ ModelLimits string `json:"model_limits" gorm:"type:text"`
AllowIps *string `json:"allow_ips" gorm:"default:''"`
UsedQuota int `json:"used_quota" gorm:"default:0"` // used quota
Group string `json:"group" gorm:"default:''"`
@@ -34,6 +35,27 @@ func (token *Token) Clean() {
token.Key = ""
}
+func MaskTokenKey(key string) string {
+ if key == "" {
+ return ""
+ }
+ if len(key) <= 4 {
+ return strings.Repeat("*", len(key))
+ }
+ if len(key) <= 8 {
+ return key[:2] + "****" + key[len(key)-2:]
+ }
+ return key[:4] + "**********" + key[len(key)-4:]
+}
+
+func (token *Token) GetFullKey() string {
+ return token.Key
+}
+
+func (token *Token) GetMaskedKey() string {
+ return MaskTokenKey(token.Key)
+}
+
func (token *Token) GetIpLimits() []string {
// delete empty spaces
//split with \n
@@ -63,12 +85,104 @@ func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
return tokens, err
}
-func SearchUserTokens(userId int, keyword string, token string) (tokens []*Token, err error) {
- if token != "" {
- token = strings.Trim(token, "sk-")
+// sanitizeLikePattern 校验并清洗用户输入的 LIKE 搜索模式。
+// 规则:
+// 1. 转义 ! 和 _(使用 ! 作为 ESCAPE 字符,兼容 MySQL/PostgreSQL/SQLite)
+// 2. 连续的 % 合并为单个 %
+// 3. 最多允许 2 个 %
+// 4. 含 % 时(模糊搜索),去掉 % 后关键词长度必须 >= 2
+// 5. 不含 % 时按精确匹配
+func sanitizeLikePattern(input string) (string, error) {
+ // 1. 先转义 ESCAPE 字符 ! 自身,再转义 _
+ // 使用 ! 而非 \ 作为 ESCAPE 字符,避免 MySQL 中反斜杠的字符串转义问题
+ input = strings.ReplaceAll(input, "!", "!!")
+ input = strings.ReplaceAll(input, `_`, `!_`)
+
+ // 2. 连续的 % 直接拒绝
+ if strings.Contains(input, "%%") {
+ return "", errors.New("搜索模式中不允许包含连续的 % 通配符")
}
- err = DB.Where("user_id = ?", userId).Where("name LIKE ?", "%"+keyword+"%").Where(commonKeyCol+" LIKE ?", "%"+token+"%").Find(&tokens).Error
- return tokens, err
+
+ // 3. 统计 % 数量,不得超过 2
+ count := strings.Count(input, "%")
+ if count > 2 {
+ return "", errors.New("搜索模式中最多允许包含 2 个 % 通配符")
+ }
+
+ // 4. 含 % 时,去掉 % 后关键词长度必须 >= 2
+ if count > 0 {
+ stripped := strings.ReplaceAll(input, "%", "")
+ if len(stripped) < 2 {
+ return "", errors.New("使用模糊搜索时,关键词长度至少为 2 个字符")
+ }
+ return input, nil
+ }
+
+ // 5. 无 % 时,精确全匹配
+ return input, nil
+}
+
+const searchHardLimit = 100
+
+func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error) {
+ // model 层强制截断
+ if limit <= 0 || limit > searchHardLimit {
+ limit = searchHardLimit
+ }
+ if offset < 0 {
+ offset = 0
+ }
+
+ if token != "" {
+ token = strings.TrimPrefix(token, "sk-")
+ }
+
+ // 超量用户(令牌数超过上限)只允许精确搜索,禁止模糊搜索
+ maxTokens := operation_setting.GetMaxUserTokens()
+ hasFuzzy := strings.Contains(keyword, "%") || strings.Contains(token, "%")
+ if hasFuzzy {
+ count, err := CountUserTokens(userId)
+ if err != nil {
+ common.SysLog("failed to count user tokens: " + err.Error())
+ return nil, 0, errors.New("获取令牌数量失败")
+ }
+ if int(count) > maxTokens {
+ return nil, 0, errors.New("令牌数量超过上限,仅允许精确搜索,请勿使用 % 通配符")
+ }
+ }
+
+ baseQuery := DB.Model(&Token{}).Where("user_id = ?", userId)
+
+ // 非空才加 LIKE 条件,空则跳过(不过滤该字段)
+ if keyword != "" {
+ keywordPattern, err := sanitizeLikePattern(keyword)
+ if err != nil {
+ return nil, 0, err
+ }
+ baseQuery = baseQuery.Where("name LIKE ? ESCAPE '!'", keywordPattern)
+ }
+ if token != "" {
+ tokenPattern, err := sanitizeLikePattern(token)
+ if err != nil {
+ return nil, 0, err
+ }
+ baseQuery = baseQuery.Where(commonKeyCol+" LIKE ? ESCAPE '!'", tokenPattern)
+ }
+
+ // 先查匹配总数(用于分页,受 maxTokens 上限保护,避免全表 COUNT)
+ err = baseQuery.Limit(maxTokens).Count(&total).Error
+ if err != nil {
+ common.SysError("failed to count search tokens: " + err.Error())
+ return nil, 0, errors.New("搜索令牌失败")
+ }
+
+ // 再分页查数据
+ err = baseQuery.Order("id desc").Offset(offset).Limit(limit).Find(&tokens).Error
+ if err != nil {
+ common.SysError("failed to search tokens: " + err.Error())
+ return nil, 0, errors.New("搜索令牌失败")
+ }
+ return tokens, total, nil
}
func ValidateUserToken(key string) (token *Token, err error) {
@@ -108,7 +222,7 @@ func ValidateUserToken(key string) (token *Token, err error) {
}
keyPrefix := key[:3]
keySuffix := key[len(key)-3:]
- return token, errors.New(fmt.Sprintf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota))
+ return token, fmt.Errorf("[sk-%s***%s] 该令牌额度已用尽 !token.UnlimitedQuota && token.RemainQuota = %d", keyPrefix, keySuffix, token.RemainQuota)
}
return token, nil
}
@@ -267,7 +381,7 @@ func DeleteTokenById(id int, userId int) (err error) {
return token.Delete()
}
-func IncreaseTokenQuota(id int, key string, quota int) (err error) {
+func IncreaseTokenQuota(tokenId int, key string, quota int) (err error) {
if quota < 0 {
return errors.New("quota 不能为负数!")
}
@@ -280,10 +394,10 @@ func IncreaseTokenQuota(id int, key string, quota int) (err error) {
})
}
if common.BatchUpdateEnabled {
- addNewRecord(BatchUpdateTypeTokenQuota, id, quota)
+ addNewRecord(BatchUpdateTypeTokenQuota, tokenId, quota)
return nil
}
- return increaseTokenQuota(id, quota)
+ return increaseTokenQuota(tokenId, quota)
}
func increaseTokenQuota(id int, quota int) (err error) {
@@ -367,3 +481,11 @@ func BatchDeleteTokens(ids []int, userId int) (int, error) {
return len(tokens), nil
}
+
+func GetTokenKeysByIds(ids []int, userId int) ([]Token, error) {
+ var tokens []Token
+ err := DB.Select("id", commonKeyCol).
+ Where("user_id = ? AND id IN (?)", userId, ids).
+ Find(&tokens).Error
+ return tokens, err
+}
diff --git a/model/topup.go b/model/topup.go
index 994094d9d1..d8c92bfe65 100644
--- a/model/topup.go
+++ b/model/topup.go
@@ -12,15 +12,15 @@ import (
)
type TopUp struct {
- Id int `json:"id"`
- UserId int `json:"user_id" gorm:"index"`
- Amount int64 `json:"amount"`
- Money float64 `json:"money"`
- TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
- PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
- CreateTime int64 `json:"create_time"`
- CompleteTime int64 `json:"complete_time"`
- Status string `json:"status"`
+ Id int `json:"id"`
+ UserId int `json:"user_id" gorm:"index"`
+ Amount int64 `json:"amount"`
+ Money float64 `json:"money"`
+ TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
+ PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
+ CreateTime int64 `json:"create_time"`
+ CompleteTime int64 `json:"complete_time"`
+ Status string `json:"status"`
}
func (topUp *TopUp) Insert() error {
@@ -95,7 +95,8 @@ func Recharge(referenceId string, customerId string) (err error) {
})
if err != nil {
- return errors.New("充值失败," + err.Error())
+ common.SysError("topup failed: " + err.Error())
+ return errors.New("充值失败,请稍后重试")
}
RecordLog(topUp.UserId, LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%d", logger.FormatQuota(int(quota)), topUp.Amount))
@@ -367,10 +368,70 @@ func RechargeCreem(referenceId string, customerEmail string, customerName string
})
if err != nil {
- return errors.New("充值失败," + err.Error())
+ common.SysError("creem topup failed: " + err.Error())
+ return errors.New("充值失败,请稍后重试")
}
RecordLog(topUp.UserId, LogTypeTopup, fmt.Sprintf("使用Creem充值成功,充值额度: %v,支付金额:%.2f", quota, topUp.Money))
return nil
}
+
+func RechargeWaffo(tradeNo string) (err error) {
+ if tradeNo == "" {
+ return errors.New("未提供支付单号")
+ }
+
+ var quotaToAdd int
+ topUp := &TopUp{}
+
+ refCol := "`trade_no`"
+ if common.UsingPostgreSQL {
+ refCol = `"trade_no"`
+ }
+
+ err = DB.Transaction(func(tx *gorm.DB) error {
+ err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(topUp).Error
+ if err != nil {
+ return errors.New("充值订单不存在")
+ }
+
+ if topUp.Status == common.TopUpStatusSuccess {
+ return nil // 幂等:已成功直接返回
+ }
+
+ if topUp.Status != common.TopUpStatusPending {
+ return errors.New("充值订单状态错误")
+ }
+
+ dAmount := decimal.NewFromInt(topUp.Amount)
+ dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
+ quotaToAdd = int(dAmount.Mul(dQuotaPerUnit).IntPart())
+ if quotaToAdd <= 0 {
+ return errors.New("无效的充值额度")
+ }
+
+ topUp.CompleteTime = common.GetTimestamp()
+ topUp.Status = common.TopUpStatusSuccess
+ if err := tx.Save(topUp).Error; err != nil {
+ return err
+ }
+
+ if err := tx.Model(&User{}).Where("id = ?", topUp.UserId).Update("quota", gorm.Expr("quota + ?", quotaToAdd)).Error; err != nil {
+ return err
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ common.SysError("waffo topup failed: " + err.Error())
+ return errors.New("充值失败,请稍后重试")
+ }
+
+ if quotaToAdd > 0 {
+ RecordLog(topUp.UserId, LogTypeTopup, fmt.Sprintf("Waffo充值成功,充值额度: %v,支付金额: %.2f", logger.FormatQuota(quotaToAdd), topUp.Money))
+ }
+
+ return nil
+}
diff --git a/model/usedata.go b/model/usedata.go
index f84beb8d90..f0ea055ae3 100644
--- a/model/usedata.go
+++ b/model/usedata.go
@@ -115,6 +115,16 @@ func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData
return quotaDatas, err
}
+func GetQuotaDataGroupByUser(startTime int64, endTime int64) (quotaData []*QuotaData, err error) {
+ var quotaDatas []*QuotaData
+ err = DB.Table("quota_data").
+ Select("username, created_at, sum(count) as count, sum(quota) as quota, sum(token_used) as token_used").
+ Where("created_at >= ? and created_at <= ?", startTime, endTime).
+ Group("username, created_at").
+ Find("aDatas).Error
+ return quotaDatas, err
+}
+
func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error) {
if username != "" {
return GetQuotaDataByUsername(username, startTime, endTime)
diff --git a/model/user.go b/model/user.go
index 395daa0b5d..1210b5435d 100644
--- a/model/user.go
+++ b/model/user.go
@@ -1,6 +1,7 @@
package model
import (
+ "database/sql"
"encoding/json"
"errors"
"fmt"
@@ -15,6 +16,8 @@ import (
"gorm.io/gorm"
)
+const UserNameMaxLength = 20
+
// User if you add sensitive fields, don't forget to clean them in setupLogin function.
// Otherwise, the sensitive information will be saved on local storage in plain text!
type User struct {
@@ -429,6 +432,65 @@ func (user *User) Insert(inviterId int) error {
return nil
}
+// InsertWithTx inserts a new user within an existing transaction.
+// This is used for OAuth registration where user creation and binding need to be atomic.
+// Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.
+func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error {
+ var err error
+ if user.Password != "" {
+ user.Password, err = common.Password2Hash(user.Password)
+ if err != nil {
+ return err
+ }
+ }
+ user.Quota = common.QuotaForNewUser
+ user.AffCode = common.GetRandomString(4)
+
+ // 初始化用户设置
+ if user.Setting == "" {
+ defaultSetting := dto.UserSetting{}
+ user.SetSetting(defaultSetting)
+ }
+
+ result := tx.Create(user)
+ if result.Error != nil {
+ return result.Error
+ }
+
+ return nil
+}
+
+// FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation.
+// This should be called after the transaction commits successfully.
+func (user *User) FinalizeOAuthUserCreation(inviterId int) {
+ // 用户创建成功后,根据角色初始化边栏配置
+ var createdUser User
+ if err := DB.Where("id = ?", user.Id).First(&createdUser).Error; err == nil {
+ defaultSidebarConfig := generateDefaultSidebarConfigForRole(createdUser.Role)
+ if defaultSidebarConfig != "" {
+ currentSetting := createdUser.GetSetting()
+ currentSetting.SidebarModules = defaultSidebarConfig
+ createdUser.SetSetting(currentSetting)
+ createdUser.Update(false)
+ common.SysLog(fmt.Sprintf("为新用户 %s (角色: %d) 初始化边栏配置", createdUser.Username, createdUser.Role))
+ }
+ }
+
+ if common.QuotaForNewUser > 0 {
+ RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", logger.LogQuota(common.QuotaForNewUser)))
+ }
+ if inviterId != 0 {
+ if common.QuotaForInvitee > 0 {
+ _ = IncreaseUserQuota(user.Id, common.QuotaForInvitee, true)
+ RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", logger.LogQuota(common.QuotaForInvitee)))
+ }
+ if common.QuotaForInviter > 0 {
+ RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", logger.LogQuota(common.QuotaForInviter)))
+ _ = inviteUser(inviterId)
+ }
+ }
+}
+
func (user *User) Update(updatePassword bool) error {
var err error
if updatePassword {
@@ -477,6 +539,37 @@ func (user *User) Edit(updatePassword bool) error {
return updateUserCache(*user)
}
+func (user *User) ClearBinding(bindingType string) error {
+ if user.Id == 0 {
+ return errors.New("user id is empty")
+ }
+
+ bindingColumnMap := map[string]string{
+ "email": "email",
+ "github": "github_id",
+ "discord": "discord_id",
+ "oidc": "oidc_id",
+ "wechat": "wechat_id",
+ "telegram": "telegram_id",
+ "linuxdo": "linux_do_id",
+ }
+
+ column, ok := bindingColumnMap[bindingType]
+ if !ok {
+ return errors.New("invalid binding type")
+ }
+
+ if err := DB.Model(&User{}).Where("id = ?", user.Id).Update(column, "").Error; err != nil {
+ return err
+ }
+
+ if err := DB.Where("id = ?", user.Id).First(user).Error; err != nil {
+ return err
+ }
+
+ return updateUserCache(*user)
+}
+
func (user *User) Delete() error {
if user.Id == 0 {
return errors.New("id 为空!")
@@ -540,6 +633,14 @@ func (user *User) FillUserByGitHubId() error {
return nil
}
+// UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
+func (user *User) UpdateGitHubId(newGitHubId string) error {
+ if user.Id == 0 {
+ return errors.New("user id is empty")
+ }
+ return DB.Model(user).Update("github_id", newGitHubId).Error
+}
+
func (user *User) FillUserByDiscordId() error {
if user.DiscordId == "" {
return errors.New("discord id 为空!")
@@ -753,10 +854,17 @@ func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)
// Don't return error - fall through to DB
}
fromDB = true
- err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&setting).Error
+ // can be nil setting
+ var safeSetting sql.NullString
+ err = DB.Model(&User{}).Where("id = ?", id).Select("setting").Find(&safeSetting).Error
if err != nil {
return settingMap, err
}
+ if safeSetting.Valid {
+ setting = safeSetting.String
+ } else {
+ setting = ""
+ }
userBase := &UserBase{
Setting: setting,
}
diff --git a/model/user_cache.go b/model/user_cache.go
index d06acd80ee..2ba1f18ec8 100644
--- a/model/user_cache.go
+++ b/model/user_cache.go
@@ -204,6 +204,10 @@ func updateUserGroupCache(userId int, group string) error {
return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
}
+func UpdateUserGroupCache(userId int, group string) error {
+ return updateUserGroupCache(userId, group)
+}
+
func updateUserNameCache(userId int, username string) error {
if !common.RedisEnabled {
return nil
@@ -217,3 +221,13 @@ func updateUserSettingCache(userId int, setting string) error {
}
return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
}
+
+// GetUserLanguage returns the user's language preference from cache
+// Uses the existing GetUserCache mechanism for efficiency
+func GetUserLanguage(userId int) string {
+ userCache, err := GetUserCache(userId)
+ if err != nil {
+ return ""
+ }
+ return userCache.GetSetting().Language
+}
diff --git a/model/user_oauth_binding.go b/model/user_oauth_binding.go
new file mode 100644
index 0000000000..492166251e
--- /dev/null
+++ b/model/user_oauth_binding.go
@@ -0,0 +1,147 @@
+package model
+
+import (
+ "errors"
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// UserOAuthBinding stores the binding relationship between users and custom OAuth providers
+type UserOAuthBinding struct {
+ Id int `json:"id" gorm:"primaryKey"`
+ UserId int `json:"user_id" gorm:"not null;uniqueIndex:ux_user_provider"` // User ID - one binding per user per provider
+ ProviderId int `json:"provider_id" gorm:"not null;uniqueIndex:ux_user_provider;uniqueIndex:ux_provider_userid"` // Custom OAuth provider ID
+ ProviderUserId string `json:"provider_user_id" gorm:"type:varchar(256);not null;uniqueIndex:ux_provider_userid"` // User ID from OAuth provider - one OAuth account per provider
+ CreatedAt time.Time `json:"created_at"`
+}
+
+func (UserOAuthBinding) TableName() string {
+ return "user_oauth_bindings"
+}
+
+// GetUserOAuthBindingsByUserId returns all OAuth bindings for a user
+func GetUserOAuthBindingsByUserId(userId int) ([]*UserOAuthBinding, error) {
+ var bindings []*UserOAuthBinding
+ err := DB.Where("user_id = ?", userId).Find(&bindings).Error
+ return bindings, err
+}
+
+// GetUserOAuthBinding returns a specific binding for a user and provider
+func GetUserOAuthBinding(userId, providerId int) (*UserOAuthBinding, error) {
+ var binding UserOAuthBinding
+ err := DB.Where("user_id = ? AND provider_id = ?", userId, providerId).First(&binding).Error
+ if err != nil {
+ return nil, err
+ }
+ return &binding, nil
+}
+
+// GetUserByOAuthBinding finds a user by provider ID and provider user ID
+func GetUserByOAuthBinding(providerId int, providerUserId string) (*User, error) {
+ var binding UserOAuthBinding
+ err := DB.Where("provider_id = ? AND provider_user_id = ?", providerId, providerUserId).First(&binding).Error
+ if err != nil {
+ return nil, err
+ }
+
+ var user User
+ err = DB.First(&user, binding.UserId).Error
+ if err != nil {
+ return nil, err
+ }
+ return &user, nil
+}
+
+// IsProviderUserIdTaken checks if a provider user ID is already bound to any user
+func IsProviderUserIdTaken(providerId int, providerUserId string) bool {
+ var count int64
+ DB.Model(&UserOAuthBinding{}).Where("provider_id = ? AND provider_user_id = ?", providerId, providerUserId).Count(&count)
+ return count > 0
+}
+
+// CreateUserOAuthBinding creates a new OAuth binding
+func CreateUserOAuthBinding(binding *UserOAuthBinding) error {
+ if binding.UserId == 0 {
+ return errors.New("user ID is required")
+ }
+ if binding.ProviderId == 0 {
+ return errors.New("provider ID is required")
+ }
+ if binding.ProviderUserId == "" {
+ return errors.New("provider user ID is required")
+ }
+
+ // Check if this provider user ID is already taken
+ if IsProviderUserIdTaken(binding.ProviderId, binding.ProviderUserId) {
+ return errors.New("this OAuth account is already bound to another user")
+ }
+
+ binding.CreatedAt = time.Now()
+ return DB.Create(binding).Error
+}
+
+// CreateUserOAuthBindingWithTx creates a new OAuth binding within a transaction
+func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error {
+ if binding.UserId == 0 {
+ return errors.New("user ID is required")
+ }
+ if binding.ProviderId == 0 {
+ return errors.New("provider ID is required")
+ }
+ if binding.ProviderUserId == "" {
+ return errors.New("provider user ID is required")
+ }
+
+ // Check if this provider user ID is already taken (use tx to check within the same transaction)
+ var count int64
+ tx.Model(&UserOAuthBinding{}).Where("provider_id = ? AND provider_user_id = ?", binding.ProviderId, binding.ProviderUserId).Count(&count)
+ if count > 0 {
+ return errors.New("this OAuth account is already bound to another user")
+ }
+
+ binding.CreatedAt = time.Now()
+ return tx.Create(binding).Error
+}
+
+// UpdateUserOAuthBinding updates an existing OAuth binding (e.g., rebind to different OAuth account)
+func UpdateUserOAuthBinding(userId, providerId int, newProviderUserId string) error {
+ // Check if the new provider user ID is already taken by another user
+ var existingBinding UserOAuthBinding
+ err := DB.Where("provider_id = ? AND provider_user_id = ?", providerId, newProviderUserId).First(&existingBinding).Error
+ if err == nil && existingBinding.UserId != userId {
+ return errors.New("this OAuth account is already bound to another user")
+ }
+
+ // Check if user already has a binding for this provider
+ var binding UserOAuthBinding
+ err = DB.Where("user_id = ? AND provider_id = ?", userId, providerId).First(&binding).Error
+ if err != nil {
+ // No existing binding, create new one
+ return CreateUserOAuthBinding(&UserOAuthBinding{
+ UserId: userId,
+ ProviderId: providerId,
+ ProviderUserId: newProviderUserId,
+ })
+ }
+
+ // Update existing binding
+ return DB.Model(&binding).Update("provider_user_id", newProviderUserId).Error
+}
+
+// DeleteUserOAuthBinding deletes an OAuth binding
+func DeleteUserOAuthBinding(userId, providerId int) error {
+ return DB.Where("user_id = ? AND provider_id = ?", userId, providerId).Delete(&UserOAuthBinding{}).Error
+}
+
+// DeleteUserOAuthBindingsByUserId deletes all OAuth bindings for a user
+func DeleteUserOAuthBindingsByUserId(userId int) error {
+ return DB.Where("user_id = ?", userId).Delete(&UserOAuthBinding{}).Error
+}
+
+// GetBindingCountByProviderId returns the number of bindings for a provider
+func GetBindingCountByProviderId(providerId int) (int64, error) {
+ var count int64
+ err := DB.Model(&UserOAuthBinding{}).Where("provider_id = ?", providerId).Count(&count).Error
+ return count, err
+}
diff --git a/oauth/discord.go b/oauth/discord.go
new file mode 100644
index 0000000000..b626d2f82e
--- /dev/null
+++ b/oauth/discord.go
@@ -0,0 +1,172 @@
+package oauth
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+)
+
+func init() {
+ Register("discord", &DiscordProvider{})
+}
+
+// DiscordProvider implements OAuth for Discord
+type DiscordProvider struct{}
+
+type discordOAuthResponse struct {
+ AccessToken string `json:"access_token"`
+ IDToken string `json:"id_token"`
+ RefreshToken string `json:"refresh_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ Scope string `json:"scope"`
+}
+
+type discordUser struct {
+ UID string `json:"id"`
+ ID string `json:"username"`
+ Name string `json:"global_name"`
+}
+
+func (p *DiscordProvider) GetName() string {
+ return "Discord"
+}
+
+func (p *DiscordProvider) IsEnabled() bool {
+ return system_setting.GetDiscordSettings().Enabled
+}
+
+func (p *DiscordProvider) ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error) {
+ if code == "" {
+ return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Discord] ExchangeToken: code=%s...", code[:min(len(code), 10)])
+
+ settings := system_setting.GetDiscordSettings()
+ redirectUri := fmt.Sprintf("%s/oauth/discord", system_setting.ServerAddress)
+ values := url.Values{}
+ values.Set("client_id", settings.ClientId)
+ values.Set("client_secret", settings.ClientSecret)
+ values.Set("code", code)
+ values.Set("grant_type", "authorization_code")
+ values.Set("redirect_uri", redirectUri)
+
+ logger.LogDebug(ctx, "[OAuth-Discord] ExchangeToken: redirect_uri=%s", redirectUri)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", "https://discord.com/api/v10/oauth2/token", strings.NewReader(values.Encode()))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{
+ Timeout: 5 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Discord] ExchangeToken error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "Discord"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-Discord] ExchangeToken response status: %d", res.StatusCode)
+
+ var discordResponse discordOAuthResponse
+ err = json.NewDecoder(res.Body).Decode(&discordResponse)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Discord] ExchangeToken decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if discordResponse.AccessToken == "" {
+ logger.LogError(ctx, "[OAuth-Discord] ExchangeToken failed: empty access token")
+ return nil, NewOAuthError(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": "Discord"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Discord] ExchangeToken success: scope=%s", discordResponse.Scope)
+
+ return &OAuthToken{
+ AccessToken: discordResponse.AccessToken,
+ TokenType: discordResponse.TokenType,
+ RefreshToken: discordResponse.RefreshToken,
+ ExpiresIn: discordResponse.ExpiresIn,
+ Scope: discordResponse.Scope,
+ IDToken: discordResponse.IDToken,
+ }, nil
+}
+
+func (p *DiscordProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error) {
+ logger.LogDebug(ctx, "[OAuth-Discord] GetUserInfo: fetching user info")
+
+ req, err := http.NewRequestWithContext(ctx, "GET", "https://discord.com/api/v10/users/@me", nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+token.AccessToken)
+
+ client := http.Client{
+ Timeout: 5 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Discord] GetUserInfo error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "Discord"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-Discord] GetUserInfo response status: %d", res.StatusCode)
+
+ if res.StatusCode != http.StatusOK {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Discord] GetUserInfo failed: status=%d", res.StatusCode))
+ return nil, NewOAuthError(i18n.MsgOAuthGetUserErr, nil)
+ }
+
+ var discordUser discordUser
+ err = json.NewDecoder(res.Body).Decode(&discordUser)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Discord] GetUserInfo decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if discordUser.UID == "" || discordUser.ID == "" {
+ logger.LogError(ctx, "[OAuth-Discord] GetUserInfo failed: empty user fields")
+ return nil, NewOAuthError(i18n.MsgOAuthUserInfoEmpty, map[string]any{"Provider": "Discord"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Discord] GetUserInfo success: uid=%s, username=%s, name=%s", discordUser.UID, discordUser.ID, discordUser.Name)
+
+ return &OAuthUser{
+ ProviderUserID: discordUser.UID,
+ Username: discordUser.ID,
+ DisplayName: discordUser.Name,
+ }, nil
+}
+
+func (p *DiscordProvider) IsUserIDTaken(providerUserID string) bool {
+ return model.IsDiscordIdAlreadyTaken(providerUserID)
+}
+
+func (p *DiscordProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
+ user.DiscordId = providerUserID
+ return user.FillUserByDiscordId()
+}
+
+func (p *DiscordProvider) SetProviderUserID(user *model.User, providerUserID string) {
+ user.DiscordId = providerUserID
+}
+
+func (p *DiscordProvider) GetProviderPrefix() string {
+ return "discord_"
+}
diff --git a/oauth/generic.go b/oauth/generic.go
new file mode 100644
index 0000000000..11bbb9b625
--- /dev/null
+++ b/oauth/generic.go
@@ -0,0 +1,673 @@
+package oauth
+
+import (
+ "context"
+ "encoding/base64"
+ stdjson "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/samber/lo"
+ "github.com/tidwall/gjson"
+)
+
+// AuthStyle defines how to send client credentials
+const (
+ AuthStyleAutoDetect = 0 // Auto-detect based on server response
+ AuthStyleInParams = 1 // Send client_id and client_secret as POST parameters
+ AuthStyleInHeader = 2 // Send as Basic Auth header
+)
+
+// GenericOAuthProvider implements OAuth for custom/generic OAuth providers
+type GenericOAuthProvider struct {
+ config *model.CustomOAuthProvider
+}
+
+type accessPolicy struct {
+ Logic string `json:"logic"`
+ Conditions []accessCondition `json:"conditions"`
+ Groups []accessPolicy `json:"groups"`
+}
+
+type accessCondition struct {
+ Field string `json:"field"`
+ Op string `json:"op"`
+ Value any `json:"value"`
+}
+
+type accessPolicyFailure struct {
+ Field string
+ Op string
+ Expected any
+ Current any
+}
+
+var supportedAccessPolicyOps = []string{
+ "eq",
+ "ne",
+ "gt",
+ "gte",
+ "lt",
+ "lte",
+ "in",
+ "not_in",
+ "contains",
+ "not_contains",
+ "exists",
+ "not_exists",
+}
+
+// NewGenericOAuthProvider creates a new generic OAuth provider from config
+func NewGenericOAuthProvider(config *model.CustomOAuthProvider) *GenericOAuthProvider {
+ return &GenericOAuthProvider{config: config}
+}
+
+func (p *GenericOAuthProvider) GetName() string {
+ return p.config.Name
+}
+
+func (p *GenericOAuthProvider) IsEnabled() bool {
+ return p.config.Enabled
+}
+
+func (p *GenericOAuthProvider) GetConfig() *model.CustomOAuthProvider {
+ return p.config
+}
+
+func (p *GenericOAuthProvider) ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error) {
+ if code == "" {
+ return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken: code=%s...", p.config.Slug, code[:min(len(code), 10)])
+
+ redirectUri := fmt.Sprintf("%s/oauth/%s", system_setting.ServerAddress, p.config.Slug)
+ values := url.Values{}
+ values.Set("grant_type", "authorization_code")
+ values.Set("code", code)
+ values.Set("redirect_uri", redirectUri)
+
+ // Determine auth style
+ authStyle := p.config.AuthStyle
+ if authStyle == AuthStyleAutoDetect {
+ // Default to params style for most OAuth servers
+ authStyle = AuthStyleInParams
+ }
+
+ var req *http.Request
+ var err error
+
+ if authStyle == AuthStyleInParams {
+ values.Set("client_id", p.config.ClientId)
+ values.Set("client_secret", p.config.ClientSecret)
+ }
+
+ req, err = http.NewRequestWithContext(ctx, "POST", p.config.TokenEndpoint, strings.NewReader(values.Encode()))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ if authStyle == AuthStyleInHeader {
+ // Basic Auth
+ credentials := base64.StdEncoding.EncodeToString([]byte(p.config.ClientId + ":" + p.config.ClientSecret))
+ req.Header.Set("Authorization", "Basic "+credentials)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken: token_endpoint=%s, redirect_uri=%s, auth_style=%d",
+ p.config.Slug, p.config.TokenEndpoint, redirectUri, authStyle)
+
+ client := http.Client{
+ Timeout: 20 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] ExchangeToken error: %s", p.config.Slug, err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": p.config.Name}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken response status: %d", p.config.Slug, res.StatusCode)
+
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] ExchangeToken read body error: %s", p.config.Slug, err.Error()))
+ return nil, err
+ }
+
+ bodyStr := string(body)
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken response body: %s", p.config.Slug, bodyStr[:min(len(bodyStr), 500)])
+
+ // Try to parse as JSON first
+ var tokenResponse struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ RefreshToken string `json:"refresh_token"`
+ ExpiresIn int `json:"expires_in"`
+ Scope string `json:"scope"`
+ IDToken string `json:"id_token"`
+ Error string `json:"error"`
+ ErrorDesc string `json:"error_description"`
+ }
+
+ if err := common.Unmarshal(body, &tokenResponse); err != nil {
+ // Try to parse as URL-encoded (some OAuth servers like GitHub return this format)
+ parsedValues, parseErr := url.ParseQuery(bodyStr)
+ if parseErr != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] ExchangeToken parse error: %s", p.config.Slug, err.Error()))
+ return nil, err
+ }
+ tokenResponse.AccessToken = parsedValues.Get("access_token")
+ tokenResponse.TokenType = parsedValues.Get("token_type")
+ tokenResponse.Scope = parsedValues.Get("scope")
+ }
+
+ if tokenResponse.Error != "" {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] ExchangeToken OAuth error: %s - %s",
+ p.config.Slug, tokenResponse.Error, tokenResponse.ErrorDesc))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": p.config.Name}, tokenResponse.ErrorDesc)
+ }
+
+ if tokenResponse.AccessToken == "" {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] ExchangeToken failed: empty access token", p.config.Slug))
+ return nil, NewOAuthError(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": p.config.Name})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] ExchangeToken success: scope=%s", p.config.Slug, tokenResponse.Scope)
+
+ return &OAuthToken{
+ AccessToken: tokenResponse.AccessToken,
+ TokenType: tokenResponse.TokenType,
+ RefreshToken: tokenResponse.RefreshToken,
+ ExpiresIn: tokenResponse.ExpiresIn,
+ Scope: tokenResponse.Scope,
+ IDToken: tokenResponse.IDToken,
+ }, nil
+}
+
+func (p *GenericOAuthProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error) {
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] GetUserInfo: fetching user info from %s", p.config.Slug, p.config.UserInfoEndpoint)
+
+ req, err := http.NewRequestWithContext(ctx, "GET", p.config.UserInfoEndpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ // Set authorization header
+ tokenType := normalizeAuthorizationTokenType(token.TokenType)
+ req.Header.Set("Authorization", fmt.Sprintf("%s %s", tokenType, token.AccessToken))
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{
+ Timeout: 20 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] GetUserInfo error: %s", p.config.Slug, err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": p.config.Name}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] GetUserInfo response status: %d", p.config.Slug, res.StatusCode)
+
+ if res.StatusCode != http.StatusOK {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] GetUserInfo failed: status=%d", p.config.Slug, res.StatusCode))
+ return nil, NewOAuthError(i18n.MsgOAuthGetUserErr, nil)
+ }
+
+ body, err := io.ReadAll(res.Body)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] GetUserInfo read body error: %s", p.config.Slug, err.Error()))
+ return nil, err
+ }
+
+ bodyStr := string(body)
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] GetUserInfo response body: %s", p.config.Slug, bodyStr[:min(len(bodyStr), 500)])
+
+ // Extract fields using gjson (supports JSONPath-like syntax)
+ userId := gjson.Get(bodyStr, p.config.UserIdField).String()
+ username := gjson.Get(bodyStr, p.config.UsernameField).String()
+ displayName := gjson.Get(bodyStr, p.config.DisplayNameField).String()
+ email := gjson.Get(bodyStr, p.config.EmailField).String()
+
+ // If user ID field returns a number, convert it
+ if userId == "" {
+ // Try to get as number
+ userIdNum := gjson.Get(bodyStr, p.config.UserIdField)
+ if userIdNum.Exists() {
+ userId = userIdNum.Raw
+ // Remove quotes if present
+ userId = strings.Trim(userId, "\"")
+ }
+ }
+
+ if userId == "" {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] GetUserInfo failed: empty user ID (field: %s)", p.config.Slug, p.config.UserIdField))
+ return nil, NewOAuthError(i18n.MsgOAuthUserInfoEmpty, map[string]any{"Provider": p.config.Name})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-Generic-%s] GetUserInfo success: id=%s, username=%s, name=%s, email=%s",
+ p.config.Slug, userId, username, displayName, email)
+
+ policyRaw := strings.TrimSpace(p.config.AccessPolicy)
+ if policyRaw != "" {
+ policy, err := parseAccessPolicy(policyRaw)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-Generic-%s] invalid access policy: %s", p.config.Slug, err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthGetUserErr, nil, "invalid access policy configuration")
+ }
+ allowed, failure := evaluateAccessPolicy(bodyStr, policy)
+ if !allowed {
+ message := renderAccessDeniedMessage(p.config.AccessDeniedMessage, p.config.Name, bodyStr, failure)
+ logger.LogWarn(ctx, fmt.Sprintf("[OAuth-Generic-%s] access denied by policy: field=%s op=%s expected=%v current=%v",
+ p.config.Slug, failure.Field, failure.Op, failure.Expected, failure.Current))
+ return nil, &AccessDeniedError{Message: message}
+ }
+ }
+
+ return &OAuthUser{
+ ProviderUserID: userId,
+ Username: username,
+ DisplayName: displayName,
+ Email: email,
+ Extra: map[string]any{
+ "provider": p.config.Slug,
+ },
+ }, nil
+}
+
+func (p *GenericOAuthProvider) IsUserIDTaken(providerUserID string) bool {
+ return model.IsProviderUserIdTaken(p.config.Id, providerUserID)
+}
+
+func (p *GenericOAuthProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
+ foundUser, err := model.GetUserByOAuthBinding(p.config.Id, providerUserID)
+ if err != nil {
+ return err
+ }
+ *user = *foundUser
+ return nil
+}
+
+func (p *GenericOAuthProvider) SetProviderUserID(user *model.User, providerUserID string) {
+ // For generic providers, we store the binding in user_oauth_bindings table
+ // This is handled separately in the OAuth controller
+}
+
+func (p *GenericOAuthProvider) GetProviderPrefix() string {
+ return p.config.Slug + "_"
+}
+
+// GetProviderId returns the provider ID for binding purposes
+func (p *GenericOAuthProvider) GetProviderId() int {
+ return p.config.Id
+}
+
+func normalizeAuthorizationTokenType(tokenType string) string {
+ tokenType = strings.TrimSpace(tokenType)
+ if tokenType == "" || strings.EqualFold(tokenType, "Bearer") {
+ return "Bearer"
+ }
+ return tokenType
+}
+
+// IsGenericProvider returns true for generic providers
+func (p *GenericOAuthProvider) IsGenericProvider() bool {
+ return true
+}
+
+func parseAccessPolicy(raw string) (*accessPolicy, error) {
+ var policy accessPolicy
+ if err := common.UnmarshalJsonStr(raw, &policy); err != nil {
+ return nil, err
+ }
+ if err := validateAccessPolicy(&policy); err != nil {
+ return nil, err
+ }
+ return &policy, nil
+}
+
+func validateAccessPolicy(policy *accessPolicy) error {
+ if policy == nil {
+ return errors.New("policy is nil")
+ }
+
+ logic := strings.ToLower(strings.TrimSpace(policy.Logic))
+ if logic == "" {
+ logic = "and"
+ }
+ if !lo.Contains([]string{"and", "or"}, logic) {
+ return fmt.Errorf("unsupported policy logic: %s", logic)
+ }
+ policy.Logic = logic
+
+ if len(policy.Conditions) == 0 && len(policy.Groups) == 0 {
+ return errors.New("policy requires at least one condition or group")
+ }
+
+ for index := range policy.Conditions {
+ if err := validateAccessCondition(&policy.Conditions[index], index); err != nil {
+ return err
+ }
+ }
+
+ for index := range policy.Groups {
+ if err := validateAccessPolicy(&policy.Groups[index]); err != nil {
+ return fmt.Errorf("invalid policy group[%d]: %w", index, err)
+ }
+ }
+
+ return nil
+}
+
+func validateAccessCondition(condition *accessCondition, index int) error {
+ if condition == nil {
+ return fmt.Errorf("condition[%d] is nil", index)
+ }
+
+ condition.Field = strings.TrimSpace(condition.Field)
+ if condition.Field == "" {
+ return fmt.Errorf("condition[%d].field is required", index)
+ }
+
+ condition.Op = normalizePolicyOp(condition.Op)
+ if !lo.Contains(supportedAccessPolicyOps, condition.Op) {
+ return fmt.Errorf("condition[%d].op is unsupported: %s", index, condition.Op)
+ }
+
+ if lo.Contains([]string{"in", "not_in"}, condition.Op) {
+ if _, ok := condition.Value.([]any); !ok {
+ return fmt.Errorf("condition[%d].value must be an array for op %s", index, condition.Op)
+ }
+ }
+
+ return nil
+}
+
+func evaluateAccessPolicy(body string, policy *accessPolicy) (bool, *accessPolicyFailure) {
+ if policy == nil {
+ return true, nil
+ }
+
+ logic := strings.ToLower(strings.TrimSpace(policy.Logic))
+ if logic == "" {
+ logic = "and"
+ }
+
+ hasAny := len(policy.Conditions) > 0 || len(policy.Groups) > 0
+ if !hasAny {
+ return true, nil
+ }
+
+ if logic == "or" {
+ var firstFailure *accessPolicyFailure
+ for _, cond := range policy.Conditions {
+ ok, failure := evaluateAccessCondition(body, cond)
+ if ok {
+ return true, nil
+ }
+ if firstFailure == nil {
+ firstFailure = failure
+ }
+ }
+ for _, group := range policy.Groups {
+ ok, failure := evaluateAccessPolicy(body, &group)
+ if ok {
+ return true, nil
+ }
+ if firstFailure == nil {
+ firstFailure = failure
+ }
+ }
+ return false, firstFailure
+ }
+
+ for _, cond := range policy.Conditions {
+ ok, failure := evaluateAccessCondition(body, cond)
+ if !ok {
+ return false, failure
+ }
+ }
+ for _, group := range policy.Groups {
+ ok, failure := evaluateAccessPolicy(body, &group)
+ if !ok {
+ return false, failure
+ }
+ }
+ return true, nil
+}
+
+func evaluateAccessCondition(body string, cond accessCondition) (bool, *accessPolicyFailure) {
+ path := cond.Field
+ op := cond.Op
+ result := gjson.Get(body, path)
+ current := gjsonResultToValue(result)
+ failure := &accessPolicyFailure{
+ Field: path,
+ Op: op,
+ Expected: cond.Value,
+ Current: current,
+ }
+
+ switch op {
+ case "exists":
+ return result.Exists(), failure
+ case "not_exists":
+ return !result.Exists(), failure
+ case "eq":
+ return compareAny(current, cond.Value) == 0, failure
+ case "ne":
+ return compareAny(current, cond.Value) != 0, failure
+ case "gt":
+ return compareAny(current, cond.Value) > 0, failure
+ case "gte":
+ return compareAny(current, cond.Value) >= 0, failure
+ case "lt":
+ return compareAny(current, cond.Value) < 0, failure
+ case "lte":
+ return compareAny(current, cond.Value) <= 0, failure
+ case "in":
+ return valueInSlice(current, cond.Value), failure
+ case "not_in":
+ return !valueInSlice(current, cond.Value), failure
+ case "contains":
+ return containsValue(current, cond.Value), failure
+ case "not_contains":
+ return !containsValue(current, cond.Value), failure
+ default:
+ return false, failure
+ }
+}
+
+func normalizePolicyOp(op string) string {
+ return strings.ToLower(strings.TrimSpace(op))
+}
+
+func gjsonResultToValue(result gjson.Result) any {
+ if !result.Exists() {
+ return nil
+ }
+ if result.IsArray() {
+ arr := result.Array()
+ values := make([]any, 0, len(arr))
+ for _, item := range arr {
+ values = append(values, gjsonResultToValue(item))
+ }
+ return values
+ }
+ switch result.Type {
+ case gjson.Null:
+ return nil
+ case gjson.True:
+ return true
+ case gjson.False:
+ return false
+ case gjson.Number:
+ return result.Num
+ case gjson.String:
+ return result.String()
+ case gjson.JSON:
+ var data any
+ if err := common.UnmarshalJsonStr(result.Raw, &data); err == nil {
+ return data
+ }
+ return result.Raw
+ default:
+ return result.Value()
+ }
+}
+
+func compareAny(left any, right any) int {
+ if lf, ok := toFloat(left); ok {
+ if rf, ok2 := toFloat(right); ok2 {
+ switch {
+ case lf < rf:
+ return -1
+ case lf > rf:
+ return 1
+ default:
+ return 0
+ }
+ }
+ }
+
+ ls := strings.TrimSpace(fmt.Sprint(left))
+ rs := strings.TrimSpace(fmt.Sprint(right))
+ switch {
+ case ls < rs:
+ return -1
+ case ls > rs:
+ return 1
+ default:
+ return 0
+ }
+}
+
+func toFloat(v any) (float64, bool) {
+ switch value := v.(type) {
+ case float64:
+ return value, true
+ case float32:
+ return float64(value), true
+ case int:
+ return float64(value), true
+ case int8:
+ return float64(value), true
+ case int16:
+ return float64(value), true
+ case int32:
+ return float64(value), true
+ case int64:
+ return float64(value), true
+ case uint:
+ return float64(value), true
+ case uint8:
+ return float64(value), true
+ case uint16:
+ return float64(value), true
+ case uint32:
+ return float64(value), true
+ case uint64:
+ return float64(value), true
+ case stdjson.Number:
+ n, err := value.Float64()
+ if err == nil {
+ return n, true
+ }
+ case string:
+ n, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
+ if err == nil {
+ return n, true
+ }
+ }
+ return 0, false
+}
+
+func valueInSlice(current any, expected any) bool {
+ list, ok := expected.([]any)
+ if !ok {
+ return false
+ }
+ return lo.ContainsBy(list, func(item any) bool {
+ return compareAny(current, item) == 0
+ })
+}
+
+func containsValue(current any, expected any) bool {
+ switch value := current.(type) {
+ case string:
+ target := strings.TrimSpace(fmt.Sprint(expected))
+ return strings.Contains(value, target)
+ case []any:
+ return lo.ContainsBy(value, func(item any) bool {
+ return compareAny(item, expected) == 0
+ })
+ }
+ return false
+}
+
+func renderAccessDeniedMessage(template string, providerName string, body string, failure *accessPolicyFailure) string {
+ defaultMessage := "Access denied: your account does not meet this provider's access requirements."
+ message := strings.TrimSpace(template)
+ if message == "" {
+ return defaultMessage
+ }
+
+ if failure == nil {
+ failure = &accessPolicyFailure{}
+ }
+
+ replacements := map[string]string{
+ "{{provider}}": providerName,
+ "{{field}}": failure.Field,
+ "{{op}}": failure.Op,
+ "{{required}}": fmt.Sprint(failure.Expected),
+ "{{current}}": fmt.Sprint(failure.Current),
+ }
+
+ for key, value := range replacements {
+ message = strings.ReplaceAll(message, key, value)
+ }
+
+ currentPattern := regexp.MustCompile(`\{\{current\.([^}]+)\}\}`)
+ message = currentPattern.ReplaceAllStringFunc(message, func(token string) string {
+ match := currentPattern.FindStringSubmatch(token)
+ if len(match) != 2 {
+ return ""
+ }
+ path := strings.TrimSpace(match[1])
+ if path == "" {
+ return ""
+ }
+ return strings.TrimSpace(gjson.Get(body, path).String())
+ })
+
+ requiredPattern := regexp.MustCompile(`\{\{required\.([^}]+)\}\}`)
+ message = requiredPattern.ReplaceAllStringFunc(message, func(token string) string {
+ match := requiredPattern.FindStringSubmatch(token)
+ if len(match) != 2 {
+ return ""
+ }
+ path := strings.TrimSpace(match[1])
+ if failure.Field == path {
+ return fmt.Sprint(failure.Expected)
+ }
+ return ""
+ })
+
+ return strings.TrimSpace(message)
+}
diff --git a/oauth/github.go b/oauth/github.go
new file mode 100644
index 0000000000..314118a376
--- /dev/null
+++ b/oauth/github.go
@@ -0,0 +1,178 @@
+package oauth
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/gin-gonic/gin"
+)
+
+func init() {
+ Register("github", &GitHubProvider{})
+}
+
+// GitHubProvider implements OAuth for GitHub
+type GitHubProvider struct{}
+
+type gitHubOAuthResponse struct {
+ AccessToken string `json:"access_token"`
+ Scope string `json:"scope"`
+ TokenType string `json:"token_type"`
+}
+
+type gitHubUser struct {
+ Id int64 `json:"id"` // GitHub numeric ID (permanent, never changes)
+ Login string `json:"login"` // GitHub username (can be changed by user)
+ Name string `json:"name"`
+ Email string `json:"email"`
+}
+
+func (p *GitHubProvider) GetName() string {
+ return "GitHub"
+}
+
+func (p *GitHubProvider) IsEnabled() bool {
+ return common.GitHubOAuthEnabled
+}
+
+func (p *GitHubProvider) ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error) {
+ if code == "" {
+ return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-GitHub] ExchangeToken: code=%s...", code[:min(len(code), 10)])
+
+ values := map[string]string{
+ "client_id": common.GitHubClientId,
+ "client_secret": common.GitHubClientSecret,
+ "code": code,
+ }
+ jsonData, err := json.Marshal(values)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", "https://github.com/login/oauth/access_token", bytes.NewBuffer(jsonData))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{
+ Timeout: 20 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] ExchangeToken error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "GitHub"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-GitHub] ExchangeToken response status: %d", res.StatusCode)
+
+ var oAuthResponse gitHubOAuthResponse
+ err = json.NewDecoder(res.Body).Decode(&oAuthResponse)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] ExchangeToken decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if oAuthResponse.AccessToken == "" {
+ logger.LogError(ctx, "[OAuth-GitHub] ExchangeToken failed: empty access token")
+ return nil, NewOAuthError(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": "GitHub"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-GitHub] ExchangeToken success: scope=%s", oAuthResponse.Scope)
+
+ return &OAuthToken{
+ AccessToken: oAuthResponse.AccessToken,
+ TokenType: oAuthResponse.TokenType,
+ Scope: oAuthResponse.Scope,
+ }, nil
+}
+
+func (p *GitHubProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error) {
+ logger.LogDebug(ctx, "[OAuth-GitHub] GetUserInfo: fetching user info")
+
+ req, err := http.NewRequestWithContext(ctx, "GET", "https://api.github.com/user", nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
+
+ client := http.Client{
+ Timeout: 20 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetUserInfo error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "GitHub"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-GitHub] GetUserInfo response status: %d", res.StatusCode)
+
+ // Check for non-200 status codes before attempting to decode
+ if res.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(res.Body)
+ bodyStr := string(body)
+ if len(bodyStr) > 500 {
+ bodyStr = bodyStr[:500] + "..."
+ }
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetUserInfo failed: status=%d, body=%s", res.StatusCode, bodyStr))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthGetUserErr, map[string]any{"Provider": "GitHub"}, fmt.Sprintf("status %d", res.StatusCode))
+ }
+
+ var githubUser gitHubUser
+ err = json.NewDecoder(res.Body).Decode(&githubUser)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetUserInfo decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if githubUser.Id == 0 || githubUser.Login == "" {
+ logger.LogError(ctx, "[OAuth-GitHub] GetUserInfo failed: empty id or login field")
+ return nil, NewOAuthError(i18n.MsgOAuthUserInfoEmpty, map[string]any{"Provider": "GitHub"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-GitHub] GetUserInfo success: id=%d, login=%s, name=%s, email=%s",
+ githubUser.Id, githubUser.Login, githubUser.Name, githubUser.Email)
+
+ return &OAuthUser{
+ ProviderUserID: strconv.FormatInt(githubUser.Id, 10), // Use numeric ID as primary identifier
+ Username: githubUser.Login,
+ DisplayName: githubUser.Name,
+ Email: githubUser.Email,
+ Extra: map[string]any{
+ "legacy_id": githubUser.Login, // Store login for migration from old accounts
+ },
+ }, nil
+}
+
+func (p *GitHubProvider) IsUserIDTaken(providerUserID string) bool {
+ return model.IsGitHubIdAlreadyTaken(providerUserID)
+}
+
+func (p *GitHubProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
+ user.GitHubId = providerUserID
+ return user.FillUserByGitHubId()
+}
+
+func (p *GitHubProvider) SetProviderUserID(user *model.User, providerUserID string) {
+ user.GitHubId = providerUserID
+}
+
+func (p *GitHubProvider) GetProviderPrefix() string {
+ return "github_"
+}
diff --git a/oauth/linuxdo.go b/oauth/linuxdo.go
new file mode 100644
index 0000000000..1ed91e0099
--- /dev/null
+++ b/oauth/linuxdo.go
@@ -0,0 +1,195 @@
+package oauth
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/gin-gonic/gin"
+)
+
+func init() {
+ Register("linuxdo", &LinuxDOProvider{})
+}
+
+// LinuxDOProvider implements OAuth for Linux DO
+type LinuxDOProvider struct{}
+
+type linuxdoUser struct {
+ Id int `json:"id"`
+ Username string `json:"username"`
+ Name string `json:"name"`
+ Active bool `json:"active"`
+ TrustLevel int `json:"trust_level"`
+ Silenced bool `json:"silenced"`
+}
+
+func (p *LinuxDOProvider) GetName() string {
+ return "Linux DO"
+}
+
+func (p *LinuxDOProvider) IsEnabled() bool {
+ return common.LinuxDOOAuthEnabled
+}
+
+func (p *LinuxDOProvider) ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error) {
+ if code == "" {
+ return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] ExchangeToken: code=%s...", code[:min(len(code), 10)])
+
+ // Get access token using Basic auth
+ tokenEndpoint := common.GetEnvOrDefaultString("LINUX_DO_TOKEN_ENDPOINT", "https://connect.linux.do/oauth2/token")
+ credentials := common.LinuxDOClientId + ":" + common.LinuxDOClientSecret
+ basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(credentials))
+
+ // Get redirect URI from request
+ scheme := "http"
+ if c.Request.TLS != nil {
+ scheme = "https"
+ }
+ redirectURI := fmt.Sprintf("%s://%s/api/oauth/linuxdo", scheme, c.Request.Host)
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] ExchangeToken: token_endpoint=%s, redirect_uri=%s", tokenEndpoint, redirectURI)
+
+ data := url.Values{}
+ data.Set("grant_type", "authorization_code")
+ data.Set("code", code)
+ data.Set("redirect_uri", redirectURI)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", tokenEndpoint, strings.NewReader(data.Encode()))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", basicAuth)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{Timeout: 5 * time.Second}
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-LinuxDO] ExchangeToken error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "Linux DO"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] ExchangeToken response status: %d", res.StatusCode)
+
+ var tokenRes struct {
+ AccessToken string `json:"access_token"`
+ Message string `json:"message"`
+ }
+ if err := json.NewDecoder(res.Body).Decode(&tokenRes); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-LinuxDO] ExchangeToken decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if tokenRes.AccessToken == "" {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-LinuxDO] ExchangeToken failed: %s", tokenRes.Message))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": "Linux DO"}, tokenRes.Message)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] ExchangeToken success")
+
+ return &OAuthToken{
+ AccessToken: tokenRes.AccessToken,
+ }, nil
+}
+
+func (p *LinuxDOProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error) {
+ userEndpoint := common.GetEnvOrDefaultString("LINUX_DO_USER_ENDPOINT", "https://connect.linux.do/api/user")
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] GetUserInfo: user_endpoint=%s", userEndpoint)
+
+ req, err := http.NewRequestWithContext(ctx, "GET", userEndpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+token.AccessToken)
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{Timeout: 5 * time.Second}
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-LinuxDO] GetUserInfo error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "Linux DO"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] GetUserInfo response status: %d", res.StatusCode)
+
+ var linuxdoUser linuxdoUser
+ if err := json.NewDecoder(res.Body).Decode(&linuxdoUser); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-LinuxDO] GetUserInfo decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if linuxdoUser.Id == 0 {
+ logger.LogError(ctx, "[OAuth-LinuxDO] GetUserInfo failed: invalid user id")
+ return nil, NewOAuthError(i18n.MsgOAuthUserInfoEmpty, map[string]any{"Provider": "Linux DO"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] GetUserInfo: id=%d, username=%s, name=%s, trust_level=%d, active=%v, silenced=%v",
+ linuxdoUser.Id, linuxdoUser.Username, linuxdoUser.Name, linuxdoUser.TrustLevel, linuxdoUser.Active, linuxdoUser.Silenced)
+
+ // Check trust level
+ if linuxdoUser.TrustLevel < common.LinuxDOMinimumTrustLevel {
+ logger.LogWarn(ctx, fmt.Sprintf("[OAuth-LinuxDO] GetUserInfo: trust level too low (required=%d, current=%d)",
+ common.LinuxDOMinimumTrustLevel, linuxdoUser.TrustLevel))
+ return nil, &TrustLevelError{
+ Required: common.LinuxDOMinimumTrustLevel,
+ Current: linuxdoUser.TrustLevel,
+ }
+ }
+
+ logger.LogDebug(ctx, "[OAuth-LinuxDO] GetUserInfo success: id=%d, username=%s", linuxdoUser.Id, linuxdoUser.Username)
+
+ return &OAuthUser{
+ ProviderUserID: strconv.Itoa(linuxdoUser.Id),
+ Username: linuxdoUser.Username,
+ DisplayName: linuxdoUser.Name,
+ Extra: map[string]any{
+ "trust_level": linuxdoUser.TrustLevel,
+ "active": linuxdoUser.Active,
+ "silenced": linuxdoUser.Silenced,
+ },
+ }, nil
+}
+
+func (p *LinuxDOProvider) IsUserIDTaken(providerUserID string) bool {
+ return model.IsLinuxDOIdAlreadyTaken(providerUserID)
+}
+
+func (p *LinuxDOProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
+ user.LinuxDOId = providerUserID
+ return user.FillUserByLinuxDOId()
+}
+
+func (p *LinuxDOProvider) SetProviderUserID(user *model.User, providerUserID string) {
+ user.LinuxDOId = providerUserID
+}
+
+func (p *LinuxDOProvider) GetProviderPrefix() string {
+ return "linuxdo_"
+}
+
+// TrustLevelError indicates the user's trust level is too low
+type TrustLevelError struct {
+ Required int
+ Current int
+}
+
+func (e *TrustLevelError) Error() string {
+ return "trust level too low"
+}
diff --git a/oauth/oidc.go b/oauth/oidc.go
new file mode 100644
index 0000000000..9bdc6d01e5
--- /dev/null
+++ b/oauth/oidc.go
@@ -0,0 +1,177 @@
+package oauth
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/i18n"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/setting/system_setting"
+ "github.com/gin-gonic/gin"
+)
+
+func init() {
+ Register("oidc", &OIDCProvider{})
+}
+
+// OIDCProvider implements OAuth for OIDC
+type OIDCProvider struct{}
+
+type oidcOAuthResponse struct {
+ AccessToken string `json:"access_token"`
+ IDToken string `json:"id_token"`
+ RefreshToken string `json:"refresh_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ Scope string `json:"scope"`
+}
+
+type oidcUser struct {
+ OpenID string `json:"sub"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ PreferredUsername string `json:"preferred_username"`
+ Picture string `json:"picture"`
+}
+
+func (p *OIDCProvider) GetName() string {
+ return "OIDC"
+}
+
+func (p *OIDCProvider) IsEnabled() bool {
+ return system_setting.GetOIDCSettings().Enabled
+}
+
+func (p *OIDCProvider) ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error) {
+ if code == "" {
+ return nil, NewOAuthError(i18n.MsgOAuthInvalidCode, nil)
+ }
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] ExchangeToken: code=%s...", code[:min(len(code), 10)])
+
+ settings := system_setting.GetOIDCSettings()
+ redirectUri := fmt.Sprintf("%s/oauth/oidc", system_setting.ServerAddress)
+ values := url.Values{}
+ values.Set("client_id", settings.ClientId)
+ values.Set("client_secret", settings.ClientSecret)
+ values.Set("code", code)
+ values.Set("grant_type", "authorization_code")
+ values.Set("redirect_uri", redirectUri)
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] ExchangeToken: token_endpoint=%s, redirect_uri=%s", settings.TokenEndpoint, redirectUri)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", settings.TokenEndpoint, strings.NewReader(values.Encode()))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+
+ client := http.Client{
+ Timeout: 5 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] ExchangeToken error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "OIDC"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] ExchangeToken response status: %d", res.StatusCode)
+
+ var oidcResponse oidcOAuthResponse
+ err = json.NewDecoder(res.Body).Decode(&oidcResponse)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] ExchangeToken decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if oidcResponse.AccessToken == "" {
+ logger.LogError(ctx, "[OAuth-OIDC] ExchangeToken failed: empty access token")
+ return nil, NewOAuthError(i18n.MsgOAuthTokenFailed, map[string]any{"Provider": "OIDC"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] ExchangeToken success: scope=%s", oidcResponse.Scope)
+
+ return &OAuthToken{
+ AccessToken: oidcResponse.AccessToken,
+ TokenType: oidcResponse.TokenType,
+ RefreshToken: oidcResponse.RefreshToken,
+ ExpiresIn: oidcResponse.ExpiresIn,
+ Scope: oidcResponse.Scope,
+ IDToken: oidcResponse.IDToken,
+ }, nil
+}
+
+func (p *OIDCProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error) {
+ settings := system_setting.GetOIDCSettings()
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] GetUserInfo: userinfo_endpoint=%s", settings.UserInfoEndpoint)
+
+ req, err := http.NewRequestWithContext(ctx, "GET", settings.UserInfoEndpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+token.AccessToken)
+
+ client := http.Client{
+ Timeout: 5 * time.Second,
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] GetUserInfo error: %s", err.Error()))
+ return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "OIDC"}, err.Error())
+ }
+ defer res.Body.Close()
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] GetUserInfo response status: %d", res.StatusCode)
+
+ if res.StatusCode != http.StatusOK {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] GetUserInfo failed: status=%d", res.StatusCode))
+ return nil, NewOAuthError(i18n.MsgOAuthGetUserErr, nil)
+ }
+
+ var oidcUser oidcUser
+ err = json.NewDecoder(res.Body).Decode(&oidcUser)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] GetUserInfo decode error: %s", err.Error()))
+ return nil, err
+ }
+
+ if oidcUser.OpenID == "" || oidcUser.Email == "" {
+ logger.LogError(ctx, fmt.Sprintf("[OAuth-OIDC] GetUserInfo failed: empty fields (sub=%s, email=%s)", oidcUser.OpenID, oidcUser.Email))
+ return nil, NewOAuthError(i18n.MsgOAuthUserInfoEmpty, map[string]any{"Provider": "OIDC"})
+ }
+
+ logger.LogDebug(ctx, "[OAuth-OIDC] GetUserInfo success: sub=%s, username=%s, name=%s, email=%s", oidcUser.OpenID, oidcUser.PreferredUsername, oidcUser.Name, oidcUser.Email)
+
+ return &OAuthUser{
+ ProviderUserID: oidcUser.OpenID,
+ Username: oidcUser.PreferredUsername,
+ DisplayName: oidcUser.Name,
+ Email: oidcUser.Email,
+ }, nil
+}
+
+func (p *OIDCProvider) IsUserIDTaken(providerUserID string) bool {
+ return model.IsOidcIdAlreadyTaken(providerUserID)
+}
+
+func (p *OIDCProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
+ user.OidcId = providerUserID
+ return user.FillUserByOidcId()
+}
+
+func (p *OIDCProvider) SetProviderUserID(user *model.User, providerUserID string) {
+ user.OidcId = providerUserID
+}
+
+func (p *OIDCProvider) GetProviderPrefix() string {
+ return "oidc_"
+}
diff --git a/oauth/provider.go b/oauth/provider.go
new file mode 100644
index 0000000000..785ed25d25
--- /dev/null
+++ b/oauth/provider.go
@@ -0,0 +1,36 @@
+package oauth
+
+import (
+ "context"
+
+ "github.com/QuantumNous/new-api/model"
+ "github.com/gin-gonic/gin"
+)
+
+// Provider defines the interface for OAuth providers
+type Provider interface {
+ // GetName returns the display name of the provider (e.g., "GitHub", "Discord")
+ GetName() string
+
+ // IsEnabled returns whether this OAuth provider is enabled
+ IsEnabled() bool
+
+ // ExchangeToken exchanges the authorization code for an access token
+ // The gin.Context is passed for providers that need request info (e.g., for redirect_uri)
+ ExchangeToken(ctx context.Context, code string, c *gin.Context) (*OAuthToken, error)
+
+ // GetUserInfo retrieves user information using the access token
+ GetUserInfo(ctx context.Context, token *OAuthToken) (*OAuthUser, error)
+
+ // IsUserIDTaken checks if the provider user ID is already associated with an account
+ IsUserIDTaken(providerUserID string) bool
+
+ // FillUserByProviderID fills the user model by provider user ID
+ FillUserByProviderID(user *model.User, providerUserID string) error
+
+ // SetProviderUserID sets the provider user ID on the user model
+ SetProviderUserID(user *model.User, providerUserID string)
+
+ // GetProviderPrefix returns the prefix for auto-generated usernames (e.g., "github_")
+ GetProviderPrefix() string
+}
diff --git a/oauth/registry.go b/oauth/registry.go
new file mode 100644
index 0000000000..91d1963645
--- /dev/null
+++ b/oauth/registry.go
@@ -0,0 +1,134 @@
+package oauth
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+)
+
+var (
+ providers = make(map[string]Provider)
+ mu sync.RWMutex
+ // customProviderSlugs tracks which providers are custom (can be unregistered)
+ customProviderSlugs = make(map[string]bool)
+)
+
+// Register registers an OAuth provider with the given name
+func Register(name string, provider Provider) {
+ mu.Lock()
+ defer mu.Unlock()
+ providers[name] = provider
+}
+
+// RegisterCustom registers a custom OAuth provider (can be unregistered later)
+func RegisterCustom(name string, provider Provider) {
+ mu.Lock()
+ defer mu.Unlock()
+ providers[name] = provider
+ customProviderSlugs[name] = true
+}
+
+// Unregister removes a provider from the registry
+func Unregister(name string) {
+ mu.Lock()
+ defer mu.Unlock()
+ delete(providers, name)
+ delete(customProviderSlugs, name)
+}
+
+// GetProvider returns the OAuth provider for the given name
+func GetProvider(name string) Provider {
+ mu.RLock()
+ defer mu.RUnlock()
+ return providers[name]
+}
+
+// GetAllProviders returns all registered OAuth providers
+func GetAllProviders() map[string]Provider {
+ mu.RLock()
+ defer mu.RUnlock()
+ result := make(map[string]Provider, len(providers))
+ for k, v := range providers {
+ result[k] = v
+ }
+ return result
+}
+
+// GetEnabledCustomProviders returns all enabled custom OAuth providers
+func GetEnabledCustomProviders() []*GenericOAuthProvider {
+ mu.RLock()
+ defer mu.RUnlock()
+ var result []*GenericOAuthProvider
+ for name, provider := range providers {
+ if customProviderSlugs[name] {
+ if gp, ok := provider.(*GenericOAuthProvider); ok && gp.IsEnabled() {
+ result = append(result, gp)
+ }
+ }
+ }
+ return result
+}
+
+// IsProviderRegistered checks if a provider is registered
+func IsProviderRegistered(name string) bool {
+ mu.RLock()
+ defer mu.RUnlock()
+ _, ok := providers[name]
+ return ok
+}
+
+// IsCustomProvider checks if a provider is a custom provider
+func IsCustomProvider(name string) bool {
+ mu.RLock()
+ defer mu.RUnlock()
+ return customProviderSlugs[name]
+}
+
+// LoadCustomProviders loads all custom OAuth providers from the database
+func LoadCustomProviders() error {
+ // First, unregister all existing custom providers
+ mu.Lock()
+ for name := range customProviderSlugs {
+ delete(providers, name)
+ }
+ customProviderSlugs = make(map[string]bool)
+ mu.Unlock()
+
+ // Load all custom providers from database
+ customProviders, err := model.GetAllCustomOAuthProviders()
+ if err != nil {
+ common.SysError("Failed to load custom OAuth providers: " + err.Error())
+ return err
+ }
+
+ // Register each custom provider
+ for _, config := range customProviders {
+ provider := NewGenericOAuthProvider(config)
+ RegisterCustom(config.Slug, provider)
+ common.SysLog("Loaded custom OAuth provider: " + config.Name + " (" + config.Slug + ")")
+ }
+
+ common.SysLog(fmt.Sprintf("Loaded %d custom OAuth providers", len(customProviders)))
+ return nil
+}
+
+// ReloadCustomProviders reloads all custom OAuth providers from the database
+func ReloadCustomProviders() error {
+ return LoadCustomProviders()
+}
+
+// RegisterOrUpdateCustomProvider registers or updates a single custom provider
+func RegisterOrUpdateCustomProvider(config *model.CustomOAuthProvider) {
+ provider := NewGenericOAuthProvider(config)
+ mu.Lock()
+ defer mu.Unlock()
+ providers[config.Slug] = provider
+ customProviderSlugs[config.Slug] = true
+}
+
+// UnregisterCustomProvider unregisters a custom provider by slug
+func UnregisterCustomProvider(slug string) {
+ Unregister(slug)
+}
diff --git a/oauth/types.go b/oauth/types.go
new file mode 100644
index 0000000000..383e6f3513
--- /dev/null
+++ b/oauth/types.go
@@ -0,0 +1,68 @@
+package oauth
+
+// OAuthToken represents the token received from OAuth provider
+type OAuthToken struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+ ExpiresIn int `json:"expires_in,omitempty"`
+ Scope string `json:"scope,omitempty"`
+ IDToken string `json:"id_token,omitempty"`
+}
+
+// OAuthUser represents the user info from OAuth provider
+type OAuthUser struct {
+ // ProviderUserID is the unique identifier from the OAuth provider
+ ProviderUserID string
+ // Username is the username from the OAuth provider (e.g., GitHub login)
+ Username string
+ // DisplayName is the display name from the OAuth provider
+ DisplayName string
+ // Email is the email from the OAuth provider
+ Email string
+ // Extra contains any additional provider-specific data
+ Extra map[string]any
+}
+
+// OAuthError represents a translatable OAuth error
+type OAuthError struct {
+ // MsgKey is the i18n message key
+ MsgKey string
+ // Params contains optional parameters for the message template
+ Params map[string]any
+ // RawError is the underlying error for logging purposes
+ RawError string
+}
+
+func (e *OAuthError) Error() string {
+ if e.RawError != "" {
+ return e.RawError
+ }
+ return e.MsgKey
+}
+
+// NewOAuthError creates a new OAuth error with the given message key
+func NewOAuthError(msgKey string, params map[string]any) *OAuthError {
+ return &OAuthError{
+ MsgKey: msgKey,
+ Params: params,
+ }
+}
+
+// NewOAuthErrorWithRaw creates a new OAuth error with raw error message for logging
+func NewOAuthErrorWithRaw(msgKey string, params map[string]any, rawError string) *OAuthError {
+ return &OAuthError{
+ MsgKey: msgKey,
+ Params: params,
+ RawError: rawError,
+ }
+}
+
+// AccessDeniedError is a direct user-facing access denial message.
+type AccessDeniedError struct {
+ Message string
+}
+
+func (e *AccessDeniedError) Error() string {
+ return e.Message
+}
diff --git a/pkg/cachex/codec.go b/pkg/cachex/codec.go
new file mode 100644
index 0000000000..2e4957a848
--- /dev/null
+++ b/pkg/cachex/codec.go
@@ -0,0 +1,53 @@
+package cachex
+
+import (
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+type ValueCodec[V any] interface {
+ Encode(v V) (string, error)
+ Decode(s string) (V, error)
+}
+
+type IntCodec struct{}
+
+func (c IntCodec) Encode(v int) (string, error) {
+ return strconv.Itoa(v), nil
+}
+
+func (c IntCodec) Decode(s string) (int, error) {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return 0, fmt.Errorf("empty int value")
+ }
+ return strconv.Atoi(s)
+}
+
+type StringCodec struct{}
+
+func (c StringCodec) Encode(v string) (string, error) { return v, nil }
+func (c StringCodec) Decode(s string) (string, error) { return s, nil }
+
+type JSONCodec[V any] struct{}
+
+func (c JSONCodec[V]) Encode(v V) (string, error) {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
+}
+
+func (c JSONCodec[V]) Decode(s string) (V, error) {
+ var v V
+ if strings.TrimSpace(s) == "" {
+ return v, fmt.Errorf("empty json value")
+ }
+ if err := json.Unmarshal([]byte(s), &v); err != nil {
+ return v, err
+ }
+ return v, nil
+}
diff --git a/pkg/cachex/hybrid_cache.go b/pkg/cachex/hybrid_cache.go
new file mode 100644
index 0000000000..9df3cfe649
--- /dev/null
+++ b/pkg/cachex/hybrid_cache.go
@@ -0,0 +1,285 @@
+package cachex
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/go-redis/redis/v8"
+ "github.com/samber/hot"
+)
+
+const (
+ defaultRedisOpTimeout = 2 * time.Second
+ defaultRedisScanTimeout = 30 * time.Second
+ defaultRedisDelTimeout = 10 * time.Second
+)
+
+type HybridCacheConfig[V any] struct {
+ Namespace Namespace
+
+ // Redis is used when RedisEnabled returns true (or RedisEnabled is nil) and Redis is not nil.
+ Redis *redis.Client
+ RedisCodec ValueCodec[V]
+ RedisEnabled func() bool
+
+ // Memory builds a hot cache used when Redis is disabled. Keys stored in memory are fully namespaced.
+ Memory func() *hot.HotCache[string, V]
+}
+
+// HybridCache is a small helper that uses Redis when enabled, otherwise falls back to in-memory hot cache.
+type HybridCache[V any] struct {
+ ns Namespace
+
+ redis *redis.Client
+ redisCodec ValueCodec[V]
+ redisEnabled func() bool
+
+ memOnce sync.Once
+ memInit func() *hot.HotCache[string, V]
+ mem *hot.HotCache[string, V]
+}
+
+func NewHybridCache[V any](cfg HybridCacheConfig[V]) *HybridCache[V] {
+ return &HybridCache[V]{
+ ns: cfg.Namespace,
+ redis: cfg.Redis,
+ redisCodec: cfg.RedisCodec,
+ redisEnabled: cfg.RedisEnabled,
+ memInit: cfg.Memory,
+ }
+}
+
+func (c *HybridCache[V]) FullKey(key string) string {
+ return c.ns.FullKey(key)
+}
+
+func (c *HybridCache[V]) redisOn() bool {
+ if c.redis == nil || c.redisCodec == nil {
+ return false
+ }
+ if c.redisEnabled == nil {
+ return true
+ }
+ return c.redisEnabled()
+}
+
+func (c *HybridCache[V]) memCache() *hot.HotCache[string, V] {
+ c.memOnce.Do(func() {
+ if c.memInit == nil {
+ c.mem = hot.NewHotCache[string, V](hot.LRU, 1).Build()
+ return
+ }
+ c.mem = c.memInit()
+ })
+ return c.mem
+}
+
+func (c *HybridCache[V]) Get(key string) (value V, found bool, err error) {
+ full := c.ns.FullKey(key)
+ if full == "" {
+ var zero V
+ return zero, false, nil
+ }
+
+ if c.redisOn() {
+ ctx, cancel := context.WithTimeout(context.Background(), defaultRedisOpTimeout)
+ defer cancel()
+
+ raw, e := c.redis.Get(ctx, full).Result()
+ if e == nil {
+ v, decErr := c.redisCodec.Decode(raw)
+ if decErr != nil {
+ var zero V
+ return zero, false, decErr
+ }
+ return v, true, nil
+ }
+ if errors.Is(e, redis.Nil) {
+ var zero V
+ return zero, false, nil
+ }
+ var zero V
+ return zero, false, e
+ }
+
+ return c.memCache().Get(full)
+}
+
+func (c *HybridCache[V]) SetWithTTL(key string, v V, ttl time.Duration) error {
+ full := c.ns.FullKey(key)
+ if full == "" {
+ return nil
+ }
+
+ if c.redisOn() {
+ raw, err := c.redisCodec.Encode(v)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), defaultRedisOpTimeout)
+ defer cancel()
+ return c.redis.Set(ctx, full, raw, ttl).Err()
+ }
+
+ c.memCache().SetWithTTL(full, v, ttl)
+ return nil
+}
+
+// Keys returns keys with valid values. In Redis, it returns all matching keys.
+func (c *HybridCache[V]) Keys() ([]string, error) {
+ if c.redisOn() {
+ return c.scanKeys(c.ns.MatchPattern())
+ }
+ return c.memCache().Keys(), nil
+}
+
+func (c *HybridCache[V]) scanKeys(match string) ([]string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), defaultRedisScanTimeout)
+ defer cancel()
+
+ var cursor uint64
+ keys := make([]string, 0, 1024)
+ for {
+ k, next, err := c.redis.Scan(ctx, cursor, match, 1000).Result()
+ if err != nil {
+ return keys, err
+ }
+ keys = append(keys, k...)
+ cursor = next
+ if cursor == 0 {
+ break
+ }
+ }
+ return keys, nil
+}
+
+func (c *HybridCache[V]) Purge() error {
+ if c.redisOn() {
+ keys, err := c.scanKeys(c.ns.MatchPattern())
+ if err != nil {
+ return err
+ }
+ if len(keys) == 0 {
+ return nil
+ }
+ _, err = c.DeleteMany(keys)
+ return err
+ }
+
+ c.memCache().Purge()
+ return nil
+}
+
+func (c *HybridCache[V]) DeleteByPrefix(prefix string) (int, error) {
+ fullPrefix := c.ns.FullKey(prefix)
+ if fullPrefix == "" {
+ return 0, nil
+ }
+ if !strings.HasSuffix(fullPrefix, ":") {
+ fullPrefix += ":"
+ }
+
+ if c.redisOn() {
+ match := fullPrefix + "*"
+ keys, err := c.scanKeys(match)
+ if err != nil {
+ return 0, err
+ }
+ if len(keys) == 0 {
+ return 0, nil
+ }
+
+ res, err := c.DeleteMany(keys)
+ if err != nil {
+ return 0, err
+ }
+ deleted := 0
+ for _, ok := range res {
+ if ok {
+ deleted++
+ }
+ }
+ return deleted, nil
+ }
+
+ // In memory, we filter keys and bulk delete.
+ allKeys := c.memCache().Keys()
+ keys := make([]string, 0, 128)
+ for _, k := range allKeys {
+ if strings.HasPrefix(k, fullPrefix) {
+ keys = append(keys, k)
+ }
+ }
+ if len(keys) == 0 {
+ return 0, nil
+ }
+ res, _ := c.DeleteMany(keys)
+ deleted := 0
+ for _, ok := range res {
+ if ok {
+ deleted++
+ }
+ }
+ return deleted, nil
+}
+
+// DeleteMany accepts either fully namespaced keys or raw keys and deletes them.
+// It returns a map keyed by fully namespaced keys.
+func (c *HybridCache[V]) DeleteMany(keys []string) (map[string]bool, error) {
+ res := make(map[string]bool, len(keys))
+ if len(keys) == 0 {
+ return res, nil
+ }
+
+ fullKeys := make([]string, 0, len(keys))
+ for _, k := range keys {
+ k = c.ns.FullKey(k)
+ if k == "" {
+ continue
+ }
+ fullKeys = append(fullKeys, k)
+ }
+ if len(fullKeys) == 0 {
+ return res, nil
+ }
+
+ if c.redisOn() {
+ ctx, cancel := context.WithTimeout(context.Background(), defaultRedisDelTimeout)
+ defer cancel()
+
+ pipe := c.redis.Pipeline()
+ cmds := make([]*redis.IntCmd, 0, len(fullKeys))
+ for _, k := range fullKeys {
+ // UNLINK is non-blocking vs DEL for large key batches.
+ cmds = append(cmds, pipe.Unlink(ctx, k))
+ }
+ _, err := pipe.Exec(ctx)
+ if err != nil && !errors.Is(err, redis.Nil) {
+ return res, err
+ }
+ for i, cmd := range cmds {
+ deleted := cmd != nil && cmd.Err() == nil && cmd.Val() > 0
+ res[fullKeys[i]] = deleted
+ }
+ return res, nil
+ }
+
+ return c.memCache().DeleteMany(fullKeys), nil
+}
+
+func (c *HybridCache[V]) Capacity() (mainCacheCapacity int, missingCacheCapacity int) {
+ if c.redisOn() {
+ return 0, 0
+ }
+ return c.memCache().Capacity()
+}
+
+func (c *HybridCache[V]) Algorithm() (mainCacheAlgorithm string, missingCacheAlgorithm string) {
+ if c.redisOn() {
+ return "redis", ""
+ }
+ return c.memCache().Algorithm()
+}
diff --git a/pkg/cachex/namespace.go b/pkg/cachex/namespace.go
new file mode 100644
index 0000000000..e6806bf2f9
--- /dev/null
+++ b/pkg/cachex/namespace.go
@@ -0,0 +1,38 @@
+package cachex
+
+import "strings"
+
+// Namespace isolates keys between different cache use-cases. (e.g. "channel_affinity:v1").
+type Namespace string
+
+func (n Namespace) prefix() string {
+ ns := strings.TrimSpace(string(n))
+ ns = strings.TrimRight(ns, ":")
+ if ns == "" {
+ return ""
+ }
+ return ns + ":"
+}
+
+func (n Namespace) FullKey(key string) string {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return ""
+ }
+ p := n.prefix()
+ if p == "" {
+ return strings.TrimLeft(key, ":")
+ }
+ if strings.HasPrefix(key, p) {
+ return key
+ }
+ return p + strings.TrimLeft(key, ":")
+}
+
+func (n Namespace) MatchPattern() string {
+ p := n.prefix()
+ if p == "" {
+ return "*"
+ }
+ return p + "*"
+}
diff --git a/relay/audio_handler.go b/relay/audio_handler.go
index 5c34b7923e..7d2a4f222c 100644
--- a/relay/audio_handler.go
+++ b/relay/audio_handler.go
@@ -70,7 +70,7 @@ func AudioHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
if usage.(*dto.Usage).CompletionTokenDetails.AudioTokens > 0 || usage.(*dto.Usage).PromptTokensDetails.AudioTokens > 0 {
service.PostAudioConsumeQuota(c, info, usage.(*dto.Usage), "")
} else {
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
}
return nil
diff --git a/relay/channel/adapter.go b/relay/channel/adapter.go
index ff7606e2e2..d2f7c6bb6d 100644
--- a/relay/channel/adapter.go
+++ b/relay/channel/adapter.go
@@ -36,6 +36,32 @@ type TaskAdaptor interface {
ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError
+ // ── Billing ──────────────────────────────────────────────────────
+
+ // EstimateBilling returns OtherRatios for pre-charge based on user request.
+ // Called after ValidateRequestAndSetAction, before price calculation.
+ // Adaptors should extract duration, resolution, etc. from the parsed request
+ // and return them as ratio multipliers (e.g. {"seconds": 5, "size": 1.666}).
+ // Return nil to use the base model price without extra ratios.
+ EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64
+
+ // AdjustBillingOnSubmit returns adjusted OtherRatios from the upstream
+ // submit response. Called after a successful DoResponse.
+ // If the upstream returned actual parameters that differ from the estimate
+ // (e.g. actual seconds), return updated ratios so the caller can recalculate
+ // the quota and settle the delta with the pre-charge.
+ // Return nil if no adjustment is needed.
+ AdjustBillingOnSubmit(info *relaycommon.RelayInfo, taskData []byte) map[string]float64
+
+ // AdjustBillingOnComplete returns the actual quota when a task reaches a
+ // terminal state (success/failure) during polling.
+ // Called by the polling loop after ParseTaskResult.
+ // Return a positive value to trigger delta settlement (supplement / refund).
+ // Return 0 to keep the pre-charged amount unchanged.
+ AdjustBillingOnComplete(task *model.Task, taskResult *relaycommon.TaskInfo) int
+
+ // ── Request / Response ───────────────────────────────────────────
+
BuildRequestURL(info *relaycommon.RelayInfo) (string, error)
BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error
BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error)
@@ -46,9 +72,9 @@ type TaskAdaptor interface {
GetModelList() []string
GetChannelName() string
- // FetchTask
- FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error)
+ // ── Polling ──────────────────────────────────────────────────────
+ FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error)
ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error)
}
diff --git a/relay/channel/ali/adaptor.go b/relay/channel/ali/adaptor.go
index 23ef5f4bea..faf7098195 100644
--- a/relay/channel/ali/adaptor.go
+++ b/relay/channel/ali/adaptor.go
@@ -13,8 +13,8 @@ import (
"github.com/QuantumNous/new-api/relay/channel/openai"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/constant"
- "github.com/QuantumNous/new-api/setting/model_setting"
"github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/setting/model_setting"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
@@ -84,6 +84,8 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/embeddings", info.ChannelBaseUrl)
case constant.RelayModeRerank:
fullRequestURL = fmt.Sprintf("%s/api/v1/services/rerank/text-rerank/text-rerank", info.ChannelBaseUrl)
+ case constant.RelayModeResponses:
+ fullRequestURL = fmt.Sprintf("%s/api/v2/apps/protocols/compatible-mode/v1/responses", info.ChannelBaseUrl)
case constant.RelayModeImagesGenerations:
if isSyncImageModel(info.OriginModelName) {
fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/multimodal-generation/generation", info.ChannelBaseUrl)
@@ -210,8 +212,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
}
func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
- //TODO implement me
- return nil, errors.New("not implemented")
+ return request, nil
}
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
@@ -222,11 +223,8 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
switch info.RelayFormat {
case types.RelayFormatClaude:
if supportsAliAnthropicMessages(info.UpstreamModelName) {
- if info.IsStream {
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
- }
-
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
}
adaptor := openai.Adaptor{}
diff --git a/relay/channel/ali/dto.go b/relay/channel/ali/dto.go
index 75be8ff790..ec564f08ea 100644
--- a/relay/channel/ali/dto.go
+++ b/relay/channel/ali/dto.go
@@ -171,12 +171,17 @@ type AliImageRequest struct {
}
type AliImageParameters struct {
- Size string `json:"size,omitempty"`
- N int `json:"n,omitempty"`
- Steps string `json:"steps,omitempty"`
- Scale string `json:"scale,omitempty"`
- Watermark *bool `json:"watermark,omitempty"`
- PromptExtend *bool `json:"prompt_extend,omitempty"`
+ Size string `json:"size,omitempty"`
+ N int `json:"n,omitempty"`
+ Steps string `json:"steps,omitempty"`
+ Scale string `json:"scale,omitempty"`
+ Watermark *bool `json:"watermark,omitempty"`
+ PromptExtend *bool `json:"prompt_extend,omitempty"`
+ ThinkingMode *bool `json:"thinking_mode,omitempty"`
+ EnableSequential *bool `json:"enable_sequential,omitempty"`
+ BboxList any `json:"bbox_list,omitempty"`
+ ColorPalette any `json:"color_palette,omitempty"`
+ Seed *int `json:"seed,omitempty"`
}
func (p *AliImageParameters) PromptExtendValue() bool {
diff --git a/relay/channel/ali/image.go b/relay/channel/ali/image.go
index cfd9a0fdd9..79bc22029f 100644
--- a/relay/channel/ali/image.go
+++ b/relay/channel/ali/image.go
@@ -18,6 +18,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
func oaiImage2AliImageRequest(info *relaycommon.RelayInfo, request dto.ImageRequest, isSync bool) (*AliImageRequest, error) {
@@ -34,7 +35,7 @@ func oaiImage2AliImageRequest(info *relaycommon.RelayInfo, request dto.ImageRequ
// 兼容没有parameters字段的情况,从openai标准字段中提取参数
imageRequest.Parameters = AliImageParameters{
Size: strings.Replace(request.Size, "x", "*", -1),
- N: int(request.N),
+ N: int(lo.FromPtrOr(request.N, uint(1))),
Watermark: request.Watermark,
}
}
@@ -53,7 +54,6 @@ func oaiImage2AliImageRequest(info *relaycommon.RelayInfo, request dto.ImageRequ
}
}
- // 检查n参数
if imageRequest.Parameters.N != 0 {
info.PriceData.AddOtherRatio("n", float64(imageRequest.Parameters.N))
}
@@ -180,6 +180,7 @@ func oaiFormEdit2AliImageEdit(c *gin.Context, info *relaycommon.RelayInfo, reque
},
}
imageRequest.Parameters = AliImageParameters{
+ N: int(lo.FromPtrOr(request.N, uint(1))),
Watermark: request.Watermark,
}
return &imageRequest, nil
@@ -327,7 +328,6 @@ func aliImageHandler(a *Adaptor, c *gin.Context, resp *http.Response, info *rela
}
imageResponses := responseAli2OpenAIImage(c, aliResponse, originRespBody, info, responseFormat)
- // 可能生成多张图片,修正计费数量n
if aliResponse.Usage.ImageCount != 0 {
info.PriceData.AddOtherRatio("n", float64(aliResponse.Usage.ImageCount))
} else if len(imageResponses.Data) != 0 {
diff --git a/relay/channel/ali/image_wan.go b/relay/channel/ali/image_wan.go
index 90ee48a0b6..e2f46060fd 100644
--- a/relay/channel/ali/image_wan.go
+++ b/relay/channel/ali/image_wan.go
@@ -9,6 +9,7 @@ import (
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
func oaiFormEdit2WanxImageEdit(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (*AliImageRequest, error) {
@@ -31,7 +32,7 @@ func oaiFormEdit2WanxImageEdit(c *gin.Context, info *relaycommon.RelayInfo, requ
//}
imageRequest.Input = wanInput
imageRequest.Parameters = AliImageParameters{
- N: int(request.N),
+ N: int(lo.FromPtrOr(request.N, uint(1))),
}
info.PriceData.AddOtherRatio("n", float64(imageRequest.Parameters.N))
@@ -39,7 +40,8 @@ func oaiFormEdit2WanxImageEdit(c *gin.Context, info *relaycommon.RelayInfo, requ
}
func isOldWanModel(modelName string) bool {
- return strings.Contains(modelName, "wan") && !strings.Contains(modelName, "wan2.6")
+ return strings.Contains(modelName, "wan") &&
+ !lo.SomeBy([]string{"wan2.6", "wan2.7"}, func(v string) bool { return strings.Contains(modelName, v) })
}
func isWanModel(modelName string) bool {
diff --git a/relay/channel/ali/rerank.go b/relay/channel/ali/rerank.go
index 1323fc8301..1f7a3451fb 100644
--- a/relay/channel/ali/rerank.go
+++ b/relay/channel/ali/rerank.go
@@ -26,7 +26,7 @@ func ConvertRerankRequest(request dto.RerankRequest) *AliRerankRequest {
Documents: request.Documents,
},
Parameters: AliRerankParameters{
- TopN: &request.TopN,
+ TopN: request.TopN,
ReturnDocuments: returnDocuments,
},
}
diff --git a/relay/channel/ali/text.go b/relay/channel/ali/text.go
index c169b9b17b..09a52adbb9 100644
--- a/relay/channel/ali/text.go
+++ b/relay/channel/ali/text.go
@@ -2,6 +2,7 @@ package ali
import (
"github.com/QuantumNous/new-api/dto"
+ "github.com/samber/lo"
)
// https://help.aliyun.com/document_detail/613695.html?spm=a2c4g.2399480.0.0.1adb778fAdzP9w#341800c0f8w0r
@@ -9,10 +10,11 @@ import (
const EnableSearchModelSuffix = "-internet"
func requestOpenAI2Ali(request dto.GeneralOpenAIRequest) *dto.GeneralOpenAIRequest {
- if request.TopP >= 1 {
- request.TopP = 0.999
- } else if request.TopP <= 0 {
- request.TopP = 0.001
+ topP := lo.FromPtrOr(request.TopP, 0)
+ if topP >= 1 {
+ request.TopP = lo.ToPtr(0.999)
+ } else if topP <= 0 {
+ request.TopP = lo.ToPtr(0.001)
}
return &request
}
diff --git a/relay/channel/api_request.go b/relay/channel/api_request.go
index 1ff1e2392c..8dfb61d400 100644
--- a/relay/channel/api_request.go
+++ b/relay/channel/api_request.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
+ "regexp"
"strings"
"sync"
"time"
@@ -38,26 +39,254 @@ func SetupApiRequestHeader(info *common.RelayInfo, c *gin.Context, req *http.Hea
}
}
-// processHeaderOverride 处理请求头覆盖,支持变量替换
-// 支持的变量:{api_key}
-func processHeaderOverride(info *common.RelayInfo) (map[string]string, error) {
+const clientHeaderPlaceholderPrefix = "{client_header:"
+
+const (
+ headerPassthroughAllKey = "*"
+ headerPassthroughRegexPrefix = "re:"
+ headerPassthroughRegexPrefixV2 = "regex:"
+)
+
+var passthroughSkipHeaderNamesLower = map[string]struct{}{
+ // RFC 7230 hop-by-hop headers.
+ "connection": {},
+ "keep-alive": {},
+ "proxy-authenticate": {},
+ "proxy-authorization": {},
+ "te": {},
+ "trailer": {},
+ "transfer-encoding": {},
+ "upgrade": {},
+
+ "cookie": {},
+
+ // Additional headers that should not be forwarded by name-matching passthrough rules.
+ "host": {},
+ "content-length": {},
+ "accept-encoding": {},
+
+ // Do not passthrough credentials by wildcard/regex.
+ "authorization": {},
+ "x-api-key": {},
+ "x-goog-api-key": {},
+
+ // WebSocket handshake headers are generated by the client/dialer.
+ "sec-websocket-key": {},
+ "sec-websocket-version": {},
+ "sec-websocket-extensions": {},
+}
+
+var headerPassthroughRegexCache sync.Map // map[string]*regexp.Regexp
+
+func getHeaderPassthroughRegex(pattern string) (*regexp.Regexp, error) {
+ pattern = strings.TrimSpace(pattern)
+ if pattern == "" {
+ return nil, errors.New("empty regex pattern")
+ }
+ if v, ok := headerPassthroughRegexCache.Load(pattern); ok {
+ if re, ok := v.(*regexp.Regexp); ok {
+ return re, nil
+ }
+ headerPassthroughRegexCache.Delete(pattern)
+ }
+ compiled, err := regexp.Compile(pattern)
+ if err != nil {
+ return nil, err
+ }
+ actual, _ := headerPassthroughRegexCache.LoadOrStore(pattern, compiled)
+ if re, ok := actual.(*regexp.Regexp); ok {
+ return re, nil
+ }
+ return compiled, nil
+}
+
+func IsHeaderPassthroughRuleKey(key string) bool {
+ return isHeaderPassthroughRuleKey(key)
+}
+func isHeaderPassthroughRuleKey(key string) bool {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return false
+ }
+ if key == headerPassthroughAllKey {
+ return true
+ }
+ lower := strings.ToLower(key)
+ return strings.HasPrefix(lower, headerPassthroughRegexPrefix) || strings.HasPrefix(lower, headerPassthroughRegexPrefixV2)
+}
+
+func shouldSkipPassthroughHeader(name string) bool {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return true
+ }
+ lower := strings.ToLower(name)
+ if _, ok := passthroughSkipHeaderNamesLower[lower]; ok {
+ return true
+ }
+ return false
+}
+
+func applyHeaderOverridePlaceholders(template string, c *gin.Context, apiKey string) (string, bool, error) {
+ trimmed := strings.TrimSpace(template)
+ if strings.HasPrefix(trimmed, clientHeaderPlaceholderPrefix) {
+ afterPrefix := trimmed[len(clientHeaderPlaceholderPrefix):]
+ end := strings.Index(afterPrefix, "}")
+ if end < 0 || end != len(afterPrefix)-1 {
+ return "", false, fmt.Errorf("client_header placeholder must be the full value: %q", template)
+ }
+
+ name := strings.TrimSpace(afterPrefix[:end])
+ if name == "" {
+ return "", false, fmt.Errorf("client_header placeholder name is empty: %q", template)
+ }
+ if c == nil || c.Request == nil {
+ return "", false, fmt.Errorf("missing request context for client_header placeholder")
+ }
+ clientHeaderValue := c.Request.Header.Get(name)
+ if strings.TrimSpace(clientHeaderValue) == "" {
+ return "", false, nil
+ }
+ // Do not interpolate {api_key} inside client-supplied content.
+ return clientHeaderValue, true, nil
+ }
+
+ if strings.Contains(template, "{api_key}") {
+ template = strings.ReplaceAll(template, "{api_key}", apiKey)
+ }
+ if strings.TrimSpace(template) == "" {
+ return "", false, nil
+ }
+ return template, true, nil
+}
+
+// processHeaderOverride applies channel header overrides, with placeholder substitution.
+// Supported placeholders:
+// - {api_key}: resolved to the channel API key
+// - {client_header:
}: resolved to the incoming request header value
+//
+// Header passthrough rules (keys only; values are ignored):
+// - "*": passthrough all incoming headers by name (excluding unsafe headers)
+// - "re:" / "regex:": passthrough headers whose names match the regex (Go regexp)
+//
+// Passthrough rules are applied first, then normal overrides are applied, so explicit overrides win.
+func processHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
headerOverride := make(map[string]string)
- for k, v := range info.HeadersOverride {
+ if info == nil {
+ return headerOverride, nil
+ }
+
+ headerOverrideSource := common.GetEffectiveHeaderOverride(info)
+
+ passAll := false
+ var passthroughRegex []*regexp.Regexp
+ if !info.IsChannelTest {
+ for k := range headerOverrideSource {
+ key := strings.TrimSpace(strings.ToLower(k))
+ if key == "" {
+ continue
+ }
+ if key == headerPassthroughAllKey {
+ passAll = true
+ continue
+ }
+
+ var pattern string
+ switch {
+ case strings.HasPrefix(key, headerPassthroughRegexPrefix):
+ pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefix):])
+ case strings.HasPrefix(key, headerPassthroughRegexPrefixV2):
+ pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefixV2):])
+ default:
+ continue
+ }
+
+ if pattern == "" {
+ return nil, types.NewError(fmt.Errorf("header passthrough regex pattern is empty: %q", k), types.ErrorCodeChannelHeaderOverrideInvalid)
+ }
+ compiled, err := getHeaderPassthroughRegex(pattern)
+ if err != nil {
+ return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
+ }
+ passthroughRegex = append(passthroughRegex, compiled)
+ }
+ }
+
+ if passAll || len(passthroughRegex) > 0 {
+ if c == nil || c.Request == nil {
+ return nil, types.NewError(fmt.Errorf("missing request context for header passthrough"), types.ErrorCodeChannelHeaderOverrideInvalid)
+ }
+ for name := range c.Request.Header {
+ if shouldSkipPassthroughHeader(name) {
+ continue
+ }
+ if !passAll {
+ matched := false
+ for _, re := range passthroughRegex {
+ if re.MatchString(name) {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ continue
+ }
+ }
+ value := strings.TrimSpace(c.Request.Header.Get(name))
+ if value == "" {
+ continue
+ }
+ headerOverride[strings.ToLower(strings.TrimSpace(name))] = value
+ }
+ }
+
+ for k, v := range headerOverrideSource {
+ if isHeaderPassthroughRuleKey(k) {
+ continue
+ }
+ key := strings.TrimSpace(strings.ToLower(k))
+ if key == "" {
+ continue
+ }
+
str, ok := v.(string)
if !ok {
return nil, types.NewError(nil, types.ErrorCodeChannelHeaderOverrideInvalid)
}
-
- // 替换支持的变量
- if strings.Contains(str, "{api_key}") {
- str = strings.ReplaceAll(str, "{api_key}", info.ApiKey)
+ if info.IsChannelTest && strings.HasPrefix(strings.TrimSpace(str), clientHeaderPlaceholderPrefix) {
+ continue
}
- headerOverride[k] = str
+ value, include, err := applyHeaderOverridePlaceholders(str, c, info.ApiKey)
+ if err != nil {
+ return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
+ }
+ if !include {
+ continue
+ }
+
+ headerOverride[key] = value
}
return headerOverride, nil
}
+func ResolveHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
+ return processHeaderOverride(info, c)
+}
+
+func applyHeaderOverrideToRequest(req *http.Request, headerOverride map[string]string) {
+ if req == nil {
+ return
+ }
+ for key, value := range headerOverride {
+ req.Header.Set(key, value)
+ // set Host in req
+ if strings.EqualFold(key, "Host") {
+ req.Host = value
+ }
+ }
+}
+
func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
fullRequestURL, err := a.GetRequestURL(info)
if err != nil {
@@ -71,17 +300,17 @@ func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody
return nil, fmt.Errorf("new request failed: %w", err)
}
headers := req.Header
- headerOverride, err := processHeaderOverride(info)
- if err != nil {
- return nil, err
- }
- for key, value := range headerOverride {
- headers.Set(key, value)
- }
err = a.SetupRequestHeader(c, &headers, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
+ // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
+ // 这样可以覆盖默认的 Authorization header 设置
+ headerOverride, err := processHeaderOverride(info, c)
+ if err != nil {
+ return nil, err
+ }
+ applyHeaderOverrideToRequest(req, headerOverride)
resp, err := doRequest(c, req, info)
if err != nil {
return nil, fmt.Errorf("do request failed: %w", err)
@@ -104,17 +333,17 @@ func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBod
// set form data
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
headers := req.Header
- headerOverride, err := processHeaderOverride(info)
- if err != nil {
- return nil, err
- }
- for key, value := range headerOverride {
- headers.Set(key, value)
- }
err = a.SetupRequestHeader(c, &headers, info)
if err != nil {
return nil, fmt.Errorf("setup request header failed: %w", err)
}
+ // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
+ // 这样可以覆盖默认的 Authorization header 设置
+ headerOverride, err := processHeaderOverride(info, c)
+ if err != nil {
+ return nil, err
+ }
+ applyHeaderOverrideToRequest(req, headerOverride)
resp, err := doRequest(c, req, info)
if err != nil {
return nil, fmt.Errorf("do request failed: %w", err)
@@ -128,17 +357,19 @@ func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody
return nil, fmt.Errorf("get request url failed: %w", err)
}
targetHeader := http.Header{}
- headerOverride, err := processHeaderOverride(info)
+ err = a.SetupRequestHeader(c, &targetHeader, info)
+ if err != nil {
+ return nil, fmt.Errorf("setup request header failed: %w", err)
+ }
+ // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
+ // 这样可以覆盖默认的 Authorization header 设置
+ headerOverride, err := processHeaderOverride(info, c)
if err != nil {
return nil, err
}
for key, value := range headerOverride {
targetHeader.Set(key, value)
}
- err = a.SetupRequestHeader(c, &targetHeader, info)
- if err != nil {
- return nil, fmt.Errorf("setup request header failed: %w", err)
- }
targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
targetConn, _, err := websocket.DefaultDialer.Dial(fullRequestURL, targetHeader)
if err != nil {
diff --git a/relay/channel/api_request_test.go b/relay/channel/api_request_test.go
new file mode 100644
index 0000000000..f697f85556
--- /dev/null
+++ b/relay/channel/api_request_test.go
@@ -0,0 +1,193 @@
+package channel
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestProcessHeaderOverride_ChannelTestSkipsPassthroughRules(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+ ctx.Request.Header.Set("X-Trace-Id", "trace-123")
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: true,
+ ChannelMeta: &relaycommon.ChannelMeta{
+ HeadersOverride: map[string]any{
+ "*": "",
+ },
+ },
+ }
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ require.Empty(t, headers)
+}
+
+func TestProcessHeaderOverride_ChannelTestSkipsClientHeaderPlaceholder(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+ ctx.Request.Header.Set("X-Trace-Id", "trace-123")
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: true,
+ ChannelMeta: &relaycommon.ChannelMeta{
+ HeadersOverride: map[string]any{
+ "X-Upstream-Trace": "{client_header:X-Trace-Id}",
+ },
+ },
+ }
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ _, ok := headers["x-upstream-trace"]
+ require.False(t, ok)
+}
+
+func TestProcessHeaderOverride_NonTestKeepsClientHeaderPlaceholder(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+ ctx.Request.Header.Set("X-Trace-Id", "trace-123")
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: false,
+ ChannelMeta: &relaycommon.ChannelMeta{
+ HeadersOverride: map[string]any{
+ "X-Upstream-Trace": "{client_header:X-Trace-Id}",
+ },
+ },
+ }
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ require.Equal(t, "trace-123", headers["x-upstream-trace"])
+}
+
+func TestProcessHeaderOverride_RuntimeOverrideIsFinalHeaderMap(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: false,
+ UseRuntimeHeadersOverride: true,
+ RuntimeHeadersOverride: map[string]any{
+ "x-static": "runtime-value",
+ "x-runtime": "runtime-only",
+ },
+ ChannelMeta: &relaycommon.ChannelMeta{
+ HeadersOverride: map[string]any{
+ "X-Static": "legacy-value",
+ "X-Legacy": "legacy-only",
+ },
+ },
+ }
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ require.Equal(t, "runtime-value", headers["x-static"])
+ require.Equal(t, "runtime-only", headers["x-runtime"])
+ _, exists := headers["x-legacy"]
+ require.False(t, exists)
+}
+
+func TestProcessHeaderOverride_PassthroughSkipsAcceptEncoding(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+ ctx.Request.Header.Set("X-Trace-Id", "trace-123")
+ ctx.Request.Header.Set("Accept-Encoding", "gzip")
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: false,
+ ChannelMeta: &relaycommon.ChannelMeta{
+ HeadersOverride: map[string]any{
+ "*": "",
+ },
+ },
+ }
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ require.Equal(t, "trace-123", headers["x-trace-id"])
+
+ _, hasAcceptEncoding := headers["accept-encoding"]
+ require.False(t, hasAcceptEncoding)
+}
+
+func TestProcessHeaderOverride_PassHeadersTemplateSetsRuntimeHeaders(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
+ ctx.Request.Header.Set("Originator", "Codex CLI")
+ ctx.Request.Header.Set("Session_id", "sess-123")
+
+ info := &relaycommon.RelayInfo{
+ IsChannelTest: false,
+ RequestHeaders: map[string]string{
+ "Originator": "Codex CLI",
+ "Session_id": "sess-123",
+ },
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ParamOverride: map[string]any{
+ "operations": []any{
+ map[string]any{
+ "mode": "pass_headers",
+ "value": []any{"Originator", "Session_id", "X-Codex-Beta-Features"},
+ },
+ },
+ },
+ HeadersOverride: map[string]any{
+ "X-Static": "legacy-value",
+ },
+ },
+ }
+
+ _, err := relaycommon.ApplyParamOverrideWithRelayInfo([]byte(`{"model":"gpt-4.1"}`), info)
+ require.NoError(t, err)
+ require.True(t, info.UseRuntimeHeadersOverride)
+ require.Equal(t, "Codex CLI", info.RuntimeHeadersOverride["originator"])
+ require.Equal(t, "sess-123", info.RuntimeHeadersOverride["session_id"])
+ _, exists := info.RuntimeHeadersOverride["x-codex-beta-features"]
+ require.False(t, exists)
+ require.Equal(t, "legacy-value", info.RuntimeHeadersOverride["x-static"])
+
+ headers, err := processHeaderOverride(info, ctx)
+ require.NoError(t, err)
+ require.Equal(t, "Codex CLI", headers["originator"])
+ require.Equal(t, "sess-123", headers["session_id"])
+ _, exists = headers["x-codex-beta-features"]
+ require.False(t, exists)
+
+ upstreamReq := httptest.NewRequest(http.MethodPost, "https://example.com/v1/responses", nil)
+ applyHeaderOverrideToRequest(upstreamReq, headers)
+ require.Equal(t, "Codex CLI", upstreamReq.Header.Get("Originator"))
+ require.Equal(t, "sess-123", upstreamReq.Header.Get("Session_id"))
+ require.Empty(t, upstreamReq.Header.Get("X-Codex-Beta-Features"))
+}
diff --git a/relay/channel/aws/adaptor.go b/relay/channel/aws/adaptor.go
index 423cf842d9..e9e5fd9137 100644
--- a/relay/channel/aws/adaptor.go
+++ b/relay/channel/aws/adaptor.go
@@ -49,12 +49,14 @@ func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayIn
for i2, mediaMessage := range content {
if mediaMessage.Source != nil {
if mediaMessage.Source.Type == "url" {
- fileData, err := service.GetFileBase64FromUrl(c, mediaMessage.Source.Url, "formatting image for Claude")
+ // 使用统一的文件服务获取图片数据
+ source := types.NewURLFileSource(mediaMessage.Source.Url)
+ base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting image for Claude")
if err != nil {
return nil, fmt.Errorf("get file base64 from url failed: %s", err.Error())
}
- mediaMessage.Source.MediaType = fileData.MimeType
- mediaMessage.Source.Data = fileData.Base64Data
+ mediaMessage.Source.MediaType = mimeType
+ mediaMessage.Source.Data = base64Data
mediaMessage.Source.Url = ""
mediaMessage.Source.Type = "base64"
content[i2] = mediaMessage
diff --git a/relay/channel/aws/constants.go b/relay/channel/aws/constants.go
index 888d96eefa..55f87ecf2a 100644
--- a/relay/channel/aws/constants.go
+++ b/relay/channel/aws/constants.go
@@ -3,9 +3,6 @@ package aws
import "strings"
var awsModelIDMap = map[string]string{
- "claude-instant-1.2": "anthropic.claude-instant-v1",
- "claude-2.0": "anthropic.claude-v2",
- "claude-2.1": "anthropic.claude-v2:1",
"claude-3-sonnet-20240229": "anthropic.claude-3-sonnet-20240229-v1:0",
"claude-3-opus-20240229": "anthropic.claude-3-opus-20240229-v1:0",
"claude-3-haiku-20240307": "anthropic.claude-3-haiku-20240307-v1:0",
@@ -17,8 +14,10 @@ var awsModelIDMap = map[string]string{
"claude-opus-4-20250514": "anthropic.claude-opus-4-20250514-v1:0",
"claude-opus-4-1-20250805": "anthropic.claude-opus-4-1-20250805-v1:0",
"claude-sonnet-4-5-20250929": "anthropic.claude-sonnet-4-5-20250929-v1:0",
+ "claude-sonnet-4-6": "anthropic.claude-sonnet-4-6",
"claude-haiku-4-5-20251001": "anthropic.claude-haiku-4-5-20251001-v1:0",
"claude-opus-4-5-20251101": "anthropic.claude-opus-4-5-20251101-v1:0",
+ "claude-opus-4-6": "anthropic.claude-opus-4-6-v1",
// Nova models
"nova-micro-v1:0": "amazon.nova-micro-v1:0",
"nova-lite-v1:0": "amazon.nova-lite-v1:0",
@@ -77,11 +76,21 @@ var awsModelCanCrossRegionMap = map[string]map[string]bool{
"ap": true,
"eu": true,
},
+ "anthropic.claude-sonnet-4-6": {
+ "us": true,
+ "ap": true,
+ "eu": true,
+ },
"anthropic.claude-opus-4-5-20251101-v1:0": {
"us": true,
"ap": true,
"eu": true,
},
+ "anthropic.claude-opus-4-6-v1": {
+ "us": true,
+ "ap": true,
+ "eu": true,
+ },
"anthropic.claude-haiku-4-5-20251001-v1:0": {
"us": true,
"ap": true,
diff --git a/relay/channel/aws/dto.go b/relay/channel/aws/dto.go
index b060a593bf..4c5c5cbc8d 100644
--- a/relay/channel/aws/dto.go
+++ b/relay/channel/aws/dto.go
@@ -26,6 +26,8 @@ type AwsClaudeRequest struct {
Tools any `json:"tools,omitempty"`
ToolChoice any `json:"tool_choice,omitempty"`
Thinking *dto.Thinking `json:"thinking,omitempty"`
+ OutputConfig json.RawMessage `json:"output_config,omitempty"`
+ //Metadata json.RawMessage `json:"metadata,omitempty"`
}
func formatRequest(requestBody io.Reader, requestHeader http.Header) (*AwsClaudeRequest, error) {
@@ -93,19 +95,19 @@ func convertToNovaRequest(req *dto.GeneralOpenAIRequest) *NovaRequest {
}
// 设置推理配置
- if req.MaxTokens != 0 || (req.Temperature != nil && *req.Temperature != 0) || req.TopP != 0 || req.TopK != 0 || req.Stop != nil {
+ if (req.MaxTokens != nil && *req.MaxTokens != 0) || (req.Temperature != nil && *req.Temperature != 0) || (req.TopP != nil && *req.TopP != 0) || (req.TopK != nil && *req.TopK != 0) || req.Stop != nil {
novaReq.InferenceConfig = &NovaInferenceConfig{}
- if req.MaxTokens != 0 {
- novaReq.InferenceConfig.MaxTokens = int(req.MaxTokens)
+ if req.MaxTokens != nil && *req.MaxTokens != 0 {
+ novaReq.InferenceConfig.MaxTokens = int(*req.MaxTokens)
}
if req.Temperature != nil && *req.Temperature != 0 {
novaReq.InferenceConfig.Temperature = *req.Temperature
}
- if req.TopP != 0 {
- novaReq.InferenceConfig.TopP = req.TopP
+ if req.TopP != nil && *req.TopP != 0 {
+ novaReq.InferenceConfig.TopP = *req.TopP
}
- if req.TopK != 0 {
- novaReq.InferenceConfig.TopK = req.TopK
+ if req.TopK != nil && *req.TopK != 0 {
+ novaReq.InferenceConfig.TopK = *req.TopK
}
if req.Stop != nil {
if stopSequences := parseStopSequences(req.Stop); len(stopSequences) > 0 {
diff --git a/relay/channel/aws/relay-aws.go b/relay/channel/aws/relay-aws.go
index ea59aedae2..1f6ff7e692 100644
--- a/relay/channel/aws/relay-aws.go
+++ b/relay/channel/aws/relay-aws.go
@@ -11,6 +11,7 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/relay/channel"
"github.com/QuantumNous/new-api/relay/channel/claude"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
@@ -106,6 +107,13 @@ func doAwsClientRequest(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor,
// init empty request.header
requestHeader := http.Header{}
a.SetupRequestHeader(c, &requestHeader, info)
+ headerOverride, err := channel.ResolveHeaderOverride(info, c)
+ if err != nil {
+ return nil, err
+ }
+ for key, value := range headerOverride {
+ requestHeader.Set(key, value)
+ }
if isNovaModel(awsModelId) {
var novaReq *NovaRequest
@@ -165,10 +173,14 @@ func doAwsClientRequest(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor,
// buildAwsRequestBody prepares the payload for AWS requests, applying passthrough rules when enabled.
func buildAwsRequestBody(c *gin.Context, info *relaycommon.RelayInfo, awsClaudeReq any) ([]byte, error) {
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return nil, errors.Wrap(err, "get request body for pass-through fail")
}
+ body, err := storage.Bytes()
+ if err != nil {
+ return nil, errors.Wrap(err, "get request body bytes fail")
+ }
var data map[string]interface{}
if err := common.Unmarshal(body, &data); err != nil {
return nil, errors.Wrap(err, "pass-through unmarshal request body fail")
@@ -233,7 +245,7 @@ func awsHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (*types
c.Writer.Header().Set("Content-Type", *awsResp.ContentType)
}
- handlerErr := claude.HandleClaudeResponseData(c, info, claudeInfo, nil, awsResp.Body, claude.RequestModeMessage)
+ handlerErr := claude.HandleClaudeResponseData(c, info, claudeInfo, nil, awsResp.Body)
if handlerErr != nil {
return handlerErr, nil
}
@@ -264,7 +276,7 @@ func awsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (
switch v := event.(type) {
case *bedrockruntimeTypes.ResponseStreamMemberChunk:
info.SetFirstResponseTime()
- respErr := claude.HandleStreamResponseData(c, info, claudeInfo, string(v.Value.Bytes), claude.RequestModeMessage)
+ respErr := claude.HandleStreamResponseData(c, info, claudeInfo, string(v.Value.Bytes))
if respErr != nil {
return respErr, nil
}
@@ -277,7 +289,7 @@ func awsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (
}
}
- claude.HandleStreamFinalResponse(c, info, claudeInfo, claude.RequestModeMessage)
+ claude.HandleStreamFinalResponse(c, info, claudeInfo)
return nil, claudeInfo.Usage
}
diff --git a/relay/channel/aws/relay_aws_test.go b/relay/channel/aws/relay_aws_test.go
new file mode 100644
index 0000000000..92745ff409
--- /dev/null
+++ b/relay/channel/aws/relay_aws_test.go
@@ -0,0 +1,55 @@
+package aws
+
+import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/QuantumNous/new-api/common"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestDoAwsClientRequest_AppliesRuntimeHeaderOverrideToAnthropicBeta(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
+
+ info := &relaycommon.RelayInfo{
+ OriginModelName: "claude-3-5-sonnet-20240620",
+ IsStream: false,
+ UseRuntimeHeadersOverride: true,
+ RuntimeHeadersOverride: map[string]any{
+ "anthropic-beta": "computer-use-2025-01-24",
+ },
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ApiKey: "access-key|secret-key|us-east-1",
+ UpstreamModelName: "claude-3-5-sonnet-20240620",
+ },
+ }
+
+ requestBody := bytes.NewBufferString(`{"messages":[{"role":"user","content":"hello"}],"max_tokens":128}`)
+ adaptor := &Adaptor{}
+
+ _, err := doAwsClientRequest(ctx, info, adaptor, requestBody)
+ require.NoError(t, err)
+
+ awsReq, ok := adaptor.AwsReq.(*bedrockruntime.InvokeModelInput)
+ require.True(t, ok)
+
+ var payload map[string]any
+ require.NoError(t, common.Unmarshal(awsReq.Body, &payload))
+
+ anthropicBeta, exists := payload["anthropic_beta"]
+ require.True(t, exists)
+
+ values, ok := anthropicBeta.([]any)
+ require.True(t, ok)
+ require.Equal(t, []any{"computer-use-2025-01-24"}, values)
+}
diff --git a/relay/channel/baidu/dto.go b/relay/channel/baidu/dto.go
index 426f63f54a..4fa73f89c2 100644
--- a/relay/channel/baidu/dto.go
+++ b/relay/channel/baidu/dto.go
@@ -1,6 +1,7 @@
package baidu
import (
+ "encoding/json"
"time"
"github.com/QuantumNous/new-api/dto"
@@ -12,16 +13,16 @@ type BaiduMessage struct {
}
type BaiduChatRequest struct {
- Messages []BaiduMessage `json:"messages"`
- Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"top_p,omitempty"`
- PenaltyScore float64 `json:"penalty_score,omitempty"`
- Stream bool `json:"stream,omitempty"`
- System string `json:"system,omitempty"`
- DisableSearch bool `json:"disable_search,omitempty"`
- EnableCitation bool `json:"enable_citation,omitempty"`
- MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
- UserId string `json:"user_id,omitempty"`
+ Messages []BaiduMessage `json:"messages"`
+ Temperature *float64 `json:"temperature,omitempty"`
+ TopP float64 `json:"top_p,omitempty"`
+ PenaltyScore float64 `json:"penalty_score,omitempty"`
+ Stream bool `json:"stream,omitempty"`
+ System string `json:"system,omitempty"`
+ DisableSearch bool `json:"disable_search,omitempty"`
+ EnableCitation bool `json:"enable_citation,omitempty"`
+ MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
+ UserId json.RawMessage `json:"user_id,omitempty"`
}
type Error struct {
diff --git a/relay/channel/baidu/relay-baidu.go b/relay/channel/baidu/relay-baidu.go
index 691d418886..a76d7689c5 100644
--- a/relay/channel/baidu/relay-baidu.go
+++ b/relay/channel/baidu/relay-baidu.go
@@ -17,6 +17,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -28,9 +29,9 @@ var baiduTokenStore sync.Map
func requestOpenAI2Baidu(request dto.GeneralOpenAIRequest) *BaiduChatRequest {
baiduRequest := BaiduChatRequest{
Temperature: request.Temperature,
- TopP: request.TopP,
- PenaltyScore: request.FrequencyPenalty,
- Stream: request.Stream,
+ TopP: lo.FromPtrOr(request.TopP, 0),
+ PenaltyScore: lo.FromPtrOr(request.FrequencyPenalty, 0),
+ Stream: lo.FromPtrOr(request.Stream, false),
DisableSearch: false,
EnableCitation: false,
UserId: request.User,
@@ -115,12 +116,12 @@ func embeddingResponseBaidu2OpenAI(response *BaiduEmbeddingResponse) *dto.OpenAI
func baiduStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*types.NewAPIError, *dto.Usage) {
usage := &dto.Usage{}
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
var baiduResponse BaiduChatStreamResponse
- err := common.Unmarshal([]byte(data), &baiduResponse)
- if err != nil {
+ if err := common.Unmarshal([]byte(data), &baiduResponse); err != nil {
common.SysLog("error unmarshalling stream response: " + err.Error())
- return true
+ sr.Error(err)
+ return
}
if baiduResponse.Usage.TotalTokens != 0 {
usage.TotalTokens = baiduResponse.Usage.TotalTokens
@@ -128,11 +129,10 @@ func baiduStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.
usage.CompletionTokens = baiduResponse.Usage.TotalTokens - baiduResponse.Usage.PromptTokens
}
response := streamResponseBaidu2OpenAI(&baiduResponse)
- err = helper.ObjectData(c, response)
- if err != nil {
+ if err := helper.ObjectData(c, response); err != nil {
common.SysLog("error sending stream response: " + err.Error())
+ sr.Error(err)
}
- return true
})
service.CloseResponseBodyGracefully(resp)
return nil, usage
diff --git a/relay/channel/claude/adaptor.go b/relay/channel/claude/adaptor.go
index b9b7447f2f..6daf5b6f24 100644
--- a/relay/channel/claude/adaptor.go
+++ b/relay/channel/claude/adaptor.go
@@ -5,7 +5,7 @@ import (
"fmt"
"io"
"net/http"
- "strings"
+ "net/url"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
@@ -16,13 +16,7 @@ import (
"github.com/gin-gonic/gin"
)
-const (
- RequestModeCompletion = 1
- RequestModeMessage = 2
-)
-
type Adaptor struct {
- RequestMode int
}
func (a *Adaptor) ConvertGeminiRequest(*gin.Context, *relaycommon.RelayInfo, *dto.GeminiChatRequest) (any, error) {
@@ -45,24 +39,35 @@ func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInf
}
func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
- if strings.HasPrefix(info.UpstreamModelName, "claude-2") || strings.HasPrefix(info.UpstreamModelName, "claude-instant") {
- a.RequestMode = RequestModeCompletion
- } else {
- a.RequestMode = RequestModeMessage
- }
}
func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
- baseURL := ""
- if a.RequestMode == RequestModeMessage {
- baseURL = fmt.Sprintf("%s/v1/messages", info.ChannelBaseUrl)
- } else {
- baseURL = fmt.Sprintf("%s/v1/complete", info.ChannelBaseUrl)
+ requestURL := fmt.Sprintf("%s/v1/messages", info.ChannelBaseUrl)
+ if !shouldAppendClaudeBetaQuery(info) {
+ return requestURL, nil
+ }
+
+ parsedURL, err := url.Parse(requestURL)
+ if err != nil {
+ return "", err
+ }
+ query := parsedURL.Query()
+ query.Set("beta", "true")
+ parsedURL.RawQuery = query.Encode()
+ return parsedURL.String(), nil
+}
+
+func shouldAppendClaudeBetaQuery(info *relaycommon.RelayInfo) bool {
+ if info == nil {
+ return false
}
if info.IsClaudeBetaQuery {
- baseURL = baseURL + "?beta=true"
+ return true
}
- return baseURL, nil
+ if info.ChannelOtherSettings.ClaudeBetaQuery {
+ return true
+ }
+ return false
}
func CommonClaudeHeadersOperation(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) {
@@ -90,11 +95,7 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
if request == nil {
return nil, errors.New("request is nil")
}
- if a.RequestMode == RequestModeCompletion {
- return RequestOpenAI2ClaudeComplete(*request), nil
- } else {
- return RequestOpenAI2ClaudeMessage(c, *request)
- }
+ return RequestOpenAI2ClaudeMessage(c, *request)
}
func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
@@ -116,12 +117,12 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
+ info.FinalRequestRelayFormat = types.RelayFormatClaude
if info.IsStream {
- return ClaudeStreamHandler(c, resp, info, a.RequestMode)
+ return ClaudeStreamHandler(c, resp, info)
} else {
- return ClaudeHandler(c, resp, info, a.RequestMode)
+ return ClaudeHandler(c, resp, info)
}
- return
}
func (a *Adaptor) GetModelList() []string {
diff --git a/relay/channel/claude/constants.go b/relay/channel/claude/constants.go
index 7debb353ea..1a3fac566e 100644
--- a/relay/channel/claude/constants.go
+++ b/relay/channel/claude/constants.go
@@ -1,10 +1,6 @@
package claude
var ModelList = []string{
- "claude-instant-1.2",
- "claude-2",
- "claude-2.0",
- "claude-2.1",
"claude-3-sonnet-20240229",
"claude-3-opus-20240229",
"claude-3-haiku-20240307",
@@ -24,6 +20,12 @@ var ModelList = []string{
"claude-sonnet-4-5-20250929-thinking",
"claude-opus-4-5-20251101",
"claude-opus-4-5-20251101-thinking",
+ "claude-opus-4-6",
+ "claude-opus-4-6-max",
+ "claude-opus-4-6-high",
+ "claude-opus-4-6-medium",
+ "claude-opus-4-6-low",
+ "claude-sonnet-4-6",
}
var ChannelName = "claude"
diff --git a/relay/channel/claude/message_delta_usage_patch_test.go b/relay/channel/claude/message_delta_usage_patch_test.go
new file mode 100644
index 0000000000..42c2c70c16
--- /dev/null
+++ b/relay/channel/claude/message_delta_usage_patch_test.go
@@ -0,0 +1,129 @@
+package claude
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/dto"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/model_setting"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestPatchClaudeMessageDeltaUsageDataPreserveUnknownFields(t *testing.T) {
+ originalData := `{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":53},"vendor_meta":{"trace_id":"trace_001"}}`
+ usage := &dto.ClaudeUsage{
+ InputTokens: 100,
+ CacheReadInputTokens: 30,
+ CacheCreationInputTokens: 50,
+ }
+
+ patchedData := patchClaudeMessageDeltaUsageData(originalData, usage)
+
+ require.Equal(t, "message_delta", gjson.Get(patchedData, "type").String())
+ require.Equal(t, "end_turn", gjson.Get(patchedData, "delta.stop_reason").String())
+ require.Equal(t, "trace_001", gjson.Get(patchedData, "vendor_meta.trace_id").String())
+ require.EqualValues(t, 53, gjson.Get(patchedData, "usage.output_tokens").Int())
+ require.EqualValues(t, 100, gjson.Get(patchedData, "usage.input_tokens").Int())
+ require.EqualValues(t, 30, gjson.Get(patchedData, "usage.cache_read_input_tokens").Int())
+ require.EqualValues(t, 50, gjson.Get(patchedData, "usage.cache_creation_input_tokens").Int())
+}
+
+func TestPatchClaudeMessageDeltaUsageDataZeroValueChecks(t *testing.T) {
+ originalData := `{"type":"message_delta","usage":{"output_tokens":53,"input_tokens":9,"cache_read_input_tokens":0}}`
+ usage := &dto.ClaudeUsage{
+ InputTokens: 100,
+ CacheReadInputTokens: 30,
+ CacheCreationInputTokens: 0,
+ }
+
+ patchedData := patchClaudeMessageDeltaUsageData(originalData, usage)
+
+ require.EqualValues(t, 9, gjson.Get(patchedData, "usage.input_tokens").Int())
+ require.EqualValues(t, 30, gjson.Get(patchedData, "usage.cache_read_input_tokens").Int())
+ assert.False(t, gjson.Get(patchedData, "usage.cache_creation_input_tokens").Exists())
+}
+
+func TestShouldSkipClaudeMessageDeltaUsagePatch(t *testing.T) {
+ originGlobalPassThrough := model_setting.GetGlobalSettings().PassThroughRequestEnabled
+ t.Cleanup(func() {
+ model_setting.GetGlobalSettings().PassThroughRequestEnabled = originGlobalPassThrough
+ })
+
+ model_setting.GetGlobalSettings().PassThroughRequestEnabled = true
+ assert.True(t, shouldSkipClaudeMessageDeltaUsagePatch(&relaycommon.RelayInfo{}))
+
+ model_setting.GetGlobalSettings().PassThroughRequestEnabled = false
+ assert.True(t, shouldSkipClaudeMessageDeltaUsagePatch(&relaycommon.RelayInfo{
+ ChannelMeta: &relaycommon.ChannelMeta{ChannelSetting: dto.ChannelSettings{PassThroughBodyEnabled: true}},
+ }))
+ assert.False(t, shouldSkipClaudeMessageDeltaUsagePatch(&relaycommon.RelayInfo{
+ ChannelMeta: &relaycommon.ChannelMeta{ChannelSetting: dto.ChannelSettings{PassThroughBodyEnabled: false}},
+ }))
+}
+
+func TestBuildMessageDeltaPatchUsage(t *testing.T) {
+ t.Run("merge missing fields from claudeInfo", func(t *testing.T) {
+ claudeResponse := &dto.ClaudeResponse{Usage: &dto.ClaudeUsage{OutputTokens: 53}}
+ claudeInfo := &ClaudeResponseInfo{
+ Usage: &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ ClaudeCacheCreation5mTokens: 10,
+ ClaudeCacheCreation1hTokens: 20,
+ },
+ }
+
+ usage := buildMessageDeltaPatchUsage(claudeResponse, claudeInfo)
+ require.NotNil(t, usage)
+ require.EqualValues(t, 100, usage.InputTokens)
+ require.EqualValues(t, 30, usage.CacheReadInputTokens)
+ require.EqualValues(t, 50, usage.CacheCreationInputTokens)
+ require.EqualValues(t, 53, usage.OutputTokens)
+ require.NotNil(t, usage.CacheCreation)
+ require.EqualValues(t, 30, usage.CacheCreation.Ephemeral5mInputTokens)
+ require.EqualValues(t, 20, usage.CacheCreation.Ephemeral1hInputTokens)
+ })
+
+ t.Run("keep upstream non-zero values", func(t *testing.T) {
+ claudeResponse := &dto.ClaudeResponse{Usage: &dto.ClaudeUsage{
+ InputTokens: 9,
+ CacheReadInputTokens: 7,
+ CacheCreationInputTokens: 6,
+ }}
+ claudeInfo := &ClaudeResponseInfo{Usage: &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ }}
+
+ usage := buildMessageDeltaPatchUsage(claudeResponse, claudeInfo)
+ require.EqualValues(t, 9, usage.InputTokens)
+ require.EqualValues(t, 7, usage.CacheReadInputTokens)
+ require.EqualValues(t, 6, usage.CacheCreationInputTokens)
+ })
+
+ t.Run("default aggregate cache creation to 5m when split missing", func(t *testing.T) {
+ claudeResponse := &dto.ClaudeResponse{Usage: &dto.ClaudeUsage{
+ OutputTokens: 53,
+ CacheCreationInputTokens: 50,
+ }}
+ claudeInfo := &ClaudeResponseInfo{Usage: &dto.Usage{
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedCreationTokens: 50,
+ },
+ }}
+
+ usage := buildMessageDeltaPatchUsage(claudeResponse, claudeInfo)
+ require.NotNil(t, usage)
+ require.NotNil(t, usage.CacheCreation)
+ require.EqualValues(t, 50, usage.CacheCreation.Ephemeral5mInputTokens)
+ require.EqualValues(t, 0, usage.CacheCreation.Ephemeral1hInputTokens)
+ })
+}
diff --git a/relay/channel/claude/relay-claude.go b/relay/channel/claude/relay-claude.go
index d3986236aa..2982945cc2 100644
--- a/relay/channel/claude/relay-claude.go
+++ b/relay/channel/claude/relay-claude.go
@@ -8,16 +8,21 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/relay/channel/openrouter"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
+ "github.com/QuantumNous/new-api/relay/reasonmap"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
+ "github.com/QuantumNous/new-api/setting/reasoning"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
)
const (
@@ -27,49 +32,16 @@ const (
)
func stopReasonClaude2OpenAI(reason string) string {
- switch reason {
- case "stop_sequence":
- return "stop"
- case "end_turn":
- return "stop"
- case "max_tokens":
- return "length"
- case "tool_use":
- return "tool_calls"
- default:
- return reason
- }
+ return reasonmap.ClaudeStopReasonToOpenAIFinishReason(reason)
}
-func RequestOpenAI2ClaudeComplete(textRequest dto.GeneralOpenAIRequest) *dto.ClaudeRequest {
-
- claudeRequest := dto.ClaudeRequest{
- Model: textRequest.Model,
- Prompt: "",
- StopSequences: nil,
- Temperature: textRequest.Temperature,
- TopP: textRequest.TopP,
- TopK: textRequest.TopK,
- Stream: textRequest.Stream,
+func maybeMarkClaudeRefusal(c *gin.Context, stopReason string) {
+ if c == nil {
+ return
}
- if claudeRequest.MaxTokensToSample == 0 {
- claudeRequest.MaxTokensToSample = 4096
+ if strings.EqualFold(stopReason, "refusal") {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "claude_stop_reason=refusal")
}
- prompt := ""
- for _, message := range textRequest.Messages {
- if message.Role == "user" {
- prompt += fmt.Sprintf("\n\nHuman: %s", message.StringContent())
- } else if message.Role == "assistant" {
- prompt += fmt.Sprintf("\n\nAssistant: %s", message.StringContent())
- } else if message.Role == "system" {
- if prompt == "" {
- prompt = message.StringContent()
- }
- }
- }
- prompt += "\n\nAssistant:"
- claudeRequest.Prompt = prompt
- return &claudeRequest
}
func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRequest) (*dto.ClaudeRequest, error) {
@@ -113,7 +85,7 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe
// 解析 UserLocation JSON
var userLocationMap map[string]interface{}
- if err := json.Unmarshal(textRequest.WebSearchOptions.UserLocation, &userLocationMap); err == nil {
+ if err := common.Unmarshal(textRequest.WebSearchOptions.UserLocation, &userLocationMap); err == nil {
// 检查是否有 approximate 字段
if approximateData, ok := userLocationMap["approximate"].(map[string]interface{}); ok {
if timezone, ok := approximateData["timezone"].(string); ok && timezone != "" {
@@ -151,14 +123,22 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe
claudeRequest := dto.ClaudeRequest{
Model: textRequest.Model,
- MaxTokens: textRequest.GetMaxTokens(),
StopSequences: nil,
Temperature: textRequest.Temperature,
- TopP: textRequest.TopP,
- TopK: textRequest.TopK,
- Stream: textRequest.Stream,
Tools: claudeTools,
}
+ if maxTokens := textRequest.GetMaxTokens(); maxTokens > 0 {
+ claudeRequest.MaxTokens = common.GetPointer(maxTokens)
+ }
+ if textRequest.TopP != nil {
+ claudeRequest.TopP = common.GetPointer(*textRequest.TopP)
+ }
+ if textRequest.TopK != nil {
+ claudeRequest.TopK = common.GetPointer(*textRequest.TopK)
+ }
+ if textRequest.IsStream(nil) {
+ claudeRequest.Stream = common.GetPointer(true)
+ }
// 处理 tool_choice 和 parallel_tool_calls
if textRequest.ToolChoice != nil || textRequest.ParallelTooCalls != nil {
@@ -168,26 +148,36 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe
}
}
- if claudeRequest.MaxTokens == 0 {
- claudeRequest.MaxTokens = uint(model_setting.GetClaudeSettings().GetDefaultMaxTokens(textRequest.Model))
+ if claudeRequest.MaxTokens == nil || *claudeRequest.MaxTokens == 0 {
+ defaultMaxTokens := uint(model_setting.GetClaudeSettings().GetDefaultMaxTokens(textRequest.Model))
+ claudeRequest.MaxTokens = &defaultMaxTokens
}
- if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
+ if baseModel, effortLevel, ok := reasoning.TrimEffortSuffix(textRequest.Model); ok && effortLevel != "" &&
+ strings.HasPrefix(textRequest.Model, "claude-opus-4-6") {
+ claudeRequest.Model = baseModel
+ claudeRequest.Thinking = &dto.Thinking{
+ Type: "adaptive",
+ }
+ claudeRequest.OutputConfig = json.RawMessage(fmt.Sprintf(`{"effort":"%s"}`, effortLevel))
+ claudeRequest.TopP = common.GetPointer[float64](0)
+ claudeRequest.Temperature = common.GetPointer[float64](1.0)
+ } else if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
strings.HasSuffix(textRequest.Model, "-thinking") {
// 因为BudgetTokens 必须大于1024
- if claudeRequest.MaxTokens < 1280 {
- claudeRequest.MaxTokens = 1280
+ if claudeRequest.MaxTokens == nil || *claudeRequest.MaxTokens < 1280 {
+ claudeRequest.MaxTokens = common.GetPointer[uint](1280)
}
// BudgetTokens 为 max_tokens 的 80%
claudeRequest.Thinking = &dto.Thinking{
Type: "enabled",
- BudgetTokens: common.GetPointer[int](int(float64(claudeRequest.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage)),
+ BudgetTokens: common.GetPointer[int](int(float64(*claudeRequest.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage)),
}
// TODO: 临时处理
// https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#important-considerations-when-using-extended-thinking
- claudeRequest.TopP = 0
+ claudeRequest.TopP = nil
claudeRequest.Temperature = common.GetPointer[float64](1.0)
if !model_setting.ShouldPreserveThinkingSuffix(textRequest.Model) {
claudeRequest.Model = strings.TrimSuffix(textRequest.Model, "-thinking")
@@ -353,37 +343,39 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe
} else {
claudeMediaMessages := make([]dto.ClaudeMediaMessage, 0)
for _, mediaMessage := range message.ParseContent() {
- claudeMediaMessage := dto.ClaudeMediaMessage{
- Type: mediaMessage.Type,
- }
- if mediaMessage.Type == "text" {
- claudeMediaMessage.Text = common.GetPointer[string](mediaMessage.Text)
- } else {
- imageUrl := mediaMessage.GetImageMedia()
- claudeMediaMessage.Type = "image"
- claudeMediaMessage.Source = &dto.ClaudeMessageSource{
- Type: "base64",
+ switch mediaMessage.Type {
+ case "text":
+ claudeMediaMessages = append(claudeMediaMessages, dto.ClaudeMediaMessage{
+ Type: "text",
+ Text: common.GetPointer[string](mediaMessage.Text),
+ })
+ default:
+ source := mediaMessage.ToFileSource()
+ if source == nil {
+ continue
}
- // 判断是否是url
- if strings.HasPrefix(imageUrl.Url, "http") {
- // 是url,获取图片的类型和base64编码的数据
- fileData, err := service.GetFileBase64FromUrl(c, imageUrl.Url, "formatting image for Claude")
- if err != nil {
- return nil, fmt.Errorf("get file base64 from url failed: %s", err.Error())
- }
- claudeMediaMessage.Source.MediaType = fileData.MimeType
- claudeMediaMessage.Source.Data = fileData.Base64Data
+ base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting image for Claude")
+ if err != nil {
+ return nil, fmt.Errorf("get file data failed: %s", err.Error())
+ }
+ claudeMediaMessage := dto.ClaudeMediaMessage{
+ Source: &dto.ClaudeMessageSource{
+ Type: "base64",
+ },
+ }
+ if strings.HasPrefix(mimeType, "application/pdf") {
+ claudeMediaMessage.Type = "document"
} else {
- _, format, base64String, err := service.DecodeBase64ImageData(imageUrl.Url)
- if err != nil {
- return nil, err
- }
- claudeMediaMessage.Source.MediaType = "image/" + format
- claudeMediaMessage.Source.Data = base64String
+ claudeMediaMessage.Type = "image"
}
+
+ claudeMediaMessage.Source.MediaType = mimeType
+ claudeMediaMessage.Source.Data = base64Data
+ claudeMediaMessages = append(claudeMediaMessages, claudeMediaMessage)
+ continue
}
- claudeMediaMessages = append(claudeMediaMessages, claudeMediaMessage)
}
+
if message.ToolCalls != nil {
for _, toolCall := range message.ParseToolCalls() {
inputObj := make(map[string]any)
@@ -415,7 +407,7 @@ func RequestOpenAI2ClaudeMessage(c *gin.Context, textRequest dto.GeneralOpenAIRe
return &claudeRequest, nil
}
-func StreamResponseClaude2OpenAI(reqMode int, claudeResponse *dto.ClaudeResponse) *dto.ChatCompletionsStreamResponse {
+func StreamResponseClaude2OpenAI(claudeResponse *dto.ClaudeResponse) *dto.ChatCompletionsStreamResponse {
var response dto.ChatCompletionsStreamResponse
response.Object = "chat.completion.chunk"
response.Model = claudeResponse.Model
@@ -429,72 +421,66 @@ func StreamResponseClaude2OpenAI(reqMode int, claudeResponse *dto.ClaudeResponse
}
}
var choice dto.ChatCompletionsStreamResponseChoice
- if reqMode == RequestModeCompletion {
- choice.Delta.SetContentString(claudeResponse.Completion)
- finishReason := stopReasonClaude2OpenAI(claudeResponse.StopReason)
- if finishReason != "null" {
- choice.FinishReason = &finishReason
- }
- } else {
- if claudeResponse.Type == "message_start" {
+ if claudeResponse.Type == "message_start" {
+ if claudeResponse.Message != nil {
response.Id = claudeResponse.Message.Id
response.Model = claudeResponse.Message.Model
- //claudeUsage = &claudeResponse.Message.Usage
- choice.Delta.SetContentString("")
- choice.Delta.Role = "assistant"
- } else if claudeResponse.Type == "content_block_start" {
- if claudeResponse.ContentBlock != nil {
- // 如果是文本块,尽可能发送首段文本(若存在)
- if claudeResponse.ContentBlock.Type == "text" && claudeResponse.ContentBlock.Text != nil {
- choice.Delta.SetContentString(*claudeResponse.ContentBlock.Text)
- }
- if claudeResponse.ContentBlock.Type == "tool_use" {
- tools = append(tools, dto.ToolCallResponse{
- Index: common.GetPointer(fcIdx),
- ID: claudeResponse.ContentBlock.Id,
- Type: "function",
- Function: dto.FunctionResponse{
- Name: claudeResponse.ContentBlock.Name,
- Arguments: "",
- },
- })
- }
- } else {
- return nil
+ }
+ //claudeUsage = &claudeResponse.Message.Usage
+ choice.Delta.SetContentString("")
+ choice.Delta.Role = "assistant"
+ } else if claudeResponse.Type == "content_block_start" {
+ if claudeResponse.ContentBlock != nil {
+ // 如果是文本块,尽可能发送首段文本(若存在)
+ if claudeResponse.ContentBlock.Type == "text" && claudeResponse.ContentBlock.Text != nil {
+ choice.Delta.SetContentString(*claudeResponse.ContentBlock.Text)
}
- } else if claudeResponse.Type == "content_block_delta" {
- if claudeResponse.Delta != nil {
- choice.Delta.Content = claudeResponse.Delta.Text
- switch claudeResponse.Delta.Type {
- case "input_json_delta":
- tools = append(tools, dto.ToolCallResponse{
- Type: "function",
- Index: common.GetPointer(fcIdx),
- Function: dto.FunctionResponse{
- Arguments: *claudeResponse.Delta.PartialJson,
- },
- })
- case "signature_delta":
- // 加密的不处理
- signatureContent := "\n"
- choice.Delta.ReasoningContent = &signatureContent
- case "thinking_delta":
- choice.Delta.ReasoningContent = claudeResponse.Delta.Thinking
- }
+ if claudeResponse.ContentBlock.Type == "tool_use" {
+ tools = append(tools, dto.ToolCallResponse{
+ Index: common.GetPointer(fcIdx),
+ ID: claudeResponse.ContentBlock.Id,
+ Type: "function",
+ Function: dto.FunctionResponse{
+ Name: claudeResponse.ContentBlock.Name,
+ Arguments: "",
+ },
+ })
}
- } else if claudeResponse.Type == "message_delta" {
- if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
- finishReason := stopReasonClaude2OpenAI(*claudeResponse.Delta.StopReason)
- if finishReason != "null" {
- choice.FinishReason = &finishReason
- }
- }
- //claudeUsage = &claudeResponse.Usage
- } else if claudeResponse.Type == "message_stop" {
- return nil
} else {
return nil
}
+ } else if claudeResponse.Type == "content_block_delta" {
+ if claudeResponse.Delta != nil {
+ choice.Delta.Content = claudeResponse.Delta.Text
+ switch claudeResponse.Delta.Type {
+ case "input_json_delta":
+ tools = append(tools, dto.ToolCallResponse{
+ Type: "function",
+ Index: common.GetPointer(fcIdx),
+ Function: dto.FunctionResponse{
+ Arguments: *claudeResponse.Delta.PartialJson,
+ },
+ })
+ case "signature_delta":
+ // 加密的不处理
+ signatureContent := "\n"
+ choice.Delta.ReasoningContent = &signatureContent
+ case "thinking_delta":
+ choice.Delta.ReasoningContent = claudeResponse.Delta.Thinking
+ }
+ }
+ } else if claudeResponse.Type == "message_delta" {
+ if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
+ finishReason := stopReasonClaude2OpenAI(*claudeResponse.Delta.StopReason)
+ if finishReason != "null" {
+ choice.FinishReason = &finishReason
+ }
+ }
+ //claudeUsage = &claudeResponse.Usage
+ } else if claudeResponse.Type == "message_stop" {
+ return nil
+ } else {
+ return nil
}
if len(tools) > 0 {
choice.Delta.Content = nil // compatible with other OpenAI derivative applications, like LobeOpenAICompatibleFactory ...
@@ -505,7 +491,7 @@ func StreamResponseClaude2OpenAI(reqMode int, claudeResponse *dto.ClaudeResponse
return &response
}
-func ResponseClaude2OpenAI(reqMode int, claudeResponse *dto.ClaudeResponse) *dto.OpenAITextResponse {
+func ResponseClaude2OpenAI(claudeResponse *dto.ClaudeResponse) *dto.OpenAITextResponse {
choices := make([]dto.OpenAITextResponseChoice, 0)
fullTextResponse := dto.OpenAITextResponse{
Id: fmt.Sprintf("chatcmpl-%s", common.GetUUID()),
@@ -523,39 +509,26 @@ func ResponseClaude2OpenAI(reqMode int, claudeResponse *dto.ClaudeResponse) *dto
tools := make([]dto.ToolCallResponse, 0)
thinkingContent := ""
- if reqMode == RequestModeCompletion {
- choice := dto.OpenAITextResponseChoice{
- Index: 0,
- Message: dto.Message{
- Role: "assistant",
- Content: strings.TrimPrefix(claudeResponse.Completion, " "),
- Name: nil,
- },
- FinishReason: stopReasonClaude2OpenAI(claudeResponse.StopReason),
- }
- choices = append(choices, choice)
- } else {
- fullTextResponse.Id = claudeResponse.Id
- for _, message := range claudeResponse.Content {
- switch message.Type {
- case "tool_use":
- args, _ := json.Marshal(message.Input)
- tools = append(tools, dto.ToolCallResponse{
- ID: message.Id,
- Type: "function", // compatible with other OpenAI derivative applications
- Function: dto.FunctionResponse{
- Name: message.Name,
- Arguments: string(args),
- },
- })
- case "thinking":
- // 加密的不管, 只输出明文的推理过程
- if message.Thinking != nil {
- thinkingContent = *message.Thinking
- }
- case "text":
- responseText = message.GetText()
+ fullTextResponse.Id = claudeResponse.Id
+ for _, message := range claudeResponse.Content {
+ switch message.Type {
+ case "tool_use":
+ args, _ := json.Marshal(message.Input)
+ tools = append(tools, dto.ToolCallResponse{
+ ID: message.Id,
+ Type: "function", // compatible with other OpenAI derivative applications
+ Function: dto.FunctionResponse{
+ Name: message.Name,
+ Arguments: string(args),
+ },
+ })
+ case "thinking":
+ // 加密的不管, 只输出明文的推理过程
+ if message.Thinking != nil {
+ thinkingContent = *message.Thinking
}
+ case "text":
+ responseText = message.GetText()
}
}
choice := dto.OpenAITextResponseChoice{
@@ -588,43 +561,190 @@ type ClaudeResponseInfo struct {
Done bool
}
-func FormatClaudeResponseInfo(requestMode int, claudeResponse *dto.ClaudeResponse, oaiResponse *dto.ChatCompletionsStreamResponse, claudeInfo *ClaudeResponseInfo) bool {
- if requestMode == RequestModeCompletion {
- claudeInfo.ResponseText.WriteString(claudeResponse.Completion)
+func cacheCreationTokensForOpenAIUsage(usage *dto.Usage) int {
+ if usage == nil {
+ return 0
+ }
+ splitCacheCreationTokens := usage.ClaudeCacheCreation5mTokens + usage.ClaudeCacheCreation1hTokens
+ if splitCacheCreationTokens == 0 {
+ return usage.PromptTokensDetails.CachedCreationTokens
+ }
+ if usage.PromptTokensDetails.CachedCreationTokens > splitCacheCreationTokens {
+ return usage.PromptTokensDetails.CachedCreationTokens
+ }
+ return splitCacheCreationTokens
+}
+
+func buildOpenAIStyleUsageFromClaudeUsage(usage *dto.Usage) dto.Usage {
+ if usage == nil {
+ return dto.Usage{}
+ }
+ clone := *usage
+ clone.ClaudeCacheCreation5mTokens, clone.ClaudeCacheCreation1hTokens = service.NormalizeCacheCreationSplit(
+ usage.PromptTokensDetails.CachedCreationTokens,
+ usage.ClaudeCacheCreation5mTokens,
+ usage.ClaudeCacheCreation1hTokens,
+ )
+ cacheCreationTokens := cacheCreationTokensForOpenAIUsage(usage)
+ totalInputTokens := usage.PromptTokens + usage.PromptTokensDetails.CachedTokens + cacheCreationTokens
+ clone.PromptTokens = totalInputTokens
+ clone.InputTokens = totalInputTokens
+ clone.TotalTokens = totalInputTokens + usage.CompletionTokens
+ clone.UsageSemantic = "openai"
+ clone.UsageSource = "anthropic"
+ return clone
+}
+
+func buildMessageDeltaPatchUsage(claudeResponse *dto.ClaudeResponse, claudeInfo *ClaudeResponseInfo) *dto.ClaudeUsage {
+ usage := &dto.ClaudeUsage{}
+ if claudeResponse != nil && claudeResponse.Usage != nil {
+ *usage = *claudeResponse.Usage
+ }
+
+ if claudeInfo == nil || claudeInfo.Usage == nil {
+ return usage
+ }
+
+ if usage.InputTokens == 0 && claudeInfo.Usage.PromptTokens > 0 {
+ usage.InputTokens = claudeInfo.Usage.PromptTokens
+ }
+ if usage.CacheReadInputTokens == 0 && claudeInfo.Usage.PromptTokensDetails.CachedTokens > 0 {
+ usage.CacheReadInputTokens = claudeInfo.Usage.PromptTokensDetails.CachedTokens
+ }
+ if usage.CacheCreationInputTokens == 0 && claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens > 0 {
+ usage.CacheCreationInputTokens = claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens
+ }
+ cacheCreation5m := 0
+ cacheCreation1h := 0
+ if usage.CacheCreation != nil {
+ cacheCreation5m = usage.CacheCreation.Ephemeral5mInputTokens
+ cacheCreation1h = usage.CacheCreation.Ephemeral1hInputTokens
} else {
- if claudeResponse.Type == "message_start" {
+ cacheCreation5m = claudeInfo.Usage.ClaudeCacheCreation5mTokens
+ cacheCreation1h = claudeInfo.Usage.ClaudeCacheCreation1hTokens
+ }
+ cacheCreation5m, cacheCreation1h = service.NormalizeCacheCreationSplit(
+ usage.CacheCreationInputTokens,
+ cacheCreation5m,
+ cacheCreation1h,
+ )
+ if usage.CacheCreation == nil && (cacheCreation5m > 0 || cacheCreation1h > 0) {
+ usage.CacheCreation = &dto.ClaudeCacheCreationUsage{}
+ }
+ if usage.CacheCreation != nil {
+ usage.CacheCreation.Ephemeral5mInputTokens = cacheCreation5m
+ usage.CacheCreation.Ephemeral1hInputTokens = cacheCreation1h
+ }
+ return usage
+}
+
+func shouldSkipClaudeMessageDeltaUsagePatch(info *relaycommon.RelayInfo) bool {
+ if model_setting.GetGlobalSettings().PassThroughRequestEnabled {
+ return true
+ }
+ if info == nil {
+ return false
+ }
+ return info.ChannelSetting.PassThroughBodyEnabled
+}
+
+func patchClaudeMessageDeltaUsageData(data string, usage *dto.ClaudeUsage) string {
+ if data == "" || usage == nil {
+ return data
+ }
+
+ data = setMessageDeltaUsageInt(data, "usage.input_tokens", usage.InputTokens)
+ data = setMessageDeltaUsageInt(data, "usage.cache_read_input_tokens", usage.CacheReadInputTokens)
+ data = setMessageDeltaUsageInt(data, "usage.cache_creation_input_tokens", usage.CacheCreationInputTokens)
+
+ if usage.CacheCreation != nil {
+ data = setMessageDeltaUsageInt(data, "usage.cache_creation.ephemeral_5m_input_tokens", usage.CacheCreation.Ephemeral5mInputTokens)
+ data = setMessageDeltaUsageInt(data, "usage.cache_creation.ephemeral_1h_input_tokens", usage.CacheCreation.Ephemeral1hInputTokens)
+ }
+
+ return data
+}
+
+func setMessageDeltaUsageInt(data string, path string, localValue int) string {
+ if localValue <= 0 {
+ return data
+ }
+
+ upstreamValue := gjson.Get(data, path)
+ if upstreamValue.Exists() && upstreamValue.Int() > 0 {
+ return data
+ }
+
+ patchedData, err := sjson.Set(data, path, localValue)
+ if err != nil {
+ return data
+ }
+ return patchedData
+}
+
+func FormatClaudeResponseInfo(claudeResponse *dto.ClaudeResponse, oaiResponse *dto.ChatCompletionsStreamResponse, claudeInfo *ClaudeResponseInfo) bool {
+ if claudeInfo == nil {
+ return false
+ }
+ if claudeInfo.Usage == nil {
+ claudeInfo.Usage = &dto.Usage{}
+ }
+ if claudeResponse.Type == "message_start" {
+ if claudeResponse.Message != nil {
claudeInfo.ResponseId = claudeResponse.Message.Id
claudeInfo.Model = claudeResponse.Message.Model
+ }
- // message_start, 获取usage
+ // message_start, 获取usage
+ if claudeResponse.Message != nil && claudeResponse.Message.Usage != nil {
claudeInfo.Usage.PromptTokens = claudeResponse.Message.Usage.InputTokens
+ claudeInfo.Usage.UsageSemantic = "anthropic"
claudeInfo.Usage.PromptTokensDetails.CachedTokens = claudeResponse.Message.Usage.CacheReadInputTokens
claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Message.Usage.CacheCreationInputTokens
claudeInfo.Usage.ClaudeCacheCreation5mTokens = claudeResponse.Message.Usage.GetCacheCreation5mTokens()
claudeInfo.Usage.ClaudeCacheCreation1hTokens = claudeResponse.Message.Usage.GetCacheCreation1hTokens()
claudeInfo.Usage.CompletionTokens = claudeResponse.Message.Usage.OutputTokens
- } else if claudeResponse.Type == "content_block_delta" {
+ }
+ } else if claudeResponse.Type == "content_block_delta" {
+ if claudeResponse.Delta != nil {
if claudeResponse.Delta.Text != nil {
claudeInfo.ResponseText.WriteString(*claudeResponse.Delta.Text)
}
if claudeResponse.Delta.Thinking != nil {
claudeInfo.ResponseText.WriteString(*claudeResponse.Delta.Thinking)
}
- } else if claudeResponse.Type == "message_delta" {
- // 最终的usage获取
+ }
+ } else if claudeResponse.Type == "message_delta" {
+ // 最终的usage获取
+ if claudeResponse.Usage != nil {
+ claudeInfo.Usage.UsageSemantic = "anthropic"
if claudeResponse.Usage.InputTokens > 0 {
// 不叠加,只取最新的
claudeInfo.Usage.PromptTokens = claudeResponse.Usage.InputTokens
}
- claudeInfo.Usage.CompletionTokens = claudeResponse.Usage.OutputTokens
+ if claudeResponse.Usage.CacheReadInputTokens > 0 {
+ claudeInfo.Usage.PromptTokensDetails.CachedTokens = claudeResponse.Usage.CacheReadInputTokens
+ }
+ if claudeResponse.Usage.CacheCreationInputTokens > 0 {
+ claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Usage.CacheCreationInputTokens
+ }
+ if cacheCreation5m := claudeResponse.Usage.GetCacheCreation5mTokens(); cacheCreation5m > 0 {
+ claudeInfo.Usage.ClaudeCacheCreation5mTokens = cacheCreation5m
+ }
+ if cacheCreation1h := claudeResponse.Usage.GetCacheCreation1hTokens(); cacheCreation1h > 0 {
+ claudeInfo.Usage.ClaudeCacheCreation1hTokens = cacheCreation1h
+ }
+ if claudeResponse.Usage.OutputTokens > 0 {
+ claudeInfo.Usage.CompletionTokens = claudeResponse.Usage.OutputTokens
+ }
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
-
- // 判断是否完整
- claudeInfo.Done = true
- } else if claudeResponse.Type == "content_block_start" {
- } else {
- return false
}
+
+ // 判断是否完整
+ claudeInfo.Done = true
+ } else if claudeResponse.Type == "content_block_start" {
+ } else {
+ return false
}
if oaiResponse != nil {
oaiResponse.Id = claudeInfo.ResponseId
@@ -634,7 +754,7 @@ func FormatClaudeResponseInfo(requestMode int, claudeResponse *dto.ClaudeRespons
return true
}
-func HandleStreamResponseData(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, data string, requestMode int) *types.NewAPIError {
+func HandleStreamResponseData(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, data string) *types.NewAPIError {
var claudeResponse dto.ClaudeResponse
err := common.UnmarshalJsonStr(data, &claudeResponse)
if err != nil {
@@ -644,23 +764,32 @@ func HandleStreamResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
if claudeError := claudeResponse.GetClaudeError(); claudeError != nil && claudeError.Type != "" {
return types.WithClaudeError(*claudeError, http.StatusInternalServerError)
}
+ if claudeResponse.StopReason != "" {
+ maybeMarkClaudeRefusal(c, claudeResponse.StopReason)
+ }
+ if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
+ maybeMarkClaudeRefusal(c, *claudeResponse.Delta.StopReason)
+ }
if info.RelayFormat == types.RelayFormatClaude {
- FormatClaudeResponseInfo(requestMode, &claudeResponse, nil, claudeInfo)
+ FormatClaudeResponseInfo(&claudeResponse, nil, claudeInfo)
- if requestMode == RequestModeCompletion {
- } else {
- if claudeResponse.Type == "message_start" {
- // message_start, 获取usage
+ if claudeResponse.Type == "message_start" {
+ // message_start, 获取usage
+ if claudeResponse.Message != nil {
info.UpstreamModelName = claudeResponse.Message.Model
- } else if claudeResponse.Type == "content_block_delta" {
- } else if claudeResponse.Type == "message_delta" {
+ }
+ } else if claudeResponse.Type == "message_delta" {
+ // 确保 message_delta 的 usage 包含完整的 input_tokens 和 cache 相关字段
+ // 解决 AWS Bedrock 等上游返回的 message_delta 缺少这些字段的问题
+ if !shouldSkipClaudeMessageDeltaUsagePatch(info) {
+ data = patchClaudeMessageDeltaUsageData(data, buildMessageDeltaPatchUsage(&claudeResponse, claudeInfo))
}
}
helper.ClaudeChunkData(c, claudeResponse, data)
} else if info.RelayFormat == types.RelayFormatOpenAI {
- response := StreamResponseClaude2OpenAI(requestMode, &claudeResponse)
+ response := StreamResponseClaude2OpenAI(&claudeResponse)
- if !FormatClaudeResponseInfo(requestMode, &claudeResponse, response, claudeInfo) {
+ if !FormatClaudeResponseInfo(&claudeResponse, response, claudeInfo) {
return nil
}
@@ -672,27 +801,35 @@ func HandleStreamResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
return nil
}
-func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, requestMode int) {
-
- if requestMode == RequestModeCompletion {
- claudeInfo.Usage = service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
- } else {
+func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
+ if claudeInfo.Usage.PromptTokens == 0 {
+ //上游出错
+ }
+ if claudeInfo.Usage.CompletionTokens == 0 || !claudeInfo.Done {
+ if common.DebugEnabled {
+ common.SysLog("claude response usage is not complete, maybe upstream error")
+ }
+ // 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
+ fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
+ if claudeInfo.Usage.CompletionTokens == 0 ||
+ (!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
+ claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
+ }
if claudeInfo.Usage.PromptTokens == 0 {
- //上游出错
- }
- if claudeInfo.Usage.CompletionTokens == 0 || !claudeInfo.Done {
- if common.DebugEnabled {
- common.SysLog("claude response usage is not complete, maybe upstream error")
- }
- claudeInfo.Usage = service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, claudeInfo.Usage.PromptTokens)
+ claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
+ claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
+ }
+ if claudeInfo.Usage != nil {
+ claudeInfo.Usage.UsageSemantic = "anthropic"
}
if info.RelayFormat == types.RelayFormatClaude {
//
} else if info.RelayFormat == types.RelayFormatOpenAI {
if info.ShouldIncludeUsage {
- response := helper.GenerateFinalUsageResponse(claudeInfo.ResponseId, claudeInfo.Created, info.UpstreamModelName, *claudeInfo.Usage)
+ openAIUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage)
+ response := helper.GenerateFinalUsageResponse(claudeInfo.ResponseId, claudeInfo.Created, info.UpstreamModelName, openAIUsage)
err := helper.ObjectData(c, response)
if err != nil {
common.SysLog("send final response failed: " + err.Error())
@@ -702,7 +839,7 @@ func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, clau
}
}
-func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, requestMode int) (*dto.Usage, *types.NewAPIError) {
+func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
claudeInfo := &ClaudeResponseInfo{
ResponseId: helper.GetResponseID(c),
Created: common.GetTimestamp(),
@@ -711,22 +848,21 @@ func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
Usage: &dto.Usage{},
}
var err *types.NewAPIError
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
- err = HandleStreamResponseData(c, info, claudeInfo, data, requestMode)
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
+ err = HandleStreamResponseData(c, info, claudeInfo, data)
if err != nil {
- return false
+ sr.Stop(err)
}
- return true
})
if err != nil {
return nil, err
}
- HandleStreamFinalResponse(c, info, claudeInfo, requestMode)
+ HandleStreamFinalResponse(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
-func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, httpResp *http.Response, data []byte, requestMode int) *types.NewAPIError {
+func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, httpResp *http.Response, data []byte) *types.NewAPIError {
var claudeResponse dto.ClaudeResponse
err := common.Unmarshal(data, &claudeResponse)
if err != nil {
@@ -735,12 +871,15 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
if claudeError := claudeResponse.GetClaudeError(); claudeError != nil && claudeError.Type != "" {
return types.WithClaudeError(*claudeError, http.StatusInternalServerError)
}
- if requestMode == RequestModeCompletion {
- claudeInfo.Usage = service.ResponseText2Usage(c, claudeResponse.Completion, info.UpstreamModelName, info.GetEstimatePromptTokens())
- } else {
+ maybeMarkClaudeRefusal(c, claudeResponse.StopReason)
+ if claudeInfo.Usage == nil {
+ claudeInfo.Usage = &dto.Usage{}
+ }
+ if claudeResponse.Usage != nil {
claudeInfo.Usage.PromptTokens = claudeResponse.Usage.InputTokens
claudeInfo.Usage.CompletionTokens = claudeResponse.Usage.OutputTokens
claudeInfo.Usage.TotalTokens = claudeResponse.Usage.InputTokens + claudeResponse.Usage.OutputTokens
+ claudeInfo.Usage.UsageSemantic = "anthropic"
claudeInfo.Usage.PromptTokensDetails.CachedTokens = claudeResponse.Usage.CacheReadInputTokens
claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Usage.CacheCreationInputTokens
claudeInfo.Usage.ClaudeCacheCreation5mTokens = claudeResponse.Usage.GetCacheCreation5mTokens()
@@ -749,8 +888,8 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
var responseData []byte
switch info.RelayFormat {
case types.RelayFormatOpenAI:
- openaiResponse := ResponseClaude2OpenAI(requestMode, &claudeResponse)
- openaiResponse.Usage = *claudeInfo.Usage
+ openaiResponse := ResponseClaude2OpenAI(&claudeResponse)
+ openaiResponse.Usage = buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage)
responseData, err = json.Marshal(openaiResponse)
if err != nil {
return types.NewError(err, types.ErrorCodeBadResponseBody)
@@ -759,7 +898,7 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
responseData = data
}
- if claudeResponse.Usage.ServerToolUse != nil && claudeResponse.Usage.ServerToolUse.WebSearchRequests > 0 {
+ if claudeResponse.Usage != nil && claudeResponse.Usage.ServerToolUse != nil && claudeResponse.Usage.ServerToolUse.WebSearchRequests > 0 {
c.Set("claude_web_search_requests", claudeResponse.Usage.ServerToolUse.WebSearchRequests)
}
@@ -767,7 +906,7 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
return nil
}
-func ClaudeHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, requestMode int) (*dto.Usage, *types.NewAPIError) {
+func ClaudeHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
defer service.CloseResponseBodyGracefully(resp)
claudeInfo := &ClaudeResponseInfo{
@@ -784,7 +923,7 @@ func ClaudeHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayI
if common.DebugEnabled {
println("responseBody: ", string(responseBody))
}
- handleErr := HandleClaudeResponseData(c, info, claudeInfo, resp, responseBody, requestMode)
+ handleErr := HandleClaudeResponseData(c, info, claudeInfo, resp, responseBody)
if handleErr != nil {
return nil, handleErr
}
@@ -831,9 +970,12 @@ func mapToolChoice(toolChoice any, parallelToolCalls *bool) *dto.ClaudeToolChoic
}
}
- // 设置 disable_parallel_tool_use
- // 如果 parallel_tool_calls 为 true,则 disable_parallel_tool_use 为 false
- claudeToolChoice.DisableParallelToolUse = !*parallelToolCalls
+ // Anthropic schema: tool_choice.type=none does not accept extra fields.
+ // When tools are disabled, parallel_tool_calls is irrelevant, so we drop it.
+ if claudeToolChoice.Type != "none" {
+ // 如果 parallel_tool_calls 为 true,则 disable_parallel_tool_use 为 false
+ claudeToolChoice.DisableParallelToolUse = !*parallelToolCalls
+ }
}
return claudeToolChoice
diff --git a/relay/channel/claude/relay_claude_test.go b/relay/channel/claude/relay_claude_test.go
new file mode 100644
index 0000000000..fdc7b38e5e
--- /dev/null
+++ b/relay/channel/claude/relay_claude_test.go
@@ -0,0 +1,382 @@
+package claude
+
+import (
+ "encoding/base64"
+ "strings"
+ "testing"
+
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFormatClaudeResponseInfo_MessageStart(t *testing.T) {
+ claudeInfo := &ClaudeResponseInfo{
+ Usage: &dto.Usage{},
+ }
+ claudeResponse := &dto.ClaudeResponse{
+ Type: "message_start",
+ Message: &dto.ClaudeMediaMessage{
+ Id: "msg_123",
+ Model: "claude-3-5-sonnet",
+ Usage: &dto.ClaudeUsage{
+ InputTokens: 100,
+ OutputTokens: 1,
+ CacheCreationInputTokens: 50,
+ CacheReadInputTokens: 30,
+ },
+ },
+ }
+
+ ok := FormatClaudeResponseInfo(claudeResponse, nil, claudeInfo)
+ if !ok {
+ t.Fatal("expected true")
+ }
+ if claudeInfo.Usage.PromptTokens != 100 {
+ t.Errorf("PromptTokens = %d, want 100", claudeInfo.Usage.PromptTokens)
+ }
+ if claudeInfo.Usage.PromptTokensDetails.CachedTokens != 30 {
+ t.Errorf("CachedTokens = %d, want 30", claudeInfo.Usage.PromptTokensDetails.CachedTokens)
+ }
+ if claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens != 50 {
+ t.Errorf("CachedCreationTokens = %d, want 50", claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens)
+ }
+ if claudeInfo.ResponseId != "msg_123" {
+ t.Errorf("ResponseId = %s, want msg_123", claudeInfo.ResponseId)
+ }
+ if claudeInfo.Model != "claude-3-5-sonnet" {
+ t.Errorf("Model = %s, want claude-3-5-sonnet", claudeInfo.Model)
+ }
+}
+
+func TestFormatClaudeResponseInfo_MessageDelta_FullUsage(t *testing.T) {
+ // message_start 先积累 usage
+ claudeInfo := &ClaudeResponseInfo{
+ Usage: &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ CompletionTokens: 1,
+ },
+ }
+
+ // message_delta 带完整 usage(原生 Anthropic 场景)
+ claudeResponse := &dto.ClaudeResponse{
+ Type: "message_delta",
+ Usage: &dto.ClaudeUsage{
+ InputTokens: 100,
+ OutputTokens: 200,
+ CacheCreationInputTokens: 50,
+ CacheReadInputTokens: 30,
+ },
+ }
+
+ ok := FormatClaudeResponseInfo(claudeResponse, nil, claudeInfo)
+ if !ok {
+ t.Fatal("expected true")
+ }
+ if claudeInfo.Usage.PromptTokens != 100 {
+ t.Errorf("PromptTokens = %d, want 100", claudeInfo.Usage.PromptTokens)
+ }
+ if claudeInfo.Usage.CompletionTokens != 200 {
+ t.Errorf("CompletionTokens = %d, want 200", claudeInfo.Usage.CompletionTokens)
+ }
+ if claudeInfo.Usage.TotalTokens != 300 {
+ t.Errorf("TotalTokens = %d, want 300", claudeInfo.Usage.TotalTokens)
+ }
+ if !claudeInfo.Done {
+ t.Error("expected Done = true")
+ }
+}
+
+func TestFormatClaudeResponseInfo_MessageDelta_OnlyOutputTokens(t *testing.T) {
+ // 模拟 Bedrock: message_start 已积累 usage
+ claudeInfo := &ClaudeResponseInfo{
+ Usage: &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ CompletionTokens: 1,
+ ClaudeCacheCreation5mTokens: 10,
+ ClaudeCacheCreation1hTokens: 20,
+ },
+ }
+
+ // Bedrock 的 message_delta 只有 output_tokens,缺少 input_tokens 和 cache 字段
+ claudeResponse := &dto.ClaudeResponse{
+ Type: "message_delta",
+ Usage: &dto.ClaudeUsage{
+ OutputTokens: 200,
+ // InputTokens, CacheCreationInputTokens, CacheReadInputTokens 都是 0
+ },
+ }
+
+ ok := FormatClaudeResponseInfo(claudeResponse, nil, claudeInfo)
+ if !ok {
+ t.Fatal("expected true")
+ }
+ // PromptTokens 应保持 message_start 的值(因为 message_delta 的 InputTokens=0,不更新)
+ if claudeInfo.Usage.PromptTokens != 100 {
+ t.Errorf("PromptTokens = %d, want 100", claudeInfo.Usage.PromptTokens)
+ }
+ if claudeInfo.Usage.CompletionTokens != 200 {
+ t.Errorf("CompletionTokens = %d, want 200", claudeInfo.Usage.CompletionTokens)
+ }
+ if claudeInfo.Usage.TotalTokens != 300 {
+ t.Errorf("TotalTokens = %d, want 300", claudeInfo.Usage.TotalTokens)
+ }
+ // cache 字段应保持 message_start 的值
+ if claudeInfo.Usage.PromptTokensDetails.CachedTokens != 30 {
+ t.Errorf("CachedTokens = %d, want 30", claudeInfo.Usage.PromptTokensDetails.CachedTokens)
+ }
+ if claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens != 50 {
+ t.Errorf("CachedCreationTokens = %d, want 50", claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens)
+ }
+ if claudeInfo.Usage.ClaudeCacheCreation5mTokens != 10 {
+ t.Errorf("ClaudeCacheCreation5mTokens = %d, want 10", claudeInfo.Usage.ClaudeCacheCreation5mTokens)
+ }
+ if claudeInfo.Usage.ClaudeCacheCreation1hTokens != 20 {
+ t.Errorf("ClaudeCacheCreation1hTokens = %d, want 20", claudeInfo.Usage.ClaudeCacheCreation1hTokens)
+ }
+ if !claudeInfo.Done {
+ t.Error("expected Done = true")
+ }
+}
+
+func TestFormatClaudeResponseInfo_NilClaudeInfo(t *testing.T) {
+ claudeResponse := &dto.ClaudeResponse{Type: "message_start"}
+ ok := FormatClaudeResponseInfo(claudeResponse, nil, nil)
+ if ok {
+ t.Error("expected false for nil claudeInfo")
+ }
+}
+
+func TestFormatClaudeResponseInfo_ContentBlockDelta(t *testing.T) {
+ text := "hello"
+ claudeInfo := &ClaudeResponseInfo{
+ Usage: &dto.Usage{},
+ ResponseText: strings.Builder{},
+ }
+ claudeResponse := &dto.ClaudeResponse{
+ Type: "content_block_delta",
+ Delta: &dto.ClaudeMediaMessage{
+ Text: &text,
+ },
+ }
+
+ ok := FormatClaudeResponseInfo(claudeResponse, nil, claudeInfo)
+ if !ok {
+ t.Fatal("expected true")
+ }
+ if claudeInfo.ResponseText.String() != "hello" {
+ t.Errorf("ResponseText = %q, want %q", claudeInfo.ResponseText.String(), "hello")
+ }
+}
+
+func TestBuildOpenAIStyleUsageFromClaudeUsage(t *testing.T) {
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ CompletionTokens: 20,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ ClaudeCacheCreation5mTokens: 10,
+ ClaudeCacheCreation1hTokens: 20,
+ UsageSemantic: "anthropic",
+ }
+
+ openAIUsage := buildOpenAIStyleUsageFromClaudeUsage(usage)
+
+ if openAIUsage.PromptTokens != 180 {
+ t.Fatalf("PromptTokens = %d, want 180", openAIUsage.PromptTokens)
+ }
+ if openAIUsage.InputTokens != 180 {
+ t.Fatalf("InputTokens = %d, want 180", openAIUsage.InputTokens)
+ }
+ if openAIUsage.TotalTokens != 200 {
+ t.Fatalf("TotalTokens = %d, want 200", openAIUsage.TotalTokens)
+ }
+ if openAIUsage.UsageSemantic != "openai" {
+ t.Fatalf("UsageSemantic = %s, want openai", openAIUsage.UsageSemantic)
+ }
+ if openAIUsage.UsageSource != "anthropic" {
+ t.Fatalf("UsageSource = %s, want anthropic", openAIUsage.UsageSource)
+ }
+}
+
+func TestBuildOpenAIStyleUsageFromClaudeUsagePreservesCacheCreationRemainder(t *testing.T) {
+ tests := []struct {
+ name string
+ cachedCreationTokens int
+ cacheCreationTokens5m int
+ cacheCreationTokens1h int
+ expectedTotalInputToken int
+ }{
+ {
+ name: "prefers aggregate when it includes remainder",
+ cachedCreationTokens: 50,
+ cacheCreationTokens5m: 10,
+ cacheCreationTokens1h: 20,
+ expectedTotalInputToken: 180,
+ },
+ {
+ name: "falls back to split tokens when aggregate missing",
+ cachedCreationTokens: 0,
+ cacheCreationTokens5m: 10,
+ cacheCreationTokens1h: 20,
+ expectedTotalInputToken: 160,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ CompletionTokens: 20,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: tt.cachedCreationTokens,
+ },
+ ClaudeCacheCreation5mTokens: tt.cacheCreationTokens5m,
+ ClaudeCacheCreation1hTokens: tt.cacheCreationTokens1h,
+ UsageSemantic: "anthropic",
+ }
+
+ openAIUsage := buildOpenAIStyleUsageFromClaudeUsage(usage)
+
+ if openAIUsage.PromptTokens != tt.expectedTotalInputToken {
+ t.Fatalf("PromptTokens = %d, want %d", openAIUsage.PromptTokens, tt.expectedTotalInputToken)
+ }
+ if openAIUsage.InputTokens != tt.expectedTotalInputToken {
+ t.Fatalf("InputTokens = %d, want %d", openAIUsage.InputTokens, tt.expectedTotalInputToken)
+ }
+ })
+ }
+}
+
+func TestBuildOpenAIStyleUsageFromClaudeUsageDefaultsAggregateCacheCreationTo5m(t *testing.T) {
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ CompletionTokens: 20,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ CachedCreationTokens: 50,
+ },
+ UsageSemantic: "anthropic",
+ }
+
+ openAIUsage := buildOpenAIStyleUsageFromClaudeUsage(usage)
+
+ require.Equal(t, 50, openAIUsage.ClaudeCacheCreation5mTokens)
+ require.Equal(t, 0, openAIUsage.ClaudeCacheCreation1hTokens)
+}
+
+func TestRequestOpenAI2ClaudeMessage_IgnoresUnsupportedFileContent(t *testing.T) {
+ request := dto.GeneralOpenAIRequest{
+ Model: "claude-3-5-sonnet",
+ Messages: []dto.Message{
+ {
+ Role: "user",
+ Content: []any{
+ dto.MediaContent{
+ Type: dto.ContentTypeText,
+ Text: "see attachment",
+ },
+ dto.MediaContent{
+ Type: dto.ContentTypeFile,
+ File: &dto.MessageFile{
+ FileName: "blob.bin",
+ FileData: "JVBERi0xLjQK",
+ },
+ },
+ },
+ },
+ },
+ }
+
+ claudeRequest, err := RequestOpenAI2ClaudeMessage(nil, request)
+ require.NoError(t, err)
+ require.Len(t, claudeRequest.Messages, 1)
+
+ content, ok := claudeRequest.Messages[0].Content.([]dto.ClaudeMediaMessage)
+ require.True(t, ok)
+ require.Len(t, content, 1)
+ require.Equal(t, "text", content[0].Type)
+ require.NotNil(t, content[0].Text)
+ require.Equal(t, "see attachment", *content[0].Text)
+}
+
+func TestRequestOpenAI2ClaudeMessage_SupportsPDFFileContent(t *testing.T) {
+ request := dto.GeneralOpenAIRequest{
+ Model: "claude-3-5-sonnet",
+ Messages: []dto.Message{
+ {
+ Role: "user",
+ Content: []any{
+ dto.MediaContent{
+ Type: dto.ContentTypeFile,
+ File: &dto.MessageFile{
+ FileName: "spec.pdf",
+ FileData: "JVBERi0xLjQK",
+ },
+ },
+ dto.MediaContent{
+ Type: dto.ContentTypeText,
+ Text: "summarize it",
+ },
+ },
+ },
+ },
+ }
+
+ claudeRequest, err := RequestOpenAI2ClaudeMessage(nil, request)
+ require.NoError(t, err)
+ require.Len(t, claudeRequest.Messages, 1)
+
+ content, ok := claudeRequest.Messages[0].Content.([]dto.ClaudeMediaMessage)
+ require.True(t, ok)
+ require.Len(t, content, 2)
+ require.Equal(t, "document", content[0].Type)
+ require.NotNil(t, content[0].Source)
+ require.Equal(t, "base64", content[0].Source.Type)
+ require.Equal(t, "application/pdf", content[0].Source.MediaType)
+ require.Equal(t, "JVBERi0xLjQK", content[0].Source.Data)
+ require.Equal(t, "text", content[1].Type)
+ require.NotNil(t, content[1].Text)
+ require.Equal(t, "summarize it", *content[1].Text)
+}
+
+func TestRequestOpenAI2ClaudeMessage_ConvertsTextFileContentToText(t *testing.T) {
+ request := dto.GeneralOpenAIRequest{
+ Model: "claude-3-5-sonnet",
+ Messages: []dto.Message{
+ {
+ Role: "user",
+ Content: []any{
+ dto.MediaContent{
+ Type: dto.ContentTypeFile,
+ File: &dto.MessageFile{
+ FileName: "notes.txt",
+ FileData: base64.StdEncoding.EncodeToString([]byte("alpha\nbeta")),
+ },
+ },
+ },
+ },
+ },
+ }
+
+ claudeRequest, err := RequestOpenAI2ClaudeMessage(nil, request)
+ require.NoError(t, err)
+ require.Len(t, claudeRequest.Messages, 1)
+
+ content, ok := claudeRequest.Messages[0].Content.([]dto.ClaudeMediaMessage)
+ require.True(t, ok)
+ require.Len(t, content, 1)
+ require.Equal(t, "text", content[0].Type)
+ require.NotNil(t, content[0].Text)
+ require.Equal(t, "alpha\nbeta", *content[0].Text)
+}
diff --git a/relay/channel/cloudflare/relay_cloudflare.go b/relay/channel/cloudflare/relay_cloudflare.go
index cb8a641a13..a543c8fda4 100644
--- a/relay/channel/cloudflare/relay_cloudflare.go
+++ b/relay/channel/cloudflare/relay_cloudflare.go
@@ -14,6 +14,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -23,7 +24,7 @@ func convertCf2CompletionsRequest(textRequest dto.GeneralOpenAIRequest) *CfReque
return &CfRequest{
Prompt: p,
MaxTokens: textRequest.GetMaxTokens(),
- Stream: textRequest.Stream,
+ Stream: lo.FromPtrOr(textRequest.Stream, false),
Temperature: textRequest.Temperature,
}
}
diff --git a/relay/channel/codex/adaptor.go b/relay/channel/codex/adaptor.go
index ab61dfac76..ef4d4fa041 100644
--- a/relay/channel/codex/adaptor.go
+++ b/relay/channel/codex/adaptor.go
@@ -26,7 +26,7 @@ func (a *Adaptor) ConvertGeminiRequest(c *gin.Context, info *relaycommon.RelayIn
}
func (a *Adaptor) ConvertClaudeRequest(*gin.Context, *relaycommon.RelayInfo, *dto.ClaudeRequest) (any, error) {
- return nil, errors.New("codex channel: endpoint not supported")
+ return nil, errors.New("codex channel: /v1/messages endpoint not supported")
}
func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
@@ -41,18 +41,20 @@ func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
}
func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
- return nil, errors.New("codex channel: endpoint not supported")
+ return nil, errors.New("codex channel: /v1/chat/completions endpoint not supported")
}
func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
- return nil, errors.New("codex channel: endpoint not supported")
+ return nil, errors.New("codex channel: /v1/rerank endpoint not supported")
}
func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
- return nil, errors.New("codex channel: endpoint not supported")
+ return nil, errors.New("codex channel: /v1/embeddings endpoint not supported")
}
func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
+ isCompact := info != nil && info.RelayMode == relayconstant.RelayModeResponsesCompact
+
if info != nil && info.ChannelSetting.SystemPrompt != "" {
systemPrompt := info.ChannelSetting.SystemPrompt
@@ -88,11 +90,19 @@ func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommo
}
}
}
+ // Codex backend requires the `instructions` field to be present.
+ // Keep it consistent with Codex CLI behavior by defaulting to an empty string.
+ if len(request.Instructions) == 0 {
+ request.Instructions = json.RawMessage(`""`)
+ }
+ if isCompact {
+ return request, nil
+ }
// codex: store must be false
request.Store = json.RawMessage("false")
// rm max_output_tokens
- request.MaxOutputTokens = 0
+ request.MaxOutputTokens = nil
request.Temperature = nil
return request, nil
}
@@ -102,10 +112,14 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
- if info.RelayMode != relayconstant.RelayModeResponses {
+ if info.RelayMode != relayconstant.RelayModeResponses && info.RelayMode != relayconstant.RelayModeResponsesCompact {
return nil, types.NewError(errors.New("codex channel: endpoint not supported"), types.ErrorCodeInvalidRequest)
}
+ if info.RelayMode == relayconstant.RelayModeResponsesCompact {
+ return openai.OaiResponsesCompactionHandler(c, resp)
+ }
+
if info.IsStream {
return openai.OaiResponsesStreamHandler(c, info, resp)
}
@@ -121,10 +135,14 @@ func (a *Adaptor) GetChannelName() string {
}
func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
- if info.RelayMode != relayconstant.RelayModeResponses {
- return "", errors.New("codex channel: only /v1/responses is supported")
+ if info.RelayMode != relayconstant.RelayModeResponses && info.RelayMode != relayconstant.RelayModeResponsesCompact {
+ return "", errors.New("codex channel: only /v1/responses and /v1/responses/compact are supported")
}
- return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, "/backend-api/codex/responses", info.ChannelType), nil
+ path := "/backend-api/codex/responses"
+ if info.RelayMode == relayconstant.RelayModeResponsesCompact {
+ path = "/backend-api/codex/responses/compact"
+ }
+ return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, path, info.ChannelType), nil
}
func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
@@ -160,5 +178,15 @@ func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *rel
req.Set("originator", "codex_cli_rs")
}
+ // chatgpt.com/backend-api/codex/responses is strict about Content-Type.
+ // Clients may omit it or include parameters like `application/json; charset=utf-8`,
+ // which can be rejected by the upstream. Force the exact media type.
+ req.Set("Content-Type", "application/json")
+ if info.IsStream {
+ req.Set("Accept", "text/event-stream")
+ } else if req.Get("Accept") == "" {
+ req.Set("Accept", "application/json")
+ }
+
return nil
}
diff --git a/relay/channel/codex/constants.go b/relay/channel/codex/constants.go
index 461e033a47..5233393eae 100644
--- a/relay/channel/codex/constants.go
+++ b/relay/channel/codex/constants.go
@@ -1,9 +1,26 @@
package codex
-var ModelList = []string{
+import (
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
+ "github.com/samber/lo"
+)
+
+var baseModelList = []string{
"gpt-5", "gpt-5-codex", "gpt-5-codex-mini",
"gpt-5.1", "gpt-5.1-codex", "gpt-5.1-codex-max", "gpt-5.1-codex-mini",
- "gpt-5.2", "gpt-5.2-codex",
+ "gpt-5.2", "gpt-5.2-codex", "gpt-5.3-codex", "gpt-5.3-codex-spark",
+ "gpt-5.4",
}
+var ModelList = withCompactModelSuffix(baseModelList)
+
const ChannelName = "codex"
+
+func withCompactModelSuffix(models []string) []string {
+ out := make([]string, 0, len(models)*2)
+ out = append(out, models...)
+ out = append(out, lo.Map(models, func(model string, _ int) string {
+ return ratio_setting.WithCompactModelSuffix(model)
+ })...)
+ return lo.Uniq(out)
+}
diff --git a/relay/channel/cohere/relay-cohere.go b/relay/channel/cohere/relay-cohere.go
index d51c05499d..c205e10633 100644
--- a/relay/channel/cohere/relay-cohere.go
+++ b/relay/channel/cohere/relay-cohere.go
@@ -16,6 +16,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
func requestOpenAI2Cohere(textRequest dto.GeneralOpenAIRequest) *CohereRequest {
@@ -23,7 +24,7 @@ func requestOpenAI2Cohere(textRequest dto.GeneralOpenAIRequest) *CohereRequest {
Model: textRequest.Model,
ChatHistory: []ChatHistory{},
Message: "",
- Stream: textRequest.Stream,
+ Stream: lo.FromPtrOr(textRequest.Stream, false),
MaxTokens: textRequest.GetMaxTokens(),
}
if common.CohereSafetySetting != "NONE" {
@@ -55,14 +56,15 @@ func requestOpenAI2Cohere(textRequest dto.GeneralOpenAIRequest) *CohereRequest {
}
func requestConvertRerank2Cohere(rerankRequest dto.RerankRequest) *CohereRerankRequest {
- if rerankRequest.TopN == 0 {
- rerankRequest.TopN = 1
+ topN := lo.FromPtrOr(rerankRequest.TopN, 1)
+ if topN <= 0 {
+ topN = 1
}
cohereReq := CohereRerankRequest{
Query: rerankRequest.Query,
Documents: rerankRequest.Documents,
Model: rerankRequest.Model,
- TopN: rerankRequest.TopN,
+ TopN: topN,
ReturnDocuments: true,
}
return &cohereReq
diff --git a/relay/channel/coze/dto.go b/relay/channel/coze/dto.go
index d5dc9a813a..da01bbb6c3 100644
--- a/relay/channel/coze/dto.go
+++ b/relay/channel/coze/dto.go
@@ -17,7 +17,7 @@ type CozeEnterMessage struct {
type CozeChatRequest struct {
BotId string `json:"bot_id"`
- UserId string `json:"user_id"`
+ UserId json.RawMessage `json:"user_id"`
AdditionalMessages []CozeEnterMessage `json:"additional_messages,omitempty"`
Stream bool `json:"stream,omitempty"`
CustomVariables json.RawMessage `json:"custom_variables,omitempty"`
diff --git a/relay/channel/coze/relay-coze.go b/relay/channel/coze/relay-coze.go
index 2edeeee0d9..69ebd8a684 100644
--- a/relay/channel/coze/relay-coze.go
+++ b/relay/channel/coze/relay-coze.go
@@ -15,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -33,14 +34,14 @@ func convertCozeChatRequest(c *gin.Context, request dto.GeneralOpenAIRequest) *C
}
}
user := request.User
- if user == "" {
- user = helper.GetResponseID(c)
+ if len(user) == 0 {
+ user = json.RawMessage(helper.GetResponseID(c))
}
cozeRequest := &CozeChatRequest{
BotId: c.GetString("bot_id"),
UserId: user,
AdditionalMessages: messages,
- Stream: request.Stream,
+ Stream: lo.FromPtrOr(request.Stream, false),
}
return cozeRequest
}
diff --git a/relay/channel/deepseek/adaptor.go b/relay/channel/deepseek/adaptor.go
index 53488f0d57..57fcf3d043 100644
--- a/relay/channel/deepseek/adaptor.go
+++ b/relay/channel/deepseek/adaptor.go
@@ -95,11 +95,8 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
switch info.RelayFormat {
case types.RelayFormatClaude:
- if info.IsStream {
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
- } else {
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
- }
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
default:
adaptor := openai.Adaptor{}
return adaptor.DoResponse(c, resp, info)
diff --git a/relay/channel/dify/dto.go b/relay/channel/dify/dto.go
index cb127554de..b4029a0ca0 100644
--- a/relay/channel/dify/dto.go
+++ b/relay/channel/dify/dto.go
@@ -1,6 +1,8 @@
package dify
-import "github.com/QuantumNous/new-api/dto"
+import (
+ "github.com/QuantumNous/new-api/dto"
+)
type DifyChatRequest struct {
Inputs map[string]interface{} `json:"inputs"`
diff --git a/relay/channel/dify/relay-dify.go b/relay/channel/dify/relay-dify.go
index 24f5218a41..80094f88bd 100644
--- a/relay/channel/dify/relay-dify.go
+++ b/relay/channel/dify/relay-dify.go
@@ -18,6 +18,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -130,10 +131,16 @@ func requestOpenAI2Dify(c *gin.Context, info *relaycommon.RelayInfo, request dto
}
user := request.User
- if user == "" {
- user = helper.GetResponseID(c)
+ if len(user) == 0 {
+ user = json.RawMessage(helper.GetResponseID(c))
}
- difyReq.User = user
+ var stringUser string
+ err := json.Unmarshal(user, &stringUser)
+ if err != nil {
+ common.SysLog("failed to unmarshal user: " + err.Error())
+ stringUser = helper.GetResponseID(c)
+ }
+ difyReq.User = stringUser
files := make([]DifyFile, 0)
var content strings.Builder
@@ -168,7 +175,7 @@ func requestOpenAI2Dify(c *gin.Context, info *relaycommon.RelayInfo, request dto
difyReq.Query = content.String()
difyReq.Files = files
mode := "blocking"
- if request.Stream {
+ if lo.FromPtrOr(request.Stream, false) {
mode = "streaming"
}
difyReq.ResponseMode = mode
@@ -216,33 +223,32 @@ func difyStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.R
usage := &dto.Usage{}
var nodeToken int
helper.SetEventStreamHeaders(c)
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
var difyResponse DifyChunkChatCompletionResponse
- err := json.Unmarshal([]byte(data), &difyResponse)
- if err != nil {
+ if err := json.Unmarshal([]byte(data), &difyResponse); err != nil {
common.SysLog("error unmarshalling stream response: " + err.Error())
- return true
+ sr.Error(err)
+ return
}
- var openaiResponse dto.ChatCompletionsStreamResponse
if difyResponse.Event == "message_end" {
usage = &difyResponse.MetaData.Usage
- return false
+ sr.Done()
+ return
} else if difyResponse.Event == "error" {
- return false
- } else {
- openaiResponse = *streamResponseDify2OpenAI(difyResponse)
- if len(openaiResponse.Choices) != 0 {
- responseText += openaiResponse.Choices[0].Delta.GetContentString()
- if openaiResponse.Choices[0].Delta.ReasoningContent != nil {
- nodeToken += 1
- }
+ sr.Stop(fmt.Errorf("dify error event"))
+ return
+ }
+ openaiResponse := *streamResponseDify2OpenAI(difyResponse)
+ if len(openaiResponse.Choices) != 0 {
+ responseText += openaiResponse.Choices[0].Delta.GetContentString()
+ if openaiResponse.Choices[0].Delta.ReasoningContent != nil {
+ nodeToken += 1
}
}
- err = helper.ObjectData(c, openaiResponse)
- if err != nil {
+ if err := helper.ObjectData(c, openaiResponse); err != nil {
common.SysLog(err.Error())
+ sr.Error(err)
}
- return true
})
helper.Done(c)
if usage.TotalTokens == 0 {
diff --git a/relay/channel/gemini/adaptor.go b/relay/channel/gemini/adaptor.go
index d8616d2d9d..680c4ee484 100644
--- a/relay/channel/gemini/adaptor.go
+++ b/relay/channel/gemini/adaptor.go
@@ -17,6 +17,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
type Adaptor struct {
@@ -58,7 +59,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
if !strings.HasPrefix(info.UpstreamModelName, "imagen") {
- return nil, errors.New("not supported model for image generation")
+ return nil, errors.New("not supported model for image generation, only imagen models are supported")
}
// convert size to aspect ratio but allow user to specify aspect ratio
@@ -91,7 +92,7 @@ func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInf
},
},
Parameters: dto.GeminiImageParameters{
- SampleCount: int(request.N),
+ SampleCount: int(lo.FromPtrOr(request.N, uint(1))),
AspectRatio: aspectRatio,
PersonGeneration: "allow_adult", // default allow adult
},
@@ -223,8 +224,9 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
switch info.UpstreamModelName {
case "text-embedding-004", "gemini-embedding-exp-03-07", "gemini-embedding-001":
// Only newer models introduced after 2024 support OutputDimensionality
- if request.Dimensions > 0 {
- geminiRequest["outputDimensionality"] = request.Dimensions
+ dimensions := lo.FromPtrOr(request.Dimensions, 0)
+ if dimensions > 0 {
+ geminiRequest["outputDimensionality"] = dimensions
}
}
geminiRequests = append(geminiRequests, geminiRequest)
diff --git a/relay/channel/gemini/constant.go b/relay/channel/gemini/constant.go
index 59163cc43f..1a2c570567 100644
--- a/relay/channel/gemini/constant.go
+++ b/relay/channel/gemini/constant.go
@@ -2,29 +2,34 @@ package gemini
var ModelList = []string{
// stable version
- "gemini-1.5-pro", "gemini-1.5-flash", "gemini-1.5-flash-8b",
- "gemini-2.0-flash",
+ "gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash",
+ "gemini-2.0-flash-001", "gemini-2.0-flash-lite-001", "gemini-2.0-flash-lite",
+ "gemini-2.5-flash-lite",
// latest version
- "gemini-1.5-pro-latest", "gemini-1.5-flash-latest",
+ "gemini-flash-latest", "gemini-flash-lite-latest", "gemini-pro-latest",
+ "gemini-2.5-flash-native-audio-latest",
// preview version
- "gemini-2.0-flash-lite-preview",
- "gemini-3-pro-preview",
- // gemini exp
- "gemini-exp-1206",
- // flash exp
- "gemini-2.0-flash-exp",
- // pro exp
- "gemini-2.0-pro-exp",
- // thinking exp
- "gemini-2.0-flash-thinking-exp",
- "gemini-2.5-pro-exp-03-25",
- "gemini-2.5-pro-preview-03-25",
- // imagen models
- "imagen-3.0-generate-002",
+ "gemini-2.5-flash-preview-tts", "gemini-2.5-pro-preview-tts",
+ "gemini-2.5-flash-image", "gemini-2.5-flash-lite-preview-09-2025",
+ "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-3.1-pro-preview",
+ "gemini-3.1-pro-preview-customtools", "gemini-3.1-flash-lite-preview",
+ "gemini-3-pro-image-preview", "nano-banana-pro-preview",
+ "gemini-3.1-flash-image-preview", "gemini-robotics-er-1.5-preview",
+ "gemini-2.5-computer-use-preview-10-2025", "deep-research-pro-preview-12-2025",
+ "gemini-2.5-flash-native-audio-preview-09-2025", "gemini-2.5-flash-native-audio-preview-12-2025",
+ // gemma models
+ "gemma-3-1b-it", "gemma-3-4b-it", "gemma-3-12b-it",
+ "gemma-3-27b-it", "gemma-3n-e4b-it", "gemma-3n-e2b-it",
// embedding models
- "gemini-embedding-exp-03-07",
- "text-embedding-004",
- "embedding-001",
+ "gemini-embedding-001", "gemini-embedding-2-preview",
+ // imagen models
+ "imagen-4.0-generate-001", "imagen-4.0-ultra-generate-001",
+ "imagen-4.0-fast-generate-001",
+ // veo models
+ "veo-2.0-generate-001", "veo-3.0-generate-001", "veo-3.0-fast-generate-001",
+ "veo-3.1-generate-preview", "veo-3.1-fast-generate-preview",
+ // other models
+ "aqa",
}
var SafetySettingList = []string{
diff --git a/relay/channel/gemini/relay-gemini-native.go b/relay/channel/gemini/relay-gemini-native.go
index 5f9ff7cdfe..1a434a4327 100644
--- a/relay/channel/gemini/relay-gemini-native.go
+++ b/relay/channel/gemini/relay-gemini-native.go
@@ -1,10 +1,12 @@
package gemini
import (
+ "fmt"
"io"
"net/http"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
@@ -35,22 +37,12 @@ func GeminiTextGenerationHandler(c *gin.Context, info *relaycommon.RelayInfo, re
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
}
+ if len(geminiResponse.Candidates) == 0 && geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
+ }
+
// 计算使用量(基于 UsageMetadata)
- usage := dto.Usage{
- PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
- CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount + geminiResponse.UsageMetadata.ThoughtsTokenCount,
- TotalTokens: geminiResponse.UsageMetadata.TotalTokenCount,
- }
-
- usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
-
- for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
- if detail.Modality == "AUDIO" {
- usage.PromptTokensDetails.AudioTokens = detail.TokenCount
- } else if detail.Modality == "TEXT" {
- usage.PromptTokensDetails.TextTokens = detail.TokenCount
- }
- }
+ usage := buildUsageFromGeminiMetadata(geminiResponse.UsageMetadata, info.GetEstimatePromptTokens())
service.IOCopyBytesGracefully(c, resp, responseBody)
diff --git a/relay/channel/gemini/relay-gemini.go b/relay/channel/gemini/relay-gemini.go
index 49c4da8d88..69175e76ef 100644
--- a/relay/channel/gemini/relay-gemini.go
+++ b/relay/channel/gemini/relay-gemini.go
@@ -24,6 +24,7 @@ import (
"github.com/QuantumNous/new-api/setting/reasoning"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
// https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference?hl=zh-cn#blob
@@ -36,6 +37,8 @@ var geminiSupportedMimeTypes = map[string]bool{
"image/jpeg": true,
"image/jpg": true, // support old image/jpeg
"image/webp": true,
+ "image/heic": true,
+ "image/heif": true,
"text/plain": true,
"video/mov": true,
"video/mpeg": true,
@@ -167,8 +170,8 @@ func ThinkingAdaptor(geminiRequest *dto.GeminiChatRequest, info *relaycommon.Rel
geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
IncludeThoughts: true,
}
- if geminiRequest.GenerationConfig.MaxOutputTokens > 0 {
- budgetTokens := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage * float64(geminiRequest.GenerationConfig.MaxOutputTokens)
+ if geminiRequest.GenerationConfig.MaxOutputTokens != nil && *geminiRequest.GenerationConfig.MaxOutputTokens > 0 {
+ budgetTokens := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage * float64(*geminiRequest.GenerationConfig.MaxOutputTokens)
clampedBudget := clampThinkingBudget(modelName, int(budgetTokens))
geminiRequest.GenerationConfig.ThinkingConfig.ThinkingBudget = common.GetPointer(clampedBudget)
} else {
@@ -200,13 +203,23 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
geminiRequest := dto.GeminiChatRequest{
Contents: make([]dto.GeminiChatContent, 0, len(textRequest.Messages)),
GenerationConfig: dto.GeminiChatGenerationConfig{
- Temperature: textRequest.Temperature,
- TopP: textRequest.TopP,
- MaxOutputTokens: textRequest.GetMaxTokens(),
- Seed: int64(textRequest.Seed),
+ Temperature: textRequest.Temperature,
},
}
+ if textRequest.TopP != nil && *textRequest.TopP > 0 {
+ geminiRequest.GenerationConfig.TopP = common.GetPointer(*textRequest.TopP)
+ }
+
+ if maxTokens := textRequest.GetMaxTokens(); maxTokens > 0 {
+ geminiRequest.GenerationConfig.MaxOutputTokens = common.GetPointer(maxTokens)
+ }
+
+ if textRequest.Seed != nil && *textRequest.Seed != 0 {
+ geminiSeed := int64(lo.FromPtr(textRequest.Seed))
+ geminiRequest.GenerationConfig.Seed = common.GetPointer(geminiSeed)
+ }
+
attachThoughtSignature := (info.ChannelType == constant.ChannelTypeGemini ||
info.ChannelType == constant.ChannelTypeVertexAi) &&
model_setting.GetGeminiSettings().FunctionCallThoughtSignatureEnabled
@@ -217,18 +230,26 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
"IMAGE",
}
}
+ if stopSequences := parseStopSequences(textRequest.Stop); len(stopSequences) > 0 {
+ // Gemini supports up to 5 stop sequences
+ if len(stopSequences) > 5 {
+ stopSequences = stopSequences[:5]
+ }
+ geminiRequest.GenerationConfig.StopSequences = stopSequences
+ }
adaptorWithExtraBody := false
// patch extra_body
if len(textRequest.ExtraBody) > 0 {
- if !strings.HasSuffix(info.UpstreamModelName, "-nothinking") {
- var extraBody map[string]interface{}
- if err := common.Unmarshal(textRequest.ExtraBody, &extraBody); err != nil {
- return nil, fmt.Errorf("invalid extra body: %w", err)
- }
- // eg. {"google":{"thinking_config":{"thinking_budget":5324,"include_thoughts":true}}}
- if googleBody, ok := extraBody["google"].(map[string]interface{}); ok {
+ var extraBody map[string]interface{}
+ if err := common.Unmarshal(textRequest.ExtraBody, &extraBody); err != nil {
+ return nil, fmt.Errorf("invalid extra body: %w", err)
+ }
+
+ // eg. {"google":{"thinking_config":{"thinking_budget":5324,"include_thoughts":true}}}
+ if googleBody, ok := extraBody["google"].(map[string]interface{}); ok {
+ if !strings.HasSuffix(info.UpstreamModelName, "-nothinking") {
adaptorWithExtraBody = true
// check error param name like thinkingConfig, should be thinking_config
if _, hasErrorParam := googleBody["thinkingConfig"]; hasErrorParam {
@@ -240,50 +261,92 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
if _, hasErrorParam := thinkingConfig["thinkingBudget"]; hasErrorParam {
return nil, errors.New("extra_body.google.thinking_config.thinkingBudget is not supported, use extra_body.google.thinking_config.thinking_budget instead")
}
- if budget, ok := thinkingConfig["thinking_budget"].(float64); ok {
- budgetInt := int(budget)
- geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
- ThinkingBudget: common.GetPointer(budgetInt),
- IncludeThoughts: true,
+ var hasThinkingConfig bool
+ var tempThinkingConfig dto.GeminiThinkingConfig
+
+ if thinkingBudget, exists := thinkingConfig["thinking_budget"]; exists {
+ switch v := thinkingBudget.(type) {
+ case float64:
+ budgetInt := int(v)
+ tempThinkingConfig.ThinkingBudget = common.GetPointer(budgetInt)
+ if budgetInt > 0 {
+ // 有正数预算
+ tempThinkingConfig.IncludeThoughts = true
+ } else {
+ // 存在但为0或负数,禁用思考
+ tempThinkingConfig.IncludeThoughts = false
+ }
+ hasThinkingConfig = true
+ default:
+ return nil, errors.New("extra_body.google.thinking_config.thinking_budget must be an integer")
}
- } else {
- geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
- IncludeThoughts: true,
+ }
+
+ if includeThoughts, exists := thinkingConfig["include_thoughts"]; exists {
+ if v, ok := includeThoughts.(bool); ok {
+ tempThinkingConfig.IncludeThoughts = v
+ hasThinkingConfig = true
+ } else {
+ return nil, errors.New("extra_body.google.thinking_config.include_thoughts must be a boolean")
+ }
+ }
+ if thinkingLevel, exists := thinkingConfig["thinking_level"]; exists {
+ if v, ok := thinkingLevel.(string); ok {
+ tempThinkingConfig.ThinkingLevel = v
+ hasThinkingConfig = true
+ } else {
+ return nil, errors.New("extra_body.google.thinking_config.thinking_level must be a string")
+ }
+ }
+
+ if hasThinkingConfig {
+ // 避免 panic: 仅在获得配置时分配,防止后续赋值时空指针
+ if geminiRequest.GenerationConfig.ThinkingConfig == nil {
+ geminiRequest.GenerationConfig.ThinkingConfig = &tempThinkingConfig
+ } else {
+ // 如果已分配,则合并内容
+ if tempThinkingConfig.ThinkingBudget != nil {
+ geminiRequest.GenerationConfig.ThinkingConfig.ThinkingBudget = tempThinkingConfig.ThinkingBudget
+ }
+ geminiRequest.GenerationConfig.ThinkingConfig.IncludeThoughts = tempThinkingConfig.IncludeThoughts
+ if tempThinkingConfig.ThinkingLevel != "" {
+ geminiRequest.GenerationConfig.ThinkingConfig.ThinkingLevel = tempThinkingConfig.ThinkingLevel
+ }
}
}
}
+ }
- // check error param name like imageConfig, should be image_config
- if _, hasErrorParam := googleBody["imageConfig"]; hasErrorParam {
- return nil, errors.New("extra_body.google.imageConfig is not supported, use extra_body.google.image_config instead")
+ // check error param name like imageConfig, should be image_config
+ if _, hasErrorParam := googleBody["imageConfig"]; hasErrorParam {
+ return nil, errors.New("extra_body.google.imageConfig is not supported, use extra_body.google.image_config instead")
+ }
+
+ if imageConfig, ok := googleBody["image_config"].(map[string]interface{}); ok {
+ // check error param name like aspectRatio, should be aspect_ratio
+ if _, hasErrorParam := imageConfig["aspectRatio"]; hasErrorParam {
+ return nil, errors.New("extra_body.google.image_config.aspectRatio is not supported, use extra_body.google.image_config.aspect_ratio instead")
+ }
+ // check error param name like imageSize, should be image_size
+ if _, hasErrorParam := imageConfig["imageSize"]; hasErrorParam {
+ return nil, errors.New("extra_body.google.image_config.imageSize is not supported, use extra_body.google.image_config.image_size instead")
}
- if imageConfig, ok := googleBody["image_config"].(map[string]interface{}); ok {
- // check error param name like aspectRatio, should be aspect_ratio
- if _, hasErrorParam := imageConfig["aspectRatio"]; hasErrorParam {
- return nil, errors.New("extra_body.google.image_config.aspectRatio is not supported, use extra_body.google.image_config.aspect_ratio instead")
- }
- // check error param name like imageSize, should be image_size
- if _, hasErrorParam := imageConfig["imageSize"]; hasErrorParam {
- return nil, errors.New("extra_body.google.image_config.imageSize is not supported, use extra_body.google.image_config.image_size instead")
- }
+ // convert snake_case to camelCase for Gemini API
+ geminiImageConfig := make(map[string]interface{})
+ if aspectRatio, ok := imageConfig["aspect_ratio"]; ok {
+ geminiImageConfig["aspectRatio"] = aspectRatio
+ }
+ if imageSize, ok := imageConfig["image_size"]; ok {
+ geminiImageConfig["imageSize"] = imageSize
+ }
- // convert snake_case to camelCase for Gemini API
- geminiImageConfig := make(map[string]interface{})
- if aspectRatio, ok := imageConfig["aspect_ratio"]; ok {
- geminiImageConfig["aspectRatio"] = aspectRatio
- }
- if imageSize, ok := imageConfig["image_size"]; ok {
- geminiImageConfig["imageSize"] = imageSize
- }
-
- if len(geminiImageConfig) > 0 {
- imageConfigBytes, err := common.Marshal(geminiImageConfig)
- if err != nil {
- return nil, fmt.Errorf("failed to marshal image_config: %w", err)
- }
- geminiRequest.GenerationConfig.ImageConfig = imageConfigBytes
+ if len(geminiImageConfig) > 0 {
+ imageConfigBytes, err := common.Marshal(geminiImageConfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal image_config: %w", err)
}
+ geminiRequest.GenerationConfig.ImageConfig = imageConfigBytes
}
}
}
@@ -359,6 +422,13 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
})
}
geminiRequest.SetTools(geminiTools)
+
+ // [NEW] Convert OpenAI tool_choice to Gemini toolConfig.functionCallingConfig
+ // Mapping: "auto" -> "AUTO", "none" -> "NONE", "required" -> "ANY"
+ // Object format: {"type": "function", "function": {"name": "xxx"}} -> "ANY" + allowedFunctionNames
+ if textRequest.ToolChoice != nil {
+ geminiRequest.ToolConfig = convertToolChoiceToGeminiConfig(textRequest.ToolChoice)
+ }
}
if textRequest.ResponseFormat != nil && (textRequest.ResponseFormat.Type == "json_schema" || textRequest.ResponseFormat.Type == "json_object") {
@@ -452,7 +522,6 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
}
openaiContent := message.ParseContent()
- imageNum := 0
for _, part := range openaiContent {
if part.Type == dto.ContentTypeText {
if part.Text == "" {
@@ -493,10 +562,6 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
}
// 提取 data URL (从 "](" 后面开始,到 ")" 之前)
dataUrl := text[bracketIdx+2 : closeIdx]
- imageNum += 1
- if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
- return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
- }
format, base64String, err := service.DecodeBase64FileData(dataUrl)
if err != nil {
return nil, fmt.Errorf("decode markdown base64 image data failed: %s", err.Error())
@@ -520,70 +585,25 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
Text: part.Text,
})
}
- } else if part.Type == dto.ContentTypeImageURL {
- imageNum += 1
-
- if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
- return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
+ } else {
+ source := part.ToFileSource()
+ if source == nil {
+ continue
}
- // 判断是否是url
- if strings.HasPrefix(part.GetImageMedia().Url, "http") {
- // 是url,获取文件的类型和base64编码的数据
- fileData, err := service.GetFileBase64FromUrl(c, part.GetImageMedia().Url, "formatting image for Gemini")
- if err != nil {
- return nil, fmt.Errorf("get file base64 from url '%s' failed: %w", part.GetImageMedia().Url, err)
- }
-
- // 校验 MimeType 是否在 Gemini 支持的白名单中
- if _, ok := geminiSupportedMimeTypes[strings.ToLower(fileData.MimeType)]; !ok {
- url := part.GetImageMedia().Url
- return nil, fmt.Errorf("mime type is not supported by Gemini: '%s', url: '%s', supported types are: %v", fileData.MimeType, url, getSupportedMimeTypesList())
- }
-
- parts = append(parts, dto.GeminiPart{
- InlineData: &dto.GeminiInlineData{
- MimeType: fileData.MimeType, // 使用原始的 MimeType,因为大小写可能对API有意义
- Data: fileData.Base64Data,
- },
- })
- } else {
- format, base64String, err := service.DecodeBase64FileData(part.GetImageMedia().Url)
- if err != nil {
- return nil, fmt.Errorf("decode base64 image data failed: %s", err.Error())
- }
- parts = append(parts, dto.GeminiPart{
- InlineData: &dto.GeminiInlineData{
- MimeType: format,
- Data: base64String,
- },
- })
- }
- } else if part.Type == dto.ContentTypeFile {
- if part.GetFile().FileId != "" {
- return nil, fmt.Errorf("only base64 file is supported in gemini")
- }
- format, base64String, err := service.DecodeBase64FileData(part.GetFile().FileData)
+ base64Data, mimeType, err := service.GetBase64Data(c, source, "formatting image for Gemini")
if err != nil {
- return nil, fmt.Errorf("decode base64 file data failed: %s", err.Error())
+ return nil, fmt.Errorf("get file data from '%s' failed: %w", source.GetIdentifier(), err)
}
+
+ // 校验 MimeType 是否在 Gemini 支持的白名单中
+ if _, ok := geminiSupportedMimeTypes[strings.ToLower(mimeType)]; !ok {
+ return nil, fmt.Errorf("mime type is not supported by Gemini: '%s', url: '%s', supported types are: %v", mimeType, source.GetIdentifier(), getSupportedMimeTypesList())
+ }
+
parts = append(parts, dto.GeminiPart{
InlineData: &dto.GeminiInlineData{
- MimeType: format,
- Data: base64String,
- },
- })
- } else if part.Type == dto.ContentTypeInputAudio {
- if part.GetInputAudio().Data == "" {
- return nil, fmt.Errorf("only base64 audio is supported in gemini")
- }
- base64String, err := service.DecodeBase64AudioData(part.GetInputAudio().Data)
- if err != nil {
- return nil, fmt.Errorf("decode base64 audio data failed: %s", err.Error())
- }
- parts = append(parts, dto.GeminiPart{
- InlineData: &dto.GeminiInlineData{
- MimeType: "audio/" + part.GetInputAudio().Format,
- Data: base64String,
+ MimeType: mimeType,
+ Data: base64Data,
},
})
}
@@ -624,6 +644,31 @@ func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, i
return &geminiRequest, nil
}
+// parseStopSequences 解析停止序列,支持字符串或字符串数组
+func parseStopSequences(stop any) []string {
+ if stop == nil {
+ return nil
+ }
+
+ switch v := stop.(type) {
+ case string:
+ if v != "" {
+ return []string{v}
+ }
+ case []string:
+ return v
+ case []interface{}:
+ sequences := make([]string, 0, len(v))
+ for _, item := range v {
+ if str, ok := item.(string); ok && str != "" {
+ sequences = append(sequences, str)
+ }
+ }
+ return sequences
+ }
+ return nil
+}
+
func hasFunctionCallContent(call *dto.FunctionCall) bool {
if call == nil {
return false
@@ -949,11 +994,9 @@ func unescapeMapOrSlice(data interface{}) interface{} {
func getResponseToolCall(item *dto.GeminiPart) *dto.ToolCallResponse {
var argsBytes []byte
var err error
- if result, ok := item.FunctionCall.Arguments.(map[string]interface{}); ok {
- argsBytes, err = json.Marshal(unescapeMapOrSlice(result))
- } else {
- argsBytes, err = json.Marshal(item.FunctionCall.Arguments)
- }
+ // 移除 unescapeMapOrSlice 调用,直接使用 json.Marshal
+ // JSON 序列化/反序列化已经正确处理了转义字符
+ argsBytes, err = json.Marshal(item.FunctionCall.Arguments)
if err != nil {
return nil
@@ -968,6 +1011,46 @@ func getResponseToolCall(item *dto.GeminiPart) *dto.ToolCallResponse {
}
}
+func buildUsageFromGeminiMetadata(metadata dto.GeminiUsageMetadata, fallbackPromptTokens int) dto.Usage {
+ promptTokens := metadata.PromptTokenCount + metadata.ToolUsePromptTokenCount
+ if promptTokens <= 0 && fallbackPromptTokens > 0 {
+ promptTokens = fallbackPromptTokens
+ }
+
+ usage := dto.Usage{
+ PromptTokens: promptTokens,
+ CompletionTokens: metadata.CandidatesTokenCount + metadata.ThoughtsTokenCount,
+ TotalTokens: metadata.TotalTokenCount,
+ }
+ usage.CompletionTokenDetails.ReasoningTokens = metadata.ThoughtsTokenCount
+ usage.PromptTokensDetails.CachedTokens = metadata.CachedContentTokenCount
+
+ for _, detail := range metadata.PromptTokensDetails {
+ if detail.Modality == "AUDIO" {
+ usage.PromptTokensDetails.AudioTokens += detail.TokenCount
+ } else if detail.Modality == "TEXT" {
+ usage.PromptTokensDetails.TextTokens += detail.TokenCount
+ }
+ }
+ for _, detail := range metadata.ToolUsePromptTokensDetails {
+ if detail.Modality == "AUDIO" {
+ usage.PromptTokensDetails.AudioTokens += detail.TokenCount
+ } else if detail.Modality == "TEXT" {
+ usage.PromptTokensDetails.TextTokens += detail.TokenCount
+ }
+ }
+
+ if usage.TotalTokens > 0 && usage.CompletionTokens <= 0 {
+ usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
+ }
+
+ if usage.PromptTokens > 0 && usage.PromptTokensDetails.TextTokens == 0 && usage.PromptTokensDetails.AudioTokens == 0 {
+ usage.PromptTokensDetails.TextTokens = usage.PromptTokens
+ }
+
+ return usage
+}
+
func responseGeminiChat2OpenAI(c *gin.Context, response *dto.GeminiChatResponse) *dto.OpenAITextResponse {
fullTextResponse := dto.OpenAITextResponse{
Id: helper.GetResponseID(c),
@@ -1031,6 +1114,24 @@ func responseGeminiChat2OpenAI(c *gin.Context, response *dto.GeminiChatResponse)
choice.FinishReason = constant.FinishReasonStop
case "MAX_TOKENS":
choice.FinishReason = constant.FinishReasonLength
+ case "SAFETY":
+ // Safety filter triggered
+ choice.FinishReason = constant.FinishReasonContentFilter
+ case "RECITATION":
+ // Recitation (citation) detected
+ choice.FinishReason = constant.FinishReasonContentFilter
+ case "BLOCKLIST":
+ // Blocklist triggered
+ choice.FinishReason = constant.FinishReasonContentFilter
+ case "PROHIBITED_CONTENT":
+ // Prohibited content detected
+ choice.FinishReason = constant.FinishReasonContentFilter
+ case "SPII":
+ // Sensitive personally identifiable information
+ choice.FinishReason = constant.FinishReasonContentFilter
+ case "OTHER":
+ // Other reasons
+ choice.FinishReason = constant.FinishReasonContentFilter
default:
choice.FinishReason = constant.FinishReasonContentFilter
}
@@ -1062,13 +1163,34 @@ func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*d
isTools := false
isThought := false
if candidate.FinishReason != nil {
- // p := GeminiConvertFinishReason(*candidate.FinishReason)
+ // Map Gemini FinishReason to OpenAI finish_reason
switch *candidate.FinishReason {
case "STOP":
+ // Normal completion
choice.FinishReason = &constant.FinishReasonStop
case "MAX_TOKENS":
+ // Reached maximum token limit
choice.FinishReason = &constant.FinishReasonLength
+ case "SAFETY":
+ // Safety filter triggered
+ choice.FinishReason = &constant.FinishReasonContentFilter
+ case "RECITATION":
+ // Recitation (citation) detected
+ choice.FinishReason = &constant.FinishReasonContentFilter
+ case "BLOCKLIST":
+ // Blocklist triggered
+ choice.FinishReason = &constant.FinishReasonContentFilter
+ case "PROHIBITED_CONTENT":
+ // Prohibited content detected
+ choice.FinishReason = &constant.FinishReasonContentFilter
+ case "SPII":
+ // Sensitive personally identifiable information
+ choice.FinishReason = &constant.FinishReasonContentFilter
+ case "OTHER":
+ // Other reasons
+ choice.FinishReason = &constant.FinishReasonContentFilter
default:
+ // Unknown reason, treat as content filter
choice.FinishReason = &constant.FinishReasonContentFilter
}
}
@@ -1143,12 +1265,15 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
var imageCount int
responseText := strings.Builder{}
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
var geminiResponse dto.GeminiChatResponse
- err := common.UnmarshalJsonStr(data, &geminiResponse)
- if err != nil {
- logger.LogError(c, "error unmarshalling stream response: "+err.Error())
- return false
+ if err := common.UnmarshalJsonStr(data, &geminiResponse); err != nil {
+ sr.Stop(fmt.Errorf("unmarshal: %w", err))
+ return
+ }
+
+ if len(geminiResponse.Candidates) == 0 && geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
}
// 统计图片数量
@@ -1165,20 +1290,13 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
// 更新使用量统计
if geminiResponse.UsageMetadata.TotalTokenCount != 0 {
- usage.PromptTokens = geminiResponse.UsageMetadata.PromptTokenCount
- usage.CompletionTokens = geminiResponse.UsageMetadata.CandidatesTokenCount + geminiResponse.UsageMetadata.ThoughtsTokenCount
- usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
- usage.TotalTokens = geminiResponse.UsageMetadata.TotalTokenCount
- for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
- if detail.Modality == "AUDIO" {
- usage.PromptTokensDetails.AudioTokens = detail.TokenCount
- } else if detail.Modality == "TEXT" {
- usage.PromptTokensDetails.TextTokens = detail.TokenCount
- }
- }
+ mappedUsage := buildUsageFromGeminiMetadata(geminiResponse.UsageMetadata, info.GetEstimatePromptTokens())
+ *usage = mappedUsage
}
- return callback(data, &geminiResponse)
+ if !callback(data, &geminiResponse) {
+ sr.Stop(fmt.Errorf("gemini callback stopped"))
+ }
})
if imageCount != 0 {
@@ -1187,14 +1305,8 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
}
}
- usage.PromptTokensDetails.TextTokens = usage.PromptTokens
- if usage.TotalTokens > 0 {
- usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
- }
-
if usage.CompletionTokens <= 0 {
- str := responseText.String()
- if len(str) > 0 {
+ if info.ReceivedResponseCount > 0 {
usage = service.ResponseText2Usage(c, responseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
} else {
usage = &dto.Usage{}
@@ -1309,31 +1421,43 @@ func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.R
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
}
if len(geminiResponse.Candidates) == 0 {
- //return nil, types.NewOpenAIError(errors.New("no candidates returned"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
- //if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
- // return nil, types.NewOpenAIError(errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason), types.ErrorCodePromptBlocked, http.StatusBadRequest)
- //} else {
- // return nil, types.NewOpenAIError(errors.New("empty response from Gemini API"), types.ErrorCodeEmptyResponse, http.StatusInternalServerError)
- //}
+ usage := buildUsageFromGeminiMetadata(geminiResponse.UsageMetadata, info.GetEstimatePromptTokens())
+
+ var newAPIError *types.NewAPIError
+ if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
+ newAPIError = types.NewOpenAIError(
+ errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason),
+ types.ErrorCodePromptBlocked,
+ http.StatusBadRequest,
+ )
+ } else {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "gemini_empty_candidates")
+ newAPIError = types.NewOpenAIError(
+ errors.New("empty response from Gemini API"),
+ types.ErrorCodeEmptyResponse,
+ http.StatusInternalServerError,
+ )
+ }
+
+ service.ResetStatusCode(newAPIError, c.GetString("status_code_mapping"))
+
+ switch info.RelayFormat {
+ case types.RelayFormatClaude:
+ c.JSON(newAPIError.StatusCode, gin.H{
+ "type": "error",
+ "error": newAPIError.ToClaudeError(),
+ })
+ default:
+ c.JSON(newAPIError.StatusCode, gin.H{
+ "error": newAPIError.ToOpenAIError(),
+ })
+ }
+ return &usage, nil
}
fullTextResponse := responseGeminiChat2OpenAI(c, &geminiResponse)
fullTextResponse.Model = info.UpstreamModelName
- usage := dto.Usage{
- PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
- CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount,
- TotalTokens: geminiResponse.UsageMetadata.TotalTokenCount,
- }
-
- usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
- usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
-
- for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
- if detail.Modality == "AUDIO" {
- usage.PromptTokensDetails.AudioTokens = detail.TokenCount
- } else if detail.Modality == "TEXT" {
- usage.PromptTokensDetails.TextTokens = detail.TokenCount
- }
- }
+ usage := buildUsageFromGeminiMetadata(geminiResponse.UsageMetadata, info.GetEstimatePromptTokens())
fullTextResponse.Usage = usage
@@ -1530,3 +1654,62 @@ func FetchGeminiModels(baseURL, apiKey, proxyURL string) ([]string, error) {
return allModels, nil
}
+
+// convertToolChoiceToGeminiConfig converts OpenAI tool_choice to Gemini toolConfig
+// OpenAI tool_choice values:
+// - "auto": Let the model decide (default)
+// - "none": Don't call any tools
+// - "required": Must call at least one tool
+// - {"type": "function", "function": {"name": "xxx"}}: Call specific function
+//
+// Gemini functionCallingConfig.mode values:
+// - "AUTO": Model decides whether to call functions
+// - "NONE": Model won't call functions
+// - "ANY": Model must call at least one function
+func convertToolChoiceToGeminiConfig(toolChoice any) *dto.ToolConfig {
+ if toolChoice == nil {
+ return nil
+ }
+
+ // Handle string values: "auto", "none", "required"
+ if toolChoiceStr, ok := toolChoice.(string); ok {
+ config := &dto.ToolConfig{
+ FunctionCallingConfig: &dto.FunctionCallingConfig{},
+ }
+ switch toolChoiceStr {
+ case "auto":
+ config.FunctionCallingConfig.Mode = "AUTO"
+ case "none":
+ config.FunctionCallingConfig.Mode = "NONE"
+ case "required":
+ config.FunctionCallingConfig.Mode = "ANY"
+ default:
+ // Unknown string value, default to AUTO
+ config.FunctionCallingConfig.Mode = "AUTO"
+ }
+ return config
+ }
+
+ // Handle object value: {"type": "function", "function": {"name": "xxx"}}
+ if toolChoiceMap, ok := toolChoice.(map[string]interface{}); ok {
+ if toolChoiceMap["type"] == "function" {
+ config := &dto.ToolConfig{
+ FunctionCallingConfig: &dto.FunctionCallingConfig{
+ Mode: "ANY",
+ },
+ }
+ // Extract function name if specified
+ if function, ok := toolChoiceMap["function"].(map[string]interface{}); ok {
+ if name, ok := function["name"].(string); ok && name != "" {
+ config.FunctionCallingConfig.AllowedFunctionNames = []string{name}
+ }
+ }
+ return config
+ }
+ // Unsupported map structure (type is not "function"), return nil
+ return nil
+ }
+
+ // Unsupported type, return nil
+ return nil
+}
diff --git a/relay/channel/gemini/relay_gemini_usage_test.go b/relay/channel/gemini/relay_gemini_usage_test.go
new file mode 100644
index 0000000000..c8f9f83430
--- /dev/null
+++ b/relay/channel/gemini/relay_gemini_usage_test.go
@@ -0,0 +1,333 @@
+package gemini
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGeminiChatHandlerCompletionTokensExcludeToolUsePromptTokens(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ info := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatGemini,
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+
+ payload := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "ok"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 151,
+ ToolUsePromptTokenCount: 18329,
+ CandidatesTokenCount: 1089,
+ ThoughtsTokenCount: 1120,
+ TotalTokenCount: 20689,
+ },
+ }
+
+ body, err := common.Marshal(payload)
+ require.NoError(t, err)
+
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }
+
+ usage, newAPIError := GeminiChatHandler(c, info, resp)
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 18480, usage.PromptTokens)
+ require.Equal(t, 2209, usage.CompletionTokens)
+ require.Equal(t, 20689, usage.TotalTokens)
+ require.Equal(t, 1120, usage.CompletionTokenDetails.ReasoningTokens)
+}
+
+func TestGeminiStreamHandlerCompletionTokensExcludeToolUsePromptTokens(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldStreamingTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 300
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldStreamingTimeout
+ })
+
+ info := &relaycommon.RelayInfo{
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+
+ chunk := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "partial"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 151,
+ ToolUsePromptTokenCount: 18329,
+ CandidatesTokenCount: 1089,
+ ThoughtsTokenCount: 1120,
+ TotalTokenCount: 20689,
+ },
+ }
+
+ chunkData, err := common.Marshal(chunk)
+ require.NoError(t, err)
+
+ streamBody := []byte("data: " + string(chunkData) + "\n" + "data: [DONE]\n")
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(streamBody)),
+ }
+
+ usage, newAPIError := geminiStreamHandler(c, info, resp, func(_ string, _ *dto.GeminiChatResponse) bool {
+ return true
+ })
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 18480, usage.PromptTokens)
+ require.Equal(t, 2209, usage.CompletionTokens)
+ require.Equal(t, 20689, usage.TotalTokens)
+ require.Equal(t, 1120, usage.CompletionTokenDetails.ReasoningTokens)
+}
+
+func TestGeminiTextGenerationHandlerPromptTokensIncludeToolUsePromptTokens(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-3-flash-preview:generateContent", nil)
+
+ info := &relaycommon.RelayInfo{
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+
+ payload := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "ok"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 151,
+ ToolUsePromptTokenCount: 18329,
+ CandidatesTokenCount: 1089,
+ ThoughtsTokenCount: 1120,
+ TotalTokenCount: 20689,
+ },
+ }
+
+ body, err := common.Marshal(payload)
+ require.NoError(t, err)
+
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }
+
+ usage, newAPIError := GeminiTextGenerationHandler(c, info, resp)
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 18480, usage.PromptTokens)
+ require.Equal(t, 2209, usage.CompletionTokens)
+ require.Equal(t, 20689, usage.TotalTokens)
+ require.Equal(t, 1120, usage.CompletionTokenDetails.ReasoningTokens)
+}
+
+func TestGeminiChatHandlerUsesEstimatedPromptTokensWhenUsagePromptMissing(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ info := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatGemini,
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+ info.SetEstimatePromptTokens(20)
+
+ payload := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "ok"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 0,
+ ToolUsePromptTokenCount: 0,
+ CandidatesTokenCount: 90,
+ ThoughtsTokenCount: 10,
+ TotalTokenCount: 110,
+ },
+ }
+
+ body, err := common.Marshal(payload)
+ require.NoError(t, err)
+
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }
+
+ usage, newAPIError := GeminiChatHandler(c, info, resp)
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 20, usage.PromptTokens)
+ require.Equal(t, 100, usage.CompletionTokens)
+ require.Equal(t, 110, usage.TotalTokens)
+}
+
+func TestGeminiStreamHandlerUsesEstimatedPromptTokensWhenUsagePromptMissing(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldStreamingTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 300
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldStreamingTimeout
+ })
+
+ info := &relaycommon.RelayInfo{
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+ info.SetEstimatePromptTokens(20)
+
+ chunk := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "partial"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 0,
+ ToolUsePromptTokenCount: 0,
+ CandidatesTokenCount: 90,
+ ThoughtsTokenCount: 10,
+ TotalTokenCount: 110,
+ },
+ }
+
+ chunkData, err := common.Marshal(chunk)
+ require.NoError(t, err)
+
+ streamBody := []byte("data: " + string(chunkData) + "\n" + "data: [DONE]\n")
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(streamBody)),
+ }
+
+ usage, newAPIError := geminiStreamHandler(c, info, resp, func(_ string, _ *dto.GeminiChatResponse) bool {
+ return true
+ })
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 20, usage.PromptTokens)
+ require.Equal(t, 100, usage.CompletionTokens)
+ require.Equal(t, 110, usage.TotalTokens)
+}
+
+func TestGeminiTextGenerationHandlerUsesEstimatedPromptTokensWhenUsagePromptMissing(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-3-flash-preview:generateContent", nil)
+
+ info := &relaycommon.RelayInfo{
+ OriginModelName: "gemini-3-flash-preview",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ UpstreamModelName: "gemini-3-flash-preview",
+ },
+ }
+ info.SetEstimatePromptTokens(20)
+
+ payload := dto.GeminiChatResponse{
+ Candidates: []dto.GeminiChatCandidate{
+ {
+ Content: dto.GeminiChatContent{
+ Role: "model",
+ Parts: []dto.GeminiPart{
+ {Text: "ok"},
+ },
+ },
+ },
+ },
+ UsageMetadata: dto.GeminiUsageMetadata{
+ PromptTokenCount: 0,
+ ToolUsePromptTokenCount: 0,
+ CandidatesTokenCount: 90,
+ ThoughtsTokenCount: 10,
+ TotalTokenCount: 110,
+ },
+ }
+
+ body, err := common.Marshal(payload)
+ require.NoError(t, err)
+
+ resp := &http.Response{
+ Body: io.NopCloser(bytes.NewReader(body)),
+ }
+
+ usage, newAPIError := GeminiTextGenerationHandler(c, info, resp)
+ require.Nil(t, newAPIError)
+ require.NotNil(t, usage)
+ require.Equal(t, 20, usage.PromptTokens)
+ require.Equal(t, 100, usage.CompletionTokens)
+ require.Equal(t, 110, usage.TotalTokens)
+}
diff --git a/relay/channel/minimax/adaptor.go b/relay/channel/minimax/adaptor.go
index 8235abc053..56d3a1ec7d 100644
--- a/relay/channel/minimax/adaptor.go
+++ b/relay/channel/minimax/adaptor.go
@@ -10,12 +10,14 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ "github.com/QuantumNous/new-api/relay/channel/claude"
"github.com/QuantumNous/new-api/relay/channel/openai"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
type Adaptor struct {
@@ -26,7 +28,8 @@ func (a *Adaptor) ConvertGeminiRequest(*gin.Context, *relaycommon.RelayInfo, *dt
}
func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, req *dto.ClaudeRequest) (any, error) {
- return nil, errors.New("not implemented")
+ adaptor := claude.Adaptor{}
+ return adaptor.ConvertClaudeRequest(c, info, req)
}
func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
@@ -35,7 +38,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
}
voiceID := request.Voice
- speed := request.Speed
+ speed := lo.FromPtrOr(request.Speed, 0.0)
outputFormat := request.ResponseFormat
minimaxRequest := MiniMaxTTSRequest{
@@ -75,7 +78,10 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
}
func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
- return request, nil
+ if info.RelayMode != constant.RelayModeImagesGenerations {
+ return nil, fmt.Errorf("unsupported image relay mode: %d", info.RelayMode)
+ }
+ return oaiImage2MiniMaxImageRequest(request), nil
}
func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
@@ -118,9 +124,18 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
if info.RelayMode == constant.RelayModeAudioSpeech {
return handleTTSResponse(c, resp, info)
}
+ if info.RelayMode == constant.RelayModeImagesGenerations {
+ return miniMaxImageHandler(c, resp, info)
+ }
- adaptor := openai.Adaptor{}
- return adaptor.DoResponse(c, resp, info)
+ switch info.RelayFormat {
+ case types.RelayFormatClaude:
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
+ default:
+ adaptor := openai.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
+ }
}
func (a *Adaptor) GetModelList() []string {
diff --git a/relay/channel/minimax/adaptor_test.go b/relay/channel/minimax/adaptor_test.go
new file mode 100644
index 0000000000..46d57c11ff
--- /dev/null
+++ b/relay/channel/minimax/adaptor_test.go
@@ -0,0 +1,137 @@
+package minimax
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/dto"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ relayconstant "github.com/QuantumNous/new-api/relay/constant"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestGetRequestURLForImageGeneration(t *testing.T) {
+ t.Parallel()
+
+ info := &relaycommon.RelayInfo{
+ RelayMode: relayconstant.RelayModeImagesGenerations,
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ChannelBaseUrl: "https://api.minimax.chat",
+ },
+ }
+
+ got, err := GetRequestURL(info)
+ if err != nil {
+ t.Fatalf("GetRequestURL returned error: %v", err)
+ }
+
+ want := "https://api.minimax.chat/v1/image_generation"
+ if got != want {
+ t.Fatalf("GetRequestURL() = %q, want %q", got, want)
+ }
+}
+
+func TestConvertImageRequest(t *testing.T) {
+ t.Parallel()
+
+ adaptor := &Adaptor{}
+ info := &relaycommon.RelayInfo{
+ RelayMode: relayconstant.RelayModeImagesGenerations,
+ OriginModelName: "image-01",
+ }
+ request := dto.ImageRequest{
+ Model: "image-01",
+ Prompt: "a red fox in snowfall",
+ Size: "1536x1024",
+ ResponseFormat: "url",
+ N: uintPtr(2),
+ }
+
+ got, err := adaptor.ConvertImageRequest(gin.CreateTestContextOnly(httptest.NewRecorder(), gin.New()), info, request)
+ if err != nil {
+ t.Fatalf("ConvertImageRequest returned error: %v", err)
+ }
+
+ body, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("json.Marshal returned error: %v", err)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(body, &payload); err != nil {
+ t.Fatalf("json.Unmarshal returned error: %v", err)
+ }
+
+ if payload["model"] != "image-01" {
+ t.Fatalf("model = %#v, want %q", payload["model"], "image-01")
+ }
+ if payload["prompt"] != request.Prompt {
+ t.Fatalf("prompt = %#v, want %q", payload["prompt"], request.Prompt)
+ }
+ if payload["n"] != float64(2) {
+ t.Fatalf("n = %#v, want 2", payload["n"])
+ }
+ if payload["aspect_ratio"] != "3:2" {
+ t.Fatalf("aspect_ratio = %#v, want %q", payload["aspect_ratio"], "3:2")
+ }
+ if payload["response_format"] != "url" {
+ t.Fatalf("response_format = %#v, want %q", payload["response_format"], "url")
+ }
+}
+
+func TestDoResponseForImageGeneration(t *testing.T) {
+ t.Parallel()
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+
+ info := &relaycommon.RelayInfo{
+ RelayMode: relayconstant.RelayModeImagesGenerations,
+ StartTime: time.Unix(1700000000, 0),
+ }
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: httptest.NewRecorder().Result().Body,
+ }
+ resp.Body = ioNopCloser(`{"data":{"image_urls":["https://example.com/minimax.png"]}}`)
+
+ adaptor := &Adaptor{}
+ usage, err := adaptor.DoResponse(c, resp, info)
+ if err != nil {
+ t.Fatalf("DoResponse returned error: %v", err)
+ }
+ if usage == nil {
+ t.Fatalf("DoResponse returned nil usage")
+ }
+
+ body := recorder.Body.String()
+ if !strings.Contains(body, `"url":"https://example.com/minimax.png"`) {
+ t.Fatalf("response body = %s, want OpenAI image response with image URL", body)
+ }
+ if strings.Contains(body, `"image_urls"`) {
+ t.Fatalf("response body = %s, should not expose raw MiniMax image_urls payload", body)
+ }
+}
+
+type nopReadCloser struct {
+ *strings.Reader
+}
+
+func (n nopReadCloser) Close() error {
+ return nil
+}
+
+func ioNopCloser(body string) nopReadCloser {
+ return nopReadCloser{Reader: strings.NewReader(body)}
+}
+
+func uintPtr(v uint) *uint {
+ return &v
+}
diff --git a/relay/channel/minimax/constants.go b/relay/channel/minimax/constants.go
index 91193c4bac..efdab04c34 100644
--- a/relay/channel/minimax/constants.go
+++ b/relay/channel/minimax/constants.go
@@ -8,6 +8,8 @@ var ModelList = []string{
"abab6-chat",
"abab5.5-chat",
"abab5.5s-chat",
+ "MiniMax-M2.7",
+ "MiniMax-M2.7-highspeed",
"speech-2.5-hd-preview",
"speech-2.5-turbo-preview",
"speech-02-hd",
@@ -15,8 +17,12 @@ var ModelList = []string{
"speech-01-hd",
"speech-01-turbo",
"MiniMax-M2.1",
- "MiniMax-M2.1-lightning",
+ "MiniMax-M2.1-highspeed",
"MiniMax-M2",
+ "MiniMax-M2.5",
+ "MiniMax-M2.5-highspeed",
+ "image-01",
+ "image-01-live",
}
var ChannelName = "minimax"
diff --git a/relay/channel/minimax/image.go b/relay/channel/minimax/image.go
new file mode 100644
index 0000000000..9b316bdc82
--- /dev/null
+++ b/relay/channel/minimax/image.go
@@ -0,0 +1,213 @@
+package minimax
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/dto"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+)
+
+type MiniMaxImageRequest struct {
+ Model string `json:"model"`
+ Prompt string `json:"prompt"`
+ AspectRatio string `json:"aspect_ratio,omitempty"`
+ ResponseFormat string `json:"response_format,omitempty"`
+ N int `json:"n,omitempty"`
+ PromptOptimizer *bool `json:"prompt_optimizer,omitempty"`
+ AigcWatermark *bool `json:"aigc_watermark,omitempty"`
+}
+
+type MiniMaxImageResponse struct {
+ ID string `json:"id"`
+ Data struct {
+ ImageURLs []string `json:"image_urls"`
+ ImageBase64 []string `json:"image_base64"`
+ } `json:"data"`
+ Metadata map[string]any `json:"metadata"`
+ BaseResp struct {
+ StatusCode int `json:"status_code"`
+ StatusMsg string `json:"status_msg"`
+ } `json:"base_resp"`
+}
+
+func oaiImage2MiniMaxImageRequest(request dto.ImageRequest) MiniMaxImageRequest {
+ responseFormat := normalizeMiniMaxResponseFormat(request.ResponseFormat)
+ minimaxRequest := MiniMaxImageRequest{
+ Model: request.Model,
+ Prompt: request.Prompt,
+ ResponseFormat: responseFormat,
+ N: 1,
+ AigcWatermark: request.Watermark,
+ }
+
+ if request.Model == "" {
+ minimaxRequest.Model = "image-01"
+ }
+ if request.N != nil && *request.N > 0 {
+ minimaxRequest.N = int(*request.N)
+ }
+ if aspectRatio := aspectRatioFromImageRequest(request); aspectRatio != "" {
+ minimaxRequest.AspectRatio = aspectRatio
+ }
+ if raw, ok := request.Extra["prompt_optimizer"]; ok {
+ var promptOptimizer bool
+ if err := common.Unmarshal(raw, &promptOptimizer); err == nil {
+ minimaxRequest.PromptOptimizer = &promptOptimizer
+ }
+ }
+
+ return minimaxRequest
+}
+
+func aspectRatioFromImageRequest(request dto.ImageRequest) string {
+ if raw, ok := request.Extra["aspect_ratio"]; ok {
+ var aspectRatio string
+ if err := common.Unmarshal(raw, &aspectRatio); err == nil && aspectRatio != "" {
+ return aspectRatio
+ }
+ }
+
+ switch request.Size {
+ case "1024x1024":
+ return "1:1"
+ case "1792x1024":
+ return "16:9"
+ case "1024x1792":
+ return "9:16"
+ case "1536x1024", "1248x832":
+ return "3:2"
+ case "1024x1536", "832x1248":
+ return "2:3"
+ case "1152x864":
+ return "4:3"
+ case "864x1152":
+ return "3:4"
+ case "1344x576":
+ return "21:9"
+ }
+
+ width, height, ok := parseImageSize(request.Size)
+ if !ok {
+ return ""
+ }
+ ratio := reduceAspectRatio(width, height)
+ switch ratio {
+ case "1:1", "16:9", "4:3", "3:2", "2:3", "3:4", "9:16", "21:9":
+ return ratio
+ default:
+ return ""
+ }
+}
+
+func parseImageSize(size string) (int, int, bool) {
+ parts := strings.Split(size, "x")
+ if len(parts) != 2 {
+ return 0, 0, false
+ }
+ width, err := strconv.Atoi(parts[0])
+ if err != nil {
+ return 0, 0, false
+ }
+ height, err := strconv.Atoi(parts[1])
+ if err != nil {
+ return 0, 0, false
+ }
+ if width <= 0 || height <= 0 {
+ return 0, 0, false
+ }
+ return width, height, true
+}
+
+func reduceAspectRatio(width, height int) string {
+ divisor := gcd(width, height)
+ return fmt.Sprintf("%d:%d", width/divisor, height/divisor)
+}
+
+func gcd(a, b int) int {
+ for b != 0 {
+ a, b = b, a%b
+ }
+ if a == 0 {
+ return 1
+ }
+ return a
+}
+
+func normalizeMiniMaxResponseFormat(responseFormat string) string {
+ switch strings.ToLower(responseFormat) {
+ case "", "url":
+ return "url"
+ case "b64_json", "base64":
+ return "base64"
+ default:
+ return responseFormat
+ }
+}
+
+func responseMiniMax2OpenAIImage(response *MiniMaxImageResponse, info *relaycommon.RelayInfo) (*dto.ImageResponse, error) {
+ imageResponse := &dto.ImageResponse{
+ Created: info.StartTime.Unix(),
+ }
+
+ for _, imageURL := range response.Data.ImageURLs {
+ imageResponse.Data = append(imageResponse.Data, dto.ImageData{Url: imageURL})
+ }
+ for _, imageBase64 := range response.Data.ImageBase64 {
+ imageResponse.Data = append(imageResponse.Data, dto.ImageData{B64Json: imageBase64})
+ }
+ if len(response.Metadata) > 0 {
+ metadata, err := common.Marshal(response.Metadata)
+ if err != nil {
+ return nil, err
+ }
+ imageResponse.Metadata = metadata
+ }
+
+ return imageResponse, nil
+}
+
+func miniMaxImageHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
+ }
+ service.CloseResponseBodyGracefully(resp)
+
+ var minimaxResponse MiniMaxImageResponse
+ if err := common.Unmarshal(responseBody, &minimaxResponse); err != nil {
+ return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
+ }
+ if minimaxResponse.BaseResp.StatusCode != 0 {
+ return nil, types.WithOpenAIError(types.OpenAIError{
+ Message: minimaxResponse.BaseResp.StatusMsg,
+ Type: "minimax_image_error",
+ Code: fmt.Sprintf("%d", minimaxResponse.BaseResp.StatusCode),
+ }, resp.StatusCode)
+ }
+
+ openAIResponse, err := responseMiniMax2OpenAIImage(&minimaxResponse, info)
+ if err != nil {
+ return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
+ }
+ jsonResponse, err := common.Marshal(openAIResponse)
+ if err != nil {
+ return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
+ }
+
+ c.Writer.Header().Set("Content-Type", "application/json")
+ c.Writer.WriteHeader(resp.StatusCode)
+ if _, err := c.Writer.Write(jsonResponse); err != nil {
+ return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
+ }
+
+ return &dto.Usage{}, nil
+}
diff --git a/relay/channel/minimax/relay-minimax.go b/relay/channel/minimax/relay-minimax.go
index b314e69d7b..a1a05150c0 100644
--- a/relay/channel/minimax/relay-minimax.go
+++ b/relay/channel/minimax/relay-minimax.go
@@ -6,6 +6,7 @@ import (
channelconstant "github.com/QuantumNous/new-api/constant"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/constant"
+ "github.com/QuantumNous/new-api/types"
)
func GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
@@ -13,13 +14,19 @@ func GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
if baseUrl == "" {
baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeMiniMax]
}
-
- switch info.RelayMode {
- case constant.RelayModeChatCompletions:
- return fmt.Sprintf("%s/v1/text/chatcompletion_v2", baseUrl), nil
- case constant.RelayModeAudioSpeech:
- return fmt.Sprintf("%s/v1/t2a_v2", baseUrl), nil
+ switch info.RelayFormat {
+ case types.RelayFormatClaude:
+ return fmt.Sprintf("%s/anthropic/v1/messages", info.ChannelBaseUrl), nil
default:
- return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
+ switch info.RelayMode {
+ case constant.RelayModeChatCompletions:
+ return fmt.Sprintf("%s/v1/text/chatcompletion_v2", baseUrl), nil
+ case constant.RelayModeImagesGenerations:
+ return fmt.Sprintf("%s/v1/image_generation", baseUrl), nil
+ case constant.RelayModeAudioSpeech:
+ return fmt.Sprintf("%s/v1/t2a_v2", baseUrl), nil
+ default:
+ return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
+ }
}
}
diff --git a/relay/channel/mistral/text.go b/relay/channel/mistral/text.go
index a6d48f68bb..d43bc36beb 100644
--- a/relay/channel/mistral/text.go
+++ b/relay/channel/mistral/text.go
@@ -66,14 +66,18 @@ func requestOpenAI2Mistral(request *dto.GeneralOpenAIRequest) *dto.GeneralOpenAI
ToolCallId: message.ToolCallId,
})
}
- return &dto.GeneralOpenAIRequest{
+ out := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: request.Stream,
Messages: messages,
Temperature: request.Temperature,
TopP: request.TopP,
- MaxTokens: request.GetMaxTokens(),
Tools: request.Tools,
ToolChoice: request.ToolChoice,
}
+ if request.MaxTokens != nil || request.MaxCompletionTokens != nil {
+ maxTokens := request.GetMaxTokens()
+ out.MaxTokens = &maxTokens
+ }
+ return out
}
diff --git a/relay/channel/moonshot/adaptor.go b/relay/channel/moonshot/adaptor.go
index 6591ee7506..c2f6ee4a4b 100644
--- a/relay/channel/moonshot/adaptor.go
+++ b/relay/channel/moonshot/adaptor.go
@@ -102,11 +102,8 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
switch info.RelayFormat {
case types.RelayFormatClaude:
- if info.IsStream {
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
- } else {
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
- }
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
default:
adaptor := openai.Adaptor{}
return adaptor.DoResponse(c, resp, info)
diff --git a/relay/channel/moonshot/constants.go b/relay/channel/moonshot/constants.go
index a7da54b33c..b9d970d2d6 100644
--- a/relay/channel/moonshot/constants.go
+++ b/relay/channel/moonshot/constants.go
@@ -1,9 +1,11 @@
package moonshot
var ModelList = []string{
- "moonshot-v1-8k",
- "moonshot-v1-32k",
- "moonshot-v1-128k",
+ "kimi-k2.5",
+ "kimi-k2-0905-preview",
+ "kimi-k2-turbo-preview",
+ "kimi-k2-thinking",
+ "kimi-k2-thinking-turbo",
}
var ChannelName = "moonshot"
diff --git a/relay/channel/ollama/relay-ollama.go b/relay/channel/ollama/relay-ollama.go
index 795e9c9754..975c244c35 100644
--- a/relay/channel/ollama/relay-ollama.go
+++ b/relay/channel/ollama/relay-ollama.go
@@ -16,12 +16,13 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*OllamaChatRequest, error) {
chatReq := &OllamaChatRequest{
Model: r.Model,
- Stream: r.Stream,
+ Stream: lo.FromPtrOr(r.Stream, false),
Options: map[string]any{},
Think: r.Think,
}
@@ -41,20 +42,20 @@ func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*Ollam
if r.Temperature != nil {
chatReq.Options["temperature"] = r.Temperature
}
- if r.TopP != 0 {
- chatReq.Options["top_p"] = r.TopP
+ if r.TopP != nil {
+ chatReq.Options["top_p"] = lo.FromPtr(r.TopP)
}
- if r.TopK != 0 {
- chatReq.Options["top_k"] = r.TopK
+ if r.TopK != nil {
+ chatReq.Options["top_k"] = lo.FromPtr(r.TopK)
}
- if r.FrequencyPenalty != 0 {
- chatReq.Options["frequency_penalty"] = r.FrequencyPenalty
+ if r.FrequencyPenalty != nil {
+ chatReq.Options["frequency_penalty"] = lo.FromPtr(r.FrequencyPenalty)
}
- if r.PresencePenalty != 0 {
- chatReq.Options["presence_penalty"] = r.PresencePenalty
+ if r.PresencePenalty != nil {
+ chatReq.Options["presence_penalty"] = lo.FromPtr(r.PresencePenalty)
}
- if r.Seed != 0 {
- chatReq.Options["seed"] = int(r.Seed)
+ if r.Seed != nil {
+ chatReq.Options["seed"] = int(lo.FromPtr(r.Seed))
}
if mt := r.GetMaxTokens(); mt != 0 {
chatReq.Options["num_predict"] = int(mt)
@@ -97,21 +98,11 @@ func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*Ollam
parts := m.ParseContent()
for _, part := range parts {
if part.Type == dto.ContentTypeImageURL {
- img := part.GetImageMedia()
- if img != nil && img.Url != "" {
- var base64Data string
- if strings.HasPrefix(img.Url, "http") {
- fileData, err := service.GetFileBase64FromUrl(c, img.Url, "fetch image for ollama chat")
- if err != nil {
- return nil, err
- }
- base64Data = fileData.Base64Data
- } else if strings.HasPrefix(img.Url, "data:") {
- if idx := strings.Index(img.Url, ","); idx != -1 && idx+1 < len(img.Url) {
- base64Data = img.Url[idx+1:]
- }
- } else {
- base64Data = img.Url
+ source := part.ToFileSource()
+ if source != nil {
+ base64Data, _, err := service.GetBase64Data(c, source, "fetch image for ollama chat")
+ if err != nil {
+ return nil, err
}
if base64Data != "" {
images = append(images, base64Data)
@@ -158,7 +149,7 @@ func openAIChatToOllamaChat(c *gin.Context, r *dto.GeneralOpenAIRequest) (*Ollam
func openAIToGenerate(c *gin.Context, r *dto.GeneralOpenAIRequest) (*OllamaGenerateRequest, error) {
gen := &OllamaGenerateRequest{
Model: r.Model,
- Stream: r.Stream,
+ Stream: lo.FromPtrOr(r.Stream, false),
Options: map[string]any{},
Think: r.Think,
}
@@ -196,20 +187,20 @@ func openAIToGenerate(c *gin.Context, r *dto.GeneralOpenAIRequest) (*OllamaGener
if r.Temperature != nil {
gen.Options["temperature"] = r.Temperature
}
- if r.TopP != 0 {
- gen.Options["top_p"] = r.TopP
+ if r.TopP != nil {
+ gen.Options["top_p"] = lo.FromPtr(r.TopP)
}
- if r.TopK != 0 {
- gen.Options["top_k"] = r.TopK
+ if r.TopK != nil {
+ gen.Options["top_k"] = lo.FromPtr(r.TopK)
}
- if r.FrequencyPenalty != 0 {
- gen.Options["frequency_penalty"] = r.FrequencyPenalty
+ if r.FrequencyPenalty != nil {
+ gen.Options["frequency_penalty"] = lo.FromPtr(r.FrequencyPenalty)
}
- if r.PresencePenalty != 0 {
- gen.Options["presence_penalty"] = r.PresencePenalty
+ if r.PresencePenalty != nil {
+ gen.Options["presence_penalty"] = lo.FromPtr(r.PresencePenalty)
}
- if r.Seed != 0 {
- gen.Options["seed"] = int(r.Seed)
+ if r.Seed != nil {
+ gen.Options["seed"] = int(lo.FromPtr(r.Seed))
}
if mt := r.GetMaxTokens(); mt != 0 {
gen.Options["num_predict"] = int(mt)
@@ -240,26 +231,27 @@ func requestOpenAI2Embeddings(r dto.EmbeddingRequest) *OllamaEmbeddingRequest {
if r.Temperature != nil {
opts["temperature"] = r.Temperature
}
- if r.TopP != 0 {
- opts["top_p"] = r.TopP
+ if r.TopP != nil {
+ opts["top_p"] = lo.FromPtr(r.TopP)
}
- if r.FrequencyPenalty != 0 {
- opts["frequency_penalty"] = r.FrequencyPenalty
+ if r.FrequencyPenalty != nil {
+ opts["frequency_penalty"] = lo.FromPtr(r.FrequencyPenalty)
}
- if r.PresencePenalty != 0 {
- opts["presence_penalty"] = r.PresencePenalty
+ if r.PresencePenalty != nil {
+ opts["presence_penalty"] = lo.FromPtr(r.PresencePenalty)
}
- if r.Seed != 0 {
- opts["seed"] = int(r.Seed)
+ if r.Seed != nil {
+ opts["seed"] = int(lo.FromPtr(r.Seed))
}
- if r.Dimensions != 0 {
- opts["dimensions"] = r.Dimensions
+ dimensions := lo.FromPtrOr(r.Dimensions, 0)
+ if r.Dimensions != nil {
+ opts["dimensions"] = dimensions
}
input := r.ParseInput()
if len(input) == 1 {
- return &OllamaEmbeddingRequest{Model: r.Model, Input: input[0], Options: opts, Dimensions: r.Dimensions}
+ return &OllamaEmbeddingRequest{Model: r.Model, Input: input[0], Options: opts, Dimensions: dimensions}
}
- return &OllamaEmbeddingRequest{Model: r.Model, Input: input, Options: opts, Dimensions: r.Dimensions}
+ return &OllamaEmbeddingRequest{Model: r.Model, Input: input, Options: opts, Dimensions: dimensions}
}
func ollamaEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
diff --git a/relay/channel/openai/adaptor.go b/relay/channel/openai/adaptor.go
index f40f5da6d4..29a8f34949 100644
--- a/relay/channel/openai/adaptor.go
+++ b/relay/channel/openai/adaptor.go
@@ -29,6 +29,7 @@ import (
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -171,7 +172,9 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
return url, nil
default:
- if info.RelayFormat == types.RelayFormatClaude || info.RelayFormat == types.RelayFormatGemini {
+ if (info.RelayFormat == types.RelayFormatClaude || info.RelayFormat == types.RelayFormatGemini) &&
+ info.RelayMode != relayconstant.RelayModeResponses &&
+ info.RelayMode != relayconstant.RelayModeResponsesCompact {
return fmt.Sprintf("%s/v1/chat/completions", info.ChannelBaseUrl), nil
}
return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, info.RequestURLPath, info.ChannelType), nil
@@ -187,6 +190,17 @@ func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *
if info.ChannelType == constant.ChannelTypeOpenAI && "" != info.Organization {
header.Set("OpenAI-Organization", info.Organization)
}
+ // 检查 Header Override 是否已设置 Authorization,如果已设置则跳过默认设置
+ // 这样可以避免在 Header Override 应用时被覆盖(虽然 Header Override 会在之后应用,但这里作为额外保护)
+ hasAuthOverride := false
+ if len(info.HeadersOverride) > 0 {
+ for k := range info.HeadersOverride {
+ if strings.EqualFold(k, "Authorization") {
+ hasAuthOverride = true
+ break
+ }
+ }
+ }
if info.RelayMode == relayconstant.RelayModeRealtime {
swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
if swp != "" {
@@ -201,14 +215,22 @@ func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *
//req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
} else {
header.Set("openai-beta", "realtime=v1")
- header.Set("Authorization", "Bearer "+info.ApiKey)
+ if !hasAuthOverride {
+ header.Set("Authorization", "Bearer "+info.ApiKey)
+ }
}
} else {
- header.Set("Authorization", "Bearer "+info.ApiKey)
+ if !hasAuthOverride {
+ header.Set("Authorization", "Bearer "+info.ApiKey)
+ }
}
if info.ChannelType == constant.ChannelTypeOpenRouter {
- header.Set("HTTP-Referer", "https://www.newapi.ai")
- header.Set("X-Title", "New API")
+ if header.Get("HTTP-Referer") == "" {
+ header.Set("HTTP-Referer", "https://www.newapi.ai")
+ }
+ if header.Get("X-OpenRouter-Title") == "" {
+ header.Set("X-OpenRouter-Title", "New API")
+ }
}
return nil
}
@@ -280,6 +302,7 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
}
reasoning := openrouter.RequestReasoning{
+ Enabled: true,
MaxTokens: *thinking.BudgetTokens,
}
@@ -297,9 +320,9 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
}
if strings.HasPrefix(info.UpstreamModelName, "o") || strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
- if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
+ if lo.FromPtrOr(request.MaxCompletionTokens, uint(0)) == 0 && lo.FromPtrOr(request.MaxTokens, uint(0)) != 0 {
request.MaxCompletionTokens = request.MaxTokens
- request.MaxTokens = 0
+ request.MaxTokens = nil
}
if strings.HasPrefix(info.UpstreamModelName, "o") {
@@ -309,8 +332,8 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
// gpt-5系列模型适配 归零不再支持的参数
if strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
request.Temperature = nil
- request.TopP = 0 // oai 的 top_p 默认值是 1.0,但是为了 omitempty 属性直接不传,这里显式设置为 0
- request.LogProbs = false
+ request.TopP = nil
+ request.LogProbs = nil
}
// 转换模型推理力度后缀
@@ -570,6 +593,9 @@ func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommo
}
request.Model = originModel
}
+ if info != nil && request.Reasoning != nil && request.Reasoning.Effort != "" {
+ info.ReasoningEffort = request.Reasoning.Effort
+ }
return request, nil
}
@@ -605,6 +631,8 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
} else {
usage, err = OaiResponsesHandler(c, info, resp)
}
+ case relayconstant.RelayModeResponsesCompact:
+ usage, err = OaiResponsesCompactionHandler(c, resp)
default:
if info.IsStream {
usage, err = OaiStreamHandler(c, info, resp)
diff --git a/relay/channel/openai/audio.go b/relay/channel/openai/audio.go
index 877f5bb1cc..3bab3c1a52 100644
--- a/relay/channel/openai/audio.go
+++ b/relay/channel/openai/audio.go
@@ -35,21 +35,21 @@ func OpenaiTTSHandler(c *gin.Context, resp *http.Response, info *relaycommon.Rel
c.Writer.WriteHeader(resp.StatusCode)
if info.IsStream {
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
if service.SundaySearch(data, "usage") {
var simpleResponse dto.SimpleResponse
- err := common.Unmarshal([]byte(data), &simpleResponse)
- if err != nil {
+ if err := common.Unmarshal([]byte(data), &simpleResponse); err != nil {
logger.LogError(c, err.Error())
- }
- if simpleResponse.Usage.TotalTokens != 0 {
+ sr.Error(err)
+ } else if simpleResponse.Usage.TotalTokens != 0 {
usage.PromptTokens = simpleResponse.Usage.InputTokens
usage.CompletionTokens = simpleResponse.OutputTokens
usage.TotalTokens = simpleResponse.TotalTokens
}
}
- _ = helper.StringData(c, data)
- return true
+ if err := helper.StringData(c, data); err != nil {
+ sr.Error(err)
+ }
})
} else {
common.SetContextKey(c, constant.ContextKeyLocalCountTokens, true)
diff --git a/relay/channel/openai/chat_via_responses.go b/relay/channel/openai/chat_via_responses.go
index 83f9734c9b..5e8ec173de 100644
--- a/relay/channel/openai/chat_via_responses.go
+++ b/relay/channel/openai/chat_via_responses.go
@@ -18,6 +18,26 @@ import (
"github.com/gin-gonic/gin"
)
+func responsesStreamIndexKey(itemID string, idx *int) string {
+ if itemID == "" {
+ return ""
+ }
+ if idx == nil {
+ return itemID
+ }
+ return fmt.Sprintf("%s:%d", itemID, *idx)
+}
+
+func stringDeltaFromPrefix(prev string, next string) string {
+ if next == "" {
+ return ""
+ }
+ if prev != "" && strings.HasPrefix(next, prev) {
+ return next[len(prev):]
+ }
+ return next
+}
+
func OaiResponsesToChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
if resp == nil || resp.Body == nil {
return nil, types.NewOpenAIError(fmt.Errorf("invalid response"), types.ErrorCodeBadResponse, http.StatusInternalServerError)
@@ -51,12 +71,22 @@ func OaiResponsesToChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp
chatResp.Usage = *usage
}
- chatBody, err := common.Marshal(chatResp)
+ var responseBody []byte
+ switch info.RelayFormat {
+ case types.RelayFormatClaude:
+ claudeResp := service.ResponseOpenAI2Claude(chatResp, info)
+ responseBody, err = common.Marshal(claudeResp)
+ case types.RelayFormatGemini:
+ geminiResp := service.ResponseOpenAI2Gemini(chatResp, info)
+ responseBody, err = common.Marshal(geminiResp)
+ default:
+ responseBody, err = common.Marshal(chatResp)
+ }
if err != nil {
return nil, types.NewOpenAIError(err, types.ErrorCodeJsonMarshalFailed, http.StatusInternalServerError)
}
- service.IOCopyBytesGracefully(c, resp, chatBody)
+ service.IOCopyBytesGracefully(c, resp, responseBody)
return usage, nil
}
@@ -86,19 +116,120 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
toolCallArgsByID := make(map[string]string)
toolCallNameSent := make(map[string]bool)
toolCallCanonicalIDByItemID := make(map[string]string)
+ hasSentReasoningSummary := false
+ needsReasoningSummarySeparator := false
+ //reasoningSummaryTextByKey := make(map[string]string)
+
+ if info.RelayFormat == types.RelayFormatClaude && info.ClaudeConvertInfo == nil {
+ info.ClaudeConvertInfo = &relaycommon.ClaudeConvertInfo{LastMessagesType: relaycommon.LastMessageTypeNone}
+ }
+
+ sendChatChunk := func(chunk *dto.ChatCompletionsStreamResponse) bool {
+ if chunk == nil {
+ return true
+ }
+ if info.RelayFormat == types.RelayFormatOpenAI {
+ if err := helper.ObjectData(c, chunk); err != nil {
+ streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ return false
+ }
+ return true
+ }
+
+ chunkData, err := common.Marshal(chunk)
+ if err != nil {
+ streamErr = types.NewOpenAIError(err, types.ErrorCodeJsonMarshalFailed, http.StatusInternalServerError)
+ return false
+ }
+ if err := HandleStreamFormat(c, info, string(chunkData), false, false); err != nil {
+ streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ return false
+ }
+ return true
+ }
sendStartIfNeeded := func() bool {
if sentStart {
return true
}
- if err := helper.ObjectData(c, helper.GenerateStartEmptyResponse(responseId, createAt, model, nil)); err != nil {
- streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ if !sendChatChunk(helper.GenerateStartEmptyResponse(responseId, createAt, model, nil)) {
return false
}
sentStart = true
return true
}
+ //sendReasoningDelta := func(delta string) bool {
+ // if delta == "" {
+ // return true
+ // }
+ // if !sendStartIfNeeded() {
+ // return false
+ // }
+ //
+ // usageText.WriteString(delta)
+ // chunk := &dto.ChatCompletionsStreamResponse{
+ // Id: responseId,
+ // Object: "chat.completion.chunk",
+ // Created: createAt,
+ // Model: model,
+ // Choices: []dto.ChatCompletionsStreamResponseChoice{
+ // {
+ // Index: 0,
+ // Delta: dto.ChatCompletionsStreamResponseChoiceDelta{
+ // ReasoningContent: &delta,
+ // },
+ // },
+ // },
+ // }
+ // if err := helper.ObjectData(c, chunk); err != nil {
+ // streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ // return false
+ // }
+ // return true
+ //}
+
+ sendReasoningSummaryDelta := func(delta string) bool {
+ if delta == "" {
+ return true
+ }
+ if needsReasoningSummarySeparator {
+ if strings.HasPrefix(delta, "\n\n") {
+ needsReasoningSummarySeparator = false
+ } else if strings.HasPrefix(delta, "\n") {
+ delta = "\n" + delta
+ needsReasoningSummarySeparator = false
+ } else {
+ delta = "\n\n" + delta
+ needsReasoningSummarySeparator = false
+ }
+ }
+ if !sendStartIfNeeded() {
+ return false
+ }
+
+ usageText.WriteString(delta)
+ chunk := &dto.ChatCompletionsStreamResponse{
+ Id: responseId,
+ Object: "chat.completion.chunk",
+ Created: createAt,
+ Model: model,
+ Choices: []dto.ChatCompletionsStreamResponseChoice{
+ {
+ Index: 0,
+ Delta: dto.ChatCompletionsStreamResponseChoiceDelta{
+ ReasoningContent: &delta,
+ },
+ },
+ },
+ }
+ if !sendChatChunk(chunk) {
+ return false
+ }
+ hasSentReasoningSummary = true
+ return true
+ }
+
sendToolCallDelta := func(callID string, name string, argsDelta string) bool {
if callID == "" {
return true
@@ -150,8 +281,7 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
},
},
}
- if err := helper.ObjectData(c, chunk); err != nil {
- streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ if !sendChatChunk(chunk) {
return false
}
sawToolCall = true
@@ -166,15 +296,17 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
return true
}
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
if streamErr != nil {
- return false
+ sr.Stop(streamErr)
+ return
}
var streamResp dto.ResponsesStreamResponse
if err := common.UnmarshalJsonStr(data, &streamResp); err != nil {
logger.LogError(c, "failed to unmarshal responses stream event: "+err.Error())
- return true
+ sr.Error(err)
+ return
}
switch streamResp.Type {
@@ -188,9 +320,47 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
}
}
+ //case "response.reasoning_text.delta":
+ //if !sendReasoningDelta(streamResp.Delta) {
+ // sr.Stop(streamErr)
+ // return
+ //}
+
+ //case "response.reasoning_text.done":
+
+ case "response.reasoning_summary_text.delta":
+ if !sendReasoningSummaryDelta(streamResp.Delta) {
+ sr.Stop(streamErr)
+ return
+ }
+
+ case "response.reasoning_summary_text.done":
+ if hasSentReasoningSummary {
+ needsReasoningSummarySeparator = true
+ }
+
+ //case "response.reasoning_summary_part.added", "response.reasoning_summary_part.done":
+ // key := responsesStreamIndexKey(strings.TrimSpace(streamResp.ItemID), streamResp.SummaryIndex)
+ // if key == "" || streamResp.Part == nil {
+ // break
+ // }
+ // // Only handle summary text parts, ignore other part types.
+ // if streamResp.Part.Type != "" && streamResp.Part.Type != "summary_text" {
+ // break
+ // }
+ // prev := reasoningSummaryTextByKey[key]
+ // next := streamResp.Part.Text
+ // delta := stringDeltaFromPrefix(prev, next)
+ // reasoningSummaryTextByKey[key] = next
+ // if !sendReasoningSummaryDelta(delta) {
+ // sr.Stop(streamErr)
+ // return
+ // }
+
case "response.output_text.delta":
if !sendStartIfNeeded() {
- return false
+ sr.Stop(streamErr)
+ return
}
if streamResp.Delta != "" {
@@ -211,9 +381,9 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
},
},
}
- if err := helper.ObjectData(c, chunk); err != nil {
- streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
- return false
+ if !sendChatChunk(chunk) {
+ sr.Stop(streamErr)
+ return
}
}
@@ -251,7 +421,8 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
}
if !sendToolCallDelta(callID, name, argsDelta) {
- return false
+ sr.Stop(streamErr)
+ return
}
case "response.function_call_arguments.delta":
@@ -265,7 +436,8 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
}
toolCallArgsByID[callID] += streamResp.Delta
if !sendToolCallDelta(callID, "", streamResp.Delta) {
- return false
+ sr.Stop(streamErr)
+ return
}
case "response.function_call_arguments.done":
@@ -304,17 +476,21 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
}
if !sendStartIfNeeded() {
- return false
+ sr.Stop(streamErr)
+ return
}
if !sentStop {
+ if info.RelayFormat == types.RelayFormatClaude && info.ClaudeConvertInfo != nil {
+ info.ClaudeConvertInfo.Usage = usage
+ }
finishReason := "stop"
if sawToolCall && outputText.Len() == 0 {
finishReason = "tool_calls"
}
stop := helper.GenerateStopResponse(responseId, createAt, model, finishReason)
- if err := helper.ObjectData(c, stop); err != nil {
- streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
- return false
+ if !sendChatChunk(stop) {
+ sr.Stop(streamErr)
+ return
}
sentStop = true
}
@@ -323,16 +499,16 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
if streamResp.Response != nil {
if oaiErr := streamResp.Response.GetOpenAIError(); oaiErr != nil && oaiErr.Type != "" {
streamErr = types.WithOpenAIError(*oaiErr, http.StatusInternalServerError)
- return false
+ sr.Stop(streamErr)
+ return
}
}
streamErr = types.NewOpenAIError(fmt.Errorf("responses stream error: %s", streamResp.Type), types.ErrorCodeBadResponse, http.StatusInternalServerError)
- return false
+ sr.Stop(streamErr)
+ return
default:
}
-
- return true
})
if streamErr != nil {
@@ -344,26 +520,31 @@ func OaiResponsesToChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo
}
if !sentStart {
- if err := helper.ObjectData(c, helper.GenerateStartEmptyResponse(responseId, createAt, model, nil)); err != nil {
- return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ if !sendChatChunk(helper.GenerateStartEmptyResponse(responseId, createAt, model, nil)) {
+ return nil, streamErr
}
}
if !sentStop {
+ if info.RelayFormat == types.RelayFormatClaude && info.ClaudeConvertInfo != nil {
+ info.ClaudeConvertInfo.Usage = usage
+ }
finishReason := "stop"
if sawToolCall && outputText.Len() == 0 {
finishReason = "tool_calls"
}
stop := helper.GenerateStopResponse(responseId, createAt, model, finishReason)
- if err := helper.ObjectData(c, stop); err != nil {
- return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
+ if !sendChatChunk(stop) {
+ return nil, streamErr
}
}
- if info.ShouldIncludeUsage && usage != nil {
+ if info.RelayFormat == types.RelayFormatOpenAI && info.ShouldIncludeUsage && usage != nil {
if err := helper.ObjectData(c, helper.GenerateFinalUsageResponse(responseId, createAt, model, *usage)); err != nil {
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError)
}
}
- helper.Done(c)
+ if info.RelayFormat == types.RelayFormatOpenAI {
+ helper.Done(c)
+ }
return usage, nil
}
diff --git a/relay/channel/openai/constant.go b/relay/channel/openai/constant.go
index af5b672485..14e3d442d4 100644
--- a/relay/channel/openai/constant.go
+++ b/relay/channel/openai/constant.go
@@ -3,14 +3,19 @@ package openai
var ModelList = []string{
"gpt-3.5-turbo", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125",
"gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613",
- "gpt-3.5-turbo-instruct",
+ "gpt-3.5-turbo-instruct", "gpt-3.5-turbo-instruct-0914",
"gpt-4", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-0125-preview",
"gpt-4-32k", "gpt-4-32k-0613",
"gpt-4-turbo-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09",
"gpt-4-vision-preview",
"chatgpt-4o-latest",
"gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20",
+ "gpt-4o-transcribe", "gpt-4o-transcribe-diarize",
+ "gpt-4o-search-preview", "gpt-4o-search-preview-2025-03-11",
"gpt-4o-mini", "gpt-4o-mini-2024-07-18",
+ "gpt-4o-mini-transcribe", "gpt-4o-mini-transcribe-2025-03-20", "gpt-4o-mini-transcribe-2025-12-15",
+ "gpt-4o-mini-tts", "gpt-4o-mini-tts-2025-03-20", "gpt-4o-mini-tts-2025-12-15",
+ "gpt-4o-mini-search-preview", "gpt-4o-mini-search-preview-2025-03-11",
"gpt-4.5-preview", "gpt-4.5-preview-2025-02-27",
"gpt-4.1", "gpt-4.1-2025-04-14",
"gpt-4.1-mini", "gpt-4.1-mini-2025-04-14",
@@ -31,17 +36,41 @@ var ModelList = []string{
"gpt-5", "gpt-5-2025-08-07", "gpt-5-chat-latest",
"gpt-5-mini", "gpt-5-mini-2025-08-07",
"gpt-5-nano", "gpt-5-nano-2025-08-07",
- "gpt-4o-audio-preview", "gpt-4o-audio-preview-2024-10-01",
- "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17",
+ "gpt-5-codex",
+ "gpt-5-pro", "gpt-5-pro-2025-10-06",
+ "gpt-5-search-api", "gpt-5-search-api-2025-10-14",
+ "gpt-5.1", "gpt-5.1-2025-11-13", "gpt-5.1-chat-latest",
+ "gpt-5.1-codex", "gpt-5.1-codex-mini", "gpt-5.1-codex-max",
+ "gpt-5.2", "gpt-5.2-2025-12-11", "gpt-5.2-chat-latest",
+ "gpt-5.2-pro", "gpt-5.2-pro-2025-12-11",
+ "gpt-5.2-codex",
+ "gpt-5.3-chat-latest",
+ "gpt-5.3-codex",
+ "gpt-5.4", "gpt-5.4-2026-03-05",
+ "gpt-5.4-pro", "gpt-5.4-pro-2026-03-05",
+ "gpt-4o-audio-preview", "gpt-4o-audio-preview-2024-10-01", "gpt-4o-audio-preview-2024-12-17", "gpt-4o-audio-preview-2025-06-03",
+ "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-realtime-preview-2025-06-03",
"gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17",
+ "gpt-4o-mini-audio-preview", "gpt-4o-mini-audio-preview-2024-12-17",
+ "gpt-audio", "gpt-audio-2025-08-28",
+ "gpt-audio-mini", "gpt-audio-mini-2025-10-06", "gpt-audio-mini-2025-12-15",
+ "gpt-audio-1.5",
+ "gpt-realtime", "gpt-realtime-2025-08-28",
+ "gpt-realtime-mini", "gpt-realtime-mini-2025-10-06", "gpt-realtime-mini-2025-12-15",
+ "gpt-realtime-1.5",
"text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large",
"text-curie-001", "text-babbage-001", "text-ada-001",
"text-moderation-latest", "text-moderation-stable",
+ "omni-moderation-latest", "omni-moderation-2024-09-26",
"text-davinci-edit-001",
"davinci-002", "babbage-002",
- "dall-e-3", "gpt-image-1",
+ "dall-e-2", "dall-e-3",
+ "gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5",
+ "chatgpt-image-latest",
"whisper-1",
"tts-1", "tts-1-1106", "tts-1-hd", "tts-1-hd-1106",
+ "computer-use-preview", "computer-use-preview-2025-03-11",
+ "sora-2", "sora-2-pro",
}
var ChannelName = "openai"
diff --git a/relay/channel/openai/relay-openai.go b/relay/channel/openai/relay-openai.go
index a4c6ef6056..d33c5555f2 100644
--- a/relay/channel/openai/relay-openai.go
+++ b/relay/channel/openai/relay-openai.go
@@ -126,11 +126,11 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
// 检查是否为音频模型
isAudioModel := strings.Contains(strings.ToLower(model), "audio")
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
if lastStreamData != "" {
- err := HandleStreamFormat(c, info, lastStreamData, info.ChannelSetting.ForceFormat, info.ChannelSetting.ThinkingToContent)
- if err != nil {
+ if err := HandleStreamFormat(c, info, lastStreamData, info.ChannelSetting.ForceFormat, info.ChannelSetting.ThinkingToContent); err != nil {
common.SysLog("error handling stream format: " + err.Error())
+ sr.Error(err)
}
}
if len(data) > 0 {
@@ -142,7 +142,6 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
lastStreamData = data
streamItems = append(streamItems, data)
}
- return true
})
// 对音频模型,从倒数第二个stream data中提取usage信息
@@ -229,6 +228,13 @@ func OpenaiHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo
return nil, types.WithOpenAIError(*oaiError, resp.StatusCode)
}
+ for _, choice := range simpleResponse.Choices {
+ if choice.FinishReason == constant.FinishReasonContentFilter {
+ common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "openai_finish_reason=content_filter")
+ break
+ }
+ }
+
forceFormat := false
if info.ChannelSetting.ForceFormat {
forceFormat = true
@@ -620,6 +626,12 @@ func applyUsagePostProcessing(info *relaycommon.RelayInfo, usage *dto.Usage, res
usage.PromptTokensDetails.CachedTokens = usage.PromptCacheHitTokens
}
}
+ case constant.ChannelTypeOpenAI:
+ if usage.PromptTokensDetails.CachedTokens == 0 {
+ if cachedTokens, ok := extractLlamaCachedTokensFromBody(responseBody); ok {
+ usage.PromptTokensDetails.CachedTokens = cachedTokens
+ }
+ }
}
}
@@ -682,3 +694,25 @@ func extractMoonshotCachedTokensFromBody(body []byte) (int, bool) {
return 0, false
}
+
+// extractLlamaCachedTokensFromBody 从llama.cpp的非标准位置提取cache_n
+func extractLlamaCachedTokensFromBody(body []byte) (int, bool) {
+ if len(body) == 0 {
+ return 0, false
+ }
+
+ var payload struct {
+ Timings struct {
+ CachedTokens *int `json:"cache_n"`
+ } `json:"timings"`
+ }
+
+ if err := common.Unmarshal(body, &payload); err != nil {
+ return 0, false
+ }
+
+ if payload.Timings.CachedTokens == nil {
+ return 0, false
+ }
+ return *payload.Timings.CachedTokens, true
+}
diff --git a/relay/channel/openai/relay_responses.go b/relay/channel/openai/relay_responses.go
index b92c8c7234..2665b8d027 100644
--- a/relay/channel/openai/relay_responses.go
+++ b/relay/channel/openai/relay_responses.go
@@ -79,55 +79,55 @@ func OaiResponsesStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp
var usage = &dto.Usage{}
var responseTextBuilder strings.Builder
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
// 检查当前数据是否包含 completed 状态和 usage 信息
var streamResponse dto.ResponsesStreamResponse
- if err := common.UnmarshalJsonStr(data, &streamResponse); err == nil {
- sendResponsesStreamData(c, streamResponse, data)
- switch streamResponse.Type {
- case "response.completed":
- if streamResponse.Response != nil {
- if streamResponse.Response.Usage != nil {
- if streamResponse.Response.Usage.InputTokens != 0 {
- usage.PromptTokens = streamResponse.Response.Usage.InputTokens
- }
- if streamResponse.Response.Usage.OutputTokens != 0 {
- usage.CompletionTokens = streamResponse.Response.Usage.OutputTokens
- }
- if streamResponse.Response.Usage.TotalTokens != 0 {
- usage.TotalTokens = streamResponse.Response.Usage.TotalTokens
- }
- if streamResponse.Response.Usage.InputTokensDetails != nil {
- usage.PromptTokensDetails.CachedTokens = streamResponse.Response.Usage.InputTokensDetails.CachedTokens
- }
+ if err := common.UnmarshalJsonStr(data, &streamResponse); err != nil {
+ logger.LogError(c, "failed to unmarshal stream response: "+err.Error())
+ sr.Error(err)
+ return
+ }
+ sendResponsesStreamData(c, streamResponse, data)
+ switch streamResponse.Type {
+ case "response.completed":
+ if streamResponse.Response != nil {
+ if streamResponse.Response.Usage != nil {
+ if streamResponse.Response.Usage.InputTokens != 0 {
+ usage.PromptTokens = streamResponse.Response.Usage.InputTokens
}
- if streamResponse.Response.HasImageGenerationCall() {
- c.Set("image_generation_call", true)
- c.Set("image_generation_call_quality", streamResponse.Response.GetQuality())
- c.Set("image_generation_call_size", streamResponse.Response.GetSize())
+ if streamResponse.Response.Usage.OutputTokens != 0 {
+ usage.CompletionTokens = streamResponse.Response.Usage.OutputTokens
+ }
+ if streamResponse.Response.Usage.TotalTokens != 0 {
+ usage.TotalTokens = streamResponse.Response.Usage.TotalTokens
+ }
+ if streamResponse.Response.Usage.InputTokensDetails != nil {
+ usage.PromptTokensDetails.CachedTokens = streamResponse.Response.Usage.InputTokensDetails.CachedTokens
}
}
- case "response.output_text.delta":
- // 处理输出文本
- responseTextBuilder.WriteString(streamResponse.Delta)
- case dto.ResponsesOutputTypeItemDone:
- // 函数调用处理
- if streamResponse.Item != nil {
- switch streamResponse.Item.Type {
- case dto.BuildInCallWebSearchCall:
- if info != nil && info.ResponsesUsageInfo != nil && info.ResponsesUsageInfo.BuiltInTools != nil {
- if webSearchTool, exists := info.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool != nil {
- webSearchTool.CallCount++
- }
+ if streamResponse.Response.HasImageGenerationCall() {
+ c.Set("image_generation_call", true)
+ c.Set("image_generation_call_quality", streamResponse.Response.GetQuality())
+ c.Set("image_generation_call_size", streamResponse.Response.GetSize())
+ }
+ }
+ case "response.output_text.delta":
+ // 处理输出文本
+ responseTextBuilder.WriteString(streamResponse.Delta)
+ case dto.ResponsesOutputTypeItemDone:
+ // 函数调用处理
+ if streamResponse.Item != nil {
+ switch streamResponse.Item.Type {
+ case dto.BuildInCallWebSearchCall:
+ if info != nil && info.ResponsesUsageInfo != nil && info.ResponsesUsageInfo.BuiltInTools != nil {
+ if webSearchTool, exists := info.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool != nil {
+ webSearchTool.CallCount++
}
}
}
}
- } else {
- logger.LogError(c, "failed to unmarshal stream response: "+err.Error())
}
- return true
})
if usage.CompletionTokens == 0 {
diff --git a/relay/channel/openai/relay_responses_compact.go b/relay/channel/openai/relay_responses_compact.go
new file mode 100644
index 0000000000..390de8ed68
--- /dev/null
+++ b/relay/channel/openai/relay_responses_compact.go
@@ -0,0 +1,44 @@
+package openai
+
+import (
+ "io"
+ "net/http"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/service"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+)
+
+func OaiResponsesCompactionHandler(c *gin.Context, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
+ defer service.CloseResponseBodyGracefully(resp)
+
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
+ }
+
+ var compactResp dto.OpenAIResponsesCompactionResponse
+ if err := common.Unmarshal(responseBody, &compactResp); err != nil {
+ return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
+ }
+ if oaiError := compactResp.GetOpenAIError(); oaiError != nil && oaiError.Type != "" {
+ return nil, types.WithOpenAIError(*oaiError, resp.StatusCode)
+ }
+
+ service.IOCopyBytesGracefully(c, resp, responseBody)
+
+ usage := dto.Usage{}
+ if compactResp.Usage != nil {
+ usage.PromptTokens = compactResp.Usage.InputTokens
+ usage.CompletionTokens = compactResp.Usage.OutputTokens
+ usage.TotalTokens = compactResp.Usage.TotalTokens
+ if compactResp.Usage.InputTokensDetails != nil {
+ usage.PromptTokensDetails.CachedTokens = compactResp.Usage.InputTokensDetails.CachedTokens
+ }
+ }
+
+ return &usage, nil
+}
diff --git a/relay/channel/openrouter/dto.go b/relay/channel/openrouter/dto.go
index a324998525..73a1e445a4 100644
--- a/relay/channel/openrouter/dto.go
+++ b/relay/channel/openrouter/dto.go
@@ -3,6 +3,7 @@ package openrouter
import "encoding/json"
type RequestReasoning struct {
+ Enabled bool `json:"enabled"`
// One of the following (not both):
Effort string `json:"effort,omitempty"` // Can be "high", "medium", or "low" (OpenAI-style)
MaxTokens int `json:"max_tokens,omitempty"` // Specific token limit (Anthropic-style)
diff --git a/relay/channel/perplexity/adaptor.go b/relay/channel/perplexity/adaptor.go
index 43e39b12e1..6b03690945 100644
--- a/relay/channel/perplexity/adaptor.go
+++ b/relay/channel/perplexity/adaptor.go
@@ -10,7 +10,9 @@ import (
"github.com/QuantumNous/new-api/relay/channel"
"github.com/QuantumNous/new-api/relay/channel/openai"
relaycommon "github.com/QuantumNous/new-api/relay/common"
+ relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -42,6 +44,9 @@ func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
}
func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
+ if info.RelayMode == relayconstant.RelayModeResponses {
+ return fmt.Sprintf("%s/v1/responses", info.ChannelBaseUrl), nil
+ }
return fmt.Sprintf("%s/chat/completions", info.ChannelBaseUrl), nil
}
@@ -55,8 +60,8 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
if request == nil {
return nil, errors.New("request is nil")
}
- if request.TopP >= 1 {
- request.TopP = 0.99
+ if lo.FromPtrOr(request.TopP, 0) >= 1 {
+ request.TopP = lo.ToPtr(0.99)
}
return requestOpenAI2Perplexity(*request), nil
}
@@ -71,8 +76,7 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
}
func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
- // TODO implement me
- return nil, errors.New("not implemented")
+ return request, nil
}
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
diff --git a/relay/channel/perplexity/relay-perplexity.go b/relay/channel/perplexity/relay-perplexity.go
index b07bed68aa..4f5767e370 100644
--- a/relay/channel/perplexity/relay-perplexity.go
+++ b/relay/channel/perplexity/relay-perplexity.go
@@ -10,13 +10,12 @@ func requestOpenAI2Perplexity(request dto.GeneralOpenAIRequest) *dto.GeneralOpen
Content: message.Content,
})
}
- return &dto.GeneralOpenAIRequest{
+ req := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: request.Stream,
Messages: messages,
Temperature: request.Temperature,
TopP: request.TopP,
- MaxTokens: request.GetMaxTokens(),
FrequencyPenalty: request.FrequencyPenalty,
PresencePenalty: request.PresencePenalty,
SearchDomainFilter: request.SearchDomainFilter,
@@ -25,4 +24,9 @@ func requestOpenAI2Perplexity(request dto.GeneralOpenAIRequest) *dto.GeneralOpen
ReturnRelatedQuestions: request.ReturnRelatedQuestions,
SearchMode: request.SearchMode,
}
+ if request.MaxTokens != nil || request.MaxCompletionTokens != nil {
+ maxTokens := request.GetMaxTokens()
+ req.MaxTokens = &maxTokens
+ }
+ return req
}
diff --git a/relay/channel/replicate/adaptor.go b/relay/channel/replicate/adaptor.go
index 9ee5216159..673502054b 100644
--- a/relay/channel/replicate/adaptor.go
+++ b/relay/channel/replicate/adaptor.go
@@ -22,6 +22,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
type Adaptor struct {
@@ -115,8 +116,8 @@ func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInf
}
}
- if request.N > 0 {
- inputPayload["num_outputs"] = int(request.N)
+ if imageN := lo.FromPtrOr(request.N, uint(0)); imageN > 0 {
+ inputPayload["num_outputs"] = int(imageN)
}
if strings.EqualFold(request.Quality, "hd") || strings.EqualFold(request.Quality, "high") {
diff --git a/relay/channel/siliconflow/adaptor.go b/relay/channel/siliconflow/adaptor.go
index 02a82edfcc..3e9bee55ad 100644
--- a/relay/channel/siliconflow/adaptor.go
+++ b/relay/channel/siliconflow/adaptor.go
@@ -15,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
type Adaptor struct {
@@ -53,7 +54,9 @@ func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInf
sfRequest.ImageSize = request.Size
}
if sfRequest.BatchSize == 0 {
- sfRequest.BatchSize = request.N
+ if request.N != nil {
+ sfRequest.BatchSize = lo.FromPtr(request.N)
+ }
}
return sfRequest, nil
diff --git a/relay/channel/task/ali/adaptor.go b/relay/channel/task/ali/adaptor.go
index d55452c08d..f698fc9f62 100644
--- a/relay/channel/task/ali/adaptor.go
+++ b/relay/channel/task/ali/adaptor.go
@@ -13,6 +13,7 @@ import (
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
"github.com/samber/lo"
@@ -108,10 +109,10 @@ type AliMetadata struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
- aliReq *AliVideoRequest
}
func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
@@ -121,17 +122,7 @@ func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
}
func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
- // 阿里通义万相支持 JSON 格式,不使用 multipart
- var taskReq relaycommon.TaskSubmitReq
- if err := common.UnmarshalBodyReusable(c, &taskReq); err != nil {
- return service.TaskErrorWrapper(err, "unmarshal_task_request_failed", http.StatusBadRequest)
- }
- aliReq, err := a.convertToAliRequest(info, taskReq)
- if err != nil {
- return service.TaskErrorWrapper(err, "convert_to_ali_request_failed", http.StatusInternalServerError)
- }
- a.aliReq = aliReq
- logger.LogJson(c, "ali video request body", aliReq)
+ // ValidateMultipartDirect 负责解析并将原始 TaskSubmitReq 存入 context
return relaycommon.ValidateMultipartDirect(c, info)
}
@@ -148,11 +139,21 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
}
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
- bodyBytes, err := common.Marshal(a.aliReq)
+ taskReq, err := relaycommon.GetTaskRequest(c)
+ if err != nil {
+ return nil, errors.Wrap(err, "get_task_request_failed")
+ }
+
+ aliReq, err := a.convertToAliRequest(info, taskReq)
+ if err != nil {
+ return nil, errors.Wrap(err, "convert_to_ali_request_failed")
+ }
+ logger.LogJson(c, "ali video request body", aliReq)
+
+ bodyBytes, err := common.Marshal(aliReq)
if err != nil {
return nil, errors.Wrap(err, "marshal_ali_request_failed")
}
-
return bytes.NewReader(bodyBytes), nil
}
@@ -252,8 +253,12 @@ func ProcessAliOtherRatios(aliReq *AliVideoRequest) (map[string]float64, error)
}
func (a *TaskAdaptor) convertToAliRequest(info *relaycommon.RelayInfo, req relaycommon.TaskSubmitReq) (*AliVideoRequest, error) {
+ upstreamModel := req.Model
+ if info.IsModelMapped {
+ upstreamModel = info.UpstreamModelName
+ }
aliReq := &AliVideoRequest{
- Model: req.Model,
+ Model: upstreamModel,
Input: AliVideoInput{
Prompt: req.Prompt,
ImgURL: req.InputReference,
@@ -331,23 +336,37 @@ func (a *TaskAdaptor) convertToAliRequest(info *relaycommon.RelayInfo, req relay
}
}
- if aliReq.Model != req.Model {
+ if aliReq.Model != upstreamModel {
return nil, errors.New("can't change model with metadata")
}
- info.PriceData.OtherRatios = map[string]float64{
+ return aliReq, nil
+}
+
+// EstimateBilling 根据用户请求参数计算 OtherRatios(时长、分辨率等)。
+// 在 ValidateRequestAndSetAction 之后、价格计算之前调用。
+func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
+ taskReq, err := relaycommon.GetTaskRequest(c)
+ if err != nil {
+ return nil
+ }
+
+ aliReq, err := a.convertToAliRequest(info, taskReq)
+ if err != nil {
+ return nil
+ }
+
+ otherRatios := map[string]float64{
"seconds": float64(aliReq.Parameters.Duration),
}
-
ratios, err := ProcessAliOtherRatios(aliReq)
if err != nil {
- return nil, err
+ return otherRatios
}
- for s, f := range ratios {
- info.PriceData.OtherRatios[s] = f
+ for k, v := range ratios {
+ otherRatios[k] = v
}
-
- return aliReq, nil
+ return otherRatios
}
// DoRequest delegates to common helper
@@ -384,7 +403,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
// 转换为 OpenAI 格式响应
openAIResp := dto.NewOpenAIVideo()
- openAIResp.ID = aliResp.Output.TaskID
+ openAIResp.ID = info.PublicTaskID
+ openAIResp.TaskID = info.PublicTaskID
openAIResp.Model = c.GetString("model")
if openAIResp.Model == "" && info != nil {
openAIResp.Model = info.OriginModelName
diff --git a/relay/channel/task/doubao/adaptor.go b/relay/channel/task/doubao/adaptor.go
index 6051c7e8b8..a6dabb5f10 100644
--- a/relay/channel/task/doubao/adaptor.go
+++ b/relay/channel/task/doubao/adaptor.go
@@ -2,10 +2,10 @@ package doubao
import (
"bytes"
- "encoding/json"
"fmt"
"io"
"net/http"
+ "strconv"
"time"
"github.com/QuantumNous/new-api/common"
@@ -14,11 +14,13 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
+ "github.com/samber/lo"
)
// ============================
@@ -26,36 +28,37 @@ import (
// ============================
type ContentItem struct {
- Type string `json:"type"` // "text", "image_url" or "video"
- Text string `json:"text,omitempty"` // for text type
- ImageURL *ImageURL `json:"image_url,omitempty"` // for image_url type
- Video *VideoReference `json:"video,omitempty"` // for video (sample) type
+ Type string `json:"type,omitempty"`
+ Text string `json:"text,omitempty"`
+ ImageURL *MediaURL `json:"image_url,omitempty"`
+ VideoURL *MediaURL `json:"video_url,omitempty"`
+ AudioURL *MediaURL `json:"audio_url,omitempty"`
+ Role string `json:"role,omitempty"`
}
-type ImageURL struct {
- URL string `json:"url"`
-}
-
-type VideoReference struct {
- URL string `json:"url"` // Draft video URL
+type MediaURL struct {
+ URL string `json:"url,omitempty"`
}
type requestPayload struct {
Model string `json:"model"`
- Content []ContentItem `json:"content"`
+ Content []ContentItem `json:"content,omitempty"`
CallbackURL string `json:"callback_url,omitempty"`
ReturnLastFrame *dto.BoolValue `json:"return_last_frame,omitempty"`
ServiceTier string `json:"service_tier,omitempty"`
- ExecutionExpiresAfter dto.IntValue `json:"execution_expires_after,omitempty"`
+ ExecutionExpiresAfter *dto.IntValue `json:"execution_expires_after,omitempty"`
GenerateAudio *dto.BoolValue `json:"generate_audio,omitempty"`
Draft *dto.BoolValue `json:"draft,omitempty"`
- Resolution string `json:"resolution,omitempty"`
- Ratio string `json:"ratio,omitempty"`
- Duration dto.IntValue `json:"duration,omitempty"`
- Frames dto.IntValue `json:"frames,omitempty"`
- Seed dto.IntValue `json:"seed,omitempty"`
- CameraFixed *dto.BoolValue `json:"camera_fixed,omitempty"`
- Watermark *dto.BoolValue `json:"watermark,omitempty"`
+ Tools []struct {
+ Type string `json:"type,omitempty"`
+ } `json:"tools,omitempty"`
+ Resolution string `json:"resolution,omitempty"`
+ Ratio string `json:"ratio,omitempty"`
+ Duration *dto.IntValue `json:"duration,omitempty"`
+ Frames *dto.IntValue `json:"frames,omitempty"`
+ Seed *dto.IntValue `json:"seed,omitempty"`
+ CameraFixed *dto.BoolValue `json:"camera_fixed,omitempty"`
+ Watermark *dto.BoolValue `json:"watermark,omitempty"`
}
type responsePayload struct {
@@ -75,10 +78,20 @@ type responseTask struct {
Ratio string `json:"ratio"`
FramesPerSecond int `json:"framespersecond"`
ServiceTier string `json:"service_tier"`
- Usage struct {
+ Tools []struct {
+ Type string `json:"type"`
+ } `json:"tools"`
+ Usage struct {
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
+ ToolUsage struct {
+ WebSearch int `json:"web_search"`
+ } `json:"tool_usage"`
} `json:"usage"`
+ Error struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ } `json:"error"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
@@ -88,6 +101,7 @@ type responseTask struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -106,18 +120,61 @@ func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycom
}
// BuildRequestURL constructs the upstream URL.
-func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
+func (a *TaskAdaptor) BuildRequestURL(_ *relaycommon.RelayInfo) (string, error) {
return fmt.Sprintf("%s/api/v3/contents/generations/tasks", a.baseURL), nil
}
// BuildRequestHeader sets required headers.
-func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
+func (a *TaskAdaptor) BuildRequestHeader(_ *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+a.apiKey)
return nil
}
+// EstimateBilling 检测请求 metadata 中是否包含视频输入,返回视频折扣 OtherRatio。
+func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
+ req, err := relaycommon.GetTaskRequest(c)
+ if err != nil {
+ return nil
+ }
+ if hasVideoInMetadata(req.Metadata) {
+ if ratio, ok := GetVideoInputRatio(info.OriginModelName); ok {
+ return map[string]float64{"video_input": ratio}
+ }
+ }
+ return nil
+}
+
+// hasVideoInMetadata 直接检查 metadata 的 content 数组是否包含 video_url 条目,
+// 避免构建完整的上游 requestPayload。
+func hasVideoInMetadata(metadata map[string]interface{}) bool {
+ if metadata == nil {
+ return false
+ }
+ contentRaw, ok := metadata["content"]
+ if !ok {
+ return false
+ }
+ contentSlice, ok := contentRaw.([]interface{})
+ if !ok {
+ return false
+ }
+ for _, item := range contentSlice {
+ itemMap, ok := item.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if itemMap["type"] == "video_url" {
+ return true
+ }
+ if _, has := itemMap["video_url"]; has {
+ return true
+ }
+ }
+ return false
+}
+
// BuildRequestBody converts request into Doubao specific format.
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
req, err := relaycommon.GetTaskRequest(c)
@@ -129,8 +186,12 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
if err != nil {
return nil, errors.Wrap(err, "convert request payload failed")
}
- info.UpstreamModelName = body.Model
- data, err := json.Marshal(body)
+ if info.IsModelMapped {
+ body.Model = info.UpstreamModelName
+ } else {
+ info.UpstreamModelName = body.Model
+ }
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -153,7 +214,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
// Parse Doubao response
var dResp responsePayload
- if err := json.Unmarshal(responseBody, &dResp); err != nil {
+ if err := common.Unmarshal(responseBody, &dResp); err != nil {
taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
return
}
@@ -164,8 +225,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
ov := dto.NewOpenAIVideo()
- ov.ID = dResp.ID
- ov.TaskID = dResp.ID
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
@@ -212,20 +273,12 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
Content: []ContentItem{},
}
- // Add text prompt
- if req.Prompt != "" {
- r.Content = append(r.Content, ContentItem{
- Type: "text",
- Text: req.Prompt,
- })
- }
-
// Add images if present
if req.HasImage() {
for _, imgURL := range req.Images {
r.Content = append(r.Content, ContentItem{
Type: "image_url",
- ImageURL: &ImageURL{
+ ImageURL: &MediaURL{
URL: imgURL,
},
})
@@ -233,21 +286,26 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
}
metadata := req.Metadata
- medaBytes, err := json.Marshal(metadata)
- if err != nil {
- return nil, errors.Wrap(err, "metadata marshal metadata failed")
- }
- err = json.Unmarshal(medaBytes, &r)
- if err != nil {
+ if err := taskcommon.UnmarshalMetadata(metadata, &r); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}
+ if sec, _ := strconv.Atoi(req.Seconds); sec > 0 {
+ r.Duration = lo.ToPtr(dto.IntValue(sec))
+ }
+
+ r.Content = lo.Reject(r.Content, func(c ContentItem, _ int) bool { return c.Type == "text" })
+ r.Content = append(r.Content, ContentItem{
+ Type: "text",
+ Text: req.Prompt,
+ })
+
return &r, nil
}
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
resTask := responseTask{}
- if err := json.Unmarshal(respBody, &resTask); err != nil {
+ if err := common.Unmarshal(respBody, &resTask); err != nil {
return nil, errors.Wrap(err, "unmarshal task result failed")
}
@@ -273,7 +331,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
case "failed":
taskResult.Status = model.TaskStatusFailure
taskResult.Progress = "100%"
- taskResult.Reason = "task failed"
+ taskResult.Reason = resTask.Error.Message
default:
// Unknown status, treat as processing
taskResult.Status = model.TaskStatusInProgress
@@ -285,7 +343,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
var dResp responseTask
- if err := json.Unmarshal(originTask.Data, &dResp); err != nil {
+ if err := common.Unmarshal(originTask.Data, &dResp); err != nil {
return nil, errors.Wrap(err, "unmarshal doubao task data failed")
}
@@ -301,11 +359,10 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, erro
if dResp.Status == "failed" {
openAIVideo.Error = &dto.OpenAIVideoError{
- Message: "task failed",
- Code: "failed",
+ Message: dResp.Error.Message,
+ Code: dResp.Error.Code,
}
}
- jsonData, _ := common.Marshal(openAIVideo)
- return jsonData, nil
+ return common.Marshal(openAIVideo)
}
diff --git a/relay/channel/task/doubao/constants.go b/relay/channel/task/doubao/constants.go
index 13b1b1d994..d65773d306 100644
--- a/relay/channel/task/doubao/constants.go
+++ b/relay/channel/task/doubao/constants.go
@@ -5,6 +5,21 @@ var ModelList = []string{
"doubao-seedance-1-0-lite-t2v",
"doubao-seedance-1-0-lite-i2v",
"doubao-seedance-1-5-pro-251215",
+ "doubao-seedance-2-0-260128",
+ "doubao-seedance-2-0-fast-260128",
}
var ChannelName = "doubao-video"
+
+// videoInputRatioMap 视频输入折扣比率(含视频单价 / 不含视频单价)。
+// 管理员应将 ModelRatio 设置为"不含视频"的较高费率,
+// 系统在检测到视频输入时自动乘以此折扣。
+var videoInputRatioMap = map[string]float64{
+ "doubao-seedance-2-0-260128": 28.0 / 46.0, // ~0.6087
+ "doubao-seedance-2-0-fast-260128": 22.0 / 37.0, // ~0.5946
+}
+
+func GetVideoInputRatio(modelName string) (float64, bool) {
+ r, ok := videoInputRatioMap[modelName]
+ return r, ok
+}
diff --git a/relay/channel/task/gemini/adaptor.go b/relay/channel/task/gemini/adaptor.go
index 16c6919b7c..48aa06319a 100644
--- a/relay/channel/task/gemini/adaptor.go
+++ b/relay/channel/task/gemini/adaptor.go
@@ -2,8 +2,6 @@ package gemini
import (
"bytes"
- "encoding/base64"
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -16,77 +14,20 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
- "github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
-// ============================
-// Request / Response structures
-// ============================
-
-// GeminiVideoGenerationConfig represents the video generation configuration
-// Based on: https://ai.google.dev/gemini-api/docs/video
-type GeminiVideoGenerationConfig struct {
- AspectRatio string `json:"aspectRatio,omitempty"` // "16:9" or "9:16"
- DurationSeconds float64 `json:"durationSeconds,omitempty"` // 4, 6, or 8 (as number)
- NegativePrompt string `json:"negativePrompt,omitempty"` // unwanted elements
- PersonGeneration string `json:"personGeneration,omitempty"` // "allow_all" for text-to-video, "allow_adult" for image-to-video
- Resolution string `json:"resolution,omitempty"` // video resolution
-}
-
-// GeminiVideoRequest represents a single video generation instance
-type GeminiVideoRequest struct {
- Prompt string `json:"prompt"`
-}
-
-// GeminiVideoPayload represents the complete video generation request payload
-type GeminiVideoPayload struct {
- Instances []GeminiVideoRequest `json:"instances"`
- Parameters GeminiVideoGenerationConfig `json:"parameters,omitempty"`
-}
-
-type submitResponse struct {
- Name string `json:"name"`
-}
-
-type operationVideo struct {
- MimeType string `json:"mimeType"`
- BytesBase64Encoded string `json:"bytesBase64Encoded"`
- Encoding string `json:"encoding"`
-}
-
-type operationResponse struct {
- Name string `json:"name"`
- Done bool `json:"done"`
- Response struct {
- Type string `json:"@type"`
- RaiMediaFilteredCount int `json:"raiMediaFilteredCount"`
- Videos []operationVideo `json:"videos"`
- BytesBase64Encoded string `json:"bytesBase64Encoded"`
- Encoding string `json:"encoding"`
- Video string `json:"video"`
- GenerateVideoResponse struct {
- GeneratedSamples []struct {
- Video struct {
- URI string `json:"uri"`
- } `json:"video"`
- } `json:"generatedSamples"`
- } `json:"generateVideoResponse"`
- } `json:"response"`
- Error struct {
- Message string `json:"message"`
- } `json:"error"`
-}
-
// ============================
// Adaptor implementation
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -100,13 +41,12 @@ func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
// ValidateRequestAndSetAction parses body, validates fields and sets default action.
func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
- // Use the standard validation method for TaskSubmitReq
return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionTextGenerate)
}
-// BuildRequestURL constructs the upstream URL.
+// BuildRequestURL constructs the Gemini API predictLongRunning endpoint for Veo.
func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
- modelName := info.OriginModelName
+ modelName := info.UpstreamModelName
version := model_setting.GetGeminiVersionSetting(modelName)
return fmt.Sprintf(
@@ -125,7 +65,7 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
return nil
}
-// BuildRequestBody converts request into Gemini specific format.
+// BuildRequestBody converts request into the Veo predictLongRunning format.
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
v, ok := c.Get("task_request")
if !ok {
@@ -136,25 +76,38 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
return nil, fmt.Errorf("unexpected task_request type")
}
- // Create structured video generation request
- body := GeminiVideoPayload{
- Instances: []GeminiVideoRequest{
- {Prompt: req.Prompt},
- },
- Parameters: GeminiVideoGenerationConfig{},
+ instance := VeoInstance{Prompt: req.Prompt}
+ if img := ExtractMultipartImage(c, info); img != nil {
+ instance.Image = img
+ } else if len(req.Images) > 0 {
+ if parsed := ParseImageInput(req.Images[0]); parsed != nil {
+ instance.Image = parsed
+ info.Action = constant.TaskActionGenerate
+ }
}
- metadata := req.Metadata
- medaBytes, err := json.Marshal(metadata)
- if err != nil {
- return nil, errors.Wrap(err, "metadata marshal metadata failed")
- }
- err = json.Unmarshal(medaBytes, &body.Parameters)
- if err != nil {
+ params := &VeoParameters{}
+ if err := taskcommon.UnmarshalMetadata(req.Metadata, params); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}
+ if params.DurationSeconds == 0 && req.Duration > 0 {
+ params.DurationSeconds = req.Duration
+ }
+ if params.Resolution == "" && req.Size != "" {
+ params.Resolution = SizeToVeoResolution(req.Size)
+ }
+ if params.AspectRatio == "" && req.Size != "" {
+ params.AspectRatio = SizeToVeoAspectRatio(req.Size)
+ }
+ params.Resolution = strings.ToLower(params.Resolution)
+ params.SampleCount = 1
- data, err := json.Marshal(body)
+ body := VeoRequestPayload{
+ Instances: []VeoInstance{instance},
+ Parameters: params,
+ }
+
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -175,16 +128,16 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
_ = resp.Body.Close()
var s submitResponse
- if err := json.Unmarshal(responseBody, &s); err != nil {
+ if err := common.Unmarshal(responseBody, &s); err != nil {
return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
}
if strings.TrimSpace(s.Name) == "" {
return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
}
- taskID = encodeLocalTaskID(s.Name)
+ taskID = taskcommon.EncodeLocalTaskID(s.Name)
ov := dto.NewOpenAIVideo()
- ov.ID = taskID
- ov.TaskID = taskID
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)
@@ -192,26 +145,51 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
func (a *TaskAdaptor) GetModelList() []string {
- return []string{"veo-3.0-generate-001", "veo-3.1-generate-preview", "veo-3.1-fast-generate-preview"}
+ return []string{
+ "veo-3.0-generate-001",
+ "veo-3.0-fast-generate-001",
+ "veo-3.1-generate-preview",
+ "veo-3.1-fast-generate-preview",
+ }
}
func (a *TaskAdaptor) GetChannelName() string {
return "gemini"
}
-// FetchTask fetch task status
+// EstimateBilling returns OtherRatios based on durationSeconds and resolution.
+func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
+ v, ok := c.Get("task_request")
+ if !ok {
+ return nil
+ }
+ req, ok := v.(relaycommon.TaskSubmitReq)
+ if !ok {
+ return nil
+ }
+
+ seconds := ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
+ resolution := ResolveVeoResolution(req.Metadata, req.Size)
+ resRatio := VeoResolutionRatio(info.UpstreamModelName, resolution)
+
+ return map[string]float64{
+ "seconds": float64(seconds),
+ "resolution": resRatio,
+ }
+}
+
+// FetchTask polls task status via the Gemini operations GET endpoint.
func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
taskID, ok := body["task_id"].(string)
if !ok {
return nil, fmt.Errorf("invalid task_id")
}
- upstreamName, err := decodeLocalTaskID(taskID)
+ upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
if err != nil {
return nil, fmt.Errorf("decode task_id failed: %w", err)
}
- // For Gemini API, we use GET request to the operations endpoint
version := model_setting.GetGeminiVersionSetting("default")
url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
@@ -232,7 +210,7 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
var op operationResponse
- if err := json.Unmarshal(respBody, &op); err != nil {
+ if err := common.Unmarshal(respBody, &op); err != nil {
return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
}
@@ -254,13 +232,10 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
ti.Status = model.TaskStatusSuccess
ti.Progress = "100%"
- taskID := encodeLocalTaskID(op.Name)
- ti.TaskID = taskID
- ti.Url = fmt.Sprintf("%s/v1/videos/%s/content", system_setting.ServerAddress, taskID)
+ ti.TaskID = taskcommon.EncodeLocalTaskID(op.Name)
- // Extract URL from generateVideoResponse if available
- if len(op.Response.GenerateVideoResponse.GeneratedSamples) > 0 {
- if uri := op.Response.GenerateVideoResponse.GeneratedSamples[0].Video.URI; uri != "" {
+ if len(op.Response.GenerateVideoResponse.GeneratedVideos) > 0 {
+ if uri := op.Response.GenerateVideoResponse.GeneratedVideos[0].Video.URI; uri != "" {
ti.RemoteUrl = uri
}
}
@@ -269,7 +244,8 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
}
func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
- upstreamName, err := decodeLocalTaskID(task.TaskID)
+ upstreamTaskID := task.GetUpstreamTaskID()
+ upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
if err != nil {
upstreamName = ""
}
@@ -297,18 +273,6 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
// helpers
// ============================
-func encodeLocalTaskID(name string) string {
- return base64.RawURLEncoding.EncodeToString([]byte(name))
-}
-
-func decodeLocalTaskID(local string) (string, error) {
- b, err := base64.RawURLEncoding.DecodeString(local)
- if err != nil {
- return "", err
- }
- return string(b), nil
-}
-
var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
func extractModelFromOperationName(name string) string {
diff --git a/relay/channel/task/gemini/billing.go b/relay/channel/task/gemini/billing.go
new file mode 100644
index 0000000000..b081eb2f62
--- /dev/null
+++ b/relay/channel/task/gemini/billing.go
@@ -0,0 +1,138 @@
+package gemini
+
+import (
+ "strconv"
+ "strings"
+)
+
+// ParseVeoDurationSeconds extracts durationSeconds from metadata.
+// Returns 8 (Veo default) when not specified or invalid.
+func ParseVeoDurationSeconds(metadata map[string]any) int {
+ if metadata == nil {
+ return 8
+ }
+ v, ok := metadata["durationSeconds"]
+ if !ok {
+ return 8
+ }
+ switch n := v.(type) {
+ case float64:
+ if int(n) > 0 {
+ return int(n)
+ }
+ case int:
+ if n > 0 {
+ return n
+ }
+ }
+ return 8
+}
+
+// ParseVeoResolution extracts resolution from metadata.
+// Returns "720p" when not specified.
+func ParseVeoResolution(metadata map[string]any) string {
+ if metadata == nil {
+ return "720p"
+ }
+ v, ok := metadata["resolution"]
+ if !ok {
+ return "720p"
+ }
+ if s, ok := v.(string); ok && s != "" {
+ return strings.ToLower(s)
+ }
+ return "720p"
+}
+
+// ResolveVeoDuration returns the effective duration in seconds.
+// Priority: metadata["durationSeconds"] > stdDuration > stdSeconds > default (8).
+func ResolveVeoDuration(metadata map[string]any, stdDuration int, stdSeconds string) int {
+ if metadata != nil {
+ if _, exists := metadata["durationSeconds"]; exists {
+ if d := ParseVeoDurationSeconds(metadata); d > 0 {
+ return d
+ }
+ }
+ }
+ if stdDuration > 0 {
+ return stdDuration
+ }
+ if s, err := strconv.Atoi(stdSeconds); err == nil && s > 0 {
+ return s
+ }
+ return 8
+}
+
+// ResolveVeoResolution returns the effective resolution string (lowercase).
+// Priority: metadata["resolution"] > SizeToVeoResolution(stdSize) > default ("720p").
+func ResolveVeoResolution(metadata map[string]any, stdSize string) string {
+ if metadata != nil {
+ if _, exists := metadata["resolution"]; exists {
+ if r := ParseVeoResolution(metadata); r != "" {
+ return r
+ }
+ }
+ }
+ if stdSize != "" {
+ return SizeToVeoResolution(stdSize)
+ }
+ return "720p"
+}
+
+// SizeToVeoResolution converts a "WxH" size string to a Veo resolution label.
+func SizeToVeoResolution(size string) string {
+ parts := strings.SplitN(strings.ToLower(size), "x", 2)
+ if len(parts) != 2 {
+ return "720p"
+ }
+ w, _ := strconv.Atoi(parts[0])
+ h, _ := strconv.Atoi(parts[1])
+ maxDim := w
+ if h > maxDim {
+ maxDim = h
+ }
+ if maxDim >= 3840 {
+ return "4k"
+ }
+ if maxDim >= 1920 {
+ return "1080p"
+ }
+ return "720p"
+}
+
+// SizeToVeoAspectRatio converts a "WxH" size string to a Veo aspect ratio.
+func SizeToVeoAspectRatio(size string) string {
+ parts := strings.SplitN(strings.ToLower(size), "x", 2)
+ if len(parts) != 2 {
+ return "16:9"
+ }
+ w, _ := strconv.Atoi(parts[0])
+ h, _ := strconv.Atoi(parts[1])
+ if w <= 0 || h <= 0 {
+ return "16:9"
+ }
+ if h > w {
+ return "9:16"
+ }
+ return "16:9"
+}
+
+// VeoResolutionRatio returns the pricing multiplier for the given resolution.
+// Standard resolutions (720p, 1080p) return 1.0.
+// 4K returns a model-specific multiplier based on Google's official pricing.
+func VeoResolutionRatio(modelName, resolution string) float64 {
+ if resolution != "4k" {
+ return 1.0
+ }
+ // 4K multipliers derived from Vertex AI official pricing (video+audio base):
+ // veo-3.1-generate: $0.60 / $0.40 = 1.5
+ // veo-3.1-fast-generate: $0.35 / $0.15 ≈ 2.333
+ // Veo 3.0 models do not support 4K; return 1.0 as fallback.
+ if strings.Contains(modelName, "3.1-fast-generate") {
+ return 2.333333
+ }
+ if strings.Contains(modelName, "3.1-generate") || strings.Contains(modelName, "3.1") {
+ return 1.5
+ }
+ return 1.0
+}
diff --git a/relay/channel/task/gemini/dto.go b/relay/channel/task/gemini/dto.go
new file mode 100644
index 0000000000..70a13feec4
--- /dev/null
+++ b/relay/channel/task/gemini/dto.go
@@ -0,0 +1,71 @@
+package gemini
+
+// VeoImageInput represents an image input for Veo image-to-video.
+// Used by both Gemini and Vertex adaptors.
+type VeoImageInput struct {
+ BytesBase64Encoded string `json:"bytesBase64Encoded"`
+ MimeType string `json:"mimeType"`
+}
+
+// VeoInstance represents a single instance in the Veo predictLongRunning request.
+type VeoInstance struct {
+ Prompt string `json:"prompt"`
+ Image *VeoImageInput `json:"image,omitempty"`
+ // TODO: support referenceImages (style/asset references, up to 3 images)
+ // TODO: support lastFrame (first+last frame interpolation, Veo 3.1)
+}
+
+// VeoParameters represents the parameters block for Veo predictLongRunning.
+type VeoParameters struct {
+ SampleCount int `json:"sampleCount"`
+ DurationSeconds int `json:"durationSeconds,omitempty"`
+ AspectRatio string `json:"aspectRatio,omitempty"`
+ Resolution string `json:"resolution,omitempty"`
+ NegativePrompt string `json:"negativePrompt,omitempty"`
+ PersonGeneration string `json:"personGeneration,omitempty"`
+ StorageUri string `json:"storageUri,omitempty"`
+ CompressionQuality string `json:"compressionQuality,omitempty"`
+ ResizeMode string `json:"resizeMode,omitempty"`
+ Seed *int `json:"seed,omitempty"`
+ GenerateAudio *bool `json:"generateAudio,omitempty"`
+}
+
+// VeoRequestPayload is the top-level request body for the Veo
+// predictLongRunning endpoint (used by both Gemini and Vertex).
+type VeoRequestPayload struct {
+ Instances []VeoInstance `json:"instances"`
+ Parameters *VeoParameters `json:"parameters,omitempty"`
+}
+
+type submitResponse struct {
+ Name string `json:"name"`
+}
+
+type operationVideo struct {
+ MimeType string `json:"mimeType"`
+ BytesBase64Encoded string `json:"bytesBase64Encoded"`
+ Encoding string `json:"encoding"`
+}
+
+type operationResponse struct {
+ Name string `json:"name"`
+ Done bool `json:"done"`
+ Response struct {
+ Type string `json:"@type"`
+ RaiMediaFilteredCount int `json:"raiMediaFilteredCount"`
+ Videos []operationVideo `json:"videos"`
+ BytesBase64Encoded string `json:"bytesBase64Encoded"`
+ Encoding string `json:"encoding"`
+ Video string `json:"video"`
+ GenerateVideoResponse struct {
+ GeneratedVideos []struct {
+ Video struct {
+ URI string `json:"uri"`
+ } `json:"video"`
+ } `json:"generatedVideos"`
+ } `json:"generateVideoResponse"`
+ } `json:"response"`
+ Error struct {
+ Message string `json:"message"`
+ } `json:"error"`
+}
diff --git a/relay/channel/task/gemini/image.go b/relay/channel/task/gemini/image.go
new file mode 100644
index 0000000000..da11b47212
--- /dev/null
+++ b/relay/channel/task/gemini/image.go
@@ -0,0 +1,100 @@
+package gemini
+
+import (
+ "encoding/base64"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/QuantumNous/new-api/constant"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/gin-gonic/gin"
+)
+
+const maxVeoImageSize = 20 * 1024 * 1024 // 20 MB
+
+// ExtractMultipartImage reads the first `input_reference` file from a multipart
+// form upload and returns a VeoImageInput. Returns nil if no file is present.
+func ExtractMultipartImage(c *gin.Context, info *relaycommon.RelayInfo) *VeoImageInput {
+ mf, err := c.MultipartForm()
+ if err != nil {
+ return nil
+ }
+ files, exists := mf.File["input_reference"]
+ if !exists || len(files) == 0 {
+ return nil
+ }
+ fh := files[0]
+ if fh.Size > maxVeoImageSize {
+ return nil
+ }
+ file, err := fh.Open()
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+
+ fileBytes, err := io.ReadAll(file)
+ if err != nil {
+ return nil
+ }
+
+ mimeType := fh.Header.Get("Content-Type")
+ if mimeType == "" || mimeType == "application/octet-stream" {
+ mimeType = http.DetectContentType(fileBytes)
+ }
+
+ info.Action = constant.TaskActionGenerate
+ return &VeoImageInput{
+ BytesBase64Encoded: base64.StdEncoding.EncodeToString(fileBytes),
+ MimeType: mimeType,
+ }
+}
+
+// ParseImageInput parses an image string (data URI or raw base64) into a
+// VeoImageInput. Returns nil if the input is empty or invalid.
+// TODO: support downloading HTTP URL images and converting to base64
+func ParseImageInput(imageStr string) *VeoImageInput {
+ imageStr = strings.TrimSpace(imageStr)
+ if imageStr == "" {
+ return nil
+ }
+
+ if strings.HasPrefix(imageStr, "data:") {
+ return parseDataURI(imageStr)
+ }
+
+ raw, err := base64.StdEncoding.DecodeString(imageStr)
+ if err != nil {
+ return nil
+ }
+ return &VeoImageInput{
+ BytesBase64Encoded: imageStr,
+ MimeType: http.DetectContentType(raw),
+ }
+}
+
+func parseDataURI(uri string) *VeoImageInput {
+ // data:image/png;base64,iVBOR...
+ rest := uri[len("data:"):]
+ idx := strings.Index(rest, ",")
+ if idx < 0 {
+ return nil
+ }
+ meta := rest[:idx]
+ b64 := rest[idx+1:]
+ if b64 == "" {
+ return nil
+ }
+
+ mimeType := "application/octet-stream"
+ parts := strings.SplitN(meta, ";", 2)
+ if len(parts) >= 1 && parts[0] != "" {
+ mimeType = parts[0]
+ }
+
+ return &VeoImageInput{
+ BytesBase64Encoded: b64,
+ MimeType: mimeType,
+ }
+}
diff --git a/relay/channel/task/hailuo/adaptor.go b/relay/channel/task/hailuo/adaptor.go
index c77905bfb2..28b3a97f19 100644
--- a/relay/channel/task/hailuo/adaptor.go
+++ b/relay/channel/task/hailuo/adaptor.go
@@ -2,7 +2,6 @@ package hailuo
import (
"bytes"
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -18,12 +17,14 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
)
// https://platform.minimaxi.com/docs/api-reference/video-generation-intro
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -60,12 +61,12 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
return nil, fmt.Errorf("invalid request type in context")
}
- body, err := a.convertToRequestPayload(&req)
+ body, err := a.convertToRequestPayload(&req, info)
if err != nil {
return nil, errors.Wrap(err, "convert request payload failed")
}
- data, err := json.Marshal(body)
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -86,7 +87,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
_ = resp.Body.Close()
var hResp VideoResponse
- if err := json.Unmarshal(responseBody, &hResp); err != nil {
+ if err := common.Unmarshal(responseBody, &hResp); err != nil {
taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
return
}
@@ -101,8 +102,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
ov := dto.NewOpenAIVideo()
- ov.ID = hResp.TaskID
- ov.TaskID = hResp.TaskID
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
@@ -141,8 +142,8 @@ func (a *TaskAdaptor) GetChannelName() string {
return ChannelName
}
-func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*VideoRequest, error) {
- modelConfig := GetModelConfig(req.Model)
+func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq, info *relaycommon.RelayInfo) (*VideoRequest, error) {
+ modelConfig := GetModelConfig(info.UpstreamModelName)
duration := DefaultDuration
if req.Duration > 0 {
duration = req.Duration
@@ -153,7 +154,7 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
}
videoRequest := &VideoRequest{
- Model: req.Model,
+ Model: info.UpstreamModelName,
Prompt: req.Prompt,
Duration: &duration,
Resolution: resolution,
@@ -182,7 +183,7 @@ func (a *TaskAdaptor) parseResolutionFromSize(size string, modelConfig ModelConf
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
resTask := QueryTaskResponse{}
- if err := json.Unmarshal(respBody, &resTask); err != nil {
+ if err := common.Unmarshal(respBody, &resTask); err != nil {
return nil, errors.Wrap(err, "unmarshal task result failed")
}
@@ -224,7 +225,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
var hailuoResp QueryTaskResponse
- if err := json.Unmarshal(originTask.Data, &hailuoResp); err != nil {
+ if err := common.Unmarshal(originTask.Data, &hailuoResp); err != nil {
return nil, errors.Wrap(err, "unmarshal hailuo task data failed")
}
@@ -271,7 +272,7 @@ func (a *TaskAdaptor) buildVideoURL(_, fileID string) string {
}
var retrieveResp RetrieveFileResponse
- if err := json.Unmarshal(responseBody, &retrieveResp); err != nil {
+ if err := common.Unmarshal(responseBody, &retrieveResp); err != nil {
return ""
}
diff --git a/relay/channel/task/jimeng/adaptor.go b/relay/channel/task/jimeng/adaptor.go
index 1522a967f8..e6211b1e4f 100644
--- a/relay/channel/task/jimeng/adaptor.go
+++ b/relay/channel/task/jimeng/adaptor.go
@@ -6,7 +6,6 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -25,6 +24,7 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
)
@@ -77,6 +77,7 @@ const (
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
accessKey string
secretKey string
@@ -164,11 +165,11 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
}
}
- body, err := a.convertToRequestPayload(&req)
+ body, err := a.convertToRequestPayload(&req, info)
if err != nil {
return nil, errors.Wrap(err, "convert request payload failed")
}
- data, err := json.Marshal(body)
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -191,7 +192,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
// Parse Jimeng response
var jResp responsePayload
- if err := json.Unmarshal(responseBody, &jResp); err != nil {
+ if err := common.Unmarshal(responseBody, &jResp); err != nil {
taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
return
}
@@ -202,8 +203,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
ov := dto.NewOpenAIVideo()
- ov.ID = jResp.Data.TaskID
- ov.TaskID = jResp.Data.TaskID
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)
@@ -225,7 +226,7 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
"req_key": "jimeng_vgfm_t2v_l20", // This is fixed value from doc: https://www.volcengine.com/docs/85621/1544774
"task_id": taskID,
}
- payloadBytes, err := json.Marshal(payload)
+ payloadBytes, err := common.Marshal(payload)
if err != nil {
return nil, errors.Wrap(err, "marshal fetch task payload failed")
}
@@ -377,9 +378,9 @@ func hmacSHA256(key []byte, data []byte) []byte {
return h.Sum(nil)
}
-func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
+func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq, info *relaycommon.RelayInfo) (*requestPayload, error) {
r := requestPayload{
- ReqKey: req.Model,
+ ReqKey: info.UpstreamModelName,
Prompt: req.Prompt,
}
@@ -398,13 +399,7 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
r.BinaryDataBase64 = req.Images
}
}
- metadata := req.Metadata
- medaBytes, err := json.Marshal(metadata)
- if err != nil {
- return nil, errors.Wrap(err, "metadata marshal metadata failed")
- }
- err = json.Unmarshal(medaBytes, &r)
- if err != nil {
+ if err := taskcommon.UnmarshalMetadata(req.Metadata, &r); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}
@@ -432,7 +427,7 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
resTask := responseTask{}
- if err := json.Unmarshal(respBody, &resTask); err != nil {
+ if err := common.Unmarshal(respBody, &resTask); err != nil {
return nil, errors.Wrap(err, "unmarshal task result failed")
}
taskResult := relaycommon.TaskInfo{}
@@ -458,7 +453,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
var jimengResp responseTask
- if err := json.Unmarshal(originTask.Data, &jimengResp); err != nil {
+ if err := common.Unmarshal(originTask.Data, &jimengResp); err != nil {
return nil, errors.Wrap(err, "unmarshal jimeng task data failed")
}
@@ -477,8 +472,7 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, erro
}
}
- jsonData, _ := common.Marshal(openAIVideo)
- return jsonData, nil
+ return common.Marshal(openAIVideo)
}
func isNewAPIRelay(apiKey string) bool {
diff --git a/relay/channel/task/kling/adaptor.go b/relay/channel/task/kling/adaptor.go
index 5fb8534815..413ade04d0 100644
--- a/relay/channel/task/kling/adaptor.go
+++ b/relay/channel/task/kling/adaptor.go
@@ -2,10 +2,11 @@ package kling
import (
"bytes"
- "encoding/json"
"fmt"
"io"
+ "math"
"net/http"
+ "strconv"
"strings"
"time"
@@ -21,6 +22,7 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
)
@@ -80,15 +82,28 @@ type responsePayload struct {
TaskId string `json:"task_id"`
TaskStatus string `json:"task_status"`
TaskStatusMsg string `json:"task_status_msg"`
- TaskResult struct {
+ TaskInfo struct {
+ ExternalTaskId string `json:"external_task_id"`
+ } `json:"task_info"`
+ WatermarkInfo struct {
+ Enabled bool `json:"enabled"`
+ } `json:"watermark_info"`
+ TaskResult struct {
Videos []struct {
- Id string `json:"id"`
- Url string `json:"url"`
- Duration string `json:"duration"`
+ Id string `json:"id"`
+ Url string `json:"url"`
+ WatermarkUrl string `json:"watermark_url"`
+ Duration string `json:"duration"`
} `json:"videos"`
+ Images []struct {
+ Index int `json:"index"`
+ Url string `json:"url"`
+ WatermarkUrl string `json:"watermark_url"`
+ } `json:"images"`
} `json:"task_result"`
- CreatedAt int64 `json:"created_at"`
- UpdatedAt int64 `json:"updated_at"`
+ CreatedAt int64 `json:"created_at"`
+ UpdatedAt int64 `json:"updated_at"`
+ FinalUnitDeduction string `json:"final_unit_deduction"`
} `json:"data"`
}
@@ -97,6 +112,7 @@ type responsePayload struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -149,14 +165,14 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
}
req := v.(relaycommon.TaskSubmitReq)
- body, err := a.convertToRequestPayload(&req)
+ body, err := a.convertToRequestPayload(&req, info)
if err != nil {
return nil, err
}
if body.Image == "" && body.ImageTail == "" {
c.Set("action", constant.TaskActionTextGenerate)
}
- data, err := json.Marshal(body)
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -180,7 +196,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
var kResp responsePayload
- err = json.Unmarshal(responseBody, &kResp)
+ err = common.Unmarshal(responseBody, &kResp)
if err != nil {
taskErr = service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
return
@@ -190,8 +206,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
return
}
ov := dto.NewOpenAIVideo()
- ov.ID = kResp.Data.TaskId
- ov.TaskID = kResp.Data.TaskId
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)
@@ -247,15 +263,15 @@ func (a *TaskAdaptor) GetChannelName() string {
// helpers
// ============================
-func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
+func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq, info *relaycommon.RelayInfo) (*requestPayload, error) {
r := requestPayload{
Prompt: req.Prompt,
Image: req.Image,
- Mode: defaultString(req.Mode, "std"),
- Duration: fmt.Sprintf("%d", defaultInt(req.Duration, 5)),
+ Mode: taskcommon.DefaultString(req.Mode, "std"),
+ Duration: fmt.Sprintf("%d", taskcommon.DefaultInt(req.Duration, 5)),
AspectRatio: a.getAspectRatio(req.Size),
- ModelName: req.Model,
- Model: req.Model, // Keep consistent with model_name, double writing improves compatibility
+ ModelName: info.UpstreamModelName,
+ Model: info.UpstreamModelName,
CfgScale: 0.5,
StaticMask: "",
DynamicMasks: []DynamicMask{},
@@ -265,14 +281,9 @@ func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*
}
if r.ModelName == "" {
r.ModelName = "kling-v1"
+ r.Model = "kling-v1"
}
- metadata := req.Metadata
- medaBytes, err := json.Marshal(metadata)
- if err != nil {
- return nil, errors.Wrap(err, "metadata marshal metadata failed")
- }
- err = json.Unmarshal(medaBytes, &r)
- if err != nil {
+ if err := taskcommon.UnmarshalMetadata(req.Metadata, &r); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}
return &r, nil
@@ -291,20 +302,6 @@ func (a *TaskAdaptor) getAspectRatio(size string) string {
}
}
-func defaultString(s, def string) string {
- if strings.TrimSpace(s) == "" {
- return def
- }
- return s
-}
-
-func defaultInt(v int, def int) int {
- if v == 0 {
- return def
- }
- return v
-}
-
// ============================
// JWT helpers
// ============================
@@ -340,7 +337,7 @@ func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
taskInfo := &relaycommon.TaskInfo{}
resPayload := responsePayload{}
- err := json.Unmarshal(respBody, &resPayload)
+ err := common.Unmarshal(respBody, &resPayload)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal response body")
}
@@ -356,15 +353,22 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
taskInfo.Status = model.TaskStatusInProgress
case "succeed":
taskInfo.Status = model.TaskStatusSuccess
+ if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
+ video := videos[0]
+ taskInfo.Url = video.Url
+ }
+ if tokens, err := strconv.ParseFloat(resPayload.Data.FinalUnitDeduction, 64); err == nil {
+ rounded := int(math.Ceil(tokens))
+ if rounded > 0 {
+ taskInfo.CompletionTokens = rounded
+ taskInfo.TotalTokens = rounded
+ }
+ }
case "failed":
taskInfo.Status = model.TaskStatusFailure
default:
return nil, fmt.Errorf("unknown task status: %s", status)
}
- if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
- video := videos[0]
- taskInfo.Url = video.Url
- }
return taskInfo, nil
}
@@ -374,7 +378,7 @@ func isNewAPIRelay(apiKey string) bool {
func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
var klingResp responsePayload
- if err := json.Unmarshal(originTask.Data, &klingResp); err != nil {
+ if err := common.Unmarshal(originTask.Data, &klingResp); err != nil {
return nil, errors.Wrap(err, "unmarshal kling task data failed")
}
@@ -401,6 +405,12 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, erro
Code: fmt.Sprintf("%d", klingResp.Code),
}
}
- jsonData, _ := common.Marshal(openAIVideo)
- return jsonData, nil
+
+ // https://app.klingai.com/cn/dev/document-api/apiReference/model/textToVideo
+ if data := klingResp.Data; data.TaskStatus == "failed" {
+ openAIVideo.Error = &dto.OpenAIVideoError{
+ Message: data.TaskStatusMsg,
+ }
+ }
+ return common.Marshal(openAIVideo)
}
diff --git a/relay/channel/task/sora/adaptor.go b/relay/channel/task/sora/adaptor.go
index 9dc03796c9..e9029aa20d 100644
--- a/relay/channel/task/sora/adaptor.go
+++ b/relay/channel/task/sora/adaptor.go
@@ -4,7 +4,10 @@ import (
"bytes"
"fmt"
"io"
+ "mime/multipart"
"net/http"
+ "net/textproto"
+ "strconv"
"strings"
"github.com/QuantumNous/new-api/common"
@@ -12,12 +15,13 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
- "github.com/QuantumNous/new-api/setting/system_setting"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
+ "github.com/tidwall/sjson"
)
// ============================
@@ -58,6 +62,7 @@ type responseTask struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -70,15 +75,15 @@ func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
}
func validateRemixRequest(c *gin.Context) *dto.TaskError {
- var req struct {
- Prompt string `json:"prompt"`
- }
+ var req relaycommon.TaskSubmitReq
if err := common.UnmarshalBodyReusable(c, &req); err != nil {
return service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
}
if strings.TrimSpace(req.Prompt) == "" {
return service.TaskErrorWrapperLocal(fmt.Errorf("field prompt is required"), "invalid_request", http.StatusBadRequest)
}
+ // 存储原始请求到 context,与 ValidateMultipartDirect 路径保持一致
+ c.Set("task_request", req)
return nil
}
@@ -89,6 +94,41 @@ func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycom
return relaycommon.ValidateMultipartDirect(c, info)
}
+// EstimateBilling 根据用户请求的 seconds 和 size 计算 OtherRatios。
+func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
+ // remix 路径的 OtherRatios 已在 ResolveOriginTask 中设置
+ if info.Action == constant.TaskActionRemix {
+ return nil
+ }
+
+ req, err := relaycommon.GetTaskRequest(c)
+ if err != nil {
+ return nil
+ }
+
+ seconds, _ := strconv.Atoi(req.Seconds)
+ if seconds == 0 {
+ seconds = req.Duration
+ }
+ if seconds <= 0 {
+ seconds = 4
+ }
+
+ size := req.Size
+ if size == "" {
+ size = "720x1280"
+ }
+
+ ratios := map[string]float64{
+ "seconds": float64(seconds),
+ "size": 1,
+ }
+ if size == "1792x1024" || size == "1024x1792" {
+ ratios["size"] = 1.666667
+ }
+ return ratios
+}
+
func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
if info.Action == constant.TaskActionRemix {
return fmt.Sprintf("%s/v1/videos/%s/remix", a.baseURL, info.OriginTaskID), nil
@@ -104,11 +144,79 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
}
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
- cachedBody, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return nil, errors.Wrap(err, "get_request_body_failed")
}
- return bytes.NewReader(cachedBody), nil
+ cachedBody, err := storage.Bytes()
+ if err != nil {
+ return nil, errors.Wrap(err, "read_body_bytes_failed")
+ }
+ contentType := c.GetHeader("Content-Type")
+
+ if strings.HasPrefix(contentType, "application/json") {
+ var bodyMap map[string]interface{}
+ if err := common.Unmarshal(cachedBody, &bodyMap); err == nil {
+ bodyMap["model"] = info.UpstreamModelName
+ if newBody, err := common.Marshal(bodyMap); err == nil {
+ return bytes.NewReader(newBody), nil
+ }
+ }
+ return bytes.NewReader(cachedBody), nil
+ }
+
+ if strings.Contains(contentType, "multipart/form-data") {
+ formData, err := common.ParseMultipartFormReusable(c)
+ if err != nil {
+ return bytes.NewReader(cachedBody), nil
+ }
+ var buf bytes.Buffer
+ writer := multipart.NewWriter(&buf)
+ writer.WriteField("model", info.UpstreamModelName)
+ for key, values := range formData.Value {
+ if key == "model" {
+ continue
+ }
+ for _, v := range values {
+ writer.WriteField(key, v)
+ }
+ }
+ for fieldName, fileHeaders := range formData.File {
+ for _, fh := range fileHeaders {
+ f, err := fh.Open()
+ if err != nil {
+ continue
+ }
+ ct := fh.Header.Get("Content-Type")
+ if ct == "" || ct == "application/octet-stream" {
+ buf512 := make([]byte, 512)
+ n, _ := io.ReadFull(f, buf512)
+ ct = http.DetectContentType(buf512[:n])
+ // Re-open after sniffing so the full content is copied below
+ f.Close()
+ f, err = fh.Open()
+ if err != nil {
+ continue
+ }
+ }
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fh.Filename))
+ h.Set("Content-Type", ct)
+ part, err := writer.CreatePart(h)
+ if err != nil {
+ f.Close()
+ continue
+ }
+ io.Copy(part, f)
+ f.Close()
+ }
+ }
+ writer.Close()
+ c.Request.Header.Set("Content-Type", writer.FormDataContentType())
+ return &buf, nil
+ }
+
+ return common.ReaderOnly(storage), nil
}
// DoRequest delegates to common helper.
@@ -117,7 +225,7 @@ func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, req
}
// DoResponse handles upstream response, returns taskID etc.
-func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, _ *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
+func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
@@ -132,17 +240,20 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, _ *relayco
return
}
- if dResp.ID == "" {
- if dResp.TaskID == "" {
- taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
- return
- }
- dResp.ID = dResp.TaskID
- dResp.TaskID = ""
+ upstreamID := dResp.ID
+ if upstreamID == "" {
+ upstreamID = dResp.TaskID
+ }
+ if upstreamID == "" {
+ taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
+ return
}
+ // 使用公开 task_xxxx ID 返回给客户端
+ dResp.ID = info.PublicTaskID
+ dResp.TaskID = info.PublicTaskID
c.JSON(http.StatusOK, dResp)
- return dResp.ID, responseBody, nil
+ return upstreamID, responseBody, nil
}
// FetchTask fetch task status
@@ -193,7 +304,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
taskResult.Status = model.TaskStatusInProgress
case "completed":
taskResult.Status = model.TaskStatusSuccess
- taskResult.Url = fmt.Sprintf("%s/v1/videos/%s/content", system_setting.ServerAddress, resTask.ID)
+ // Url intentionally left empty — the caller constructs the proxy URL using the public task ID
case "failed", "cancelled":
taskResult.Status = model.TaskStatusFailure
if resTask.Error != nil {
@@ -211,5 +322,10 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
}
func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
- return task.Data, nil
+ data := task.Data
+ var err error
+ if data, err = sjson.SetBytes(data, "id", task.TaskID); err != nil {
+ return nil, errors.Wrap(err, "set id failed")
+ }
+ return data, nil
}
diff --git a/relay/channel/task/suno/adaptor.go b/relay/channel/task/suno/adaptor.go
index 8ea9a1c7fe..35b5e423b7 100644
--- a/relay/channel/task/suno/adaptor.go
+++ b/relay/channel/task/suno/adaptor.go
@@ -2,18 +2,16 @@ package suno
import (
"bytes"
- "context"
- "encoding/json"
"fmt"
"io"
"net/http"
"strings"
- "time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
@@ -21,11 +19,16 @@ import (
)
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
}
+// ParseTaskResult is not used for Suno tasks.
+// Suno polling uses a dedicated batch-fetch path (service.UpdateSunoTasks) that
+// receives dto.TaskResponse[[]dto.SunoDataResponse] from the upstream /fetch API.
+// This differs from the per-task polling used by video adaptors.
func (a *TaskAdaptor) ParseTaskResult([]byte) (*relaycommon.TaskInfo, error) {
- return nil, fmt.Errorf("not implement") // todo implement this method if needed
+ return nil, fmt.Errorf("suno uses batch polling via UpdateSunoTasks, ParseTaskResult is not applicable")
}
func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
@@ -47,13 +50,13 @@ func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycom
return
}
- if sunoRequest.ContinueClipId != "" {
- if sunoRequest.TaskID == "" {
- taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("task id is empty"), "invalid_request", http.StatusBadRequest)
- return
- }
- info.OriginTaskID = sunoRequest.TaskID
- }
+ //if sunoRequest.ContinueClipId != "" {
+ // if sunoRequest.TaskID == "" {
+ // taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("task id is empty"), "invalid_request", http.StatusBadRequest)
+ // return
+ // }
+ // info.OriginTaskID = sunoRequest.TaskID
+ //}
info.Action = action
c.Set("task_request", sunoRequest)
@@ -76,12 +79,9 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
sunoRequest, ok := c.Get("task_request")
if !ok {
- err := common.UnmarshalBodyReusable(c, &sunoRequest)
- if err != nil {
- return nil, err
- }
+ return nil, fmt.Errorf("task_request not found in context")
}
- data, err := json.Marshal(sunoRequest)
+ data, err := common.Marshal(sunoRequest)
if err != nil {
return nil, err
}
@@ -99,7 +99,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
return
}
var sunoResponse dto.TaskResponse[string]
- err = json.Unmarshal(responseBody, &sunoResponse)
+ err = common.Unmarshal(responseBody, &sunoResponse)
if err != nil {
taskErr = service.TaskErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError)
return
@@ -109,17 +109,13 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
return
}
- for k, v := range resp.Header {
- c.Writer.Header().Set(k, v[0])
- }
- c.Writer.Header().Set("Content-Type", "application/json")
- c.Writer.WriteHeader(resp.StatusCode)
-
- _, err = io.Copy(c.Writer, bytes.NewBuffer(responseBody))
- if err != nil {
- taskErr = service.TaskErrorWrapper(err, "copy_response_body_failed", http.StatusInternalServerError)
- return
+ // 使用公开 task_xxxx ID 替换上游 ID 返回给客户端
+ publicResponse := dto.TaskResponse[string]{
+ Code: sunoResponse.Code,
+ Message: sunoResponse.Message,
+ Data: info.PublicTaskID,
}
+ c.JSON(http.StatusOK, publicResponse)
return sunoResponse.Data, nil, nil
}
@@ -134,7 +130,7 @@ func (a *TaskAdaptor) GetChannelName() string {
func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
requestUrl := fmt.Sprintf("%s/suno/fetch", baseUrl)
- byteBody, err := json.Marshal(body)
+ byteBody, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -144,13 +140,6 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
common.SysLog(fmt.Sprintf("Get Task error: %v", err))
return nil, err
}
- defer req.Body.Close()
- // 设置超时时间
- timeout := time.Second * 15
- ctx, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
- // 使用带有超时的 context 创建新的请求
- req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+key)
client, err := service.GetHttpClientWithProxy(proxy)
diff --git a/relay/channel/task/taskcommon/helpers.go b/relay/channel/task/taskcommon/helpers.go
new file mode 100644
index 0000000000..7d1820c9de
--- /dev/null
+++ b/relay/channel/task/taskcommon/helpers.go
@@ -0,0 +1,97 @@
+package taskcommon
+
+import (
+ "encoding/base64"
+ "fmt"
+
+ "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/setting/system_setting"
+ "github.com/gin-gonic/gin"
+)
+
+// UnmarshalMetadata converts a map[string]any metadata to a typed struct via JSON round-trip.
+// This replaces the repeated pattern: json.Marshal(metadata) → json.Unmarshal(bytes, &target).
+func UnmarshalMetadata(metadata map[string]any, target any) error {
+ if metadata == nil {
+ return nil
+ }
+ // Prevent metadata from overriding model fields to avoid billing bypass.
+ delete(metadata, "model")
+ metaBytes, err := common.Marshal(metadata)
+ if err != nil {
+ return fmt.Errorf("marshal metadata failed: %w", err)
+ }
+ if err := common.Unmarshal(metaBytes, target); err != nil {
+ return fmt.Errorf("unmarshal metadata failed: %w", err)
+ }
+ return nil
+}
+
+// DefaultString returns val if non-empty, otherwise fallback.
+func DefaultString(val, fallback string) string {
+ if val == "" {
+ return fallback
+ }
+ return val
+}
+
+// DefaultInt returns val if non-zero, otherwise fallback.
+func DefaultInt(val, fallback int) int {
+ if val == 0 {
+ return fallback
+ }
+ return val
+}
+
+// EncodeLocalTaskID encodes an upstream operation name to a URL-safe base64 string.
+// Used by Gemini/Vertex to store upstream names as task IDs.
+func EncodeLocalTaskID(name string) string {
+ return base64.RawURLEncoding.EncodeToString([]byte(name))
+}
+
+// DecodeLocalTaskID decodes a base64-encoded upstream operation name.
+func DecodeLocalTaskID(id string) (string, error) {
+ b, err := base64.RawURLEncoding.DecodeString(id)
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
+}
+
+// BuildProxyURL constructs the video proxy URL using the public task ID.
+// e.g., "https://your-server.com/v1/videos/task_xxxx/content"
+func BuildProxyURL(taskID string) string {
+ return fmt.Sprintf("%s/v1/videos/%s/content", system_setting.ServerAddress, taskID)
+}
+
+// Status-to-progress mapping constants for polling updates.
+const (
+ ProgressSubmitted = "10%"
+ ProgressQueued = "20%"
+ ProgressInProgress = "30%"
+ ProgressComplete = "100%"
+)
+
+// ---------------------------------------------------------------------------
+// BaseBilling — embeddable no-op implementations for TaskAdaptor billing methods.
+// Adaptors that do not need custom billing can embed this struct directly.
+// ---------------------------------------------------------------------------
+
+type BaseBilling struct{}
+
+// EstimateBilling returns nil (no extra ratios; use base model price).
+func (BaseBilling) EstimateBilling(_ *gin.Context, _ *relaycommon.RelayInfo) map[string]float64 {
+ return nil
+}
+
+// AdjustBillingOnSubmit returns nil (no submit-time adjustment).
+func (BaseBilling) AdjustBillingOnSubmit(_ *relaycommon.RelayInfo, _ []byte) map[string]float64 {
+ return nil
+}
+
+// AdjustBillingOnComplete returns 0 (keep pre-charged amount).
+func (BaseBilling) AdjustBillingOnComplete(_ *model.Task, _ *relaycommon.TaskInfo) int {
+ return 0
+}
diff --git a/relay/channel/task/vertex/adaptor.go b/relay/channel/task/vertex/adaptor.go
index 8ec77266e9..b76364ee98 100644
--- a/relay/channel/task/vertex/adaptor.go
+++ b/relay/channel/task/vertex/adaptor.go
@@ -2,13 +2,12 @@ package vertex
import (
"bytes"
- "encoding/base64"
- "encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strings"
+ "time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
@@ -17,6 +16,8 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel"
+ geminitask "github.com/QuantumNous/new-api/relay/channel/task/gemini"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
vertexcore "github.com/QuantumNous/new-api/relay/channel/vertex"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
@@ -26,9 +27,8 @@ import (
// Request / Response structures
// ============================
-type requestPayload struct {
- Instances []map[string]any `json:"instances"`
- Parameters map[string]any `json:"parameters,omitempty"`
+type fetchOperationPayload struct {
+ OperationName string `json:"operationName"`
}
type submitResponse struct {
@@ -62,6 +62,7 @@ type operationResponse struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
apiKey string
baseURL string
@@ -82,10 +83,10 @@ func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycom
// BuildRequestURL constructs the upstream URL.
func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
adc := &vertexcore.Credentials{}
- if err := json.Unmarshal([]byte(a.apiKey), adc); err != nil {
+ if err := common.Unmarshal([]byte(a.apiKey), adc); err != nil {
return "", fmt.Errorf("failed to decode credentials: %w", err)
}
- modelName := info.OriginModelName
+ modelName := info.UpstreamModelName
if modelName == "" {
modelName = "veo-3.0-generate-001"
}
@@ -116,7 +117,7 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
req.Header.Set("Accept", "application/json")
adc := &vertexcore.Credentials{}
- if err := json.Unmarshal([]byte(a.apiKey), adc); err != nil {
+ if err := common.Unmarshal([]byte(a.apiKey), adc); err != nil {
return fmt.Errorf("failed to decode credentials: %w", err)
}
@@ -133,6 +134,24 @@ func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info
return nil
}
+// EstimateBilling returns OtherRatios based on durationSeconds and resolution.
+func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
+ v, ok := c.Get("task_request")
+ if !ok {
+ return nil
+ }
+ req := v.(relaycommon.TaskSubmitReq)
+
+ seconds := geminitask.ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
+ resolution := geminitask.ResolveVeoResolution(req.Metadata, req.Size)
+ resRatio := geminitask.VeoResolutionRatio(info.UpstreamModelName, resolution)
+
+ return map[string]float64{
+ "seconds": float64(seconds),
+ "resolution": resRatio,
+ }
+}
+
// BuildRequestBody converts request into Vertex specific format.
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
v, ok := c.Get("task_request")
@@ -141,50 +160,38 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
}
req := v.(relaycommon.TaskSubmitReq)
- body := requestPayload{
- Instances: []map[string]any{{"prompt": req.Prompt}},
- Parameters: map[string]any{},
- }
- if req.Metadata != nil {
- if v, ok := req.Metadata["storageUri"]; ok {
- body.Parameters["storageUri"] = v
- }
- if v, ok := req.Metadata["sampleCount"]; ok {
- if i, ok := v.(int); ok {
- body.Parameters["sampleCount"] = i
- }
- if f, ok := v.(float64); ok {
- body.Parameters["sampleCount"] = int(f)
- }
+ instance := geminitask.VeoInstance{Prompt: req.Prompt}
+ if img := geminitask.ExtractMultipartImage(c, info); img != nil {
+ instance.Image = img
+ } else if len(req.Images) > 0 {
+ if parsed := geminitask.ParseImageInput(req.Images[0]); parsed != nil {
+ instance.Image = parsed
+ info.Action = constant.TaskActionGenerate
}
}
- if _, ok := body.Parameters["sampleCount"]; !ok {
- body.Parameters["sampleCount"] = 1
+
+ params := &geminitask.VeoParameters{}
+ if err := taskcommon.UnmarshalMetadata(req.Metadata, params); err != nil {
+ return nil, fmt.Errorf("unmarshal metadata failed: %w", err)
+ }
+ if params.DurationSeconds == 0 && req.Duration > 0 {
+ params.DurationSeconds = req.Duration
+ }
+ if params.Resolution == "" && req.Size != "" {
+ params.Resolution = geminitask.SizeToVeoResolution(req.Size)
+ }
+ if params.AspectRatio == "" && req.Size != "" {
+ params.AspectRatio = geminitask.SizeToVeoAspectRatio(req.Size)
+ }
+ params.Resolution = strings.ToLower(params.Resolution)
+ params.SampleCount = 1
+
+ body := geminitask.VeoRequestPayload{
+ Instances: []geminitask.VeoInstance{instance},
+ Parameters: params,
}
- if body.Parameters["sampleCount"].(int) <= 0 {
- return nil, fmt.Errorf("sampleCount must be greater than 0")
- }
-
- // if req.Duration > 0 {
- // body.Parameters["durationSeconds"] = req.Duration
- // } else if req.Seconds != "" {
- // seconds, err := strconv.Atoi(req.Seconds)
- // if err != nil {
- // return nil, errors.Wrap(err, "convert seconds to int failed")
- // }
- // body.Parameters["durationSeconds"] = seconds
- // }
-
- info.PriceData.OtherRatios = map[string]float64{
- "sampleCount": float64(body.Parameters["sampleCount"].(int)),
- }
-
- // if v, ok := body.Parameters["durationSeconds"]; ok {
- // info.PriceData.OtherRatios["durationSeconds"] = float64(v.(int))
- // }
-
- data, err := json.Marshal(body)
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -205,18 +212,30 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
_ = resp.Body.Close()
var s submitResponse
- if err := json.Unmarshal(responseBody, &s); err != nil {
+ if err := common.Unmarshal(responseBody, &s); err != nil {
return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
}
if strings.TrimSpace(s.Name) == "" {
return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
}
- localID := encodeLocalTaskID(s.Name)
- c.JSON(http.StatusOK, gin.H{"task_id": localID})
+ localID := taskcommon.EncodeLocalTaskID(s.Name)
+ ov := dto.NewOpenAIVideo()
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
+ ov.CreatedAt = time.Now().Unix()
+ ov.Model = info.OriginModelName
+ c.JSON(http.StatusOK, ov)
return localID, responseBody, nil
}
-func (a *TaskAdaptor) GetModelList() []string { return []string{"veo-3.0-generate-001"} }
+func (a *TaskAdaptor) GetModelList() []string {
+ return []string{
+ "veo-3.0-generate-001",
+ "veo-3.0-fast-generate-001",
+ "veo-3.1-generate-preview",
+ "veo-3.1-fast-generate-preview",
+ }
+}
func (a *TaskAdaptor) GetChannelName() string { return "vertex" }
// FetchTask fetch task status
@@ -225,7 +244,7 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
if !ok {
return nil, fmt.Errorf("invalid task_id")
}
- upstreamName, err := decodeLocalTaskID(taskID)
+ upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
if err != nil {
return nil, fmt.Errorf("decode task_id failed: %w", err)
}
@@ -244,13 +263,13 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
} else {
url = fmt.Sprintf("https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:fetchPredictOperation", region, project, region, modelName)
}
- payload := map[string]string{"operationName": upstreamName}
- data, err := json.Marshal(payload)
+ payload := fetchOperationPayload{OperationName: upstreamName}
+ data, err := common.Marshal(payload)
if err != nil {
return nil, err
}
adc := &vertexcore.Credentials{}
- if err := json.Unmarshal([]byte(key), adc); err != nil {
+ if err := common.Unmarshal([]byte(key), adc); err != nil {
return nil, fmt.Errorf("failed to decode credentials: %w", err)
}
token, err := vertexcore.AcquireAccessToken(*adc, proxy)
@@ -274,7 +293,7 @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
var op operationResponse
- if err := json.Unmarshal(respBody, &op); err != nil {
+ if err := common.Unmarshal(respBody, &op); err != nil {
return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
}
ti := &relaycommon.TaskInfo{}
@@ -338,7 +357,10 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
}
func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
- upstreamName, err := decodeLocalTaskID(task.TaskID)
+ // Use GetUpstreamTaskID() to get the real upstream operation name for model extraction.
+ // task.TaskID is now a public task_xxxx ID, no longer a base64-encoded upstream name.
+ upstreamTaskID := task.GetUpstreamTaskID()
+ upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
if err != nil {
upstreamName = ""
}
@@ -353,8 +375,8 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
v.SetProgressStr(task.Progress)
v.CreatedAt = task.CreatedAt
v.CompletedAt = task.UpdatedAt
- if strings.HasPrefix(task.FailReason, "data:") && len(task.FailReason) > 0 {
- v.SetMetadata("url", task.FailReason)
+ if resultURL := task.GetResultURL(); strings.HasPrefix(resultURL, "data:") && len(resultURL) > 0 {
+ v.SetMetadata("url", resultURL)
}
return common.Marshal(v)
@@ -364,18 +386,6 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
// helpers
// ============================
-func encodeLocalTaskID(name string) string {
- return base64.RawURLEncoding.EncodeToString([]byte(name))
-}
-
-func decodeLocalTaskID(local string) (string, error) {
- b, err := base64.RawURLEncoding.DecodeString(local)
- if err != nil {
- return "", err
- }
- return string(b), nil
-}
-
var regionRe = regexp.MustCompile(`locations/([a-z0-9-]+)/`)
func extractRegionFromOperationName(name string) string {
diff --git a/relay/channel/task/vidu/adaptor.go b/relay/channel/task/vidu/adaptor.go
index 3657161c02..6ae1c181bf 100644
--- a/relay/channel/task/vidu/adaptor.go
+++ b/relay/channel/task/vidu/adaptor.go
@@ -2,7 +2,6 @@ package vidu
import (
"bytes"
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -16,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
@@ -73,6 +73,7 @@ type creation struct {
// ============================
type TaskAdaptor struct {
+ taskcommon.BaseBilling
ChannelType int
baseURL string
}
@@ -115,7 +116,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
}
req := v.(relaycommon.TaskSubmitReq)
- body, err := a.convertToRequestPayload(&req)
+ body, err := a.convertToRequestPayload(&req, info)
if err != nil {
return nil, err
}
@@ -127,7 +128,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
}
}
- data, err := json.Marshal(body)
+ data, err := common.Marshal(body)
if err != nil {
return nil, err
}
@@ -168,7 +169,7 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
var vResp responsePayload
- err = json.Unmarshal(responseBody, &vResp)
+ err = common.Unmarshal(responseBody, &vResp)
if err != nil {
taskErr = service.TaskErrorWrapper(errors.Wrap(err, fmt.Sprintf("%s", responseBody)), "unmarshal_response_failed", http.StatusInternalServerError)
return
@@ -180,8 +181,8 @@ func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *rela
}
ov := dto.NewOpenAIVideo()
- ov.ID = vResp.TaskId
- ov.TaskID = vResp.TaskId
+ ov.ID = info.PublicTaskID
+ ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)
@@ -223,47 +224,27 @@ func (a *TaskAdaptor) GetChannelName() string {
// helpers
// ============================
-func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
+func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq, info *relaycommon.RelayInfo) (*requestPayload, error) {
r := requestPayload{
- Model: defaultString(req.Model, "viduq1"),
+ Model: taskcommon.DefaultString(info.UpstreamModelName, "viduq1"),
Images: req.Images,
Prompt: req.Prompt,
- Duration: defaultInt(req.Duration, 5),
- Resolution: defaultString(req.Size, "1080p"),
+ Duration: taskcommon.DefaultInt(req.Duration, 5),
+ Resolution: taskcommon.DefaultString(req.Size, "1080p"),
MovementAmplitude: "auto",
Bgm: false,
}
- metadata := req.Metadata
- medaBytes, err := json.Marshal(metadata)
- if err != nil {
- return nil, errors.Wrap(err, "metadata marshal metadata failed")
- }
- err = json.Unmarshal(medaBytes, &r)
- if err != nil {
+ if err := taskcommon.UnmarshalMetadata(req.Metadata, &r); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}
return &r, nil
}
-func defaultString(value, defaultValue string) string {
- if value == "" {
- return defaultValue
- }
- return value
-}
-
-func defaultInt(value, defaultValue int) int {
- if value == 0 {
- return defaultValue
- }
- return value
-}
-
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
taskInfo := &relaycommon.TaskInfo{}
var taskResp taskResultResponse
- err := json.Unmarshal(respBody, &taskResp)
+ err := common.Unmarshal(respBody, &taskResp)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal response body")
}
@@ -293,7 +274,7 @@ func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, e
func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
var viduResp taskResultResponse
- if err := json.Unmarshal(originTask.Data, &viduResp); err != nil {
+ if err := common.Unmarshal(originTask.Data, &viduResp); err != nil {
return nil, errors.Wrap(err, "unmarshal vidu task data failed")
}
@@ -315,6 +296,5 @@ func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, erro
}
}
- jsonData, _ := common.Marshal(openAIVideo)
- return jsonData, nil
+ return common.Marshal(openAIVideo)
}
diff --git a/relay/channel/tencent/relay-tencent.go b/relay/channel/tencent/relay-tencent.go
index dbe7750e40..0343f5784e 100644
--- a/relay/channel/tencent/relay-tencent.go
+++ b/relay/channel/tencent/relay-tencent.go
@@ -37,12 +37,12 @@ func requestOpenAI2Tencent(a *Adaptor, request dto.GeneralOpenAIRequest) *Tencen
})
}
var req = TencentChatRequest{
- Stream: &request.Stream,
+ Stream: request.Stream,
Messages: messages,
Model: &request.Model,
}
- if request.TopP != 0 {
- req.TopP = &request.TopP
+ if request.TopP != nil {
+ req.TopP = request.TopP
}
req.Temperature = request.Temperature
return &req
diff --git a/relay/channel/vertex/adaptor.go b/relay/channel/vertex/adaptor.go
index bd9cc97c5c..7e56c52b6e 100644
--- a/relay/channel/vertex/adaptor.go
+++ b/relay/channel/vertex/adaptor.go
@@ -21,12 +21,13 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
const (
- RequestModeClaude = 1
- RequestModeGemini = 2
- RequestModeLlama = 3
+ RequestModeClaude = 1
+ RequestModeGemini = 2
+ RequestModeOpenSource = 3
)
var claudeModelMap = map[string]string{
@@ -42,6 +43,7 @@ var claudeModelMap = map[string]string{
"claude-sonnet-4-5-20250929": "claude-sonnet-4-5@20250929",
"claude-haiku-4-5-20251001": "claude-haiku-4-5@20251001",
"claude-opus-4-5-20251101": "claude-opus-4-5@20251101",
+ "claude-opus-4-6": "claude-opus-4-6",
}
const anthropicVersion = "vertex-2023-10-16"
@@ -115,7 +117,7 @@ func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
} else if strings.Contains(info.UpstreamModelName, "llama") ||
// open source models
strings.Contains(info.UpstreamModelName, "-maas") {
- a.RequestMode = RequestModeLlama
+ a.RequestMode = RequestModeOpenSource
} else {
a.RequestMode = RequestModeGemini
}
@@ -166,10 +168,9 @@ func (a *Adaptor) getRequestUrl(info *relaycommon.RelayInfo, modelName, suffix s
suffix,
), nil
}
- } else if a.RequestMode == RequestModeLlama {
+ } else if a.RequestMode == RequestModeOpenSource {
return fmt.Sprintf(
- "https://%s-aiplatform.googleapis.com/v1beta1/projects/%s/locations/%s/endpoints/openapi/chat/completions",
- region,
+ "https://aiplatform.googleapis.com/v1beta1/projects/%s/locations/%s/endpoints/openapi/chat/completions",
adc.ProjectID,
region,
), nil
@@ -242,7 +243,7 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
model = v
}
return a.getRequestUrl(info, model, suffix)
- } else if a.RequestMode == RequestModeLlama {
+ } else if a.RequestMode == RequestModeOpenSource {
return a.getRequestUrl(info, "", "")
}
return "", errors.New("unsupported request mode")
@@ -292,11 +293,11 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
imgReq := dto.ImageRequest{
Model: request.Model,
Prompt: prompt,
- N: 1,
+ N: lo.ToPtr(uint(1)),
Size: "1024x1024",
}
- if request.N > 0 {
- imgReq.N = uint(request.N)
+ if request.N != nil && *request.N > 0 {
+ imgReq.N = lo.ToPtr(uint(*request.N))
}
if request.Size != "" {
imgReq.Size = request.Size
@@ -305,7 +306,7 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
var extra map[string]any
if err := json.Unmarshal(request.ExtraBody, &extra); err == nil {
if n, ok := extra["n"].(float64); ok && n > 0 {
- imgReq.N = uint(n)
+ imgReq.N = lo.ToPtr(uint(n))
}
if size, ok := extra["size"].(string); ok {
imgReq.Size = size
@@ -340,7 +341,7 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
}
c.Set("request_model", request.Model)
return geminiRequest, nil
- } else if a.RequestMode == RequestModeLlama {
+ } else if a.RequestMode == RequestModeOpenSource {
return request, nil
}
return nil, errors.New("unsupported request mode")
@@ -365,23 +366,24 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
+ claudeAdaptor := claude.Adaptor{}
if info.IsStream {
switch a.RequestMode {
case RequestModeClaude:
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
+ return claudeAdaptor.DoResponse(c, resp, info)
case RequestModeGemini:
if info.RelayMode == constant.RelayModeGemini {
return gemini.GeminiTextGenerationStreamHandler(c, info, resp)
} else {
return gemini.GeminiChatStreamHandler(c, info, resp)
}
- case RequestModeLlama:
+ case RequestModeOpenSource:
return openai.OaiStreamHandler(c, info, resp)
}
} else {
switch a.RequestMode {
case RequestModeClaude:
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
+ return claudeAdaptor.DoResponse(c, resp, info)
case RequestModeGemini:
if info.RelayMode == constant.RelayModeGemini {
return gemini.GeminiTextGenerationHandler(c, info, resp)
@@ -391,7 +393,7 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
}
return gemini.GeminiChatHandler(c, info, resp)
}
- case RequestModeLlama:
+ case RequestModeOpenSource:
return openai.OpenaiHandler(c, info, resp)
}
}
diff --git a/relay/channel/vertex/dto.go b/relay/channel/vertex/dto.go
index 68044ff328..c1d13a6dd7 100644
--- a/relay/channel/vertex/dto.go
+++ b/relay/channel/vertex/dto.go
@@ -1,6 +1,8 @@
package vertex
import (
+ "encoding/json"
+
"github.com/QuantumNous/new-api/dto"
)
@@ -8,15 +10,17 @@ type VertexAIClaudeRequest struct {
AnthropicVersion string `json:"anthropic_version"`
Messages []dto.ClaudeMessage `json:"messages"`
System any `json:"system,omitempty"`
- MaxTokens uint `json:"max_tokens,omitempty"`
+ MaxTokens *uint `json:"max_tokens,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
- Stream bool `json:"stream,omitempty"`
+ Stream *bool `json:"stream,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
- TopP float64 `json:"top_p,omitempty"`
- TopK int `json:"top_k,omitempty"`
+ TopP *float64 `json:"top_p,omitempty"`
+ TopK *int `json:"top_k,omitempty"`
Tools any `json:"tools,omitempty"`
ToolChoice any `json:"tool_choice,omitempty"`
Thinking *dto.Thinking `json:"thinking,omitempty"`
+ OutputConfig json.RawMessage `json:"output_config,omitempty"`
+ //Metadata json.RawMessage `json:"metadata,omitempty"`
}
func copyRequest(req *dto.ClaudeRequest, version string) *VertexAIClaudeRequest {
@@ -33,5 +37,6 @@ func copyRequest(req *dto.ClaudeRequest, version string) *VertexAIClaudeRequest
Tools: req.Tools,
ToolChoice: req.ToolChoice,
Thinking: req.Thinking,
+ OutputConfig: req.OutputConfig,
}
}
diff --git a/relay/channel/volcengine/adaptor.go b/relay/channel/volcengine/adaptor.go
index 9e09d9d8d2..ba9f223bd2 100644
--- a/relay/channel/volcengine/adaptor.go
+++ b/relay/channel/volcengine/adaptor.go
@@ -21,6 +21,7 @@ import (
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
const (
@@ -56,7 +57,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
}
voiceType := mapVoiceType(request.Voice)
- speedRatio := request.Speed
+ speedRatio := lo.FromPtrOr(request.Speed, 0.0)
encoding := mapEncoding(request.ResponseFormat)
c.Set(contextKeyResponseFormat, encoding)
@@ -347,10 +348,8 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
if info.RelayFormat == types.RelayFormatClaude {
if _, ok := channelconstant.ChannelSpecialBases[info.ChannelBaseUrl]; ok {
- if info.IsStream {
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
- }
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
}
}
diff --git a/relay/channel/xai/adaptor.go b/relay/channel/xai/adaptor.go
index b130723e7e..c73bd8cf27 100644
--- a/relay/channel/xai/adaptor.go
+++ b/relay/channel/xai/adaptor.go
@@ -15,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/relay/constant"
"github.com/gin-gonic/gin"
+ "github.com/samber/lo"
)
type Adaptor struct {
@@ -40,7 +41,7 @@ func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInf
xaiRequest := ImageRequest{
Model: request.Model,
Prompt: request.Prompt,
- N: int(request.N),
+ N: int(lo.FromPtrOr(request.N, uint(1))),
ResponseFormat: request.ResponseFormat,
}
return xaiRequest, nil
@@ -73,9 +74,9 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
return toMap, nil
}
if strings.HasPrefix(request.Model, "grok-3-mini") {
- if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
+ if lo.FromPtrOr(request.MaxCompletionTokens, uint(0)) == 0 && lo.FromPtrOr(request.MaxTokens, uint(0)) != 0 {
request.MaxCompletionTokens = request.MaxTokens
- request.MaxTokens = 0
+ request.MaxTokens = nil
}
if strings.HasSuffix(request.Model, "-high") {
request.ReasoningEffort = "high"
@@ -83,9 +84,6 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
} else if strings.HasSuffix(request.Model, "-low") {
request.ReasoningEffort = "low"
request.Model = strings.TrimSuffix(request.Model, "-low")
- } else if strings.HasSuffix(request.Model, "-medium") {
- request.ReasoningEffort = "medium"
- request.Model = strings.TrimSuffix(request.Model, "-medium")
}
info.ReasoningEffort = request.ReasoningEffort
info.UpstreamModelName = request.Model
@@ -103,8 +101,10 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
}
func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
- // TODO implement me
- return nil, errors.New("not implemented")
+ if request.Model == "" && info != nil {
+ request.Model = info.UpstreamModelName
+ }
+ return request, nil
}
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
@@ -115,6 +115,12 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycom
switch info.RelayMode {
case constant.RelayModeImagesGenerations, constant.RelayModeImagesEdits:
usage, err = openai.OpenaiHandlerWithUsage(c, info, resp)
+ case constant.RelayModeResponses:
+ if info.IsStream {
+ usage, err = openai.OaiResponsesStreamHandler(c, info, resp)
+ } else {
+ usage, err = openai.OaiResponsesHandler(c, info, resp)
+ }
default:
if info.IsStream {
usage, err = xAIStreamHandler(c, info, resp)
diff --git a/relay/channel/xai/constants.go b/relay/channel/xai/constants.go
index 311b4bb6e2..c20532d4ce 100644
--- a/relay/channel/xai/constants.go
+++ b/relay/channel/xai/constants.go
@@ -1,20 +1,32 @@
package xai
var ModelList = []string{
- // grok-4
- "grok-4", "grok-4-0709", "grok-4-0709-search",
- // grok-3
- "grok-3-beta", "grok-3-mini-beta",
- // grok-3 mini
- "grok-3-fast-beta", "grok-3-mini-fast-beta",
- // extend grok-3-mini reasoning
- "grok-3-mini-beta-high", "grok-3-mini-beta-low", "grok-3-mini-beta-medium",
- "grok-3-mini-fast-beta-high", "grok-3-mini-fast-beta-low", "grok-3-mini-fast-beta-medium",
- // image model
- "grok-2-image",
- // legacy models
- "grok-2", "grok-2-vision",
- "grok-beta", "grok-vision-beta",
+ // language models
+ "grok-4-1-fast-reasoning",
+ "grok-4-1-fast-non-reasoning",
+ "grok-code-fast-1",
+ "grok-4-fast-reasoning",
+ "grok-4-fast-non-reasoning",
+ "grok-4-0709",
+ "grok-3-mini",
+ "grok-3",
+ "grok-2-vision-1212",
+ // search variants
+ "grok-4-1-fast-reasoning-search",
+ "grok-4-1-fast-non-reasoning-search",
+ "grok-4-fast-reasoning-search",
+ "grok-4-fast-non-reasoning-search",
+ "grok-4-0709-search",
+ "grok-3-mini-search",
+ "grok-3-search",
+ // grok-3-mini reasoning effort variants
+ "grok-3-mini-high", "grok-3-mini-low",
+ // image generation models
+ "grok-imagine-image-pro",
+ "grok-imagine-image",
+ "grok-2-image-1212",
+ // video generation model
+ "grok-imagine-video",
}
var ChannelName = "xai"
diff --git a/relay/channel/xai/text.go b/relay/channel/xai/text.go
index aa4d329f31..f9a8ee2e6f 100644
--- a/relay/channel/xai/text.go
+++ b/relay/channel/xai/text.go
@@ -1,7 +1,6 @@
package xai
import (
- "encoding/json"
"io"
"net/http"
"strings"
@@ -44,12 +43,12 @@ func xAIStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
helper.SetEventStreamHeaders(c)
- helper.StreamScannerHandler(c, resp, info, func(data string) bool {
+ helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
var xAIResp *dto.ChatCompletionsStreamResponse
- err := json.Unmarshal([]byte(data), &xAIResp)
- if err != nil {
+ if err := common.UnmarshalJsonStr(data, &xAIResp); err != nil {
common.SysLog("error unmarshalling stream response: " + err.Error())
- return true
+ sr.Error(err)
+ return
}
// 把 xAI 的usage转换为 OpenAI 的usage
@@ -62,11 +61,10 @@ func xAIStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
openaiResponse := streamResponseXAI2OpenAI(xAIResp, usage)
_ = openai.ProcessStreamResponse(*openaiResponse, &responseTextBuilder, &toolCount)
- err = helper.ObjectData(c, openaiResponse)
- if err != nil {
+ if err := helper.ObjectData(c, openaiResponse); err != nil {
common.SysLog(err.Error())
+ sr.Error(err)
}
- return true
})
if !containStreamUsage {
diff --git a/relay/channel/xunfei/relay-xunfei.go b/relay/channel/xunfei/relay-xunfei.go
index b8fbd2958a..70fde810a5 100644
--- a/relay/channel/xunfei/relay-xunfei.go
+++ b/relay/channel/xunfei/relay-xunfei.go
@@ -16,6 +16,7 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -48,7 +49,7 @@ func requestOpenAI2Xunfei(request dto.GeneralOpenAIRequest, xunfeiAppId string,
xunfeiRequest.Header.AppId = xunfeiAppId
xunfeiRequest.Parameter.Chat.Domain = domain
xunfeiRequest.Parameter.Chat.Temperature = request.Temperature
- xunfeiRequest.Parameter.Chat.TopK = request.N
+ xunfeiRequest.Parameter.Chat.TopK = lo.FromPtrOr(request.N, 0)
xunfeiRequest.Parameter.Chat.MaxTokens = request.GetMaxTokens()
xunfeiRequest.Payload.Message.Text = messages
return &xunfeiRequest
diff --git a/relay/channel/zhipu/adaptor.go b/relay/channel/zhipu/adaptor.go
index 23016fd3b4..3ed4b35961 100644
--- a/relay/channel/zhipu/adaptor.go
+++ b/relay/channel/zhipu/adaptor.go
@@ -10,6 +10,7 @@ import (
"github.com/QuantumNous/new-api/relay/channel"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -60,8 +61,8 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
if request == nil {
return nil, errors.New("request is nil")
}
- if request.TopP >= 1 {
- request.TopP = 0.99
+ if lo.FromPtrOr(request.TopP, 0) >= 1 {
+ request.TopP = lo.ToPtr(0.99)
}
return requestOpenAI2Zhipu(*request), nil
}
diff --git a/relay/channel/zhipu/relay-zhipu.go b/relay/channel/zhipu/relay-zhipu.go
index 964dff0827..c3c96a05a9 100644
--- a/relay/channel/zhipu/relay-zhipu.go
+++ b/relay/channel/zhipu/relay-zhipu.go
@@ -16,6 +16,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
@@ -98,7 +99,7 @@ func requestOpenAI2Zhipu(request dto.GeneralOpenAIRequest) *ZhipuRequest {
return &ZhipuRequest{
Prompt: messages,
Temperature: request.Temperature,
- TopP: request.TopP,
+ TopP: lo.FromPtrOr(request.TopP, 0),
Incremental: false,
}
}
diff --git a/relay/channel/zhipu_4v/adaptor.go b/relay/channel/zhipu_4v/adaptor.go
index b11bea105f..088848c002 100644
--- a/relay/channel/zhipu_4v/adaptor.go
+++ b/relay/channel/zhipu_4v/adaptor.go
@@ -14,6 +14,7 @@ import (
relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -83,8 +84,8 @@ func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayIn
if request == nil {
return nil, errors.New("request is nil")
}
- if request.TopP >= 1 {
- request.TopP = 0.99
+ if lo.FromPtrOr(request.TopP, 0) >= 1 {
+ request.TopP = lo.ToPtr(0.99)
}
return requestOpenAI2Zhipu(*request), nil
}
@@ -109,11 +110,8 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
switch info.RelayFormat {
case types.RelayFormatClaude:
- if info.IsStream {
- return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
- } else {
- return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
- }
+ adaptor := claude.Adaptor{}
+ return adaptor.DoResponse(c, resp, info)
default:
if info.RelayMode == relayconstant.RelayModeImagesGenerations {
return zhipu4vImageHandler(c, resp, info)
diff --git a/relay/channel/zhipu_4v/constants.go b/relay/channel/zhipu_4v/constants.go
index 0d505373ec..c1c1f28952 100644
--- a/relay/channel/zhipu_4v/constants.go
+++ b/relay/channel/zhipu_4v/constants.go
@@ -1,7 +1,7 @@
package zhipu_4v
var ModelList = []string{
- "glm-4", "glm-4v", "glm-3-turbo", "glm-4-alltools", "glm-4-plus", "glm-4-0520", "glm-4-air", "glm-4-airx", "glm-4-long", "glm-4-flash", "glm-4v-plus", "glm-4.6",
+ "glm-4", "glm-4v", "glm-3-turbo", "glm-4-alltools", "glm-4-plus", "glm-4-0520", "glm-4-air", "glm-4-airx", "glm-4-long", "glm-4-flash", "glm-4v-plus", "glm-4.6", "glm-4.6v", "glm-4.7", "glm-4.7-flash", "glm-5",
}
var ChannelName = "zhipu_4v"
diff --git a/relay/channel/zhipu_4v/relay-zhipu_v4.go b/relay/channel/zhipu_4v/relay-zhipu_v4.go
index 53e94e14b3..91ef0c4764 100644
--- a/relay/channel/zhipu_4v/relay-zhipu_v4.go
+++ b/relay/channel/zhipu_4v/relay-zhipu_v4.go
@@ -41,16 +41,20 @@ func requestOpenAI2Zhipu(request dto.GeneralOpenAIRequest) *dto.GeneralOpenAIReq
} else {
Stop, _ = request.Stop.([]string)
}
- return &dto.GeneralOpenAIRequest{
+ out := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: request.Stream,
Messages: messages,
Temperature: request.Temperature,
TopP: request.TopP,
- MaxTokens: request.GetMaxTokens(),
Stop: Stop,
Tools: request.Tools,
ToolChoice: request.ToolChoice,
THINKING: request.THINKING,
}
+ if request.MaxTokens != nil || request.MaxCompletionTokens != nil {
+ maxTokens := request.GetMaxTokens()
+ out.MaxTokens = &maxTokens
+ }
+ return out
}
diff --git a/relay/chat_completions_via_responses.go b/relay/chat_completions_via_responses.go
index 38dae3c566..8f69b93756 100644
--- a/relay/chat_completions_via_responses.go
+++ b/relay/chat_completions_via_responses.go
@@ -70,21 +70,20 @@ func applySystemPromptIfNeeded(c *gin.Context, info *relaycommon.RelayInfo, requ
}
func chatCompletionsViaResponses(c *gin.Context, info *relaycommon.RelayInfo, adaptor channel.Adaptor, request *dto.GeneralOpenAIRequest) (*dto.Usage, *types.NewAPIError) {
- overrideCtx := relaycommon.BuildParamOverrideContext(info)
chatJSON, err := common.Marshal(request)
if err != nil {
return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
- chatJSON, err = relaycommon.RemoveDisabledFields(chatJSON, info.ChannelOtherSettings)
+ chatJSON, err = relaycommon.RemoveDisabledFields(chatJSON, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
if err != nil {
return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
if len(info.ParamOverride) > 0 {
- chatJSON, err = relaycommon.ApplyParamOverride(chatJSON, info.ParamOverride, overrideCtx)
+ chatJSON, err = relaycommon.ApplyParamOverrideWithRelayInfo(chatJSON, info)
if err != nil {
- return nil, types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return nil, newAPIErrorFromParamOverride(err)
}
}
@@ -120,7 +119,7 @@ func chatCompletionsViaResponses(c *gin.Context, info *relaycommon.RelayInfo, ad
return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
- jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
+ jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
if err != nil {
return nil, types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
diff --git a/relay/claude_handler.go b/relay/claude_handler.go
index 7e05116daf..dc4c93f8ae 100644
--- a/relay/claude_handler.go
+++ b/relay/claude_handler.go
@@ -2,6 +2,7 @@ package relay
import (
"bytes"
+ "encoding/json"
"fmt"
"io"
"net/http"
@@ -14,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
+ "github.com/QuantumNous/new-api/setting/reasoning"
"github.com/QuantumNous/new-api/types"
"github.com/gin-gonic/gin"
@@ -45,26 +47,35 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
}
adaptor.Init(info)
- if request.MaxTokens == 0 {
- request.MaxTokens = uint(model_setting.GetClaudeSettings().GetDefaultMaxTokens(request.Model))
+ if request.MaxTokens == nil || *request.MaxTokens == 0 {
+ defaultMaxTokens := uint(model_setting.GetClaudeSettings().GetDefaultMaxTokens(request.Model))
+ request.MaxTokens = &defaultMaxTokens
}
- if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
+ if baseModel, effortLevel, ok := reasoning.TrimEffortSuffix(request.Model); ok && effortLevel != "" &&
+ strings.HasPrefix(request.Model, "claude-opus-4-6") {
+ request.Model = baseModel
+ request.Thinking = &dto.Thinking{
+ Type: "adaptive",
+ }
+ request.OutputConfig = json.RawMessage(fmt.Sprintf(`{"effort":"%s"}`, effortLevel))
+ request.Temperature = common.GetPointer[float64](1.0)
+ info.UpstreamModelName = request.Model
+ } else if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
strings.HasSuffix(request.Model, "-thinking") {
if request.Thinking == nil {
// 因为BudgetTokens 必须大于1024
- if request.MaxTokens < 1280 {
- request.MaxTokens = 1280
+ if request.MaxTokens == nil || *request.MaxTokens < 1280 {
+ request.MaxTokens = common.GetPointer[uint](1280)
}
// BudgetTokens 为 max_tokens 的 80%
request.Thinking = &dto.Thinking{
Type: "enabled",
- BudgetTokens: common.GetPointer[int](int(float64(request.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage)),
+ BudgetTokens: common.GetPointer[int](int(float64(*request.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage)),
}
// TODO: 临时处理
// https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#important-considerations-when-using-extended-thinking
- request.TopP = 0
request.Temperature = common.GetPointer[float64](1.0)
}
if !model_setting.ShouldPreserveThinkingSuffix(info.OriginModelName) {
@@ -98,13 +109,30 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
}
}
+ if !model_setting.GetGlobalSettings().PassThroughRequestEnabled &&
+ !info.ChannelSetting.PassThroughBodyEnabled &&
+ service.ShouldChatCompletionsUseResponsesGlobal(info.ChannelId, info.ChannelType, info.OriginModelName) {
+ openAIRequest, convErr := service.ClaudeToOpenAIRequest(*request, info)
+ if convErr != nil {
+ return types.NewError(convErr, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
+ }
+
+ usage, newApiErr := chatCompletionsViaResponses(c, info, adaptor, openAIRequest)
+ if newApiErr != nil {
+ return newApiErr
+ }
+
+ service.PostTextConsumeQuota(c, info, usage, nil)
+ return nil
+ }
+
var requestBody io.Reader
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
}
- requestBody = bytes.NewBuffer(body)
+ requestBody = common.ReaderOnly(storage)
} else {
convertedRequest, err := adaptor.ConvertClaudeRequest(c, info, request)
if err != nil {
@@ -117,16 +145,16 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
}
// remove disabled fields for Claude API
- jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
+ jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
if err != nil {
return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -162,6 +190,6 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
return newAPIError
}
- service.PostClaudeConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
return nil
}
diff --git a/relay/common/billing.go b/relay/common/billing.go
new file mode 100644
index 0000000000..78f5cb1951
--- /dev/null
+++ b/relay/common/billing.go
@@ -0,0 +1,21 @@
+package common
+
+import "github.com/gin-gonic/gin"
+
+// BillingSettler 抽象计费会话的生命周期操作。
+// 由 service.BillingSession 实现,存储在 RelayInfo 上以避免循环引用。
+type BillingSettler interface {
+ // Settle 根据实际消耗额度进行结算,计算 delta = actualQuota - preConsumedQuota,
+ // 同时调整资金来源(钱包/订阅)和令牌额度。
+ Settle(actualQuota int) error
+
+ // Refund 退还所有预扣费额度(资金来源 + 令牌),幂等安全。
+ // 通过 gopool 异步执行。如果已经结算或退款则不做任何操作。
+ Refund(c *gin.Context)
+
+ // NeedsRefund 返回会话是否存在需要退还的预扣状态(未结算且未退款)。
+ NeedsRefund() bool
+
+ // GetPreConsumedQuota 返回实际预扣的额度值(信任用户可能为 0)。
+ GetPreConsumedQuota() int
+}
diff --git a/relay/common/override.go b/relay/common/override.go
index 1a0c2478d4..af0b43616b 100644
--- a/relay/common/override.go
+++ b/relay/common/override.go
@@ -1,18 +1,43 @@
package common
import (
+ "errors"
"fmt"
+ "net/http"
"regexp"
+ "sort"
"strconv"
"strings"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
var negativeIndexRegexp = regexp.MustCompile(`\.(-\d+)`)
+const (
+ paramOverrideContextRequestHeaders = "request_headers"
+ paramOverrideContextHeaderOverride = "header_override"
+ paramOverrideContextAuditRecorder = "__param_override_audit_recorder"
+)
+
+var errSourceHeaderNotFound = errors.New("source header does not exist")
+
+var paramOverrideKeyAuditPaths = map[string]struct{}{
+ "model": {},
+ "original_model": {},
+ "upstream_model": {},
+ "service_tier": {},
+ "inference_geo": {},
+}
+
+type paramOverrideAuditRecorder struct {
+ lines []string
+}
+
type ConditionOperation struct {
Path string `json:"path"` // JSON路径
Mode string `json:"mode"` // full, prefix, suffix, contains, gt, gte, lt, lte
@@ -23,7 +48,7 @@ type ConditionOperation struct {
type ParamOperation struct {
Path string `json:"path"`
- Mode string `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace
+ Mode string `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace, return_error, prune_objects, set_header, delete_header, copy_header, move_header, pass_headers, sync_fields
Value interface{} `json:"value"`
KeepOrigin bool `json:"keep_origin"`
From string `json:"from,omitempty"`
@@ -32,97 +57,444 @@ type ParamOperation struct {
Logic string `json:"logic,omitempty"` // AND, OR (默认OR)
}
+type ParamOverrideReturnError struct {
+ Message string
+ StatusCode int
+ Code string
+ Type string
+ SkipRetry bool
+}
+
+func (e *ParamOverrideReturnError) Error() string {
+ if e == nil {
+ return "param override return error"
+ }
+ if e.Message == "" {
+ return "param override return error"
+ }
+ return e.Message
+}
+
+func AsParamOverrideReturnError(err error) (*ParamOverrideReturnError, bool) {
+ if err == nil {
+ return nil, false
+ }
+ var target *ParamOverrideReturnError
+ if errors.As(err, &target) {
+ return target, true
+ }
+ return nil, false
+}
+
+func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIError {
+ if err == nil {
+ return types.NewError(
+ errors.New("param override return error is nil"),
+ types.ErrorCodeChannelParamOverrideInvalid,
+ types.ErrOptionWithSkipRetry(),
+ )
+ }
+
+ statusCode := err.StatusCode
+ if statusCode < http.StatusContinue || statusCode > http.StatusNetworkAuthenticationRequired {
+ statusCode = http.StatusBadRequest
+ }
+
+ errorCode := err.Code
+ if strings.TrimSpace(errorCode) == "" {
+ errorCode = string(types.ErrorCodeInvalidRequest)
+ }
+
+ errorType := err.Type
+ if strings.TrimSpace(errorType) == "" {
+ errorType = "invalid_request_error"
+ }
+
+ message := strings.TrimSpace(err.Message)
+ if message == "" {
+ message = "request blocked by param override"
+ }
+
+ opts := make([]types.NewAPIErrorOptions, 0, 1)
+ if err.SkipRetry {
+ opts = append(opts, types.ErrOptionWithSkipRetry())
+ }
+
+ return types.WithOpenAIError(types.OpenAIError{
+ Message: message,
+ Type: errorType,
+ Code: errorCode,
+ }, statusCode, opts...)
+}
+
func ApplyParamOverride(jsonData []byte, paramOverride map[string]interface{}, conditionContext map[string]interface{}) ([]byte, error) {
if len(paramOverride) == 0 {
return jsonData, nil
}
+ auditRecorder := getParamOverrideAuditRecorder(conditionContext)
// 尝试断言为操作格式
if operations, ok := tryParseOperations(paramOverride); ok {
+ legacyOverride := buildLegacyParamOverride(paramOverride)
+ workingJSON := jsonData
+ var err error
+ if len(legacyOverride) > 0 {
+ workingJSON, err = applyOperationsLegacy(workingJSON, legacyOverride, auditRecorder)
+ if err != nil {
+ return nil, err
+ }
+ }
+
// 使用新方法
- result, err := applyOperations(string(jsonData), operations, conditionContext)
+ result, err := applyOperations(string(workingJSON), operations, conditionContext)
return []byte(result), err
}
// 直接使用旧方法
- return applyOperationsLegacy(jsonData, paramOverride)
+ return applyOperationsLegacy(jsonData, paramOverride, auditRecorder)
+}
+
+func buildLegacyParamOverride(paramOverride map[string]interface{}) map[string]interface{} {
+ if len(paramOverride) == 0 {
+ return nil
+ }
+ legacy := make(map[string]interface{}, len(paramOverride))
+ for key, value := range paramOverride {
+ if strings.EqualFold(strings.TrimSpace(key), "operations") {
+ continue
+ }
+ legacy[key] = value
+ }
+ return legacy
+}
+
+func ApplyParamOverrideWithRelayInfo(jsonData []byte, info *RelayInfo) ([]byte, error) {
+ paramOverride := getParamOverrideMap(info)
+ if len(paramOverride) == 0 {
+ return jsonData, nil
+ }
+
+ overrideCtx := BuildParamOverrideContext(info)
+ var recorder *paramOverrideAuditRecorder
+ if shouldEnableParamOverrideAudit(paramOverride) {
+ recorder = ¶mOverrideAuditRecorder{}
+ overrideCtx[paramOverrideContextAuditRecorder] = recorder
+ }
+ result, err := ApplyParamOverride(jsonData, paramOverride, overrideCtx)
+ if err != nil {
+ return nil, err
+ }
+ syncRuntimeHeaderOverrideFromContext(info, overrideCtx)
+ if info != nil {
+ if recorder != nil {
+ info.ParamOverrideAudit = recorder.lines
+ } else {
+ info.ParamOverrideAudit = nil
+ }
+ }
+ return result, nil
+}
+
+func shouldEnableParamOverrideAudit(paramOverride map[string]interface{}) bool {
+ if common.DebugEnabled {
+ return true
+ }
+ if len(paramOverride) == 0 {
+ return false
+ }
+ if operations, ok := tryParseOperations(paramOverride); ok {
+ for _, operation := range operations {
+ if shouldAuditParamPath(strings.TrimSpace(operation.Path)) ||
+ shouldAuditParamPath(strings.TrimSpace(operation.To)) {
+ return true
+ }
+ }
+ for key := range buildLegacyParamOverride(paramOverride) {
+ if shouldAuditParamPath(strings.TrimSpace(key)) {
+ return true
+ }
+ }
+ return false
+ }
+ for key := range paramOverride {
+ if shouldAuditParamPath(strings.TrimSpace(key)) {
+ return true
+ }
+ }
+ return false
+}
+
+func getParamOverrideAuditRecorder(context map[string]interface{}) *paramOverrideAuditRecorder {
+ if context == nil {
+ return nil
+ }
+ recorder, _ := context[paramOverrideContextAuditRecorder].(*paramOverrideAuditRecorder)
+ return recorder
+}
+
+func (r *paramOverrideAuditRecorder) recordOperation(mode, path, from, to string, value interface{}) {
+ if r == nil {
+ return
+ }
+ line := buildParamOverrideAuditLine(mode, path, from, to, value)
+ if line == "" {
+ return
+ }
+ if lo.Contains(r.lines, line) {
+ return
+ }
+ r.lines = append(r.lines, line)
+}
+
+func shouldAuditParamPath(path string) bool {
+ path = strings.TrimSpace(path)
+ if path == "" {
+ return false
+ }
+ if common.DebugEnabled {
+ return true
+ }
+ _, ok := paramOverrideKeyAuditPaths[path]
+ return ok
+}
+
+func shouldAuditOperation(mode, path, from, to string) bool {
+ if common.DebugEnabled {
+ return true
+ }
+ for _, candidate := range []string{path, to} {
+ if shouldAuditParamPath(candidate) {
+ return true
+ }
+ }
+ return false
+}
+
+func formatParamOverrideAuditValue(value interface{}) string {
+ switch typed := value.(type) {
+ case nil:
+ return ""
+ case string:
+ return typed
+ default:
+ return common.GetJsonString(typed)
+ }
+}
+
+func buildParamOverrideAuditLine(mode, path, from, to string, value interface{}) string {
+ mode = strings.TrimSpace(mode)
+ path = strings.TrimSpace(path)
+ from = strings.TrimSpace(from)
+ to = strings.TrimSpace(to)
+
+ if !shouldAuditOperation(mode, path, from, to) {
+ return ""
+ }
+
+ switch mode {
+ case "set":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("set %s = %s", path, formatParamOverrideAuditValue(value))
+ case "delete":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("delete %s", path)
+ case "copy":
+ if from == "" || to == "" {
+ return ""
+ }
+ return fmt.Sprintf("copy %s -> %s", from, to)
+ case "move":
+ if from == "" || to == "" {
+ return ""
+ }
+ return fmt.Sprintf("move %s -> %s", from, to)
+ case "prepend":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("prepend %s with %s", path, formatParamOverrideAuditValue(value))
+ case "append":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("append %s with %s", path, formatParamOverrideAuditValue(value))
+ case "trim_prefix", "trim_suffix", "ensure_prefix", "ensure_suffix":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s %s with %s", mode, path, formatParamOverrideAuditValue(value))
+ case "trim_space", "to_lower", "to_upper":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s %s", mode, path)
+ case "replace", "regex_replace":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s %s from %s to %s", mode, path, from, to)
+ case "set_header":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("set_header %s = %s", path, formatParamOverrideAuditValue(value))
+ case "delete_header":
+ if path == "" {
+ return ""
+ }
+ return fmt.Sprintf("delete_header %s", path)
+ case "copy_header", "move_header":
+ if from == "" || to == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s %s -> %s", mode, from, to)
+ case "pass_headers":
+ return fmt.Sprintf("pass_headers %s", formatParamOverrideAuditValue(value))
+ case "sync_fields":
+ if from == "" || to == "" {
+ return ""
+ }
+ return fmt.Sprintf("sync_fields %s -> %s", from, to)
+ case "return_error":
+ return fmt.Sprintf("return_error %s", formatParamOverrideAuditValue(value))
+ default:
+ if path == "" {
+ return mode
+ }
+ return fmt.Sprintf("%s %s", mode, path)
+ }
+}
+
+func getParamOverrideMap(info *RelayInfo) map[string]interface{} {
+ if info == nil || info.ChannelMeta == nil {
+ return nil
+ }
+ return info.ChannelMeta.ParamOverride
+}
+
+func getHeaderOverrideMap(info *RelayInfo) map[string]interface{} {
+ if info == nil || info.ChannelMeta == nil {
+ return nil
+ }
+ return info.ChannelMeta.HeadersOverride
+}
+
+func sanitizeHeaderOverrideMap(source map[string]interface{}) map[string]interface{} {
+ if len(source) == 0 {
+ return map[string]interface{}{}
+ }
+ target := make(map[string]interface{}, len(source))
+ for key, value := range source {
+ normalizedKey := normalizeHeaderContextKey(key)
+ if normalizedKey == "" {
+ continue
+ }
+ normalizedValue := strings.TrimSpace(fmt.Sprintf("%v", value))
+ if normalizedValue == "" {
+ if isHeaderPassthroughRuleKeyForOverride(normalizedKey) {
+ target[normalizedKey] = ""
+ }
+ continue
+ }
+ target[normalizedKey] = normalizedValue
+ }
+ return target
+}
+
+func isHeaderPassthroughRuleKeyForOverride(key string) bool {
+ key = strings.TrimSpace(strings.ToLower(key))
+ if key == "" {
+ return false
+ }
+ if key == "*" {
+ return true
+ }
+ return strings.HasPrefix(key, "re:") || strings.HasPrefix(key, "regex:")
+}
+
+func GetEffectiveHeaderOverride(info *RelayInfo) map[string]interface{} {
+ if info == nil {
+ return map[string]interface{}{}
+ }
+ if info.UseRuntimeHeadersOverride {
+ return sanitizeHeaderOverrideMap(info.RuntimeHeadersOverride)
+ }
+ return sanitizeHeaderOverrideMap(getHeaderOverrideMap(info))
}
func tryParseOperations(paramOverride map[string]interface{}) ([]ParamOperation, bool) {
// 检查是否包含 "operations" 字段
- if opsValue, exists := paramOverride["operations"]; exists {
- if opsSlice, ok := opsValue.([]interface{}); ok {
- var operations []ParamOperation
- for _, op := range opsSlice {
- if opMap, ok := op.(map[string]interface{}); ok {
- operation := ParamOperation{}
-
- // 断言必要字段
- if path, ok := opMap["path"].(string); ok {
- operation.Path = path
- }
- if mode, ok := opMap["mode"].(string); ok {
- operation.Mode = mode
- } else {
- return nil, false // mode 是必需的
- }
-
- // 可选字段
- if value, exists := opMap["value"]; exists {
- operation.Value = value
- }
- if keepOrigin, ok := opMap["keep_origin"].(bool); ok {
- operation.KeepOrigin = keepOrigin
- }
- if from, ok := opMap["from"].(string); ok {
- operation.From = from
- }
- if to, ok := opMap["to"].(string); ok {
- operation.To = to
- }
- if logic, ok := opMap["logic"].(string); ok {
- operation.Logic = logic
- } else {
- operation.Logic = "OR" // 默认为OR
- }
-
- // 解析条件
- if conditions, exists := opMap["conditions"]; exists {
- if condSlice, ok := conditions.([]interface{}); ok {
- for _, cond := range condSlice {
- if condMap, ok := cond.(map[string]interface{}); ok {
- condition := ConditionOperation{}
- if path, ok := condMap["path"].(string); ok {
- condition.Path = path
- }
- if mode, ok := condMap["mode"].(string); ok {
- condition.Mode = mode
- }
- if value, ok := condMap["value"]; ok {
- condition.Value = value
- }
- if invert, ok := condMap["invert"].(bool); ok {
- condition.Invert = invert
- }
- if passMissingKey, ok := condMap["pass_missing_key"].(bool); ok {
- condition.PassMissingKey = passMissingKey
- }
- operation.Conditions = append(operation.Conditions, condition)
- }
- }
- }
- }
-
- operations = append(operations, operation)
- } else {
- return nil, false
- }
- }
- return operations, true
- }
+ opsValue, exists := paramOverride["operations"]
+ if !exists {
+ return nil, false
}
- return nil, false
+ var opMaps []map[string]interface{}
+ switch ops := opsValue.(type) {
+ case []interface{}:
+ opMaps = make([]map[string]interface{}, 0, len(ops))
+ for _, op := range ops {
+ opMap, ok := op.(map[string]interface{})
+ if !ok {
+ return nil, false
+ }
+ opMaps = append(opMaps, opMap)
+ }
+ case []map[string]interface{}:
+ opMaps = ops
+ default:
+ return nil, false
+ }
+
+ operations := make([]ParamOperation, 0, len(opMaps))
+ for _, opMap := range opMaps {
+ operation := ParamOperation{}
+
+ // 断言必要字段
+ if path, ok := opMap["path"].(string); ok {
+ operation.Path = path
+ }
+ if mode, ok := opMap["mode"].(string); ok {
+ operation.Mode = mode
+ } else {
+ return nil, false // mode 是必需的
+ }
+
+ // 可选字段
+ if value, exists := opMap["value"]; exists {
+ operation.Value = value
+ }
+ if keepOrigin, ok := opMap["keep_origin"].(bool); ok {
+ operation.KeepOrigin = keepOrigin
+ }
+ if from, ok := opMap["from"].(string); ok {
+ operation.From = from
+ }
+ if to, ok := opMap["to"].(string); ok {
+ operation.To = to
+ }
+ if logic, ok := opMap["logic"].(string); ok {
+ operation.Logic = logic
+ } else {
+ operation.Logic = "OR" // 默认为OR
+ }
+
+ // 解析条件
+ if conditions, exists := opMap["conditions"]; exists {
+ parsedConditions, err := parseConditionOperations(conditions)
+ if err != nil {
+ return nil, false
+ }
+ operation.Conditions = append(operation.Conditions, parsedConditions...)
+ }
+
+ operations = append(operations, operation)
+ }
+ return operations, true
}
func checkConditions(jsonStr, contextJSON string, conditions []ConditionOperation, logic string) (bool, error) {
@@ -139,20 +511,9 @@ func checkConditions(jsonStr, contextJSON string, conditions []ConditionOperatio
}
if strings.ToUpper(logic) == "AND" {
- for _, result := range results {
- if !result {
- return false, nil
- }
- }
- return true, nil
- } else {
- for _, result := range results {
- if result {
- return true, nil
- }
- }
- return false, nil
+ return lo.EveryBy(results, func(item bool) bool { return item }), nil
}
+ return lo.SomeBy(results, func(item bool) bool { return item }), nil
}
func checkSingleCondition(jsonStr, contextJSON string, condition ConditionOperation) (bool, error) {
@@ -294,7 +655,7 @@ func compareNumeric(jsonValue, targetValue gjson.Result, operator string) (bool,
}
// applyOperationsLegacy 原参数覆盖方法
-func applyOperationsLegacy(jsonData []byte, paramOverride map[string]interface{}) ([]byte, error) {
+func applyOperationsLegacy(jsonData []byte, paramOverride map[string]interface{}, auditRecorder *paramOverrideAuditRecorder) ([]byte, error) {
reqMap := make(map[string]interface{})
err := common.Unmarshal(jsonData, &reqMap)
if err != nil {
@@ -303,19 +664,18 @@ func applyOperationsLegacy(jsonData []byte, paramOverride map[string]interface{}
for key, value := range paramOverride {
reqMap[key] = value
+ auditRecorder.recordOperation("set", key, "", "", value)
}
return common.Marshal(reqMap)
}
func applyOperations(jsonStr string, operations []ParamOperation, conditionContext map[string]interface{}) (string, error) {
- var contextJSON string
- if conditionContext != nil && len(conditionContext) > 0 {
- ctxBytes, err := common.Marshal(conditionContext)
- if err != nil {
- return "", fmt.Errorf("failed to marshal condition context: %v", err)
- }
- contextJSON = string(ctxBytes)
+ context := ensureContextMap(conditionContext)
+ auditRecorder := getParamOverrideAuditRecorder(context)
+ contextJSON, err := marshalContextJSON(context)
+ if err != nil {
+ return "", fmt.Errorf("failed to marshal condition context: %v", err)
}
result := jsonStr
@@ -330,19 +690,44 @@ func applyOperations(jsonStr string, operations []ParamOperation, conditionConte
}
// 处理路径中的负数索引
opPath := processNegativeIndex(result, op.Path)
+ var opPaths []string
+ if isPathBasedOperation(op.Mode) {
+ opPaths, err = resolveOperationPaths(result, opPath)
+ if err != nil {
+ return "", err
+ }
+ if len(opPaths) == 0 {
+ continue
+ }
+ }
switch op.Mode {
case "delete":
- result, err = sjson.Delete(result, opPath)
+ for _, path := range opPaths {
+ result, err = deleteValue(result, path)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("delete", path, "", "", nil)
+ }
case "set":
- if op.KeepOrigin && gjson.Get(result, opPath).Exists() {
- continue
+ for _, path := range opPaths {
+ if op.KeepOrigin && gjson.Get(result, path).Exists() {
+ continue
+ }
+ result, err = sjson.Set(result, path, op.Value)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("set", path, "", "", op.Value)
}
- result, err = sjson.Set(result, opPath, op.Value)
case "move":
opFrom := processNegativeIndex(result, op.From)
opTo := processNegativeIndex(result, op.To)
result, err = moveValue(result, opFrom, opTo)
+ if err == nil {
+ auditRecorder.recordOperation("move", "", opFrom, opTo, nil)
+ }
case "copy":
if op.From == "" || op.To == "" {
return "", fmt.Errorf("copy from/to is required")
@@ -350,38 +735,761 @@ func applyOperations(jsonStr string, operations []ParamOperation, conditionConte
opFrom := processNegativeIndex(result, op.From)
opTo := processNegativeIndex(result, op.To)
result, err = copyValue(result, opFrom, opTo)
+ if err == nil {
+ auditRecorder.recordOperation("copy", "", opFrom, opTo, nil)
+ }
case "prepend":
- result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, true)
+ for _, path := range opPaths {
+ result, err = modifyValue(result, path, op.Value, op.KeepOrigin, true)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("prepend", path, "", "", op.Value)
+ }
case "append":
- result, err = modifyValue(result, opPath, op.Value, op.KeepOrigin, false)
+ for _, path := range opPaths {
+ result, err = modifyValue(result, path, op.Value, op.KeepOrigin, false)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("append", path, "", "", op.Value)
+ }
case "trim_prefix":
- result, err = trimStringValue(result, opPath, op.Value, true)
+ for _, path := range opPaths {
+ result, err = trimStringValue(result, path, op.Value, true)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("trim_prefix", path, "", "", op.Value)
+ }
case "trim_suffix":
- result, err = trimStringValue(result, opPath, op.Value, false)
+ for _, path := range opPaths {
+ result, err = trimStringValue(result, path, op.Value, false)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("trim_suffix", path, "", "", op.Value)
+ }
case "ensure_prefix":
- result, err = ensureStringAffix(result, opPath, op.Value, true)
+ for _, path := range opPaths {
+ result, err = ensureStringAffix(result, path, op.Value, true)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("ensure_prefix", path, "", "", op.Value)
+ }
case "ensure_suffix":
- result, err = ensureStringAffix(result, opPath, op.Value, false)
+ for _, path := range opPaths {
+ result, err = ensureStringAffix(result, path, op.Value, false)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("ensure_suffix", path, "", "", op.Value)
+ }
case "trim_space":
- result, err = transformStringValue(result, opPath, strings.TrimSpace)
+ for _, path := range opPaths {
+ result, err = transformStringValue(result, path, strings.TrimSpace)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("trim_space", path, "", "", nil)
+ }
case "to_lower":
- result, err = transformStringValue(result, opPath, strings.ToLower)
+ for _, path := range opPaths {
+ result, err = transformStringValue(result, path, strings.ToLower)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("to_lower", path, "", "", nil)
+ }
case "to_upper":
- result, err = transformStringValue(result, opPath, strings.ToUpper)
+ for _, path := range opPaths {
+ result, err = transformStringValue(result, path, strings.ToUpper)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("to_upper", path, "", "", nil)
+ }
case "replace":
- result, err = replaceStringValue(result, opPath, op.From, op.To)
+ for _, path := range opPaths {
+ result, err = replaceStringValue(result, path, op.From, op.To)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("replace", path, op.From, op.To, nil)
+ }
case "regex_replace":
- result, err = regexReplaceStringValue(result, opPath, op.From, op.To)
+ for _, path := range opPaths {
+ result, err = regexReplaceStringValue(result, path, op.From, op.To)
+ if err != nil {
+ break
+ }
+ auditRecorder.recordOperation("regex_replace", path, op.From, op.To, nil)
+ }
+ case "return_error":
+ auditRecorder.recordOperation("return_error", op.Path, "", "", op.Value)
+ returnErr, parseErr := parseParamOverrideReturnError(op.Value)
+ if parseErr != nil {
+ return "", parseErr
+ }
+ return "", returnErr
+ case "prune_objects":
+ for _, path := range opPaths {
+ result, err = pruneObjects(result, path, contextJSON, op.Value)
+ if err != nil {
+ break
+ }
+ }
+ case "set_header":
+ err = setHeaderOverrideInContext(context, op.Path, op.Value, op.KeepOrigin)
+ if err == nil {
+ auditRecorder.recordOperation("set_header", op.Path, "", "", op.Value)
+ contextJSON, err = marshalContextJSON(context)
+ }
+ case "delete_header":
+ err = deleteHeaderOverrideInContext(context, op.Path)
+ if err == nil {
+ auditRecorder.recordOperation("delete_header", op.Path, "", "", nil)
+ contextJSON, err = marshalContextJSON(context)
+ }
+ case "copy_header":
+ sourceHeader := strings.TrimSpace(op.From)
+ targetHeader := strings.TrimSpace(op.To)
+ if sourceHeader == "" {
+ sourceHeader = strings.TrimSpace(op.Path)
+ }
+ if targetHeader == "" {
+ targetHeader = strings.TrimSpace(op.Path)
+ }
+ err = copyHeaderInContext(context, sourceHeader, targetHeader, op.KeepOrigin)
+ if errors.Is(err, errSourceHeaderNotFound) {
+ err = nil
+ }
+ if err == nil {
+ auditRecorder.recordOperation("copy_header", "", sourceHeader, targetHeader, nil)
+ contextJSON, err = marshalContextJSON(context)
+ }
+ case "move_header":
+ sourceHeader := strings.TrimSpace(op.From)
+ targetHeader := strings.TrimSpace(op.To)
+ if sourceHeader == "" {
+ sourceHeader = strings.TrimSpace(op.Path)
+ }
+ if targetHeader == "" {
+ targetHeader = strings.TrimSpace(op.Path)
+ }
+ err = moveHeaderInContext(context, sourceHeader, targetHeader, op.KeepOrigin)
+ if errors.Is(err, errSourceHeaderNotFound) {
+ err = nil
+ }
+ if err == nil {
+ auditRecorder.recordOperation("move_header", "", sourceHeader, targetHeader, nil)
+ contextJSON, err = marshalContextJSON(context)
+ }
+ case "pass_headers":
+ headerNames, parseErr := parseHeaderPassThroughNames(op.Value)
+ if parseErr != nil {
+ return "", parseErr
+ }
+ for _, headerName := range headerNames {
+ if err = copyHeaderInContext(context, headerName, headerName, op.KeepOrigin); err != nil {
+ if errors.Is(err, errSourceHeaderNotFound) {
+ err = nil
+ continue
+ }
+ break
+ }
+ }
+ if err == nil {
+ auditRecorder.recordOperation("pass_headers", "", "", "", headerNames)
+ contextJSON, err = marshalContextJSON(context)
+ }
+ case "sync_fields":
+ result, err = syncFieldsBetweenTargets(result, context, op.From, op.To)
+ if err == nil {
+ auditRecorder.recordOperation("sync_fields", "", op.From, op.To, nil)
+ contextJSON, err = marshalContextJSON(context)
+ }
default:
return "", fmt.Errorf("unknown operation: %s", op.Mode)
}
if err != nil {
- return "", fmt.Errorf("operation %s failed: %v", op.Mode, err)
+ return "", fmt.Errorf("operation %s failed: %w", op.Mode, err)
}
}
return result, nil
}
+func parseParamOverrideReturnError(value interface{}) (*ParamOverrideReturnError, error) {
+ result := &ParamOverrideReturnError{
+ StatusCode: http.StatusBadRequest,
+ Code: string(types.ErrorCodeInvalidRequest),
+ Type: "invalid_request_error",
+ SkipRetry: true,
+ }
+
+ switch raw := value.(type) {
+ case nil:
+ return nil, fmt.Errorf("return_error value is required")
+ case string:
+ result.Message = strings.TrimSpace(raw)
+ case map[string]interface{}:
+ if message, ok := raw["message"].(string); ok {
+ result.Message = strings.TrimSpace(message)
+ }
+ if result.Message == "" {
+ if message, ok := raw["msg"].(string); ok {
+ result.Message = strings.TrimSpace(message)
+ }
+ }
+
+ if code, exists := raw["code"]; exists {
+ codeStr := strings.TrimSpace(fmt.Sprintf("%v", code))
+ if codeStr != "" {
+ result.Code = codeStr
+ }
+ }
+ if errType, ok := raw["type"].(string); ok {
+ errType = strings.TrimSpace(errType)
+ if errType != "" {
+ result.Type = errType
+ }
+ }
+ if skipRetry, ok := raw["skip_retry"].(bool); ok {
+ result.SkipRetry = skipRetry
+ }
+
+ if statusCodeRaw, exists := raw["status_code"]; exists {
+ statusCode, ok := parseOverrideInt(statusCodeRaw)
+ if !ok {
+ return nil, fmt.Errorf("return_error status_code must be an integer")
+ }
+ result.StatusCode = statusCode
+ } else if statusRaw, exists := raw["status"]; exists {
+ statusCode, ok := parseOverrideInt(statusRaw)
+ if !ok {
+ return nil, fmt.Errorf("return_error status must be an integer")
+ }
+ result.StatusCode = statusCode
+ }
+ default:
+ return nil, fmt.Errorf("return_error value must be string or object")
+ }
+
+ if result.Message == "" {
+ return nil, fmt.Errorf("return_error message is required")
+ }
+ if result.StatusCode < http.StatusContinue || result.StatusCode > http.StatusNetworkAuthenticationRequired {
+ return nil, fmt.Errorf("return_error status code out of range: %d", result.StatusCode)
+ }
+
+ return result, nil
+}
+
+func parseOverrideInt(v interface{}) (int, bool) {
+ switch value := v.(type) {
+ case int:
+ return value, true
+ case float64:
+ if value != float64(int(value)) {
+ return 0, false
+ }
+ return int(value), true
+ default:
+ return 0, false
+ }
+}
+
+func ensureContextMap(conditionContext map[string]interface{}) map[string]interface{} {
+ if conditionContext != nil {
+ return conditionContext
+ }
+ return make(map[string]interface{})
+}
+
+func marshalContextJSON(context map[string]interface{}) (string, error) {
+ if context == nil || len(context) == 0 {
+ return "", nil
+ }
+ ctxBytes, err := common.Marshal(context)
+ if err != nil {
+ return "", err
+ }
+ return string(ctxBytes), nil
+}
+
+func setHeaderOverrideInContext(context map[string]interface{}, headerName string, value interface{}, keepOrigin bool) error {
+ headerName = normalizeHeaderContextKey(headerName)
+ if headerName == "" {
+ return fmt.Errorf("header name is required")
+ }
+
+ rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
+ if keepOrigin {
+ if existing, ok := rawHeaders[headerName]; ok {
+ existingValue := strings.TrimSpace(fmt.Sprintf("%v", existing))
+ if existingValue != "" {
+ return nil
+ }
+ }
+ }
+
+ headerValue, hasValue, err := resolveHeaderOverrideValue(context, headerName, value)
+ if err != nil {
+ return err
+ }
+ if !hasValue {
+ delete(rawHeaders, headerName)
+ return nil
+ }
+
+ rawHeaders[headerName] = headerValue
+ return nil
+}
+
+func resolveHeaderOverrideValue(context map[string]interface{}, headerName string, value interface{}) (string, bool, error) {
+ if value == nil {
+ return "", false, fmt.Errorf("header value is required")
+ }
+
+ if mapping, ok := value.(map[string]interface{}); ok {
+ return resolveHeaderOverrideValueByMapping(context, headerName, mapping)
+ }
+ if mapping, ok := value.(map[string]string); ok {
+ converted := make(map[string]interface{}, len(mapping))
+ for key, item := range mapping {
+ converted[key] = item
+ }
+ return resolveHeaderOverrideValueByMapping(context, headerName, converted)
+ }
+
+ headerValue := strings.TrimSpace(fmt.Sprintf("%v", value))
+ if headerValue == "" {
+ return "", false, nil
+ }
+ return headerValue, true, nil
+}
+
+func resolveHeaderOverrideValueByMapping(context map[string]interface{}, headerName string, mapping map[string]interface{}) (string, bool, error) {
+ if len(mapping) == 0 {
+ return "", false, fmt.Errorf("header value mapping cannot be empty")
+ }
+
+ appendTokens, err := parseHeaderAppendTokens(mapping)
+ if err != nil {
+ return "", false, err
+ }
+ keepOnlyDeclared := parseHeaderKeepOnlyDeclared(mapping)
+
+ sourceValue, exists := getHeaderValueFromContext(context, headerName)
+ sourceTokens := make([]string, 0)
+ if exists {
+ sourceTokens = splitHeaderListValue(sourceValue)
+ }
+
+ wildcardValue, hasWildcard := mapping["*"]
+ resultTokens := make([]string, 0, len(sourceTokens)+len(appendTokens))
+ for _, token := range sourceTokens {
+ replacementRaw, hasReplacement := mapping[token]
+ if !hasReplacement && hasWildcard && !keepOnlyDeclared {
+ replacementRaw = wildcardValue
+ hasReplacement = true
+ }
+ if !hasReplacement {
+ if keepOnlyDeclared {
+ continue
+ }
+ resultTokens = append(resultTokens, token)
+ continue
+ }
+ replacementTokens, err := parseHeaderReplacementTokens(replacementRaw)
+ if err != nil {
+ return "", false, err
+ }
+ resultTokens = append(resultTokens, replacementTokens...)
+ }
+
+ resultTokens = append(resultTokens, appendTokens...)
+ resultTokens = lo.Uniq(resultTokens)
+ if len(resultTokens) == 0 {
+ return "", false, nil
+ }
+ return strings.Join(resultTokens, ","), true, nil
+}
+
+func parseHeaderAppendTokens(mapping map[string]interface{}) ([]string, error) {
+ appendRaw, ok := mapping["$append"]
+ if !ok {
+ return nil, nil
+ }
+ return parseHeaderReplacementTokens(appendRaw)
+}
+
+func parseHeaderKeepOnlyDeclared(mapping map[string]interface{}) bool {
+ keepOnlyDeclaredRaw, ok := mapping["$keep_only_declared"]
+ if !ok {
+ return false
+ }
+ keepOnlyDeclared, ok := keepOnlyDeclaredRaw.(bool)
+ if !ok {
+ return false
+ }
+ return keepOnlyDeclared
+}
+
+func parseHeaderReplacementTokens(value interface{}) ([]string, error) {
+ switch raw := value.(type) {
+ case nil:
+ return nil, nil
+ case string:
+ return splitHeaderListValue(raw), nil
+ case []string:
+ tokens := make([]string, 0, len(raw))
+ for _, item := range raw {
+ tokens = append(tokens, splitHeaderListValue(item)...)
+ }
+ return lo.Uniq(tokens), nil
+ case []interface{}:
+ tokens := make([]string, 0, len(raw))
+ for _, item := range raw {
+ itemTokens, err := parseHeaderReplacementTokens(item)
+ if err != nil {
+ return nil, err
+ }
+ tokens = append(tokens, itemTokens...)
+ }
+ return lo.Uniq(tokens), nil
+ case map[string]interface{}, map[string]string:
+ return nil, fmt.Errorf("header replacement value must be string, array or null")
+ default:
+ token := strings.TrimSpace(fmt.Sprintf("%v", raw))
+ if token == "" {
+ return nil, nil
+ }
+ return []string{token}, nil
+ }
+}
+
+func splitHeaderListValue(raw string) []string {
+ items := strings.Split(raw, ",")
+ return lo.FilterMap(items, func(item string, _ int) (string, bool) {
+ token := strings.TrimSpace(item)
+ if token == "" {
+ return "", false
+ }
+ return token, true
+ })
+}
+
+func copyHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
+ fromHeader = normalizeHeaderContextKey(fromHeader)
+ toHeader = normalizeHeaderContextKey(toHeader)
+ if fromHeader == "" || toHeader == "" {
+ return fmt.Errorf("copy_header from/to is required")
+ }
+ value, exists := getHeaderValueFromContext(context, fromHeader)
+ if !exists {
+ return fmt.Errorf("%w: %s", errSourceHeaderNotFound, fromHeader)
+ }
+ return setHeaderOverrideInContext(context, toHeader, value, keepOrigin)
+}
+
+func moveHeaderInContext(context map[string]interface{}, fromHeader, toHeader string, keepOrigin bool) error {
+ fromHeader = normalizeHeaderContextKey(fromHeader)
+ toHeader = normalizeHeaderContextKey(toHeader)
+ if fromHeader == "" || toHeader == "" {
+ return fmt.Errorf("move_header from/to is required")
+ }
+ if err := copyHeaderInContext(context, fromHeader, toHeader, keepOrigin); err != nil {
+ return err
+ }
+ if strings.EqualFold(fromHeader, toHeader) {
+ return nil
+ }
+ return deleteHeaderOverrideInContext(context, fromHeader)
+}
+
+func deleteHeaderOverrideInContext(context map[string]interface{}, headerName string) error {
+ headerName = normalizeHeaderContextKey(headerName)
+ if headerName == "" {
+ return fmt.Errorf("header name is required")
+ }
+ rawHeaders := ensureMapKeyInContext(context, paramOverrideContextHeaderOverride)
+ delete(rawHeaders, headerName)
+ return nil
+}
+
+func parseHeaderPassThroughNames(value interface{}) ([]string, error) {
+ normalizeNames := func(values []string) []string {
+ names := lo.FilterMap(values, func(item string, _ int) (string, bool) {
+ headerName := normalizeHeaderContextKey(item)
+ if headerName == "" {
+ return "", false
+ }
+ return headerName, true
+ })
+ return lo.Uniq(names)
+ }
+
+ switch raw := value.(type) {
+ case nil:
+ return nil, fmt.Errorf("pass_headers value is required")
+ case string:
+ trimmed := strings.TrimSpace(raw)
+ if trimmed == "" {
+ return nil, fmt.Errorf("pass_headers value is required")
+ }
+ if strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{") {
+ var parsed interface{}
+ if err := common.UnmarshalJsonStr(trimmed, &parsed); err == nil {
+ return parseHeaderPassThroughNames(parsed)
+ }
+ }
+ names := normalizeNames(strings.Split(trimmed, ","))
+ if len(names) == 0 {
+ return nil, fmt.Errorf("pass_headers value is invalid")
+ }
+ return names, nil
+ case []interface{}:
+ names := lo.FilterMap(raw, func(item interface{}, _ int) (string, bool) {
+ headerName := normalizeHeaderContextKey(fmt.Sprintf("%v", item))
+ if headerName == "" {
+ return "", false
+ }
+ return headerName, true
+ })
+ names = lo.Uniq(names)
+ if len(names) == 0 {
+ return nil, fmt.Errorf("pass_headers value is invalid")
+ }
+ return names, nil
+ case []string:
+ names := lo.FilterMap(raw, func(item string, _ int) (string, bool) {
+ headerName := normalizeHeaderContextKey(item)
+ if headerName == "" {
+ return "", false
+ }
+ return headerName, true
+ })
+ names = lo.Uniq(names)
+ if len(names) == 0 {
+ return nil, fmt.Errorf("pass_headers value is invalid")
+ }
+ return names, nil
+ case map[string]interface{}:
+ candidates := make([]string, 0, 8)
+ if headersRaw, ok := raw["headers"]; ok {
+ names, err := parseHeaderPassThroughNames(headersRaw)
+ if err == nil {
+ candidates = append(candidates, names...)
+ }
+ }
+ if namesRaw, ok := raw["names"]; ok {
+ names, err := parseHeaderPassThroughNames(namesRaw)
+ if err == nil {
+ candidates = append(candidates, names...)
+ }
+ }
+ if headerRaw, ok := raw["header"]; ok {
+ names, err := parseHeaderPassThroughNames(headerRaw)
+ if err == nil {
+ candidates = append(candidates, names...)
+ }
+ }
+ names := normalizeNames(candidates)
+ if len(names) == 0 {
+ return nil, fmt.Errorf("pass_headers value is invalid")
+ }
+ return names, nil
+ default:
+ return nil, fmt.Errorf("pass_headers value must be string, array or object")
+ }
+}
+
+type syncTarget struct {
+ kind string
+ key string
+}
+
+func parseSyncTarget(spec string) (syncTarget, error) {
+ raw := strings.TrimSpace(spec)
+ if raw == "" {
+ return syncTarget{}, fmt.Errorf("sync_fields target is required")
+ }
+
+ idx := strings.Index(raw, ":")
+ if idx < 0 {
+ // Backward compatibility: treat bare value as JSON path.
+ return syncTarget{
+ kind: "json",
+ key: raw,
+ }, nil
+ }
+
+ kind := strings.ToLower(strings.TrimSpace(raw[:idx]))
+ key := strings.TrimSpace(raw[idx+1:])
+ if key == "" {
+ return syncTarget{}, fmt.Errorf("sync_fields target key is required: %s", raw)
+ }
+
+ switch kind {
+ case "json", "body":
+ return syncTarget{
+ kind: "json",
+ key: key,
+ }, nil
+ case "header":
+ return syncTarget{
+ kind: "header",
+ key: key,
+ }, nil
+ default:
+ return syncTarget{}, fmt.Errorf("sync_fields target prefix is invalid: %s", raw)
+ }
+}
+
+func readSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget) (interface{}, bool, error) {
+ switch target.kind {
+ case "json":
+ path := processNegativeIndex(jsonStr, target.key)
+ value := gjson.Get(jsonStr, path)
+ if !value.Exists() || value.Type == gjson.Null {
+ return nil, false, nil
+ }
+ if value.Type == gjson.String && strings.TrimSpace(value.String()) == "" {
+ return nil, false, nil
+ }
+ return value.Value(), true, nil
+ case "header":
+ value, ok := getHeaderValueFromContext(context, target.key)
+ if !ok || strings.TrimSpace(value) == "" {
+ return nil, false, nil
+ }
+ return value, true, nil
+ default:
+ return nil, false, fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
+ }
+}
+
+func writeSyncTargetValue(jsonStr string, context map[string]interface{}, target syncTarget, value interface{}) (string, error) {
+ switch target.kind {
+ case "json":
+ path := processNegativeIndex(jsonStr, target.key)
+ nextJSON, err := sjson.Set(jsonStr, path, value)
+ if err != nil {
+ return "", err
+ }
+ return nextJSON, nil
+ case "header":
+ if err := setHeaderOverrideInContext(context, target.key, value, false); err != nil {
+ return "", err
+ }
+ return jsonStr, nil
+ default:
+ return "", fmt.Errorf("unsupported sync_fields target kind: %s", target.kind)
+ }
+}
+
+func syncFieldsBetweenTargets(jsonStr string, context map[string]interface{}, fromSpec string, toSpec string) (string, error) {
+ fromTarget, err := parseSyncTarget(fromSpec)
+ if err != nil {
+ return "", err
+ }
+ toTarget, err := parseSyncTarget(toSpec)
+ if err != nil {
+ return "", err
+ }
+
+ fromValue, fromExists, err := readSyncTargetValue(jsonStr, context, fromTarget)
+ if err != nil {
+ return "", err
+ }
+ toValue, toExists, err := readSyncTargetValue(jsonStr, context, toTarget)
+ if err != nil {
+ return "", err
+ }
+
+ // If one side exists and the other side is missing, sync the missing side.
+ if fromExists && !toExists {
+ return writeSyncTargetValue(jsonStr, context, toTarget, fromValue)
+ }
+ if toExists && !fromExists {
+ return writeSyncTargetValue(jsonStr, context, fromTarget, toValue)
+ }
+ return jsonStr, nil
+}
+
+func ensureMapKeyInContext(context map[string]interface{}, key string) map[string]interface{} {
+ if context == nil {
+ return map[string]interface{}{}
+ }
+ if existing, ok := context[key]; ok {
+ if mapVal, ok := existing.(map[string]interface{}); ok {
+ return mapVal
+ }
+ }
+ result := make(map[string]interface{})
+ context[key] = result
+ return result
+}
+
+func getHeaderValueFromContext(context map[string]interface{}, headerName string) (string, bool) {
+ headerName = normalizeHeaderContextKey(headerName)
+ if headerName == "" {
+ return "", false
+ }
+ for _, key := range []string{paramOverrideContextHeaderOverride, paramOverrideContextRequestHeaders} {
+ source := ensureMapKeyInContext(context, key)
+ raw, ok := source[headerName]
+ if !ok {
+ continue
+ }
+ value := strings.TrimSpace(fmt.Sprintf("%v", raw))
+ if value != "" {
+ return value, true
+ }
+ }
+ return "", false
+}
+
+func normalizeHeaderContextKey(key string) string {
+ return strings.TrimSpace(strings.ToLower(key))
+}
+
+func buildRequestHeadersContext(headers map[string]string) map[string]interface{} {
+ if len(headers) == 0 {
+ return map[string]interface{}{}
+ }
+ entries := lo.Entries(headers)
+ normalizedEntries := lo.FilterMap(entries, func(item lo.Entry[string, string], _ int) (lo.Entry[string, string], bool) {
+ normalized := normalizeHeaderContextKey(item.Key)
+ value := strings.TrimSpace(item.Value)
+ if normalized == "" || value == "" {
+ return lo.Entry[string, string]{}, false
+ }
+ return lo.Entry[string, string]{Key: normalized, Value: value}, true
+ })
+ return lo.SliceToMap(normalizedEntries, func(item lo.Entry[string, string]) (string, interface{}) {
+ return item.Key, item.Value
+ })
+}
+
+func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]interface{}) {
+ if info == nil || context == nil {
+ return
+ }
+ raw, exists := context[paramOverrideContextHeaderOverride]
+ if !exists {
+ return
+ }
+ rawMap, ok := raw.(map[string]interface{})
+ if !ok {
+ return
+ }
+ info.RuntimeHeadersOverride = sanitizeHeaderOverrideMap(rawMap)
+ info.UseRuntimeHeadersOverride = true
+}
+
func moveValue(jsonStr, fromPath, toPath string) (string, error) {
sourceValue := gjson.Get(jsonStr, fromPath)
if !sourceValue.Exists() {
@@ -402,6 +1510,92 @@ func copyValue(jsonStr, fromPath, toPath string) (string, error) {
return sjson.Set(jsonStr, toPath, sourceValue.Value())
}
+func isPathBasedOperation(mode string) bool {
+ switch mode {
+ case "delete", "set", "prepend", "append", "trim_prefix", "trim_suffix", "ensure_prefix", "ensure_suffix", "trim_space", "to_lower", "to_upper", "replace", "regex_replace", "prune_objects":
+ return true
+ default:
+ return false
+ }
+}
+
+func resolveOperationPaths(jsonStr, path string) ([]string, error) {
+ if !strings.Contains(path, "*") {
+ return []string{path}, nil
+ }
+ return expandWildcardPaths(jsonStr, path)
+}
+
+func expandWildcardPaths(jsonStr, path string) ([]string, error) {
+ var root interface{}
+ if err := common.Unmarshal([]byte(jsonStr), &root); err != nil {
+ return nil, err
+ }
+
+ segments := strings.Split(path, ".")
+ paths := collectWildcardPaths(root, segments, nil)
+ return lo.Uniq(paths), nil
+}
+
+func collectWildcardPaths(node interface{}, segments []string, prefix []string) []string {
+ if len(segments) == 0 {
+ return []string{strings.Join(prefix, ".")}
+ }
+
+ segment := strings.TrimSpace(segments[0])
+ if segment == "" {
+ return nil
+ }
+ isLast := len(segments) == 1
+
+ if segment == "*" {
+ switch typed := node.(type) {
+ case map[string]interface{}:
+ keys := lo.Keys(typed)
+ sort.Strings(keys)
+ return lo.FlatMap(keys, func(key string, _ int) []string {
+ return collectWildcardPaths(typed[key], segments[1:], append(prefix, key))
+ })
+ case []interface{}:
+ return lo.FlatMap(lo.Range(len(typed)), func(index int, _ int) []string {
+ return collectWildcardPaths(typed[index], segments[1:], append(prefix, strconv.Itoa(index)))
+ })
+ default:
+ return nil
+ }
+ }
+
+ switch typed := node.(type) {
+ case map[string]interface{}:
+ if isLast {
+ return []string{strings.Join(append(prefix, segment), ".")}
+ }
+ next, exists := typed[segment]
+ if !exists {
+ return nil
+ }
+ return collectWildcardPaths(next, segments[1:], append(prefix, segment))
+ case []interface{}:
+ index, err := strconv.Atoi(segment)
+ if err != nil || index < 0 || index >= len(typed) {
+ return nil
+ }
+ if isLast {
+ return []string{strings.Join(append(prefix, segment), ".")}
+ }
+ return collectWildcardPaths(typed[index], segments[1:], append(prefix, segment))
+ default:
+ return nil
+ }
+}
+
+func deleteValue(jsonStr, path string) (string, error) {
+ if strings.TrimSpace(path) == "" {
+ return jsonStr, nil
+ }
+ return sjson.Delete(jsonStr, path)
+}
+
func modifyValue(jsonStr, path string, value interface{}, keepOrigin, isPrepend bool) (string, error) {
current := gjson.Get(jsonStr, path)
switch {
@@ -537,6 +1731,235 @@ func regexReplaceStringValue(jsonStr, path, pattern, replacement string) (string
return sjson.Set(jsonStr, path, re.ReplaceAllString(current.String(), replacement))
}
+type pruneObjectsOptions struct {
+ conditions []ConditionOperation
+ logic string
+ recursive bool
+}
+
+func pruneObjects(jsonStr, path, contextJSON string, value interface{}) (string, error) {
+ options, err := parsePruneObjectsOptions(value)
+ if err != nil {
+ return "", err
+ }
+
+ if path == "" {
+ var root interface{}
+ if err := common.Unmarshal([]byte(jsonStr), &root); err != nil {
+ return "", err
+ }
+ cleaned, _, err := pruneObjectsNode(root, options, contextJSON, true)
+ if err != nil {
+ return "", err
+ }
+ cleanedBytes, err := common.Marshal(cleaned)
+ if err != nil {
+ return "", err
+ }
+ return string(cleanedBytes), nil
+ }
+
+ target := gjson.Get(jsonStr, path)
+ if !target.Exists() {
+ return jsonStr, nil
+ }
+
+ var targetNode interface{}
+ if target.Type == gjson.JSON {
+ if err := common.Unmarshal([]byte(target.Raw), &targetNode); err != nil {
+ return "", err
+ }
+ } else {
+ targetNode = target.Value()
+ }
+
+ cleaned, _, err := pruneObjectsNode(targetNode, options, contextJSON, true)
+ if err != nil {
+ return "", err
+ }
+ cleanedBytes, err := common.Marshal(cleaned)
+ if err != nil {
+ return "", err
+ }
+ return sjson.SetRaw(jsonStr, path, string(cleanedBytes))
+}
+
+func parsePruneObjectsOptions(value interface{}) (pruneObjectsOptions, error) {
+ opts := pruneObjectsOptions{
+ logic: "AND",
+ recursive: true,
+ }
+
+ switch raw := value.(type) {
+ case nil:
+ return opts, fmt.Errorf("prune_objects value is required")
+ case string:
+ v := strings.TrimSpace(raw)
+ if v == "" {
+ return opts, fmt.Errorf("prune_objects value is required")
+ }
+ opts.conditions = []ConditionOperation{
+ {
+ Path: "type",
+ Mode: "full",
+ Value: v,
+ },
+ }
+ case map[string]interface{}:
+ if logic, ok := raw["logic"].(string); ok && strings.TrimSpace(logic) != "" {
+ opts.logic = logic
+ }
+ if recursive, ok := raw["recursive"].(bool); ok {
+ opts.recursive = recursive
+ }
+
+ if condRaw, exists := raw["conditions"]; exists {
+ conditions, err := parseConditionOperations(condRaw)
+ if err != nil {
+ return opts, err
+ }
+ opts.conditions = append(opts.conditions, conditions...)
+ }
+
+ if whereRaw, exists := raw["where"]; exists {
+ whereMap, ok := whereRaw.(map[string]interface{})
+ if !ok {
+ return opts, fmt.Errorf("prune_objects where must be object")
+ }
+ for key, val := range whereMap {
+ key = strings.TrimSpace(key)
+ if key == "" {
+ continue
+ }
+ opts.conditions = append(opts.conditions, ConditionOperation{
+ Path: key,
+ Mode: "full",
+ Value: val,
+ })
+ }
+ }
+
+ if matchType, exists := raw["type"]; exists {
+ opts.conditions = append(opts.conditions, ConditionOperation{
+ Path: "type",
+ Mode: "full",
+ Value: matchType,
+ })
+ }
+ default:
+ return opts, fmt.Errorf("prune_objects value must be string or object")
+ }
+
+ if len(opts.conditions) == 0 {
+ return opts, fmt.Errorf("prune_objects conditions are required")
+ }
+ return opts, nil
+}
+
+func parseConditionOperations(raw interface{}) ([]ConditionOperation, error) {
+ switch typed := raw.(type) {
+ case map[string]interface{}:
+ entries := lo.Entries(typed)
+ conditions := lo.FilterMap(entries, func(item lo.Entry[string, interface{}], _ int) (ConditionOperation, bool) {
+ path := strings.TrimSpace(item.Key)
+ if path == "" {
+ return ConditionOperation{}, false
+ }
+ return ConditionOperation{
+ Path: path,
+ Mode: "full",
+ Value: item.Value,
+ }, true
+ })
+ if len(conditions) == 0 {
+ return nil, fmt.Errorf("conditions object must contain at least one key")
+ }
+ return conditions, nil
+ case []interface{}:
+ items := typed
+ result := make([]ConditionOperation, 0, len(items))
+ for _, item := range items {
+ itemMap, ok := item.(map[string]interface{})
+ if !ok {
+ return nil, fmt.Errorf("condition must be object")
+ }
+ path, _ := itemMap["path"].(string)
+ mode, _ := itemMap["mode"].(string)
+ if strings.TrimSpace(path) == "" || strings.TrimSpace(mode) == "" {
+ return nil, fmt.Errorf("condition path/mode is required")
+ }
+ condition := ConditionOperation{
+ Path: path,
+ Mode: mode,
+ }
+ if value, exists := itemMap["value"]; exists {
+ condition.Value = value
+ }
+ if invert, ok := itemMap["invert"].(bool); ok {
+ condition.Invert = invert
+ }
+ if passMissingKey, ok := itemMap["pass_missing_key"].(bool); ok {
+ condition.PassMissingKey = passMissingKey
+ }
+ result = append(result, condition)
+ }
+ return result, nil
+ default:
+ return nil, fmt.Errorf("conditions must be an array or object")
+ }
+}
+
+func pruneObjectsNode(node interface{}, options pruneObjectsOptions, contextJSON string, isRoot bool) (interface{}, bool, error) {
+ switch value := node.(type) {
+ case []interface{}:
+ result := make([]interface{}, 0, len(value))
+ for _, item := range value {
+ next, drop, err := pruneObjectsNode(item, options, contextJSON, false)
+ if err != nil {
+ return nil, false, err
+ }
+ if drop {
+ continue
+ }
+ result = append(result, next)
+ }
+ return result, false, nil
+ case map[string]interface{}:
+ shouldDrop, err := shouldPruneObject(value, options, contextJSON)
+ if err != nil {
+ return nil, false, err
+ }
+ if shouldDrop && !isRoot {
+ return nil, true, nil
+ }
+ if !options.recursive {
+ return value, false, nil
+ }
+ for key, child := range value {
+ next, drop, err := pruneObjectsNode(child, options, contextJSON, false)
+ if err != nil {
+ return nil, false, err
+ }
+ if drop {
+ delete(value, key)
+ continue
+ }
+ value[key] = next
+ }
+ return value, false, nil
+ default:
+ return node, false, nil
+ }
+}
+
+func shouldPruneObject(node map[string]interface{}, options pruneObjectsOptions, contextJSON string) (bool, error) {
+ nodeBytes, err := common.Marshal(node)
+ if err != nil {
+ return false, err
+ }
+ return checkConditions(string(nodeBytes), contextJSON, options.conditions, options.logic)
+}
+
func mergeObjects(jsonStr, path string, value interface{}, keepOrigin bool) (string, error) {
current := gjson.Get(jsonStr, path)
var currentMap, newMap map[string]interface{}
@@ -598,6 +2021,37 @@ func BuildParamOverrideContext(info *RelayInfo) map[string]interface{} {
}
}
+ ctx[paramOverrideContextRequestHeaders] = buildRequestHeadersContext(info.RequestHeaders)
+
+ headerOverrideSource := GetEffectiveHeaderOverride(info)
+ ctx[paramOverrideContextHeaderOverride] = sanitizeHeaderOverrideMap(headerOverrideSource)
+
+ ctx["retry_index"] = info.RetryIndex
+ ctx["is_retry"] = info.RetryIndex > 0
+ ctx["retry"] = map[string]interface{}{
+ "index": info.RetryIndex,
+ "is_retry": info.RetryIndex > 0,
+ }
+
+ if info.LastError != nil {
+ code := string(info.LastError.GetErrorCode())
+ errorType := string(info.LastError.GetErrorType())
+ lastError := map[string]interface{}{
+ "status_code": info.LastError.StatusCode,
+ "message": info.LastError.Error(),
+ "code": code,
+ "error_code": code,
+ "type": errorType,
+ "error_type": errorType,
+ "skip_retry": types.IsSkipRetryError(info.LastError),
+ }
+ ctx["last_error"] = lastError
+ ctx["last_error_status_code"] = info.LastError.StatusCode
+ ctx["last_error_message"] = info.LastError.Error()
+ ctx["last_error_code"] = code
+ ctx["last_error_type"] = errorType
+ }
+
ctx["is_channel_test"] = info.IsChannelTest
return ctx
}
diff --git a/relay/common/override_test.go b/relay/common/override_test.go
index 021df3f60e..1a7793ba2c 100644
--- a/relay/common/override_test.go
+++ b/relay/common/override_test.go
@@ -2,8 +2,16 @@ package common
import (
"encoding/json"
+ "fmt"
"reflect"
"testing"
+
+ common2 "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/setting/model_setting"
+ "github.com/samber/lo"
)
func TestApplyParamOverrideTrimPrefix(t *testing.T) {
@@ -69,6 +77,48 @@ func TestApplyParamOverrideTrimNoop(t *testing.T) {
assertJSONEqual(t, `{"model":"gpt-4","temperature":0.7}`, string(out))
}
+func TestApplyParamOverrideMixedLegacyAndOperations(t *testing.T) {
+ input := []byte(`{"model":"openai/gpt-4","temperature":0.7}`)
+ override := map[string]interface{}{
+ "temperature": 0.2,
+ "top_p": 0.95,
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "model",
+ "mode": "trim_prefix",
+ "value": "openai/",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"gpt-4","temperature":0.2,"top_p":0.95}`, string(out))
+}
+
+func TestApplyParamOverrideMixedLegacyAndOperationsConflictPrefersOperations(t *testing.T) {
+ input := []byte(`{"model":"openai/gpt-4","temperature":0.7}`)
+ override := map[string]interface{}{
+ "model": "legacy-model",
+ "temperature": 0.2,
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "model",
+ "mode": "set",
+ "value": "op-model",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"op-model","temperature":0.2}`, string(out))
+}
+
func TestApplyParamOverrideTrimRequiresValue(t *testing.T) {
// trim_prefix requires value example:
// {"operations":[{"path":"model","mode":"trim_prefix"}]}
@@ -195,6 +245,224 @@ func TestApplyParamOverrideDelete(t *testing.T) {
}
}
+func TestApplyParamOverrideDeleteWildcardPath(t *testing.T) {
+ input := []byte(`{"tools":[{"type":"bash","custom":{"input_examples":["a"],"other":1}},{"type":"code","custom":{"input_examples":["b"]}},{"type":"noop","custom":{"other":2}}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.input_examples",
+ "mode": "delete",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"tools":[{"type":"bash","custom":{"other":1}},{"type":"code","custom":{}},{"type":"noop","custom":{"other":2}}]}`, string(out))
+}
+
+func TestApplyParamOverrideSetWildcardPath(t *testing.T) {
+ input := []byte(`{"tools":[{"custom":{"tag":"A"}},{"custom":{"tag":"B"}},{"custom":{"tag":"C"}}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.enabled",
+ "mode": "set",
+ "value": true,
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ var got struct {
+ Tools []struct {
+ Custom struct {
+ Enabled bool `json:"enabled"`
+ } `json:"custom"`
+ } `json:"tools"`
+ }
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatalf("failed to unmarshal output JSON: %v", err)
+ }
+
+ if !lo.EveryBy(got.Tools, func(item struct {
+ Custom struct {
+ Enabled bool `json:"enabled"`
+ } `json:"custom"`
+ }) bool {
+ return item.Custom.Enabled
+ }) {
+ t.Fatalf("expected wildcard set to enable all tools, got: %s", string(out))
+ }
+}
+
+func TestApplyParamOverrideTrimSpaceWildcardPath(t *testing.T) {
+ input := []byte(`{"tools":[{"custom":{"name":" alpha "}},{"custom":{"name":" beta"}},{"custom":{"name":"gamma "}}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.name",
+ "mode": "trim_space",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ var got struct {
+ Tools []struct {
+ Custom struct {
+ Name string `json:"name"`
+ } `json:"custom"`
+ } `json:"tools"`
+ }
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatalf("failed to unmarshal output JSON: %v", err)
+ }
+
+ names := lo.Map(got.Tools, func(item struct {
+ Custom struct {
+ Name string `json:"name"`
+ } `json:"custom"`
+ }, _ int) string {
+ return item.Custom.Name
+ })
+ if !reflect.DeepEqual(names, []string{"alpha", "beta", "gamma"}) {
+ t.Fatalf("unexpected names after wildcard trim_space: %v", names)
+ }
+}
+
+func TestApplyParamOverrideDeleteWildcardEqualsIndexedPaths(t *testing.T) {
+ input := []byte(`{"tools":[{"custom":{"input_examples":["a"],"other":1}},{"custom":{"input_examples":["b"],"other":2}},{"custom":{"input_examples":["c"],"other":3}}]}`)
+
+ wildcardOverride := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.input_examples",
+ "mode": "delete",
+ },
+ },
+ }
+
+ indexedOverride := map[string]interface{}{
+ "operations": lo.Map(lo.Range(3), func(index int, _ int) interface{} {
+ return map[string]interface{}{
+ "path": fmt.Sprintf("tools.%d.custom.input_examples", index),
+ "mode": "delete",
+ }
+ }),
+ }
+
+ wildcardOut, err := ApplyParamOverride(input, wildcardOverride, nil)
+ if err != nil {
+ t.Fatalf("wildcard ApplyParamOverride returned error: %v", err)
+ }
+
+ indexedOut, err := ApplyParamOverride(input, indexedOverride, nil)
+ if err != nil {
+ t.Fatalf("indexed ApplyParamOverride returned error: %v", err)
+ }
+
+ assertJSONEqual(t, string(indexedOut), string(wildcardOut))
+}
+
+func TestApplyParamOverrideSetWildcardKeepOrigin(t *testing.T) {
+ input := []byte(`{"tools":[{"custom":{"tag":"A"}},{"custom":{"tag":"B","enabled":false}},{"custom":{"tag":"C"}}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.enabled",
+ "mode": "set",
+ "value": true,
+ "keep_origin": true,
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ var got struct {
+ Tools []struct {
+ Custom struct {
+ Enabled bool `json:"enabled"`
+ } `json:"custom"`
+ } `json:"tools"`
+ }
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatalf("failed to unmarshal output JSON: %v", err)
+ }
+
+ enabledValues := lo.Map(got.Tools, func(item struct {
+ Custom struct {
+ Enabled bool `json:"enabled"`
+ } `json:"custom"`
+ }, _ int) bool {
+ return item.Custom.Enabled
+ })
+ if !reflect.DeepEqual(enabledValues, []bool{true, false, true}) {
+ t.Fatalf("unexpected enabled values after wildcard keep_origin set: %v", enabledValues)
+ }
+}
+
+func TestApplyParamOverrideTrimSpaceMultiWildcardPath(t *testing.T) {
+ input := []byte(`{"tools":[{"custom":{"items":[{"name":" alpha "},{"name":" beta "}]}},{"custom":{"items":[{"name":" gamma"}]}}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "tools.*.custom.items.*.name",
+ "mode": "trim_space",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ var got struct {
+ Tools []struct {
+ Custom struct {
+ Items []struct {
+ Name string `json:"name"`
+ } `json:"items"`
+ } `json:"custom"`
+ } `json:"tools"`
+ }
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatalf("failed to unmarshal output JSON: %v", err)
+ }
+
+ names := lo.FlatMap(got.Tools, func(tool struct {
+ Custom struct {
+ Items []struct {
+ Name string `json:"name"`
+ } `json:"items"`
+ } `json:"custom"`
+ }, _ int) []string {
+ return lo.Map(tool.Custom.Items, func(item struct {
+ Name string `json:"name"`
+ }, _ int) string {
+ return item.Name
+ })
+ })
+ if !reflect.DeepEqual(names, []string{"alpha", "beta", "gamma"}) {
+ t.Fatalf("unexpected names after multi wildcard trim_space: %v", names)
+ }
+}
+
func TestApplyParamOverrideSet(t *testing.T) {
input := []byte(`{"model":"gpt-4","temperature":0.7}`)
override := map[string]interface{}{
@@ -214,6 +482,42 @@ func TestApplyParamOverrideSet(t *testing.T) {
assertJSONEqual(t, `{"model":"gpt-4","temperature":0.1}`, string(out))
}
+func TestApplyParamOverrideSetWithDescriptionKeepsCompatibility(t *testing.T) {
+ input := []byte(`{"model":"gpt-4","temperature":0.7}`)
+ overrideWithoutDesc := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ },
+ },
+ }
+ overrideWithDesc := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "description": "set temperature for deterministic output",
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ },
+ },
+ }
+
+ outWithoutDesc, err := ApplyParamOverride(input, overrideWithoutDesc, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride without description returned error: %v", err)
+ }
+
+ outWithDesc, err := ApplyParamOverride(input, overrideWithDesc, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride with description returned error: %v", err)
+ }
+
+ assertJSONEqual(t, string(outWithoutDesc), string(outWithDesc))
+ assertJSONEqual(t, `{"model":"gpt-4","temperature":0.1}`, string(outWithDesc))
+}
+
func TestApplyParamOverrideSetKeepOrigin(t *testing.T) {
input := []byte(`{"model":"gpt-4","temperature":0.7}`)
override := map[string]interface{}{
@@ -772,6 +1076,1096 @@ func TestApplyParamOverrideToUpper(t *testing.T) {
assertJSONEqual(t, `{"model":"GPT-4"}`, string(out))
}
+func TestApplyParamOverrideReturnError(t *testing.T) {
+ input := []byte(`{"model":"gemini-2.5-pro"}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "return_error",
+ "value": map[string]interface{}{
+ "message": "forced bad request by param override",
+ "status_code": 422,
+ "code": "forced_bad_request",
+ "type": "invalid_request_error",
+ "skip_retry": true,
+ },
+ "conditions": []interface{}{
+ map[string]interface{}{
+ "path": "retry.is_retry",
+ "mode": "full",
+ "value": true,
+ },
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "retry": map[string]interface{}{
+ "index": 1,
+ "is_retry": true,
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, ctx)
+ if err == nil {
+ t.Fatalf("expected error, got nil")
+ }
+ returnErr, ok := AsParamOverrideReturnError(err)
+ if !ok {
+ t.Fatalf("expected ParamOverrideReturnError, got %T: %v", err, err)
+ }
+ if returnErr.StatusCode != 422 {
+ t.Fatalf("expected status 422, got %d", returnErr.StatusCode)
+ }
+ if returnErr.Code != "forced_bad_request" {
+ t.Fatalf("expected code forced_bad_request, got %s", returnErr.Code)
+ }
+ if !returnErr.SkipRetry {
+ t.Fatalf("expected skip_retry true")
+ }
+}
+
+func TestApplyParamOverridePruneObjectsByTypeString(t *testing.T) {
+ input := []byte(`{
+ "messages":[
+ {"role":"assistant","content":[
+ {"type":"output_text","text":"a"},
+ {"type":"redacted_thinking","text":"secret"},
+ {"type":"tool_call","name":"tool_a"}
+ ]},
+ {"role":"assistant","content":[
+ {"type":"output_text","text":"b"},
+ {"type":"wrapper","parts":[
+ {"type":"redacted_thinking","text":"secret2"},
+ {"type":"output_text","text":"c"}
+ ]}
+ ]}
+ ]
+ }`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "prune_objects",
+ "value": "redacted_thinking",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{
+ "messages":[
+ {"role":"assistant","content":[
+ {"type":"output_text","text":"a"},
+ {"type":"tool_call","name":"tool_a"}
+ ]},
+ {"role":"assistant","content":[
+ {"type":"output_text","text":"b"},
+ {"type":"wrapper","parts":[
+ {"type":"output_text","text":"c"}
+ ]}
+ ]}
+ ]
+ }`, string(out))
+}
+
+func TestApplyParamOverridePruneObjectsWhereAndPath(t *testing.T) {
+ input := []byte(`{
+ "a":{"items":[{"type":"redacted_thinking","id":1},{"type":"output_text","id":2}]},
+ "b":{"items":[{"type":"redacted_thinking","id":3},{"type":"output_text","id":4}]}
+ }`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "a",
+ "mode": "prune_objects",
+ "value": map[string]interface{}{
+ "where": map[string]interface{}{
+ "type": "redacted_thinking",
+ },
+ },
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{
+ "a":{"items":[{"type":"output_text","id":2}]},
+ "b":{"items":[{"type":"redacted_thinking","id":3},{"type":"output_text","id":4}]}
+ }`, string(out))
+}
+
+func TestApplyParamOverrideNormalizeThinkingSignatureUnsupported(t *testing.T) {
+ input := []byte(`{"items":[{"type":"redacted_thinking"}]}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "normalize_thinking_signature",
+ },
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, nil)
+ if err == nil {
+ t.Fatalf("expected error, got nil")
+ }
+}
+
+func TestApplyParamOverrideConditionFromRetryAndLastErrorContext(t *testing.T) {
+ info := &RelayInfo{
+ RetryIndex: 1,
+ LastError: types.WithOpenAIError(types.OpenAIError{
+ Message: "invalid thinking signature",
+ Type: "invalid_request_error",
+ Code: "bad_thought_signature",
+ }, 400),
+ }
+ ctx := BuildParamOverrideContext(info)
+
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ "logic": "AND",
+ "conditions": []interface{}{
+ map[string]interface{}{
+ "path": "is_retry",
+ "mode": "full",
+ "value": true,
+ },
+ map[string]interface{}{
+ "path": "last_error.code",
+ "mode": "contains",
+ "value": "thought_signature",
+ },
+ },
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.1}`, string(out))
+}
+
+func TestApplyParamOverrideConditionFromRequestHeaders(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ "conditions": []interface{}{
+ map[string]interface{}{
+ "path": "request_headers.authorization",
+ "mode": "contains",
+ "value": "Bearer ",
+ },
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "authorization": "Bearer token-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.1}`, string(out))
+}
+
+func TestApplyParamOverrideSetHeaderAndUseInLaterCondition(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "X-Debug-Mode",
+ "value": "enabled",
+ },
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ "conditions": []interface{}{
+ map[string]interface{}{
+ "path": "header_override.x-debug-mode",
+ "mode": "full",
+ "value": "enabled",
+ },
+ },
+ },
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, nil)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.1}`, string(out))
+}
+
+func TestApplyParamOverrideCopyHeaderFromRequestHeaders(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "copy_header",
+ "from": "Authorization",
+ "to": "X-Upstream-Auth",
+ },
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ "conditions": []interface{}{
+ map[string]interface{}{
+ "path": "header_override.x-upstream-auth",
+ "mode": "contains",
+ "value": "Bearer ",
+ },
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "authorization": "Bearer token-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.1}`, string(out))
+}
+
+func TestApplyParamOverridePassHeadersSkipsMissingHeaders(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "pass_headers",
+ "value": []interface{}{"X-Codex-Beta-Features", "Session_id"},
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "session_id": "sess-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["session_id"] != "sess-123" {
+ t.Fatalf("expected session_id to be passed, got: %v", headers["session_id"])
+ }
+ if _, exists := headers["x-codex-beta-features"]; exists {
+ t.Fatalf("expected missing header to be skipped")
+ }
+}
+
+func TestApplyParamOverrideCopyHeaderSkipsMissingSource(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "copy_header",
+ "from": "X-Missing-Header",
+ "to": "X-Upstream-Auth",
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "authorization": "Bearer token-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ return
+ }
+ if _, exists := headers["x-upstream-auth"]; exists {
+ t.Fatalf("expected X-Upstream-Auth to be skipped when source header is missing")
+ }
+}
+
+func TestApplyParamOverrideMoveHeaderSkipsMissingSource(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "move_header",
+ "from": "X-Missing-Header",
+ "to": "X-Upstream-Auth",
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "authorization": "Bearer token-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ return
+ }
+ if _, exists := headers["x-upstream-auth"]; exists {
+ t.Fatalf("expected X-Upstream-Auth to be skipped when source header is missing")
+ }
+}
+
+func TestApplyParamOverrideSyncFieldsHeaderToJSON(t *testing.T) {
+ input := []byte(`{"model":"gpt-4"}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "sync_fields",
+ "from": "header:session_id",
+ "to": "json:prompt_cache_key",
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "session_id": "sess-123",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"gpt-4","prompt_cache_key":"sess-123"}`, string(out))
+}
+
+func TestApplyParamOverrideSyncFieldsJSONToHeader(t *testing.T) {
+ input := []byte(`{"model":"gpt-4","prompt_cache_key":"cache-abc"}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "sync_fields",
+ "from": "header:session_id",
+ "to": "json:prompt_cache_key",
+ },
+ },
+ }
+ ctx := map[string]interface{}{}
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"gpt-4","prompt_cache_key":"cache-abc"}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["session_id"] != "cache-abc" {
+ t.Fatalf("expected session_id to be synced from prompt_cache_key, got: %v", headers["session_id"])
+ }
+}
+
+func TestApplyParamOverrideSyncFieldsNoChangeWhenBothExist(t *testing.T) {
+ input := []byte(`{"model":"gpt-4","prompt_cache_key":"cache-body"}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "sync_fields",
+ "from": "header:session_id",
+ "to": "json:prompt_cache_key",
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "session_id": "cache-header",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"gpt-4","prompt_cache_key":"cache-body"}`, string(out))
+
+ headers, _ := ctx["header_override"].(map[string]interface{})
+ if headers != nil {
+ if _, exists := headers["session_id"]; exists {
+ t.Fatalf("expected no override when both sides already have value")
+ }
+ }
+}
+
+func TestApplyParamOverrideSyncFieldsInvalidTarget(t *testing.T) {
+ input := []byte(`{"model":"gpt-4"}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "sync_fields",
+ "from": "foo:session_id",
+ "to": "json:prompt_cache_key",
+ },
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, nil)
+ if err == nil {
+ t.Fatalf("expected error, got nil")
+ }
+}
+
+func TestApplyParamOverrideSetHeaderKeepOrigin(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "X-Feature-Flag",
+ "value": "new-value",
+ "keep_origin": true,
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "header_override": map[string]interface{}{
+ "x-feature-flag": "legacy-value",
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["x-feature-flag"] != "legacy-value" {
+ t.Fatalf("expected keep_origin to preserve old value, got: %v", headers["x-feature-flag"])
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapRewritesCommaSeparatedHeader(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "advanced-tool-use-2025-11-20": nil,
+ "computer-use-2025-01-24": "computer-use-2025-01-24",
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "request_headers": map[string]interface{}{
+ "anthropic-beta": "advanced-tool-use-2025-11-20, computer-use-2025-01-24",
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["anthropic-beta"] != "computer-use-2025-01-24" {
+ t.Fatalf("expected anthropic-beta to keep only mapped value, got: %v", headers["anthropic-beta"])
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapDeleteWholeHeaderWhenAllTokensCleared(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "advanced-tool-use-2025-11-20": nil,
+ "computer-use-2025-01-24": nil,
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "header_override": map[string]interface{}{
+ "anthropic-beta": "advanced-tool-use-2025-11-20,computer-use-2025-01-24",
+ },
+ }
+
+ _, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if _, exists := headers["anthropic-beta"]; exists {
+ t.Fatalf("expected anthropic-beta to be deleted when all mapped values are null")
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapAppendsTokens(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "$append": []interface{}{"context-1m-2025-08-07", "computer-use-2025-01-24"},
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "header_override": map[string]interface{}{
+ "anthropic-beta": "computer-use-2025-01-24",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["anthropic-beta"] != "computer-use-2025-01-24,context-1m-2025-08-07" {
+ t.Fatalf("expected anthropic-beta to append new token without duplicates, got: %v", headers["anthropic-beta"])
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapAppendsTokensWhenHeaderMissing(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "$append": []interface{}{"context-1m-2025-08-07", "computer-use-2025-01-24"},
+ },
+ },
+ },
+ }
+
+ ctx := map[string]interface{}{}
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["anthropic-beta"] != "context-1m-2025-08-07,computer-use-2025-01-24" {
+ t.Fatalf("expected anthropic-beta to be created from appended tokens, got: %v", headers["anthropic-beta"])
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDropsUndeclaredTokens(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "computer-use-2025-01-24": "computer-use-2025-01-24",
+ "$append": []interface{}{"context-1m-2025-08-07"},
+ "$keep_only_declared": true,
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "header_override": map[string]interface{}{
+ "anthropic-beta": "advanced-tool-use-2025-11-20,computer-use-2025-01-24",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if headers["anthropic-beta"] != "computer-use-2025-01-24,context-1m-2025-08-07" {
+ t.Fatalf("expected anthropic-beta to keep only declared tokens, got: %v", headers["anthropic-beta"])
+ }
+}
+
+func TestApplyParamOverrideSetHeaderMapKeepOnlyDeclaredDeletesHeaderWhenNothingDeclaredMatches(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "computer-use-2025-01-24": "computer-use-2025-01-24",
+ "$keep_only_declared": true,
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "header_override": map[string]interface{}{
+ "anthropic-beta": "advanced-tool-use-2025-11-20",
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ headers, ok := ctx["header_override"].(map[string]interface{})
+ if !ok {
+ t.Fatalf("expected header_override context map")
+ }
+ if _, exists := headers["anthropic-beta"]; exists {
+ t.Fatalf("expected anthropic-beta to be deleted when no declared tokens remain, got: %v", headers["anthropic-beta"])
+ }
+}
+
+func TestApplyParamOverrideConditionsObjectShorthand(t *testing.T) {
+ input := []byte(`{"temperature":0.7}`)
+ override := map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "path": "temperature",
+ "mode": "set",
+ "value": 0.1,
+ "logic": "AND",
+ "conditions": map[string]interface{}{
+ "is_retry": true,
+ "last_error.status_code": 400.0,
+ },
+ },
+ },
+ }
+ ctx := map[string]interface{}{
+ "is_retry": true,
+ "last_error": map[string]interface{}{
+ "status_code": 400.0,
+ },
+ }
+
+ out, err := ApplyParamOverride(input, override, ctx)
+ if err != nil {
+ t.Fatalf("ApplyParamOverride returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.1}`, string(out))
+}
+
+func TestApplyParamOverrideWithRelayInfoSyncRuntimeHeaders(t *testing.T) {
+ info := &RelayInfo{
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "X-Injected-By-Param-Override",
+ "value": "enabled",
+ },
+ map[string]interface{}{
+ "mode": "delete_header",
+ "path": "X-Delete-Me",
+ },
+ },
+ },
+ HeadersOverride: map[string]interface{}{
+ "X-Delete-Me": "legacy",
+ "X-Keep-Me": "keep",
+ },
+ },
+ }
+
+ input := []byte(`{"temperature":0.7}`)
+ out, err := ApplyParamOverrideWithRelayInfo(input, info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"temperature":0.7}`, string(out))
+
+ if !info.UseRuntimeHeadersOverride {
+ t.Fatalf("expected runtime header override to be enabled")
+ }
+ if info.RuntimeHeadersOverride["x-keep-me"] != "keep" {
+ t.Fatalf("expected x-keep-me header to be preserved, got: %v", info.RuntimeHeadersOverride["x-keep-me"])
+ }
+ if info.RuntimeHeadersOverride["x-injected-by-param-override"] != "enabled" {
+ t.Fatalf("expected x-injected-by-param-override header to be set, got: %v", info.RuntimeHeadersOverride["x-injected-by-param-override"])
+ }
+ if _, exists := info.RuntimeHeadersOverride["x-delete-me"]; exists {
+ t.Fatalf("expected x-delete-me header to be deleted")
+ }
+}
+
+func TestApplyParamOverrideWithRelayInfoMixedLegacyAndOperations(t *testing.T) {
+ info := &RelayInfo{
+ RequestHeaders: map[string]string{
+ "Originator": "Codex CLI",
+ },
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "temperature": 0.2,
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "pass_headers",
+ "value": []interface{}{"Originator"},
+ },
+ },
+ },
+ HeadersOverride: map[string]interface{}{
+ "X-Static": "legacy-static",
+ },
+ },
+ }
+
+ out, err := ApplyParamOverrideWithRelayInfo([]byte(`{"model":"gpt-5","temperature":0.7}`), info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"model":"gpt-5","temperature":0.2}`, string(out))
+
+ if !info.UseRuntimeHeadersOverride {
+ t.Fatalf("expected runtime header override to be enabled")
+ }
+ if info.RuntimeHeadersOverride["x-static"] != "legacy-static" {
+ t.Fatalf("expected x-static to be preserved, got: %v", info.RuntimeHeadersOverride["x-static"])
+ }
+ if info.RuntimeHeadersOverride["originator"] != "Codex CLI" {
+ t.Fatalf("expected originator header to be passed, got: %v", info.RuntimeHeadersOverride["originator"])
+ }
+}
+
+func TestApplyParamOverrideWithRelayInfoMoveAndCopyHeaders(t *testing.T) {
+ info := &RelayInfo{
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "move_header",
+ "from": "X-Legacy-Trace",
+ "to": "X-Trace",
+ },
+ map[string]interface{}{
+ "mode": "copy_header",
+ "from": "X-Trace",
+ "to": "X-Trace-Backup",
+ },
+ },
+ },
+ HeadersOverride: map[string]interface{}{
+ "X-Legacy-Trace": "trace-123",
+ },
+ },
+ }
+
+ input := []byte(`{"temperature":0.7}`)
+ _, err := ApplyParamOverrideWithRelayInfo(input, info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+ if _, exists := info.RuntimeHeadersOverride["x-legacy-trace"]; exists {
+ t.Fatalf("expected source header to be removed after move")
+ }
+ if info.RuntimeHeadersOverride["x-trace"] != "trace-123" {
+ t.Fatalf("expected x-trace to be set, got: %v", info.RuntimeHeadersOverride["x-trace"])
+ }
+ if info.RuntimeHeadersOverride["x-trace-backup"] != "trace-123" {
+ t.Fatalf("expected x-trace-backup to be copied, got: %v", info.RuntimeHeadersOverride["x-trace-backup"])
+ }
+}
+
+func TestApplyParamOverrideWithRelayInfoSetHeaderMapRewritesAnthropicBeta(t *testing.T) {
+ info := &RelayInfo{
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "set_header",
+ "path": "anthropic-beta",
+ "value": map[string]interface{}{
+ "advanced-tool-use-2025-11-20": nil,
+ "computer-use-2025-01-24": "computer-use-2025-01-24",
+ },
+ },
+ },
+ },
+ HeadersOverride: map[string]interface{}{
+ "anthropic-beta": "advanced-tool-use-2025-11-20, computer-use-2025-01-24",
+ },
+ },
+ }
+
+ _, err := ApplyParamOverrideWithRelayInfo([]byte(`{"temperature":0.7}`), info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+
+ if !info.UseRuntimeHeadersOverride {
+ t.Fatalf("expected runtime header override to be enabled")
+ }
+ if info.RuntimeHeadersOverride["anthropic-beta"] != "computer-use-2025-01-24" {
+ t.Fatalf("expected anthropic-beta to be rewritten, got: %v", info.RuntimeHeadersOverride["anthropic-beta"])
+ }
+}
+
+func TestGetEffectiveHeaderOverrideUsesRuntimeOverrideAsFinalResult(t *testing.T) {
+ info := &RelayInfo{
+ UseRuntimeHeadersOverride: true,
+ RuntimeHeadersOverride: map[string]interface{}{
+ "x-runtime": "runtime-only",
+ },
+ ChannelMeta: &ChannelMeta{
+ HeadersOverride: map[string]interface{}{
+ "X-Static": "static-value",
+ "X-Deleted": "should-not-exist",
+ },
+ },
+ }
+
+ effective := GetEffectiveHeaderOverride(info)
+ if effective["x-runtime"] != "runtime-only" {
+ t.Fatalf("expected x-runtime from runtime override, got: %v", effective["x-runtime"])
+ }
+ if _, exists := effective["x-static"]; exists {
+ t.Fatalf("expected runtime override to be final and not merge channel headers")
+ }
+}
+
+func TestRemoveDisabledFieldsSkipWhenChannelPassThroughEnabled(t *testing.T) {
+ input := `{
+ "service_tier":"flex",
+ "safety_identifier":"user-123",
+ "store":true,
+ "stream_options":{"include_obfuscation":false}
+ }`
+ settings := dto.ChannelOtherSettings{}
+
+ out, err := RemoveDisabledFields([]byte(input), settings, true)
+ if err != nil {
+ t.Fatalf("RemoveDisabledFields returned error: %v", err)
+ }
+ assertJSONEqual(t, input, string(out))
+}
+
+func TestRemoveDisabledFieldsSkipWhenGlobalPassThroughEnabled(t *testing.T) {
+ original := model_setting.GetGlobalSettings().PassThroughRequestEnabled
+ model_setting.GetGlobalSettings().PassThroughRequestEnabled = true
+ t.Cleanup(func() {
+ model_setting.GetGlobalSettings().PassThroughRequestEnabled = original
+ })
+
+ input := `{
+ "service_tier":"flex",
+ "safety_identifier":"user-123",
+ "stream_options":{"include_obfuscation":false}
+ }`
+ settings := dto.ChannelOtherSettings{}
+
+ out, err := RemoveDisabledFields([]byte(input), settings, false)
+ if err != nil {
+ t.Fatalf("RemoveDisabledFields returned error: %v", err)
+ }
+ assertJSONEqual(t, input, string(out))
+}
+
+func TestRemoveDisabledFieldsDefaultFiltering(t *testing.T) {
+ input := `{
+ "service_tier":"flex",
+ "inference_geo":"eu",
+ "safety_identifier":"user-123",
+ "store":true,
+ "stream_options":{"include_obfuscation":false}
+ }`
+ settings := dto.ChannelOtherSettings{}
+
+ out, err := RemoveDisabledFields([]byte(input), settings, false)
+ if err != nil {
+ t.Fatalf("RemoveDisabledFields returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"store":true}`, string(out))
+}
+
+func TestRemoveDisabledFieldsAllowInferenceGeo(t *testing.T) {
+ input := `{
+ "inference_geo":"eu",
+ "store":true
+ }`
+ settings := dto.ChannelOtherSettings{
+ AllowInferenceGeo: true,
+ }
+
+ out, err := RemoveDisabledFields([]byte(input), settings, false)
+ if err != nil {
+ t.Fatalf("RemoveDisabledFields returned error: %v", err)
+ }
+ assertJSONEqual(t, `{"inference_geo":"eu","store":true}`, string(out))
+}
+
+func TestApplyParamOverrideWithRelayInfoRecordsOperationAuditInDebugMode(t *testing.T) {
+ originalDebugEnabled := common2.DebugEnabled
+ common2.DebugEnabled = true
+ t.Cleanup(func() {
+ common2.DebugEnabled = originalDebugEnabled
+ })
+
+ info := &RelayInfo{
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "copy",
+ "from": "metadata.target_model",
+ "to": "model",
+ },
+ map[string]interface{}{
+ "mode": "set",
+ "path": "service_tier",
+ "value": "flex",
+ },
+ map[string]interface{}{
+ "mode": "set",
+ "path": "temperature",
+ "value": 0.1,
+ },
+ },
+ },
+ },
+ }
+
+ out, err := ApplyParamOverrideWithRelayInfo([]byte(`{
+ "model":"gpt-4.1",
+ "temperature":0.7,
+ "metadata":{"target_model":"gpt-4.1-mini"}
+ }`), info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+ assertJSONEqual(t, `{
+ "model":"gpt-4.1-mini",
+ "temperature":0.1,
+ "service_tier":"flex",
+ "metadata":{"target_model":"gpt-4.1-mini"}
+ }`, string(out))
+
+ expected := []string{
+ "copy metadata.target_model -> model",
+ "set service_tier = flex",
+ "set temperature = 0.1",
+ }
+ if !reflect.DeepEqual(info.ParamOverrideAudit, expected) {
+ t.Fatalf("unexpected param override audit, got %#v", info.ParamOverrideAudit)
+ }
+}
+
+func TestApplyParamOverrideWithRelayInfoRecordsOnlyKeyOperationsWhenDebugDisabled(t *testing.T) {
+ originalDebugEnabled := common2.DebugEnabled
+ common2.DebugEnabled = false
+ t.Cleanup(func() {
+ common2.DebugEnabled = originalDebugEnabled
+ })
+
+ info := &RelayInfo{
+ ChannelMeta: &ChannelMeta{
+ ParamOverride: map[string]interface{}{
+ "operations": []interface{}{
+ map[string]interface{}{
+ "mode": "copy",
+ "from": "metadata.target_model",
+ "to": "model",
+ },
+ map[string]interface{}{
+ "mode": "set",
+ "path": "temperature",
+ "value": 0.1,
+ },
+ },
+ },
+ },
+ }
+
+ _, err := ApplyParamOverrideWithRelayInfo([]byte(`{
+ "model":"gpt-4.1",
+ "temperature":0.7,
+ "metadata":{"target_model":"gpt-4.1-mini"}
+ }`), info)
+ if err != nil {
+ t.Fatalf("ApplyParamOverrideWithRelayInfo returned error: %v", err)
+ }
+
+ expected := []string{
+ "copy metadata.target_model -> model",
+ }
+ if !reflect.DeepEqual(info.ParamOverrideAudit, expected) {
+ t.Fatalf("unexpected param override audit, got %#v", info.ParamOverrideAudit)
+ }
+}
+
func assertJSONEqual(t *testing.T, want, got string) {
t.Helper()
diff --git a/relay/common/relay_info.go b/relay/common/relay_info.go
index 5c24ce57af..7d4f063c5a 100644
--- a/relay/common/relay_info.go
+++ b/relay/common/relay_info.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "strconv"
"strings"
"time"
@@ -37,6 +38,9 @@ type ClaudeConvertInfo struct {
Usage *dto.Usage
FinishReason string
Done bool
+
+ ToolCallBaseIndex int
+ ToolCallMaxIndexOffset int
}
type RerankerInfo struct {
@@ -98,6 +102,7 @@ type RelayInfo struct {
RelayMode int
OriginModelName string
RequestURLPath string
+ RequestHeaders map[string]string
ShouldIncludeUsage bool
DisablePing bool // 是否禁止向下游发送自定义 Ping
ClientWs *websocket.Conn
@@ -113,9 +118,39 @@ type RelayInfo struct {
UserQuota int
RelayFormat types.RelayFormat
SendResponseCount int
- FinalPreConsumedQuota int // 最终预消耗的配额
- IsClaudeBetaQuery bool // /v1/messages?beta=true
- IsChannelTest bool // channel test request
+ ReceivedResponseCount int
+ FinalPreConsumedQuota int // 最终预消耗的配额
+ // ForcePreConsume 为 true 时禁用 BillingSession 的信任额度旁路,
+ // 强制预扣全额。用于异步任务(视频/音乐生成等),因为请求返回后任务仍在运行,
+ // 必须在提交前锁定全额。
+ ForcePreConsume bool
+ // Billing 是计费会话,封装了预扣费/结算/退款的统一生命周期。
+ // 免费模型时为 nil。
+ Billing BillingSettler
+ // BillingSource indicates whether this request is billed from wallet quota or subscription.
+ // "" or "wallet" => wallet; "subscription" => subscription
+ BillingSource string
+ // SubscriptionId is the user_subscriptions.id used when BillingSource == "subscription"
+ SubscriptionId int
+ // SubscriptionPreConsumed is the amount pre-consumed on subscription item (quota units or 1)
+ SubscriptionPreConsumed int64
+ // SubscriptionPostDelta is the post-consume delta applied to amount_used (quota units; can be negative).
+ SubscriptionPostDelta int64
+ // SubscriptionPlanId / SubscriptionPlanTitle are used for logging/UI display.
+ SubscriptionPlanId int
+ SubscriptionPlanTitle string
+ // RequestId is used for idempotent pre-consume/refund
+ RequestId string
+ // SubscriptionAmountTotal / SubscriptionAmountUsedAfterPreConsume are used to compute remaining in logs.
+ SubscriptionAmountTotal int64
+ SubscriptionAmountUsedAfterPreConsume int64
+ IsClaudeBetaQuery bool // /v1/messages?beta=true
+ IsChannelTest bool // channel test request
+ RetryIndex int
+ LastError *types.NewAPIError
+ RuntimeHeadersOverride map[string]interface{}
+ UseRuntimeHeadersOverride bool
+ ParamOverrideAudit []string
PriceData types.PriceData
@@ -124,6 +159,11 @@ type RelayInfo struct {
// RequestConversionChain records request format conversions in order, e.g.
// ["openai", "openai_responses"] or ["openai", "claude"].
RequestConversionChain []types.RelayFormat
+ // 最终请求到上游的格式。可由 adaptor 显式设置;
+ // 若为空,调用 GetFinalRequestRelayFormat 会回退到 RequestConversionChain 的最后一项或 RelayFormat。
+ FinalRequestRelayFormat types.RelayFormat
+
+ StreamStatus *StreamStatus
ThinkingContentInfo
TokenCountMeta
@@ -264,21 +304,24 @@ func (info *RelayInfo) ToString() string {
// 定义支持流式选项的通道类型
var streamSupportedChannels = map[int]bool{
- constant.ChannelTypeOpenAI: true,
- constant.ChannelTypeAnthropic: true,
- constant.ChannelTypeAws: true,
- constant.ChannelTypeGemini: true,
- constant.ChannelCloudflare: true,
- constant.ChannelTypeAzure: true,
- constant.ChannelTypeVolcEngine: true,
- constant.ChannelTypeOllama: true,
- constant.ChannelTypeXai: true,
- constant.ChannelTypeDeepSeek: true,
- constant.ChannelTypeBaiduV2: true,
- constant.ChannelTypeZhipu_v4: true,
- constant.ChannelTypeAli: true,
- constant.ChannelTypeSubmodel: true,
- constant.ChannelTypeCodex: true,
+ constant.ChannelTypeOpenAI: true,
+ constant.ChannelTypeAnthropic: true,
+ constant.ChannelTypeAws: true,
+ constant.ChannelTypeGemini: true,
+ constant.ChannelCloudflare: true,
+ constant.ChannelTypeAzure: true,
+ constant.ChannelTypeVolcEngine: true,
+ constant.ChannelTypeOllama: true,
+ constant.ChannelTypeXai: true,
+ constant.ChannelTypeDeepSeek: true,
+ constant.ChannelTypeBaiduV2: true,
+ constant.ChannelTypeZhipu_v4: true,
+ constant.ChannelTypeAli: true,
+ constant.ChannelTypeSubmodel: true,
+ constant.ChannelTypeCodex: true,
+ constant.ChannelTypeMoonshot: true,
+ constant.ChannelTypeMiniMax: true,
+ constant.ChannelTypeSiliconFlow: true,
}
func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo {
@@ -298,9 +341,7 @@ func GenRelayInfoClaude(c *gin.Context, request dto.Request) *RelayInfo {
info.ClaudeConvertInfo = &ClaudeConvertInfo{
LastMessagesType: LastMessageTypeNone,
}
- if c.Query("beta") == "true" {
- info.IsClaudeBetaQuery = true
- }
+ info.IsClaudeBetaQuery = c.Query("beta") == "true"
return info
}
@@ -400,9 +441,14 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
// firstResponseTime = time.Now() - 1 second
+ reqId := common.GetContextKeyString(c, common.RequestIdKey)
+ if reqId == "" {
+ reqId = common.GetTimeString() + common.GetRandomString(8)
+ }
info := &RelayInfo{
Request: request,
+ RequestId: reqId,
UserId: common.GetContextKeyInt(c, constant.ContextKeyUserId),
UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
@@ -419,6 +465,7 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
isFirstResponse: true,
RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
RequestURLPath: c.Request.URL.String(),
+ RequestHeaders: cloneRequestHeaders(c),
IsStream: isStream,
StartTime: startTime,
@@ -451,6 +498,27 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
return info
}
+func cloneRequestHeaders(c *gin.Context) map[string]string {
+ if c == nil || c.Request == nil {
+ return nil
+ }
+ if len(c.Request.Header) == 0 {
+ return nil
+ }
+ headers := make(map[string]string, len(c.Request.Header))
+ for key := range c.Request.Header {
+ value := strings.TrimSpace(c.Request.Header.Get(key))
+ if value == "" {
+ continue
+ }
+ headers[key] = value
+ }
+ if len(headers) == 0 {
+ return nil
+ }
+ return headers
+}
+
func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Request, ws *websocket.Conn) (*RelayInfo, error) {
var info *RelayInfo
var err error
@@ -481,10 +549,17 @@ func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Req
break
}
err = errors.New("request is not a OpenAIResponsesRequest")
+ case types.RelayFormatOpenAIResponsesCompaction:
+ if request, ok := request.(*dto.OpenAIResponsesCompactionRequest); ok {
+ return GenRelayInfoResponsesCompaction(c, request), nil
+ }
+ return nil, errors.New("request is not a OpenAIResponsesCompactionRequest")
case types.RelayFormatTask:
info = genBaseRelayInfo(c, nil)
+ info.TaskRelayInfo = &TaskRelayInfo{}
case types.RelayFormatMjProxy:
info = genBaseRelayInfo(c, nil)
+ info.TaskRelayInfo = &TaskRelayInfo{}
default:
err = errors.New("invalid relay format")
}
@@ -531,6 +606,28 @@ func (info *RelayInfo) AppendRequestConversion(format types.RelayFormat) {
info.RequestConversionChain = append(info.RequestConversionChain, format)
}
+func (info *RelayInfo) GetFinalRequestRelayFormat() types.RelayFormat {
+ if info == nil {
+ return ""
+ }
+ if info.FinalRequestRelayFormat != "" {
+ return info.FinalRequestRelayFormat
+ }
+ if n := len(info.RequestConversionChain); n > 0 {
+ return info.RequestConversionChain[n-1]
+ }
+ return info.RelayFormat
+}
+
+func GenRelayInfoResponsesCompaction(c *gin.Context, request *dto.OpenAIResponsesCompactionRequest) *RelayInfo {
+ info := genBaseRelayInfo(c, request)
+ if info.RelayMode == relayconstant.RelayModeUnknown {
+ info.RelayMode = relayconstant.RelayModeResponsesCompact
+ }
+ info.RelayFormat = types.RelayFormatOpenAIResponsesCompaction
+ return info
+}
+
//func (info *RelayInfo) SetPromptTokens(promptTokens int) {
// info.promptTokens = promptTokens
//}
@@ -557,8 +654,16 @@ func (info *RelayInfo) HasSendResponse() bool {
type TaskRelayInfo struct {
Action string
OriginTaskID string
+ // PublicTaskID 是提交时预生成的 task_xxxx 格式公开 ID,
+ // 供 DoResponse 在返回给客户端时使用(避免暴露上游真实 ID)。
+ PublicTaskID string
ConsumeQuota bool
+
+ // LockedChannel holds the full channel object when the request is bound to
+ // a specific channel (e.g., remix on origin task's channel). Stored as any
+ // to avoid an import cycle with model; callers type-assert to *model.Channel.
+ LockedChannel any
}
type TaskSubmitReq struct {
@@ -586,6 +691,7 @@ func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error {
type Alias TaskSubmitReq
aux := &struct {
Metadata json.RawMessage `json:"metadata,omitempty"`
+ Duration json.RawMessage `json:"duration,omitempty"`
*Alias
}{
Alias: (*Alias)(t),
@@ -595,6 +701,20 @@ func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error {
return err
}
+ if len(aux.Duration) > 0 {
+ var durationInt int
+ if err := common.Unmarshal(aux.Duration, &durationInt); err == nil {
+ t.Duration = durationInt
+ } else {
+ var durationStr string
+ if err := common.Unmarshal(aux.Duration, &durationStr); err == nil && durationStr != "" {
+ if v, err := strconv.Atoi(durationStr); err == nil {
+ t.Duration = v
+ }
+ }
+ }
+ }
+
if len(aux.Metadata) > 0 {
var metadataStr string
if err := common.Unmarshal(aux.Metadata, &metadataStr); err == nil && metadataStr != "" {
@@ -616,11 +736,11 @@ func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error {
func (t *TaskSubmitReq) UnmarshalMetadata(v any) error {
metadata := t.Metadata
if metadata != nil {
- metadataBytes, err := json.Marshal(metadata)
+ metadataBytes, err := common.Marshal(metadata)
if err != nil {
return fmt.Errorf("marshal metadata failed: %w", err)
}
- err = json.Unmarshal(metadataBytes, v)
+ err = common.Unmarshal(metadataBytes, v)
if err != nil {
return fmt.Errorf("unmarshal metadata to target failed: %w", err)
}
@@ -649,9 +769,15 @@ func FailTaskInfo(reason string) *TaskInfo {
// RemoveDisabledFields 从请求 JSON 数据中移除渠道设置中禁用的字段
// service_tier: 服务层级字段,可能导致额外计费(OpenAI、Claude、Responses API 支持)
+// inference_geo: Claude 数据驻留推理区域字段(仅 Claude 支持,默认过滤)
// store: 数据存储授权字段,涉及用户隐私(仅 OpenAI、Responses API 支持,默认允许透传,禁用后可能导致 Codex 无法使用)
// safety_identifier: 安全标识符,用于向 OpenAI 报告违规用户(仅 OpenAI 支持,涉及用户隐私)
-func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings) ([]byte, error) {
+// stream_options.include_obfuscation: 响应流混淆控制字段(仅 OpenAI Responses API 支持)
+func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings, channelPassThroughEnabled bool) ([]byte, error) {
+ if model_setting.GetGlobalSettings().PassThroughRequestEnabled || channelPassThroughEnabled {
+ return jsonData, nil
+ }
+
var data map[string]interface{}
if err := common.Unmarshal(jsonData, &data); err != nil {
common.SysError("RemoveDisabledFields Unmarshal error :" + err.Error())
@@ -665,6 +791,13 @@ func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOther
}
}
+ // 默认移除 inference_geo,除非明确允许(避免在未授权情况下透传数据驻留区域)
+ if !channelOtherSettings.AllowInferenceGeo {
+ if _, exists := data["inference_geo"]; exists {
+ delete(data, "inference_geo")
+ }
+ }
+
// 默认允许 store 透传,除非明确禁用(禁用可能影响 Codex 使用)
if channelOtherSettings.DisableStore {
if _, exists := data["store"]; exists {
@@ -679,6 +812,22 @@ func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOther
}
}
+ // 默认移除 stream_options.include_obfuscation,除非明确允许(避免关闭响应流混淆保护)
+ if !channelOtherSettings.AllowIncludeObfuscation {
+ if streamOptionsAny, exists := data["stream_options"]; exists {
+ if streamOptions, ok := streamOptionsAny.(map[string]interface{}); ok {
+ if _, includeExists := streamOptions["include_obfuscation"]; includeExists {
+ delete(streamOptions, "include_obfuscation")
+ }
+ if len(streamOptions) == 0 {
+ delete(data, "stream_options")
+ } else {
+ data["stream_options"] = streamOptions
+ }
+ }
+ }
+ }
+
jsonDataAfter, err := common.Marshal(data)
if err != nil {
common.SysError("RemoveDisabledFields Marshal error :" + err.Error())
diff --git a/relay/common/relay_info_test.go b/relay/common/relay_info_test.go
new file mode 100644
index 0000000000..e53ec804ca
--- /dev/null
+++ b/relay/common/relay_info_test.go
@@ -0,0 +1,40 @@
+package common
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRelayInfoGetFinalRequestRelayFormatPrefersExplicitFinal(t *testing.T) {
+ info := &RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ RequestConversionChain: []types.RelayFormat{types.RelayFormatOpenAI, types.RelayFormatClaude},
+ FinalRequestRelayFormat: types.RelayFormatOpenAIResponses,
+ }
+
+ require.Equal(t, types.RelayFormat(types.RelayFormatOpenAIResponses), info.GetFinalRequestRelayFormat())
+}
+
+func TestRelayInfoGetFinalRequestRelayFormatFallsBackToConversionChain(t *testing.T) {
+ info := &RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ RequestConversionChain: []types.RelayFormat{types.RelayFormatOpenAI, types.RelayFormatClaude},
+ }
+
+ require.Equal(t, types.RelayFormat(types.RelayFormatClaude), info.GetFinalRequestRelayFormat())
+}
+
+func TestRelayInfoGetFinalRequestRelayFormatFallsBackToRelayFormat(t *testing.T) {
+ info := &RelayInfo{
+ RelayFormat: types.RelayFormatGemini,
+ }
+
+ require.Equal(t, types.RelayFormat(types.RelayFormatGemini), info.GetFinalRequestRelayFormat())
+}
+
+func TestRelayInfoGetFinalRequestRelayFormatNilReceiver(t *testing.T) {
+ var info *RelayInfo
+ require.Equal(t, types.RelayFormat(""), info.GetFinalRequestRelayFormat())
+}
diff --git a/relay/common/relay_utils.go b/relay/common/relay_utils.go
index b662f90536..18df77a645 100644
--- a/relay/common/relay_utils.go
+++ b/relay/common/relay_utils.go
@@ -173,16 +173,10 @@ func ValidateMultipartDirect(c *gin.Context, info *RelayInfo) *dto.TaskError {
if model == "sora-2-pro" && !lo.Contains([]string{"720x1280", "1280x720", "1792x1024", "1024x1792"}, size) {
return createTaskError(fmt.Errorf("sora-2 size is invalid"), "invalid_size", http.StatusBadRequest, true)
}
- info.PriceData.OtherRatios = map[string]float64{
- "seconds": float64(seconds),
- "size": 1,
- }
- if lo.Contains([]string{"1792x1024", "1024x1792"}, size) {
- info.PriceData.OtherRatios["size"] = 1.666667
- }
+ // OtherRatios 已移到 Sora adaptor 的 EstimateBilling 中设置
}
- info.Action = action
+ storeTaskRequest(c, info, action, req)
return nil
}
@@ -210,7 +204,9 @@ func ValidateBasicTaskRequest(c *gin.Context, info *RelayInfo, action string) *d
if err != nil {
return createTaskError(err, "invalid_multipart_form", http.StatusBadRequest, true)
}
- } else if err := common.UnmarshalBodyReusable(c, &req); err != nil {
+ }
+ // 为了metadata字段的兼容性,统一UnmarshalBodyReusable
+ if err := common.UnmarshalBodyReusable(c, &req); err != nil {
return createTaskError(err, "invalid_request", http.StatusBadRequest, true)
}
diff --git a/relay/common/stream_status.go b/relay/common/stream_status.go
new file mode 100644
index 0000000000..57b0bb973b
--- /dev/null
+++ b/relay/common/stream_status.go
@@ -0,0 +1,112 @@
+package common
+
+import (
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+)
+
+type StreamEndReason string
+
+const (
+ StreamEndReasonNone StreamEndReason = ""
+ StreamEndReasonDone StreamEndReason = "done"
+ StreamEndReasonTimeout StreamEndReason = "timeout"
+ StreamEndReasonClientGone StreamEndReason = "client_gone"
+ StreamEndReasonScannerErr StreamEndReason = "scanner_error"
+ StreamEndReasonHandlerStop StreamEndReason = "handler_stop"
+ StreamEndReasonEOF StreamEndReason = "eof"
+ StreamEndReasonPanic StreamEndReason = "panic"
+ StreamEndReasonPingFail StreamEndReason = "ping_fail"
+)
+
+const maxStreamErrorEntries = 20
+
+type StreamErrorEntry struct {
+ Message string
+ Timestamp time.Time
+}
+
+type StreamStatus struct {
+ EndReason StreamEndReason
+ EndError error
+ endOnce sync.Once
+
+ mu sync.Mutex
+ Errors []StreamErrorEntry
+ ErrorCount int
+}
+
+func NewStreamStatus() *StreamStatus {
+ return &StreamStatus{}
+}
+
+func (s *StreamStatus) SetEndReason(reason StreamEndReason, err error) {
+ if s == nil {
+ return
+ }
+ s.endOnce.Do(func() {
+ s.EndReason = reason
+ s.EndError = err
+ })
+}
+
+func (s *StreamStatus) RecordError(msg string) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.ErrorCount++
+ if len(s.Errors) < maxStreamErrorEntries {
+ s.Errors = append(s.Errors, StreamErrorEntry{
+ Message: msg,
+ Timestamp: time.Now(),
+ })
+ }
+}
+
+func (s *StreamStatus) HasErrors() bool {
+ if s == nil {
+ return false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.ErrorCount > 0
+}
+
+func (s *StreamStatus) TotalErrorCount() int {
+ if s == nil {
+ return 0
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.ErrorCount
+}
+
+func (s *StreamStatus) IsNormalEnd() bool {
+ if s == nil {
+ return true
+ }
+ return s.EndReason == StreamEndReasonDone ||
+ s.EndReason == StreamEndReasonEOF ||
+ s.EndReason == StreamEndReasonHandlerStop
+}
+
+func (s *StreamStatus) Summary() string {
+ if s == nil {
+ return "StreamStatus"
+ }
+ b := &strings.Builder{}
+ fmt.Fprintf(b, "reason=%s", s.EndReason)
+ if s.EndError != nil {
+ fmt.Fprintf(b, " end_error=%q", s.EndError.Error())
+ }
+ s.mu.Lock()
+ if s.ErrorCount > 0 {
+ fmt.Fprintf(b, " soft_errors=%d", s.ErrorCount)
+ }
+ s.mu.Unlock()
+ return b.String()
+}
diff --git a/relay/common/stream_status_test.go b/relay/common/stream_status_test.go
new file mode 100644
index 0000000000..4a31cb79fb
--- /dev/null
+++ b/relay/common/stream_status_test.go
@@ -0,0 +1,182 @@
+package common
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestStreamStatus_SetEndReason_FirstWins(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ s.SetEndReason(StreamEndReasonDone, nil)
+ s.SetEndReason(StreamEndReasonTimeout, nil)
+ s.SetEndReason(StreamEndReasonClientGone, fmt.Errorf("context canceled"))
+
+ assert.Equal(t, StreamEndReasonDone, s.EndReason)
+ assert.Nil(t, s.EndError)
+}
+
+func TestStreamStatus_SetEndReason_WithError(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ expectedErr := fmt.Errorf("read: connection reset")
+ s.SetEndReason(StreamEndReasonScannerErr, expectedErr)
+
+ assert.Equal(t, StreamEndReasonScannerErr, s.EndReason)
+ assert.Equal(t, expectedErr, s.EndError)
+}
+
+func TestStreamStatus_SetEndReason_NilSafe(t *testing.T) {
+ t.Parallel()
+ var s *StreamStatus
+ s.SetEndReason(StreamEndReasonDone, nil)
+}
+
+func TestStreamStatus_SetEndReason_Concurrent(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ reasons := []StreamEndReason{
+ StreamEndReasonDone,
+ StreamEndReasonTimeout,
+ StreamEndReasonClientGone,
+ StreamEndReasonScannerErr,
+ StreamEndReasonHandlerStop,
+ StreamEndReasonEOF,
+ StreamEndReasonPanic,
+ StreamEndReasonPingFail,
+ }
+
+ var wg sync.WaitGroup
+ for _, r := range reasons {
+ wg.Add(1)
+ go func(reason StreamEndReason) {
+ defer wg.Done()
+ s.SetEndReason(reason, nil)
+ }(r)
+ }
+ wg.Wait()
+
+ assert.NotEqual(t, StreamEndReasonNone, s.EndReason)
+}
+
+func TestStreamStatus_RecordError_Basic(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ s.RecordError("bad json")
+ s.RecordError("another bad json")
+ s.RecordError("client gone")
+
+ assert.True(t, s.HasErrors())
+ assert.Equal(t, 3, s.TotalErrorCount())
+ assert.Len(t, s.Errors, 3)
+}
+
+func TestStreamStatus_RecordError_CapAtMax(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ for i := 0; i < 30; i++ {
+ s.RecordError(fmt.Sprintf("error_%d", i))
+ }
+
+ assert.Equal(t, maxStreamErrorEntries, len(s.Errors))
+ assert.Equal(t, 30, s.TotalErrorCount())
+}
+
+func TestStreamStatus_RecordError_NilSafe(t *testing.T) {
+ t.Parallel()
+ var s *StreamStatus
+ s.RecordError("should not panic")
+}
+
+func TestStreamStatus_RecordError_Concurrent(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+
+ var wg sync.WaitGroup
+ for i := 0; i < 100; i++ {
+ wg.Add(1)
+ go func(idx int) {
+ defer wg.Done()
+ s.RecordError(fmt.Sprintf("error_%d", idx))
+ }(i)
+ }
+ wg.Wait()
+
+ assert.Equal(t, 100, s.TotalErrorCount())
+ assert.LessOrEqual(t, len(s.Errors), maxStreamErrorEntries)
+}
+
+func TestStreamStatus_HasErrors_Empty(t *testing.T) {
+ t.Parallel()
+ s := NewStreamStatus()
+ assert.False(t, s.HasErrors())
+ assert.Equal(t, 0, s.TotalErrorCount())
+}
+
+func TestStreamStatus_HasErrors_NilSafe(t *testing.T) {
+ t.Parallel()
+ var s *StreamStatus
+ assert.False(t, s.HasErrors())
+ assert.Equal(t, 0, s.TotalErrorCount())
+}
+
+func TestStreamStatus_IsNormalEnd(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ reason StreamEndReason
+ normal bool
+ }{
+ {StreamEndReasonDone, true},
+ {StreamEndReasonEOF, true},
+ {StreamEndReasonHandlerStop, true},
+ {StreamEndReasonTimeout, false},
+ {StreamEndReasonClientGone, false},
+ {StreamEndReasonScannerErr, false},
+ {StreamEndReasonPanic, false},
+ {StreamEndReasonPingFail, false},
+ {StreamEndReasonNone, false},
+ }
+ for _, tt := range tests {
+ s := NewStreamStatus()
+ s.SetEndReason(tt.reason, nil)
+ assert.Equal(t, tt.normal, s.IsNormalEnd(), "reason=%s", tt.reason)
+ }
+}
+
+func TestStreamStatus_IsNormalEnd_NilSafe(t *testing.T) {
+ t.Parallel()
+ var s *StreamStatus
+ assert.True(t, s.IsNormalEnd())
+}
+
+func TestStreamStatus_Summary(t *testing.T) {
+ t.Parallel()
+
+ s := NewStreamStatus()
+ s.SetEndReason(StreamEndReasonDone, nil)
+ summary := s.Summary()
+ assert.Contains(t, summary, "reason=done")
+ assert.NotContains(t, summary, "soft_errors")
+
+ s2 := NewStreamStatus()
+ s2.SetEndReason(StreamEndReasonTimeout, nil)
+ s2.RecordError("bad json")
+ s2.RecordError("write failed")
+ summary2 := s2.Summary()
+ assert.Contains(t, summary2, "reason=timeout")
+ assert.Contains(t, summary2, "soft_errors=2")
+}
+
+func TestStreamStatus_Summary_NilSafe(t *testing.T) {
+ t.Parallel()
+ var s *StreamStatus
+ assert.Equal(t, "StreamStatus", s.Summary())
+}
diff --git a/relay/compatible_handler.go b/relay/compatible_handler.go
index eab5052d75..7a5624eb34 100644
--- a/relay/compatible_handler.go
+++ b/relay/compatible_handler.go
@@ -6,23 +6,19 @@ import (
"io"
"net/http"
"strings"
- "time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
- "github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
- "github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/QuantumNous/new-api/types"
-
- "github.com/shopspring/decimal"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -56,7 +52,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
}
// 如果不支持StreamOptions,将StreamOptions设置为nil
- if !info.SupportStreamOptions || !request.Stream {
+ if !info.SupportStreamOptions || !lo.FromPtrOr(request.Stream, false) {
request.StreamOptions = nil
} else {
// 如果支持StreamOptions,且请求中没有设置StreamOptions,根据配置文件设置StreamOptions
@@ -79,7 +75,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
if info.RelayMode == relayconstant.RelayModeChatCompletions &&
!passThroughGlobal &&
!info.ChannelSetting.PassThroughBodyEnabled &&
- shouldChatCompletionsViaResponses(info) {
+ service.ShouldChatCompletionsUseResponsesGlobal(info.ChannelId, info.ChannelType, info.OriginModelName) {
applySystemPromptIfNeeded(c, info, request)
usage, newApiErr := chatCompletionsViaResponses(c, info, adaptor, request)
if newApiErr != nil {
@@ -92,7 +88,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
if containAudioTokens && containsAudioRatios {
service.PostAudioConsumeQuota(c, info, usage, "")
} else {
- postConsumeQuota(c, info, usage)
+ service.PostTextConsumeQuota(c, info, usage, nil)
}
return nil
}
@@ -100,14 +96,16 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
var requestBody io.Reader
if passThroughGlobal || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
}
if common.DebugEnabled {
- println("requestBody: ", string(body))
+ if debugBytes, bErr := storage.Bytes(); bErr == nil {
+ println("requestBody: ", string(debugBytes))
+ }
}
- requestBody = bytes.NewBuffer(body)
+ requestBody = common.ReaderOnly(storage)
} else {
convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
if err != nil {
@@ -163,16 +161,16 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
}
// remove disabled fields for OpenAI API
- jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
+ jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
if err != nil {
return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -213,313 +211,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
if containAudioTokens && containsAudioRatios {
service.PostAudioConsumeQuota(c, info, usage.(*dto.Usage), "")
} else {
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
}
return nil
}
-
-func shouldChatCompletionsViaResponses(info *relaycommon.RelayInfo) bool {
- if info == nil {
- return false
- }
- if info.RelayMode != relayconstant.RelayModeChatCompletions {
- return false
- }
- return service.ShouldChatCompletionsUseResponsesGlobal(info.ChannelId, info.OriginModelName)
-}
-
-func postConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, extraContent ...string) {
- if usage == nil {
- usage = &dto.Usage{
- PromptTokens: relayInfo.GetEstimatePromptTokens(),
- CompletionTokens: 0,
- TotalTokens: relayInfo.GetEstimatePromptTokens(),
- }
- extraContent = append(extraContent, "上游无计费信息")
- }
- useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
- promptTokens := usage.PromptTokens
- cacheTokens := usage.PromptTokensDetails.CachedTokens
- imageTokens := usage.PromptTokensDetails.ImageTokens
- audioTokens := usage.PromptTokensDetails.AudioTokens
- completionTokens := usage.CompletionTokens
- cachedCreationTokens := usage.PromptTokensDetails.CachedCreationTokens
-
- modelName := relayInfo.OriginModelName
-
- tokenName := ctx.GetString("token_name")
- completionRatio := relayInfo.PriceData.CompletionRatio
- cacheRatio := relayInfo.PriceData.CacheRatio
- imageRatio := relayInfo.PriceData.ImageRatio
- modelRatio := relayInfo.PriceData.ModelRatio
- groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
- modelPrice := relayInfo.PriceData.ModelPrice
- cachedCreationRatio := relayInfo.PriceData.CacheCreationRatio
-
- // Convert values to decimal for precise calculation
- dPromptTokens := decimal.NewFromInt(int64(promptTokens))
- dCacheTokens := decimal.NewFromInt(int64(cacheTokens))
- dImageTokens := decimal.NewFromInt(int64(imageTokens))
- dAudioTokens := decimal.NewFromInt(int64(audioTokens))
- dCompletionTokens := decimal.NewFromInt(int64(completionTokens))
- dCachedCreationTokens := decimal.NewFromInt(int64(cachedCreationTokens))
- dCompletionRatio := decimal.NewFromFloat(completionRatio)
- dCacheRatio := decimal.NewFromFloat(cacheRatio)
- dImageRatio := decimal.NewFromFloat(imageRatio)
- dModelRatio := decimal.NewFromFloat(modelRatio)
- dGroupRatio := decimal.NewFromFloat(groupRatio)
- dModelPrice := decimal.NewFromFloat(modelPrice)
- dCachedCreationRatio := decimal.NewFromFloat(cachedCreationRatio)
- dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
-
- ratio := dModelRatio.Mul(dGroupRatio)
-
- // openai web search 工具计费
- var dWebSearchQuota decimal.Decimal
- var webSearchPrice float64
- // response api 格式工具计费
- if relayInfo.ResponsesUsageInfo != nil {
- if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
- // 计算 web search 调用的配额 (配额 = 价格 * 调用次数 / 1000 * 分组倍率)
- webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, webSearchTool.SearchContextSize)
- dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
- Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
- Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
- extraContent = append(extraContent, fmt.Sprintf("Web Search 调用 %d 次,上下文大小 %s,调用花费 %s",
- webSearchTool.CallCount, webSearchTool.SearchContextSize, dWebSearchQuota.String()))
- }
- } else if strings.HasSuffix(modelName, "search-preview") {
- // search-preview 模型不支持 response api
- searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
- if searchContextSize == "" {
- searchContextSize = "medium"
- }
- webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, searchContextSize)
- dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
- Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
- extraContent = append(extraContent, fmt.Sprintf("Web Search 调用 1 次,上下文大小 %s,调用花费 %s",
- searchContextSize, dWebSearchQuota.String()))
- }
- // claude web search tool 计费
- var dClaudeWebSearchQuota decimal.Decimal
- var claudeWebSearchPrice float64
- claudeWebSearchCallCount := ctx.GetInt("claude_web_search_requests")
- if claudeWebSearchCallCount > 0 {
- claudeWebSearchPrice = operation_setting.GetClaudeWebSearchPricePerThousand()
- dClaudeWebSearchQuota = decimal.NewFromFloat(claudeWebSearchPrice).
- Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit).Mul(decimal.NewFromInt(int64(claudeWebSearchCallCount)))
- extraContent = append(extraContent, fmt.Sprintf("Claude Web Search 调用 %d 次,调用花费 %s",
- claudeWebSearchCallCount, dClaudeWebSearchQuota.String()))
- }
- // file search tool 计费
- var dFileSearchQuota decimal.Decimal
- var fileSearchPrice float64
- if relayInfo.ResponsesUsageInfo != nil {
- if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
- fileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
- dFileSearchQuota = decimal.NewFromFloat(fileSearchPrice).
- Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
- Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
- extraContent = append(extraContent, fmt.Sprintf("File Search 调用 %d 次,调用花费 %s",
- fileSearchTool.CallCount, dFileSearchQuota.String()))
- }
- }
- var dImageGenerationCallQuota decimal.Decimal
- var imageGenerationCallPrice float64
- if ctx.GetBool("image_generation_call") {
- imageGenerationCallPrice = operation_setting.GetGPTImage1PriceOnceCall(ctx.GetString("image_generation_call_quality"), ctx.GetString("image_generation_call_size"))
- dImageGenerationCallQuota = decimal.NewFromFloat(imageGenerationCallPrice).Mul(dGroupRatio).Mul(dQuotaPerUnit)
- extraContent = append(extraContent, fmt.Sprintf("Image Generation Call 花费 %s", dImageGenerationCallQuota.String()))
- }
-
- var quotaCalculateDecimal decimal.Decimal
-
- var audioInputQuota decimal.Decimal
- var audioInputPrice float64
- isClaudeUsageSemantic := relayInfo.ChannelType == constant.ChannelTypeAnthropic
- if !relayInfo.PriceData.UsePrice {
- baseTokens := dPromptTokens
- // 减去 cached tokens
- // Anthropic API 的 input_tokens 已经不包含缓存 tokens,不需要减去
- // OpenAI/OpenRouter 等 API 的 prompt_tokens 包含缓存 tokens,需要减去
- var cachedTokensWithRatio decimal.Decimal
- if !dCacheTokens.IsZero() {
- if !isClaudeUsageSemantic {
- baseTokens = baseTokens.Sub(dCacheTokens)
- }
- cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
- }
- var dCachedCreationTokensWithRatio decimal.Decimal
- if !dCachedCreationTokens.IsZero() {
- if !isClaudeUsageSemantic {
- baseTokens = baseTokens.Sub(dCachedCreationTokens)
- }
- dCachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCachedCreationRatio)
- }
-
- // 减去 image tokens
- var imageTokensWithRatio decimal.Decimal
- if !dImageTokens.IsZero() {
- baseTokens = baseTokens.Sub(dImageTokens)
- imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
- }
-
- // 减去 Gemini audio tokens
- if !dAudioTokens.IsZero() {
- audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
- if audioInputPrice > 0 {
- // 重新计算 base tokens
- baseTokens = baseTokens.Sub(dAudioTokens)
- audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
- extraContent = append(extraContent, fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String()))
- }
- }
- promptQuota := baseTokens.Add(cachedTokensWithRatio).
- Add(imageTokensWithRatio).
- Add(dCachedCreationTokensWithRatio)
-
- completionQuota := dCompletionTokens.Mul(dCompletionRatio)
-
- quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
-
- if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
- quotaCalculateDecimal = decimal.NewFromInt(1)
- }
- } else {
- quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
- }
- // 添加 responses tools call 调用的配额
- quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
- quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
- // 添加 audio input 独立计费
- quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
- // 添加 image generation call 计费
- quotaCalculateDecimal = quotaCalculateDecimal.Add(dImageGenerationCallQuota)
-
- if len(relayInfo.PriceData.OtherRatios) > 0 {
- for key, otherRatio := range relayInfo.PriceData.OtherRatios {
- dOtherRatio := decimal.NewFromFloat(otherRatio)
- quotaCalculateDecimal = quotaCalculateDecimal.Mul(dOtherRatio)
- extraContent = append(extraContent, fmt.Sprintf("其他倍率 %s: %f", key, otherRatio))
- }
- }
-
- quota := int(quotaCalculateDecimal.Round(0).IntPart())
- totalTokens := promptTokens + completionTokens
-
- //var logContent string
-
- // record all the consume log even if quota is 0
- if totalTokens == 0 {
- // in this case, must be some error happened
- // we cannot just return, because we may have to return the pre-consumed quota
- quota = 0
- extraContent = append(extraContent, "上游没有返回计费信息,无法扣费(可能是上游超时)")
- logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
- "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
- } else {
- if !ratio.IsZero() && quota == 0 {
- quota = 1
- }
- model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
- model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
- }
-
- quotaDelta := quota - relayInfo.FinalPreConsumedQuota
-
- //logger.LogInfo(ctx, fmt.Sprintf("request quota delta: %s", logger.FormatQuota(quotaDelta)))
-
- if quotaDelta > 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- } else if quotaDelta < 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(-quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- }
-
- if quotaDelta != 0 {
- err := service.PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
- if err != nil {
- logger.LogError(ctx, "error consuming token remain quota: "+err.Error())
- }
- }
-
- logModel := modelName
- if strings.HasPrefix(logModel, "gpt-4-gizmo") {
- logModel = "gpt-4-gizmo-*"
- extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
- }
- if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
- logModel = "gpt-4o-gizmo-*"
- extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
- }
- logContent := strings.Join(extraContent, ", ")
- other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
- // For chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently.
- if isClaudeUsageSemantic {
- other["claude"] = true
- other["usage_semantic"] = "anthropic"
- }
- if imageTokens != 0 {
- other["image"] = true
- other["image_ratio"] = imageRatio
- other["image_output"] = imageTokens
- }
- if cachedCreationTokens != 0 {
- other["cache_creation_tokens"] = cachedCreationTokens
- other["cache_creation_ratio"] = cachedCreationRatio
- }
- if !dWebSearchQuota.IsZero() {
- if relayInfo.ResponsesUsageInfo != nil {
- if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
- other["web_search"] = true
- other["web_search_call_count"] = webSearchTool.CallCount
- other["web_search_price"] = webSearchPrice
- }
- } else if strings.HasSuffix(modelName, "search-preview") {
- other["web_search"] = true
- other["web_search_call_count"] = 1
- other["web_search_price"] = webSearchPrice
- }
- } else if !dClaudeWebSearchQuota.IsZero() {
- other["web_search"] = true
- other["web_search_call_count"] = claudeWebSearchCallCount
- other["web_search_price"] = claudeWebSearchPrice
- }
- if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
- if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
- other["file_search"] = true
- other["file_search_call_count"] = fileSearchTool.CallCount
- other["file_search_price"] = fileSearchPrice
- }
- }
- if !audioInputQuota.IsZero() {
- other["audio_input_seperate_price"] = true
- other["audio_input_token_count"] = audioTokens
- other["audio_input_price"] = audioInputPrice
- }
- if !dImageGenerationCallQuota.IsZero() {
- other["image_generation_call"] = true
- other["image_generation_call_price"] = imageGenerationCallPrice
- }
- model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
- ChannelId: relayInfo.ChannelId,
- PromptTokens: promptTokens,
- CompletionTokens: completionTokens,
- ModelName: logModel,
- TokenName: tokenName,
- Quota: quota,
- Content: logContent,
- TokenId: relayInfo.TokenId,
- UseTimeSeconds: int(useTimeSeconds),
- IsStream: relayInfo.IsStream,
- Group: relayInfo.UsingGroup,
- Other: other,
- })
-}
diff --git a/relay/constant/relay_mode.go b/relay/constant/relay_mode.go
index 85a1b9c5f8..2567156792 100644
--- a/relay/constant/relay_mode.go
+++ b/relay/constant/relay_mode.go
@@ -50,6 +50,8 @@ const (
RelayModeRealtime
RelayModeGemini
+
+ RelayModeResponsesCompact
)
func Path2RelayMode(path string) int {
@@ -70,6 +72,8 @@ func Path2RelayMode(path string) int {
relayMode = RelayModeImagesEdits
} else if strings.HasPrefix(path, "/v1/edits") {
relayMode = RelayModeEdits
+ } else if strings.HasPrefix(path, "/v1/responses/compact") {
+ relayMode = RelayModeResponsesCompact
} else if strings.HasPrefix(path, "/v1/responses") {
relayMode = RelayModeResponses
} else if strings.HasPrefix(path, "/v1/audio/speech") {
diff --git a/relay/embedding_handler.go b/relay/embedding_handler.go
index 1a41756b8b..393c0d72b3 100644
--- a/relay/embedding_handler.go
+++ b/relay/embedding_handler.go
@@ -2,7 +2,6 @@ package relay
import (
"bytes"
- "encoding/json"
"fmt"
"net/http"
@@ -46,15 +45,15 @@ func EmbeddingHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
relaycommon.AppendRequestConversionFromRequest(info, convertedRequest)
- jsonData, err := json.Marshal(convertedRequest)
+ jsonData, err := common.Marshal(convertedRequest)
if err != nil {
return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -83,6 +82,6 @@ func EmbeddingHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
service.ResetStatusCode(newAPIError, statusCodeMappingStr)
return newAPIError
}
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
return nil
}
diff --git a/relay/gemini_handler.go b/relay/gemini_handler.go
index 779670b9e0..e663a28baa 100644
--- a/relay/gemini_handler.go
+++ b/relay/gemini_handler.go
@@ -138,11 +138,11 @@ func GeminiHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
var requestBody io.Reader
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
}
- requestBody = bytes.NewReader(body)
+ requestBody = common.ReaderOnly(storage)
} else {
// 使用 ConvertGeminiRequest 转换请求格式
convertedRequest, err := adaptor.ConvertGeminiRequest(c, info, request)
@@ -157,9 +157,9 @@ func GeminiHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -194,7 +194,7 @@ func GeminiHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
return openaiErr
}
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
return nil
}
@@ -257,14 +257,9 @@ func GeminiEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo) (newAPI
// apply param override
if len(info.ParamOverride) > 0 {
- reqMap := make(map[string]interface{})
- _ = common.Unmarshal(jsonData, &reqMap)
- for key, value := range info.ParamOverride {
- reqMap[key] = value
- }
- jsonData, err = common.Marshal(reqMap)
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
logger.LogDebug(c, "Gemini embedding request body: "+string(jsonData))
@@ -293,6 +288,6 @@ func GeminiEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo) (newAPI
return openaiErr
}
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
return nil
}
diff --git a/relay/helper/model_mapped.go b/relay/helper/model_mapped.go
index 821158faed..5d6efa0948 100644
--- a/relay/helper/model_mapped.go
+++ b/relay/helper/model_mapped.go
@@ -4,13 +4,27 @@ import (
"encoding/json"
"errors"
"fmt"
+ "strings"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/common"
+ relayconstant "github.com/QuantumNous/new-api/relay/constant"
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
"github.com/gin-gonic/gin"
)
func ModelMappedHelper(c *gin.Context, info *common.RelayInfo, request dto.Request) error {
+ if info.ChannelMeta == nil {
+ info.ChannelMeta = &common.ChannelMeta{}
+ }
+
+ isResponsesCompact := info.RelayMode == relayconstant.RelayModeResponsesCompact
+ originModelName := info.OriginModelName
+ mappingModelName := originModelName
+ if isResponsesCompact && strings.HasSuffix(originModelName, ratio_setting.CompactModelSuffix) {
+ mappingModelName = strings.TrimSuffix(originModelName, ratio_setting.CompactModelSuffix)
+ }
+
// map model name
modelMapping := c.GetString("model_mapping")
if modelMapping != "" && modelMapping != "{}" {
@@ -21,7 +35,7 @@ func ModelMappedHelper(c *gin.Context, info *common.RelayInfo, request dto.Reque
}
// 支持链式模型重定向,最终使用链尾的模型
- currentModel := info.OriginModelName
+ currentModel := mappingModelName
visitedModels := map[string]bool{
currentModel: true,
}
@@ -51,6 +65,15 @@ func ModelMappedHelper(c *gin.Context, info *common.RelayInfo, request dto.Reque
info.UpstreamModelName = currentModel
}
}
+
+ if isResponsesCompact {
+ finalUpstreamModelName := mappingModelName
+ if info.IsModelMapped && info.UpstreamModelName != "" {
+ finalUpstreamModelName = info.UpstreamModelName
+ }
+ info.UpstreamModelName = finalUpstreamModelName
+ info.OriginModelName = ratio_setting.WithCompactModelSuffix(finalUpstreamModelName)
+ }
if request != nil {
request.SetModelName(info.UpstreamModelName)
}
diff --git a/relay/helper/price.go b/relay/helper/price.go
index c310220fe5..e9c3b46376 100644
--- a/relay/helper/price.go
+++ b/relay/helper/price.go
@@ -139,27 +139,65 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
return priceData, nil
}
-// ModelPriceHelperPerCall 按次计费的 PriceHelper (MJ、Task)
-func ModelPriceHelperPerCall(c *gin.Context, info *relaycommon.RelayInfo) types.PerCallPriceData {
+// ModelPriceHelperPerCall 按次/按量计费的 PriceHelper (MJ、Task)
+func ModelPriceHelperPerCall(c *gin.Context, info *relaycommon.RelayInfo) (types.PriceData, error) {
groupRatioInfo := HandleGroupRatio(c, info)
modelPrice, success := ratio_setting.GetModelPrice(info.OriginModelName, true)
- // 如果没有配置价格,则使用默认价格
+ usePrice := success
+ var modelRatio float64
+
if !success {
defaultPrice, ok := ratio_setting.GetDefaultModelPriceMap()[info.OriginModelName]
- if !ok {
- modelPrice = 0.1
- } else {
+ if ok {
modelPrice = defaultPrice
+ usePrice = true
+ } else {
+ var ratioSuccess bool
+ var matchName string
+ modelRatio, ratioSuccess, matchName = ratio_setting.GetModelRatio(info.OriginModelName)
+ acceptUnsetRatio := false
+ if info.UserSetting.AcceptUnsetRatioModel {
+ acceptUnsetRatio = true
+ }
+ if !ratioSuccess && !acceptUnsetRatio {
+ return types.PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置,请联系管理员设置或开始自用模式;Model %s ratio or price not set, please set or start self-use mode", matchName, matchName)
+ }
}
}
- quota := int(modelPrice * common.QuotaPerUnit * groupRatioInfo.GroupRatio)
- priceData := types.PerCallPriceData{
+
+ var quota int
+ freeModel := false
+
+ if usePrice {
+ quota = int(modelPrice * common.QuotaPerUnit * groupRatioInfo.GroupRatio)
+ if !operation_setting.GetQuotaSetting().EnableFreeModelPreConsume {
+ if groupRatioInfo.GroupRatio == 0 || modelPrice == 0 {
+ quota = 0
+ freeModel = true
+ }
+ }
+ } else {
+ // 按量计费:以模型倍率的一半作为预扣额度
+ quota = int(modelRatio / 2 * common.QuotaPerUnit * groupRatioInfo.GroupRatio)
+ modelPrice = -1
+ if !operation_setting.GetQuotaSetting().EnableFreeModelPreConsume {
+ if groupRatioInfo.GroupRatio == 0 || modelRatio == 0 {
+ quota = 0
+ freeModel = true
+ }
+ }
+ }
+
+ priceData := types.PriceData{
+ FreeModel: freeModel,
ModelPrice: modelPrice,
+ ModelRatio: modelRatio,
+ UsePrice: usePrice,
Quota: quota,
GroupRatioInfo: groupRatioInfo,
}
- return priceData
+ return priceData, nil
}
func ContainPriceOrRatio(modelName string) bool {
diff --git a/relay/helper/stream_result.go b/relay/helper/stream_result.go
new file mode 100644
index 0000000000..aa77e8039a
--- /dev/null
+++ b/relay/helper/stream_result.go
@@ -0,0 +1,52 @@
+package helper
+
+import (
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+)
+
+// StreamResult is passed to each dataHandler invocation, providing methods
+// to record soft errors, signal fatal stops, or mark normal completion.
+// StreamScannerHandler checks IsStopped() after each callback invocation.
+type StreamResult struct {
+ status *relaycommon.StreamStatus
+ stopped bool
+}
+
+func newStreamResult(status *relaycommon.StreamStatus) *StreamResult {
+ return &StreamResult{status: status}
+}
+
+// Error records a soft error. The stream continues processing.
+// Can be called multiple times per chunk.
+func (r *StreamResult) Error(err error) {
+ if err == nil {
+ return
+ }
+ r.status.RecordError(err.Error())
+}
+
+// Stop records a fatal error and marks the stream to stop after this chunk.
+func (r *StreamResult) Stop(err error) {
+ if err != nil {
+ r.status.RecordError(err.Error())
+ }
+ r.status.SetEndReason(relaycommon.StreamEndReasonHandlerStop, err)
+ r.stopped = true
+}
+
+// Done signals that the handler has finished processing normally
+// (e.g., Dify "message_end"). The stream stops after this chunk.
+func (r *StreamResult) Done() {
+ r.status.SetEndReason(relaycommon.StreamEndReasonDone, nil)
+ r.stopped = true
+}
+
+// IsStopped returns whether Stop() or Done() was called during this chunk.
+func (r *StreamResult) IsStopped() bool {
+ return r.stopped
+}
+
+// reset clears the per-chunk stopped flag so the object can be reused.
+func (r *StreamResult) reset() {
+ r.stopped = false
+}
diff --git a/relay/helper/stream_scanner.go b/relay/helper/stream_scanner.go
index 13c32c6758..a9bc5e16a7 100644
--- a/relay/helper/stream_scanner.go
+++ b/relay/helper/stream_scanner.go
@@ -34,12 +34,15 @@ func getScannerBufferSize() int {
return DefaultMaxScannerBufferSize
}
-func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string) bool) {
+func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string, sr *StreamResult)) {
if resp == nil || dataHandler == nil {
return
}
+ // 无条件新建 StreamStatus
+ info.StreamStatus = relaycommon.NewStreamStatus()
+
// 确保响应体总是被关闭
defer func() {
if resp.Body != nil {
@@ -90,10 +93,10 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
// 等待所有 goroutine 退出,最多等待5秒
done := make(chan struct{})
- go func() {
+ gopool.Go(func() {
wg.Wait()
close(done)
- }()
+ })
select {
case <-done:
@@ -121,6 +124,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
wg.Done()
if r := recover(); r != nil {
logger.LogError(c, fmt.Sprintf("ping goroutine panic: %v", r))
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("ping panic: %v", r))
common.SafeSendBool(stopChan, true)
}
if common.DebugEnabled {
@@ -138,16 +142,17 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
case <-pingTicker.C:
// 使用超时机制防止写操作阻塞
done := make(chan error, 1)
- go func() {
+ gopool.Go(func() {
writeMutex.Lock()
defer writeMutex.Unlock()
done <- PingData(c)
- }()
+ })
select {
case err := <-done:
if err != nil {
logger.LogError(c, "ping data error: "+err.Error())
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, err)
return
}
if common.DebugEnabled {
@@ -155,6 +160,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
}
case <-time.After(10 * time.Second):
logger.LogError(c, "ping data send timeout")
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, fmt.Errorf("ping send timeout"))
return
case <-ctx.Done():
return
@@ -176,13 +182,39 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
})
}
+ dataChan := make(chan string, 10)
+
+ wg.Add(1)
+ gopool.Go(func() {
+ defer func() {
+ wg.Done()
+ if r := recover(); r != nil {
+ logger.LogError(c, fmt.Sprintf("data handler goroutine panic: %v", r))
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("handler panic: %v", r))
+ }
+ common.SafeSendBool(stopChan, true)
+ }()
+ sr := newStreamResult(info.StreamStatus)
+ for data := range dataChan {
+ sr.reset()
+ writeMutex.Lock()
+ dataHandler(data, sr)
+ writeMutex.Unlock()
+ if sr.IsStopped() {
+ return
+ }
+ }
+ })
+
// Scanner goroutine with improved error handling
wg.Add(1)
common.RelayCtxGo(ctx, func() {
defer func() {
+ close(dataChan)
wg.Done()
if r := recover(); r != nil {
logger.LogError(c, fmt.Sprintf("scanner goroutine panic: %v", r))
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("scanner panic: %v", r))
}
common.SafeSendBool(stopChan, true)
if common.DebugEnabled {
@@ -198,6 +230,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
case <-ctx.Done():
return
case <-c.Request.Context().Done():
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonClientGone, c.Request.Context().Err())
return
default:
}
@@ -215,34 +248,23 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
continue
}
data = data[5:]
- data = strings.TrimLeft(data, " ")
- data = strings.TrimSuffix(data, "\r")
+ data = strings.TrimSpace(data)
+ if data == "" {
+ continue
+ }
if !strings.HasPrefix(data, "[DONE]") {
info.SetFirstResponseTime()
-
- // 使用超时机制防止写操作阻塞
- done := make(chan bool, 1)
- go func() {
- writeMutex.Lock()
- defer writeMutex.Unlock()
- done <- dataHandler(data)
- }()
+ info.ReceivedResponseCount++
select {
- case success := <-done:
- if !success {
- return
- }
- case <-time.After(10 * time.Second):
- logger.LogError(c, "data handler timeout")
- return
+ case dataChan <- data:
case <-ctx.Done():
return
case <-stopChan:
return
}
} else {
- // done, 处理完成标志,直接退出停止读取剩余数据防止出错
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonDone, nil)
if common.DebugEnabled {
println("received [DONE], stopping scanner")
}
@@ -253,20 +275,25 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
if err := scanner.Err(); err != nil {
if err != io.EOF {
logger.LogError(c, "scanner error: "+err.Error())
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonScannerErr, err)
}
}
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonEOF, nil)
})
// 主循环等待完成或超时
select {
case <-ticker.C:
- // 超时处理逻辑
- logger.LogError(c, "streaming timeout")
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonTimeout, nil)
case <-stopChan:
- // 正常结束
- logger.LogInfo(c, "streaming finished")
+ // EndReason already set by the goroutine that triggered stopChan
case <-c.Request.Context().Done():
- // 客户端断开连接
- logger.LogInfo(c, "client disconnected")
+ info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonClientGone, c.Request.Context().Err())
+ }
+
+ if info.StreamStatus.IsNormalEnd() && !info.StreamStatus.HasErrors() {
+ logger.LogInfo(c, fmt.Sprintf("stream ended: %s", info.StreamStatus.Summary()))
+ } else {
+ logger.LogError(c, fmt.Sprintf("stream ended: %s, received=%d", info.StreamStatus.Summary(), info.ReceivedResponseCount))
}
}
diff --git a/relay/helper/stream_scanner_test.go b/relay/helper/stream_scanner_test.go
new file mode 100644
index 0000000000..9d6f3bb491
--- /dev/null
+++ b/relay/helper/stream_scanner_test.go
@@ -0,0 +1,690 @@
+package helper
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/constant"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func init() {
+ gin.SetMode(gin.TestMode)
+}
+
+func setupStreamTest(t *testing.T, body io.Reader) (*gin.Context, *http.Response, *relaycommon.RelayInfo) {
+ t.Helper()
+
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 30
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldTimeout
+ })
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ resp := &http.Response{
+ Body: io.NopCloser(body),
+ }
+
+ info := &relaycommon.RelayInfo{
+ ChannelMeta: &relaycommon.ChannelMeta{},
+ }
+
+ return c, resp, info
+}
+
+func buildSSEBody(n int) string {
+ var b strings.Builder
+ for i := 0; i < n; i++ {
+ fmt.Fprintf(&b, "data: {\"id\":%d,\"choices\":[{\"delta\":{\"content\":\"token_%d\"}}]}\n", i, i)
+ }
+ b.WriteString("data: [DONE]\n")
+ return b.String()
+}
+
+type slowReader struct {
+ r io.Reader
+ delay time.Duration
+}
+
+func (s *slowReader) Read(p []byte) (int, error) {
+ time.Sleep(s.delay)
+ return s.r.Read(p)
+}
+
+// ---------- Basic correctness ----------
+
+func TestStreamScannerHandler_NilInputs(t *testing.T) {
+ t.Parallel()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
+
+ info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}}
+
+ StreamScannerHandler(c, nil, info, func(data string, sr *StreamResult) {})
+ StreamScannerHandler(c, &http.Response{Body: io.NopCloser(strings.NewReader(""))}, info, nil)
+}
+
+func TestStreamScannerHandler_EmptyBody(t *testing.T) {
+ t.Parallel()
+
+ c, resp, info := setupStreamTest(t, strings.NewReader(""))
+
+ var called atomic.Bool
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ called.Store(true)
+ })
+
+ assert.False(t, called.Load(), "handler should not be called for empty body")
+}
+
+func TestStreamScannerHandler_1000Chunks(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 1000
+ body := buildSSEBody(numChunks)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+
+ assert.Equal(t, int64(numChunks), count.Load())
+ assert.Equal(t, numChunks, info.ReceivedResponseCount)
+}
+
+func TestStreamScannerHandler_10000Chunks(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 10000
+ body := buildSSEBody(numChunks)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var count atomic.Int64
+ start := time.Now()
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+
+ elapsed := time.Since(start)
+ assert.Equal(t, int64(numChunks), count.Load())
+ assert.Equal(t, numChunks, info.ReceivedResponseCount)
+ t.Logf("10000 chunks processed in %v", elapsed)
+}
+
+func TestStreamScannerHandler_OrderPreserved(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 500
+ body := buildSSEBody(numChunks)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var mu sync.Mutex
+ received := make([]string, 0, numChunks)
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ mu.Lock()
+ received = append(received, data)
+ mu.Unlock()
+ })
+
+ require.Equal(t, numChunks, len(received))
+ for i := 0; i < numChunks; i++ {
+ expected := fmt.Sprintf("{\"id\":%d,\"choices\":[{\"delta\":{\"content\":\"token_%d\"}}]}", i, i)
+ assert.Equal(t, expected, received[i], "chunk %d out of order", i)
+ }
+}
+
+func TestStreamScannerHandler_DoneStopsScanner(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(50) + "data: should_not_appear\n"
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+
+ assert.Equal(t, int64(50), count.Load(), "data after [DONE] must not be processed")
+}
+
+func TestStreamScannerHandler_StopStopsStream(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 200
+ body := buildSSEBody(numChunks)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ const stopAt int64 = 50
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ n := count.Add(1)
+ if n >= stopAt {
+ sr.Stop(fmt.Errorf("fatal at %d", n))
+ }
+ })
+
+ assert.Equal(t, stopAt, count.Load())
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonHandlerStop, info.StreamStatus.EndReason)
+}
+
+func TestStreamScannerHandler_SkipsNonDataLines(t *testing.T) {
+ t.Parallel()
+
+ var b strings.Builder
+ b.WriteString(": comment line\n")
+ b.WriteString("event: message\n")
+ b.WriteString("id: 12345\n")
+ b.WriteString("retry: 5000\n")
+ for i := 0; i < 100; i++ {
+ fmt.Fprintf(&b, "data: payload_%d\n", i)
+ b.WriteString(": interleaved comment\n")
+ }
+ b.WriteString("data: [DONE]\n")
+
+ c, resp, info := setupStreamTest(t, strings.NewReader(b.String()))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+
+ assert.Equal(t, int64(100), count.Load())
+}
+
+func TestStreamScannerHandler_DataWithExtraSpaces(t *testing.T) {
+ t.Parallel()
+
+ body := "data: {\"trimmed\":true} \ndata: [DONE]\n"
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var got string
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ got = data
+ })
+
+ assert.Equal(t, "{\"trimmed\":true}", got)
+}
+
+// ---------- Decoupling ----------
+
+func TestStreamScannerHandler_ScannerDecoupledFromSlowHandler(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 50
+ const upstreamDelay = 10 * time.Millisecond
+ const handlerDelay = 20 * time.Millisecond
+
+ pr, pw := io.Pipe()
+ go func() {
+ defer pw.Close()
+ for i := 0; i < numChunks; i++ {
+ fmt.Fprintf(pw, "data: {\"id\":%d}\n", i)
+ time.Sleep(upstreamDelay)
+ }
+ fmt.Fprint(pw, "data: [DONE]\n")
+ }()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 30
+ t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
+
+ resp := &http.Response{Body: pr}
+ info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}}
+
+ var count atomic.Int64
+ start := time.Now()
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ time.Sleep(handlerDelay)
+ count.Add(1)
+ })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("StreamScannerHandler did not complete in time")
+ }
+
+ elapsed := time.Since(start)
+ assert.Equal(t, int64(numChunks), count.Load())
+
+ coupledTime := time.Duration(numChunks) * (upstreamDelay + handlerDelay)
+ t.Logf("elapsed=%v, coupled_estimate=%v", elapsed, coupledTime)
+
+ assert.Less(t, elapsed, coupledTime*85/100,
+ "decoupled elapsed time (%v) should be significantly less than coupled estimate (%v)", elapsed, coupledTime)
+}
+
+func TestStreamScannerHandler_SlowUpstreamFastHandler(t *testing.T) {
+ t.Parallel()
+
+ const numChunks = 50
+ body := buildSSEBody(numChunks)
+ reader := &slowReader{r: strings.NewReader(body), delay: 2 * time.Millisecond}
+ c, resp, info := setupStreamTest(t, reader)
+
+ var count atomic.Int64
+ start := time.Now()
+
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("timed out with slow upstream")
+ }
+
+ elapsed := time.Since(start)
+ assert.Equal(t, int64(numChunks), count.Load())
+ t.Logf("slow upstream (%d chunks, 2ms/read): %v", numChunks, elapsed)
+}
+
+// ---------- Ping tests ----------
+
+func TestStreamScannerHandler_PingSentDuringSlowUpstream(t *testing.T) {
+ t.Parallel()
+
+ setting := operation_setting.GetGeneralSetting()
+ oldEnabled := setting.PingIntervalEnabled
+ oldSeconds := setting.PingIntervalSeconds
+ setting.PingIntervalEnabled = true
+ setting.PingIntervalSeconds = 1
+ t.Cleanup(func() {
+ setting.PingIntervalEnabled = oldEnabled
+ setting.PingIntervalSeconds = oldSeconds
+ })
+
+ pr, pw := io.Pipe()
+ go func() {
+ defer pw.Close()
+ for i := 0; i < 7; i++ {
+ fmt.Fprintf(pw, "data: chunk_%d\n", i)
+ time.Sleep(500 * time.Millisecond)
+ }
+ fmt.Fprint(pw, "data: [DONE]\n")
+ }()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 30
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldTimeout
+ })
+
+ resp := &http.Response{Body: pr}
+ info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}}
+
+ var count atomic.Int64
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("timed out waiting for stream to finish")
+ }
+
+ assert.Equal(t, int64(7), count.Load())
+
+ body := recorder.Body.String()
+ pingCount := strings.Count(body, ": PING")
+ t.Logf("received %d pings in response body", pingCount)
+ assert.GreaterOrEqual(t, pingCount, 2,
+ "expected at least 2 pings during 3.5s stream with 1s interval; got %d", pingCount)
+}
+
+func TestStreamScannerHandler_PingDisabledByRelayInfo(t *testing.T) {
+ t.Parallel()
+
+ setting := operation_setting.GetGeneralSetting()
+ oldEnabled := setting.PingIntervalEnabled
+ oldSeconds := setting.PingIntervalSeconds
+ setting.PingIntervalEnabled = true
+ setting.PingIntervalSeconds = 1
+ t.Cleanup(func() {
+ setting.PingIntervalEnabled = oldEnabled
+ setting.PingIntervalSeconds = oldSeconds
+ })
+
+ pr, pw := io.Pipe()
+ go func() {
+ defer pw.Close()
+ for i := 0; i < 5; i++ {
+ fmt.Fprintf(pw, "data: chunk_%d\n", i)
+ time.Sleep(500 * time.Millisecond)
+ }
+ fmt.Fprint(pw, "data: [DONE]\n")
+ }()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 30
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldTimeout
+ })
+
+ resp := &http.Response{Body: pr}
+ info := &relaycommon.RelayInfo{
+ DisablePing: true,
+ ChannelMeta: &relaycommon.ChannelMeta{},
+ }
+
+ var count atomic.Int64
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("timed out")
+ }
+
+ assert.Equal(t, int64(5), count.Load())
+
+ body := recorder.Body.String()
+ pingCount := strings.Count(body, ": PING")
+ assert.Equal(t, 0, pingCount, "pings should be disabled when DisablePing=true")
+}
+
+// ---------- StreamStatus integration ----------
+
+func TestStreamScannerHandler_StreamStatus_DoneReason(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(10)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {})
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonDone, info.StreamStatus.EndReason)
+ assert.Nil(t, info.StreamStatus.EndError)
+ assert.True(t, info.StreamStatus.IsNormalEnd())
+ assert.False(t, info.StreamStatus.HasErrors())
+}
+
+func TestStreamScannerHandler_StreamStatus_EOFWithoutDone(t *testing.T) {
+ t.Parallel()
+
+ var b strings.Builder
+ for i := 0; i < 5; i++ {
+ fmt.Fprintf(&b, "data: {\"id\":%d}\n", i)
+ }
+ c, resp, info := setupStreamTest(t, strings.NewReader(b.String()))
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {})
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonEOF, info.StreamStatus.EndReason)
+ assert.True(t, info.StreamStatus.IsNormalEnd())
+}
+
+func TestStreamScannerHandler_StreamStatus_HandlerStop(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(100)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ n := count.Add(1)
+ if n >= 10 {
+ sr.Stop(fmt.Errorf("stop at 10"))
+ }
+ })
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonHandlerStop, info.StreamStatus.EndReason)
+ assert.True(t, info.StreamStatus.HasErrors())
+}
+
+func TestStreamScannerHandler_StreamStatus_HandlerDone(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(20)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ n := count.Add(1)
+ if n >= 5 {
+ sr.Done()
+ }
+ })
+
+ assert.Equal(t, int64(5), count.Load())
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonDone, info.StreamStatus.EndReason)
+ assert.False(t, info.StreamStatus.HasErrors())
+}
+
+func TestStreamScannerHandler_StreamStatus_Timeout(t *testing.T) {
+ // Not parallel: modifies global constant.StreamingTimeout
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 2
+ t.Cleanup(func() { constant.StreamingTimeout = oldTimeout })
+
+ pr, pw := io.Pipe()
+ go func() {
+ fmt.Fprint(pw, "data: {\"id\":1}\n")
+ time.Sleep(10 * time.Second)
+ pw.Close()
+ }()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ resp := &http.Response{Body: pr}
+ info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}}
+
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {})
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("timed out waiting for stream timeout")
+ }
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonTimeout, info.StreamStatus.EndReason)
+ assert.False(t, info.StreamStatus.IsNormalEnd())
+}
+
+func TestStreamScannerHandler_StreamStatus_SoftErrors(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(10)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ sr.Error(fmt.Errorf("soft error for chunk"))
+ })
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonDone, info.StreamStatus.EndReason)
+ assert.True(t, info.StreamStatus.HasErrors())
+ assert.Equal(t, 10, info.StreamStatus.TotalErrorCount())
+}
+
+func TestStreamScannerHandler_StreamStatus_MultipleErrorsPerChunk(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(5)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ sr.Error(fmt.Errorf("error A"))
+ sr.Error(fmt.Errorf("error B"))
+ })
+
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonDone, info.StreamStatus.EndReason)
+ assert.Equal(t, 10, info.StreamStatus.TotalErrorCount())
+}
+
+func TestStreamScannerHandler_StreamStatus_ErrorThenStop(t *testing.T) {
+ t.Parallel()
+
+ // Use a large body without [DONE] to avoid race between scanner's [DONE]
+ // and handler's Stop on the sync.Once EndReason.
+ var b strings.Builder
+ for i := 0; i < 100; i++ {
+ fmt.Fprintf(&b, "data: {\"id\":%d}\n", i)
+ }
+ c, resp, info := setupStreamTest(t, strings.NewReader(b.String()))
+
+ var count atomic.Int64
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ sr.Error(fmt.Errorf("soft error"))
+ sr.Stop(fmt.Errorf("fatal"))
+ })
+
+ assert.Equal(t, int64(1), count.Load())
+ require.NotNil(t, info.StreamStatus)
+ assert.Equal(t, relaycommon.StreamEndReasonHandlerStop, info.StreamStatus.EndReason)
+ assert.Equal(t, 2, info.StreamStatus.TotalErrorCount())
+}
+
+func TestStreamScannerHandler_StreamStatus_InitializedIfNil(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(1)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ assert.Nil(t, info.StreamStatus)
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {})
+
+ assert.NotNil(t, info.StreamStatus)
+}
+
+func TestStreamScannerHandler_StreamStatus_PreInitialized(t *testing.T) {
+ t.Parallel()
+
+ body := buildSSEBody(5)
+ c, resp, info := setupStreamTest(t, strings.NewReader(body))
+
+ info.StreamStatus = relaycommon.NewStreamStatus()
+ info.StreamStatus.RecordError("pre-existing error")
+
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {})
+
+ assert.Equal(t, relaycommon.StreamEndReasonDone, info.StreamStatus.EndReason)
+ assert.Equal(t, 1, info.StreamStatus.TotalErrorCount())
+}
+
+func TestStreamScannerHandler_PingInterleavesWithSlowUpstream(t *testing.T) {
+ t.Parallel()
+
+ setting := operation_setting.GetGeneralSetting()
+ oldEnabled := setting.PingIntervalEnabled
+ oldSeconds := setting.PingIntervalSeconds
+ setting.PingIntervalEnabled = true
+ setting.PingIntervalSeconds = 1
+ t.Cleanup(func() {
+ setting.PingIntervalEnabled = oldEnabled
+ setting.PingIntervalSeconds = oldSeconds
+ })
+
+ pr, pw := io.Pipe()
+ go func() {
+ defer pw.Close()
+ for i := 0; i < 10; i++ {
+ fmt.Fprintf(pw, "data: chunk_%d\n", i)
+ time.Sleep(500 * time.Millisecond)
+ }
+ fmt.Fprint(pw, "data: [DONE]\n")
+ }()
+
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
+
+ oldTimeout := constant.StreamingTimeout
+ constant.StreamingTimeout = 30
+ t.Cleanup(func() {
+ constant.StreamingTimeout = oldTimeout
+ })
+
+ resp := &http.Response{Body: pr}
+ info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}}
+
+ var count atomic.Int64
+ done := make(chan struct{})
+ go func() {
+ StreamScannerHandler(c, resp, info, func(data string, sr *StreamResult) {
+ count.Add(1)
+ })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatal("timed out")
+ }
+
+ assert.Equal(t, int64(10), count.Load())
+
+ body := recorder.Body.String()
+ pingCount := strings.Count(body, ": PING")
+ t.Logf("received %d pings interleaved with 10 chunks over 5s", pingCount)
+ assert.GreaterOrEqual(t, pingCount, 3,
+ "expected at least 3 pings during 5s stream with 1s ping interval; got %d", pingCount)
+}
diff --git a/relay/helper/valid_request.go b/relay/helper/valid_request.go
index 3bdfa6ff49..c5477ccead 100644
--- a/relay/helper/valid_request.go
+++ b/relay/helper/valid_request.go
@@ -12,6 +12,7 @@ import (
"github.com/QuantumNous/new-api/logger"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/types"
+ "github.com/samber/lo"
"github.com/gin-gonic/gin"
)
@@ -34,6 +35,8 @@ func GetAndValidateRequest(c *gin.Context, format types.RelayFormat) (request dt
request, err = GetAndValidateClaudeRequest(c)
case types.RelayFormatOpenAIResponses:
request, err = GetAndValidateResponsesRequest(c)
+ case types.RelayFormatOpenAIResponsesCompaction:
+ request, err = GetAndValidateResponsesCompactionRequest(c)
case types.RelayFormatOpenAIImage:
request, err = GetAndValidOpenAIImageRequest(c, relayMode)
@@ -125,6 +128,17 @@ func GetAndValidateResponsesRequest(c *gin.Context) (*dto.OpenAIResponsesRequest
return request, nil
}
+func GetAndValidateResponsesCompactionRequest(c *gin.Context) (*dto.OpenAIResponsesCompactionRequest, error) {
+ request := &dto.OpenAIResponsesCompactionRequest{}
+ if err := common.UnmarshalBodyReusable(c, request); err != nil {
+ return nil, err
+ }
+ if request.Model == "" {
+ return nil, errors.New("model is required")
+ }
+ return request, nil
+}
+
func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageRequest, error) {
imageRequest := &dto.ImageRequest{}
@@ -138,7 +152,7 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
formData := c.Request.PostForm
imageRequest.Prompt = formData.Get("prompt")
imageRequest.Model = formData.Get("model")
- imageRequest.N = uint(common.String2Int(formData.Get("n")))
+ imageRequest.N = common.GetPointer(uint(common.String2Int(formData.Get("n"))))
imageRequest.Quality = formData.Get("quality")
imageRequest.Size = formData.Get("size")
if imageValue := formData.Get("image"); imageValue != "" {
@@ -150,8 +164,8 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
imageRequest.Quality = "standard"
}
}
- if imageRequest.N == 0 {
- imageRequest.N = 1
+ if imageRequest.N == nil || *imageRequest.N == 0 {
+ imageRequest.N = common.GetPointer(uint(1))
}
hasWatermark := formData.Has("watermark")
@@ -205,8 +219,8 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
// return nil, errors.New("prompt is required")
//}
- if imageRequest.N == 0 {
- imageRequest.N = 1
+ if imageRequest.N == nil || *imageRequest.N == 0 {
+ imageRequest.N = common.GetPointer(uint(1))
}
}
@@ -215,7 +229,7 @@ func GetAndValidOpenAIImageRequest(c *gin.Context, relayMode int) (*dto.ImageReq
func GetAndValidateClaudeRequest(c *gin.Context) (textRequest *dto.ClaudeRequest, err error) {
textRequest = &dto.ClaudeRequest{}
- err = c.ShouldBindJSON(textRequest)
+ err = common.UnmarshalBodyReusable(c, textRequest)
if err != nil {
return nil, err
}
@@ -247,7 +261,7 @@ func GetAndValidateTextRequest(c *gin.Context, relayMode int) (*dto.GeneralOpenA
textRequest.Model = c.Param("model")
}
- if textRequest.MaxTokens > math.MaxInt32/2 {
+ if lo.FromPtrOr(textRequest.MaxTokens, uint(0)) > math.MaxInt32/2 {
return nil, errors.New("max_tokens is invalid")
}
if textRequest.Model == "" {
diff --git a/relay/image_handler.go b/relay/image_handler.go
index 1ee790b74f..a4fee7d9e0 100644
--- a/relay/image_handler.go
+++ b/relay/image_handler.go
@@ -47,11 +47,11 @@ func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
var requestBody io.Reader
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
}
- requestBody = bytes.NewBuffer(body)
+ requestBody = common.ReaderOnly(storage)
} else {
convertedRequest, err := adaptor.ConvertImageRequest(c, info, *request)
if err != nil {
@@ -70,9 +70,9 @@ func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -113,11 +113,24 @@ func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
return newAPIError
}
+ imageN := uint(1)
+ if request.N != nil {
+ imageN = *request.N
+ }
+
+ // n is handled via OtherRatio so it is applied exactly once in quota
+ // calculation (both price-based and ratio-based paths).
+ // Adaptors may have already set a more accurate count from the
+ // upstream response; only set the default when they haven't.
+ if _, hasN := info.PriceData.OtherRatios["n"]; !hasN {
+ info.PriceData.AddOtherRatio("n", float64(imageN))
+ }
+
if usage.(*dto.Usage).TotalTokens == 0 {
- usage.(*dto.Usage).TotalTokens = int(request.N)
+ usage.(*dto.Usage).TotalTokens = 1
}
if usage.(*dto.Usage).PromptTokens == 0 {
- usage.(*dto.Usage).PromptTokens = int(request.N)
+ usage.(*dto.Usage).PromptTokens = 1
}
quality := "standard"
@@ -133,10 +146,10 @@ func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
if len(quality) > 0 {
logContent = append(logContent, fmt.Sprintf("品质 %s", quality))
}
- if request.N > 0 {
- logContent = append(logContent, fmt.Sprintf("生成数量 %d", request.N))
+ if imageN > 0 {
+ logContent = append(logContent, fmt.Sprintf("生成数量 %d", imageN))
}
- postConsumeQuota(c, info, usage.(*dto.Usage), logContent...)
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), logContent)
return nil
}
diff --git a/relay/mjproxy_handler.go b/relay/mjproxy_handler.go
index 8916ab181f..ee48ca64b1 100644
--- a/relay/mjproxy_handler.go
+++ b/relay/mjproxy_handler.go
@@ -49,6 +49,13 @@ func RelayMidjourneyImage(c *gin.Context) {
if httpClient == nil {
httpClient = service.GetHttpClient()
}
+ fetchSetting := system_setting.GetFetchSetting()
+ if err := common.ValidateURLWithFetchSetting(midjourneyTask.ImageUrl, fetchSetting.EnableSSRFProtection, fetchSetting.AllowPrivateIp, fetchSetting.DomainFilterMode, fetchSetting.IpFilterMode, fetchSetting.DomainList, fetchSetting.IpList, fetchSetting.AllowedPorts, fetchSetting.ApplyIPFilterForDomain); err != nil {
+ c.JSON(http.StatusForbidden, gin.H{
+ "error": fmt.Sprintf("request blocked: %v", err),
+ })
+ return
+ }
resp, err := httpClient.Get(midjourneyTask.ImageUrl)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -184,9 +191,15 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR
if swapFaceRequest.SourceBase64 == "" || swapFaceRequest.TargetBase64 == "" {
return service.MidjourneyErrorWrapper(constant.MjRequestError, "sour_base64_and_target_base64_is_required")
}
- modelName := service.CoverActionToModelName(constant.MjActionSwapFace)
+ modelName := service.CovertMjpActionToModelName(constant.MjActionSwapFace)
- priceData := helper.ModelPriceHelperPerCall(c, info)
+ priceData, err := helper.ModelPriceHelperPerCall(c, info)
+ if err != nil {
+ return &dto.MidjourneyResponse{
+ Code: 4,
+ Description: err.Error(),
+ }
+ }
userQuota, err := model.GetUserQuota(info.UserId, false)
if err != nil {
@@ -485,9 +498,15 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
- modelName := service.CoverActionToModelName(midjRequest.Action)
+ modelName := service.CovertMjpActionToModelName(midjRequest.Action)
- priceData := helper.ModelPriceHelperPerCall(c, relayInfo)
+ priceData, err := helper.ModelPriceHelperPerCall(c, relayInfo)
+ if err != nil {
+ return &dto.MidjourneyResponse{
+ Code: 4,
+ Description: err.Error(),
+ }
+ }
userQuota, err := model.GetUserQuota(relayInfo.UserId, false)
if err != nil {
diff --git a/relay/param_override_error.go b/relay/param_override_error.go
new file mode 100644
index 0000000000..c233829854
--- /dev/null
+++ b/relay/param_override_error.go
@@ -0,0 +1,13 @@
+package relay
+
+import (
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/types"
+)
+
+func newAPIErrorFromParamOverride(err error) *types.NewAPIError {
+ if fixedErr, ok := relaycommon.AsParamOverrideReturnError(err); ok {
+ return relaycommon.NewAPIErrorFromParamOverride(fixedErr)
+ }
+ return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+}
diff --git a/relay/reasonmap/reasonmap.go b/relay/reasonmap/reasonmap.go
new file mode 100644
index 0000000000..45b74bb14e
--- /dev/null
+++ b/relay/reasonmap/reasonmap.go
@@ -0,0 +1,41 @@
+package reasonmap
+
+import (
+ "strings"
+
+ "github.com/QuantumNous/new-api/constant"
+)
+
+func ClaudeStopReasonToOpenAIFinishReason(stopReason string) string {
+ switch strings.ToLower(stopReason) {
+ case "stop_sequence":
+ return "stop"
+ case "end_turn":
+ return "stop"
+ case "max_tokens":
+ return "length"
+ case "tool_use":
+ return "tool_calls"
+ case "refusal":
+ return constant.FinishReasonContentFilter
+ default:
+ return stopReason
+ }
+}
+
+func OpenAIFinishReasonToClaudeStopReason(finishReason string) string {
+ switch strings.ToLower(finishReason) {
+ case "stop":
+ return "end_turn"
+ case "stop_sequence":
+ return "stop_sequence"
+ case "length", "max_tokens":
+ return "max_tokens"
+ case constant.FinishReasonContentFilter:
+ return "refusal"
+ case "tool_calls":
+ return "tool_use"
+ default:
+ return finishReason
+ }
+}
diff --git a/relay/relay_task.go b/relay/relay_task.go
index 61588f93ba..098e23828b 100644
--- a/relay/relay_task.go
+++ b/relay/relay_task.go
@@ -2,7 +2,6 @@ package relay
import (
"bytes"
- "encoding/json"
"errors"
"fmt"
"io"
@@ -15,23 +14,29 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
+ "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
+ "github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
- "github.com/QuantumNous/new-api/setting/ratio_setting"
-
"github.com/gin-gonic/gin"
)
-/*
-Task 任务通过平台、Action 区分任务
-*/
-func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
- info.InitChannelMeta(c)
- // ensure TaskRelayInfo is initialized to avoid nil dereference when accessing embedded fields
- if info.TaskRelayInfo == nil {
- info.TaskRelayInfo = &relaycommon.TaskRelayInfo{}
- }
+type TaskSubmitResult struct {
+ UpstreamTaskID string
+ TaskData []byte
+ Platform constant.TaskPlatform
+ Quota int
+ //PerCallPrice types.PriceData
+}
+
+// ResolveOriginTask 处理基于已有任务的提交(remix / continuation):
+// 查找原始任务、从中提取模型名称、将渠道锁定到原始任务的渠道
+// (通过 info.LockedChannel,重试时复用同一渠道并轮换 key),
+// 以及提取 OtherRatios(时长、分辨率)。
+// 该函数在控制器的重试循环之前调用一次,其结果通过 info 字段和上下文持久化。
+func ResolveOriginTask(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
+ // 检测 remix action
path := c.Request.URL.Path
if strings.Contains(path, "/v1/videos/") && strings.HasSuffix(path, "/remix") {
info.Action = constant.TaskActionRemix
@@ -46,64 +51,71 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.
info.OriginTaskID = videoID
}
- platform := constant.TaskPlatform(c.GetString("platform"))
+ if info.OriginTaskID == "" {
+ return nil
+ }
- // 获取原始任务信息
- if info.OriginTaskID != "" {
- originTask, exist, err := model.GetByTaskId(info.UserId, info.OriginTaskID)
- if err != nil {
- taskErr = service.TaskErrorWrapper(err, "get_origin_task_failed", http.StatusInternalServerError)
- return
- }
- if !exist {
- taskErr = service.TaskErrorWrapperLocal(errors.New("task_origin_not_exist"), "task_not_exist", http.StatusBadRequest)
- return
- }
- if info.OriginModelName == "" {
- if originTask.Properties.OriginModelName != "" {
- info.OriginModelName = originTask.Properties.OriginModelName
- } else if originTask.Properties.UpstreamModelName != "" {
- info.OriginModelName = originTask.Properties.UpstreamModelName
- } else {
- var taskData map[string]interface{}
- _ = json.Unmarshal(originTask.Data, &taskData)
- if m, ok := taskData["model"].(string); ok && m != "" {
- info.OriginModelName = m
- platform = originTask.Platform
- }
- }
- }
- if originTask.ChannelId != info.ChannelId {
- channel, err := model.GetChannelById(originTask.ChannelId, true)
- if err != nil {
- taskErr = service.TaskErrorWrapperLocal(err, "channel_not_found", http.StatusBadRequest)
- return
- }
- if channel.Status != common.ChannelStatusEnabled {
- taskErr = service.TaskErrorWrapperLocal(errors.New("the channel of the origin task is disabled"), "task_channel_disable", http.StatusBadRequest)
- return
- }
- key, _, newAPIError := channel.GetNextEnabledKey()
- if newAPIError != nil {
- taskErr = service.TaskErrorWrapper(newAPIError, "channel_no_available_key", newAPIError.StatusCode)
- return
- }
- common.SetContextKey(c, constant.ContextKeyChannelKey, key)
- common.SetContextKey(c, constant.ContextKeyChannelType, channel.Type)
- common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, channel.GetBaseURL())
- common.SetContextKey(c, constant.ContextKeyChannelId, originTask.ChannelId)
+ // 查找原始任务
+ originTask, exist, err := model.GetByTaskId(info.UserId, info.OriginTaskID)
+ if err != nil {
+ return service.TaskErrorWrapper(err, "get_origin_task_failed", http.StatusInternalServerError)
+ }
+ if !exist {
+ return service.TaskErrorWrapperLocal(errors.New("task_origin_not_exist"), "task_not_exist", http.StatusBadRequest)
+ }
- info.ChannelBaseUrl = channel.GetBaseURL()
- info.ChannelId = originTask.ChannelId
- info.ChannelType = channel.Type
- info.ApiKey = key
- platform = originTask.Platform
- }
-
- // 使用原始任务的参数
- if info.Action == constant.TaskActionRemix {
+ // 从原始任务推导模型名称
+ if info.OriginModelName == "" {
+ if originTask.Properties.OriginModelName != "" {
+ info.OriginModelName = originTask.Properties.OriginModelName
+ } else if originTask.Properties.UpstreamModelName != "" {
+ info.OriginModelName = originTask.Properties.UpstreamModelName
+ } else {
var taskData map[string]interface{}
- _ = json.Unmarshal(originTask.Data, &taskData)
+ _ = common.Unmarshal(originTask.Data, &taskData)
+ if m, ok := taskData["model"].(string); ok && m != "" {
+ info.OriginModelName = m
+ }
+ }
+ }
+
+ // 锁定到原始任务的渠道(重试时复用同一渠道,轮换 key)
+ ch, err := model.GetChannelById(originTask.ChannelId, true)
+ if err != nil {
+ return service.TaskErrorWrapperLocal(err, "channel_not_found", http.StatusBadRequest)
+ }
+ if ch.Status != common.ChannelStatusEnabled {
+ return service.TaskErrorWrapperLocal(errors.New("the channel of the origin task is disabled"), "task_channel_disable", http.StatusBadRequest)
+ }
+ info.LockedChannel = ch
+
+ if originTask.ChannelId != info.ChannelId {
+ key, _, newAPIError := ch.GetNextEnabledKey()
+ if newAPIError != nil {
+ return service.TaskErrorWrapper(newAPIError, "channel_no_available_key", newAPIError.StatusCode)
+ }
+ common.SetContextKey(c, constant.ContextKeyChannelKey, key)
+ common.SetContextKey(c, constant.ContextKeyChannelType, ch.Type)
+ common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, ch.GetBaseURL())
+ common.SetContextKey(c, constant.ContextKeyChannelId, originTask.ChannelId)
+
+ info.ChannelBaseUrl = ch.GetBaseURL()
+ info.ChannelId = originTask.ChannelId
+ info.ChannelType = ch.Type
+ info.ApiKey = key
+ }
+
+ // 提取 remix 参数(时长、分辨率 → OtherRatios)
+ if info.Action == constant.TaskActionRemix {
+ if originTask.PrivateData.BillingContext != nil {
+ // 新的 remix 逻辑:直接从原始任务的 BillingContext 中提取 OtherRatios(如果存在)
+ for s, f := range originTask.PrivateData.BillingContext.OtherRatios {
+ info.PriceData.AddOtherRatio(s, f)
+ }
+ } else {
+ // 旧的 remix 逻辑:直接从 task data 解析 seconds 和 size(如果存在)
+ var taskData map[string]interface{}
+ _ = common.Unmarshal(originTask.Data, &taskData)
secondsStr, _ := taskData["seconds"].(string)
seconds, _ := strconv.Atoi(secondsStr)
if seconds <= 0 {
@@ -120,167 +132,150 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.
}
}
}
+
+ return nil
+}
+
+// RelayTaskSubmit 完成 task 提交的全部流程(每次尝试调用一次):
+// 刷新渠道元数据 → 确定 platform/adaptor → 验证请求 →
+// 估算计费(EstimateBilling) → 计算价格 → 预扣费(仅首次)→
+// 构建/发送/解析上游请求 → 提交后计费调整(AdjustBillingOnSubmit)。
+// 控制器负责 defer Refund 和成功后 Settle。
+func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitResult, *dto.TaskError) {
+ info.InitChannelMeta(c)
+
+ // 1. 确定 platform → 创建适配器 → 验证请求
+ platform := constant.TaskPlatform(c.GetString("platform"))
if platform == "" {
platform = GetTaskPlatform(c)
}
-
- info.InitChannelMeta(c)
adaptor := GetTaskAdaptor(platform)
if adaptor == nil {
- return service.TaskErrorWrapperLocal(fmt.Errorf("invalid api platform: %s", platform), "invalid_api_platform", http.StatusBadRequest)
+ return nil, service.TaskErrorWrapperLocal(fmt.Errorf("invalid api platform: %s", platform), "invalid_api_platform", http.StatusBadRequest)
}
adaptor.Init(info)
- // get & validate taskRequest 获取并验证文本请求
- taskErr = adaptor.ValidateRequestAndSetAction(c, info)
- if taskErr != nil {
- return
+ if taskErr := adaptor.ValidateRequestAndSetAction(c, info); taskErr != nil {
+ return nil, taskErr
}
+ // 2. 确定模型名称
modelName := info.OriginModelName
if modelName == "" {
modelName = service.CoverTaskActionToModelName(platform, info.Action)
}
- modelPrice, success := ratio_setting.GetModelPrice(modelName, true)
- if !success {
- defaultPrice, ok := ratio_setting.GetDefaultModelPriceMap()[modelName]
- if !ok {
- modelPrice = 0.1
- } else {
- modelPrice = defaultPrice
+
+ // 2.5 应用渠道的模型映射(与同步任务对齐)
+ info.OriginModelName = modelName
+ info.UpstreamModelName = modelName
+ if err := helper.ModelMappedHelper(c, info, nil); err != nil {
+ return nil, service.TaskErrorWrapperLocal(err, "model_mapping_failed", http.StatusBadRequest)
+ }
+
+ // 3. 预生成公开 task ID(仅首次)
+ if info.PublicTaskID == "" {
+ info.PublicTaskID = model.GenerateTaskID()
+ }
+
+ // 4. 价格计算:基础模型价格
+ info.OriginModelName = modelName
+ priceData, err := helper.ModelPriceHelperPerCall(c, info)
+ if err != nil {
+ return nil, service.TaskErrorWrapper(err, "model_price_error", http.StatusBadRequest)
+ }
+ info.PriceData = priceData
+
+ // 5. 计费估算:让适配器根据用户请求提供 OtherRatios(时长、分辨率等)
+ // 必须在 ModelPriceHelperPerCall 之后调用(它会重建 PriceData)。
+ // ResolveOriginTask 可能已在 remix 路径中预设了 OtherRatios,此处合并。
+ if estimatedRatios := adaptor.EstimateBilling(c, info); len(estimatedRatios) > 0 {
+ for k, v := range estimatedRatios {
+ info.PriceData.AddOtherRatio(k, v)
}
}
- // 处理 auto 分组:从 context 获取实际选中的分组
- // 当使用 auto 分组时,Distribute 中间件会将实际选中的分组存储在 ContextKeyAutoGroup 中
- if autoGroup, exists := common.GetContextKey(c, constant.ContextKeyAutoGroup); exists {
- if groupStr, ok := autoGroup.(string); ok && groupStr != "" {
- info.UsingGroup = groupStr
- }
- }
-
- // 预扣
- groupRatio := ratio_setting.GetGroupRatio(info.UsingGroup)
- var ratio float64
- userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(info.UserGroup, info.UsingGroup)
- if hasUserGroupRatio {
- ratio = modelPrice * userGroupRatio
- } else {
- ratio = modelPrice * groupRatio
- }
- // FIXME: 临时修补,支持任务仅按次计费
+ // 6. 将 OtherRatios 应用到基础额度
if !common.StringsContains(constant.TaskPricePatches, modelName) {
- if len(info.PriceData.OtherRatios) > 0 {
- for _, ra := range info.PriceData.OtherRatios {
- if 1.0 != ra {
- ratio *= ra
- }
+ for _, ra := range info.PriceData.OtherRatios {
+ if ra != 1.0 {
+ info.PriceData.Quota = int(float64(info.PriceData.Quota) * ra)
}
}
}
- println(fmt.Sprintf("model: %s, model_price: %.4f, group: %s, group_ratio: %.4f, final_ratio: %.4f", modelName, modelPrice, info.UsingGroup, groupRatio, ratio))
- userQuota, err := model.GetUserQuota(info.UserId, false)
- if err != nil {
- taskErr = service.TaskErrorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
- return
- }
- quota := int(ratio * common.QuotaPerUnit)
- if userQuota-quota < 0 {
- taskErr = service.TaskErrorWrapperLocal(errors.New("user quota is not enough"), "quota_not_enough", http.StatusForbidden)
- return
+
+ // 7. 预扣费(仅首次 — 重试时 info.Billing 已存在,跳过)
+ if info.Billing == nil && !info.PriceData.FreeModel {
+ info.ForcePreConsume = true
+ if apiErr := service.PreConsumeBilling(c, info.PriceData.Quota, info); apiErr != nil {
+ return nil, service.TaskErrorFromAPIError(apiErr)
+ }
}
- // build body
+ // 8. 构建请求体
requestBody, err := adaptor.BuildRequestBody(c, info)
if err != nil {
- taskErr = service.TaskErrorWrapper(err, "build_request_failed", http.StatusInternalServerError)
- return
+ return nil, service.TaskErrorWrapper(err, "build_request_failed", http.StatusInternalServerError)
}
- // do request
+
+ // 9. 发送请求
resp, err := adaptor.DoRequest(c, info, requestBody)
if err != nil {
- taskErr = service.TaskErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
- return
+ return nil, service.TaskErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
}
- // handle response
if resp != nil && resp.StatusCode != http.StatusOK {
responseBody, _ := io.ReadAll(resp.Body)
- taskErr = service.TaskErrorWrapper(fmt.Errorf("%s", string(responseBody)), "fail_to_fetch_task", resp.StatusCode)
- return
+ return nil, service.TaskErrorWrapper(fmt.Errorf("%s", string(responseBody)), "fail_to_fetch_task", resp.StatusCode)
}
- defer func() {
- // release quota
- if info.ConsumeQuota && taskErr == nil {
+ // 10. 返回 OtherRatios 给下游(header 必须在 DoResponse 写 body 之前设置)
+ otherRatios := info.PriceData.OtherRatios
+ if otherRatios == nil {
+ otherRatios = map[string]float64{}
+ }
+ ratiosJSON, _ := common.Marshal(otherRatios)
+ c.Header("X-New-Api-Other-Ratios", string(ratiosJSON))
- err := service.PostConsumeQuota(info, quota, 0, true)
- if err != nil {
- common.SysLog("error consuming token remain quota: " + err.Error())
- }
- if quota != 0 {
- tokenName := c.GetString("token_name")
- //gRatio := groupRatio
- //if hasUserGroupRatio {
- // gRatio = userGroupRatio
- //}
- logContent := fmt.Sprintf("操作 %s", info.Action)
- // FIXME: 临时修补,支持任务仅按次计费
- if common.StringsContains(constant.TaskPricePatches, modelName) {
- logContent = fmt.Sprintf("%s,按次计费", logContent)
- } else {
- if len(info.PriceData.OtherRatios) > 0 {
- var contents []string
- for key, ra := range info.PriceData.OtherRatios {
- if 1.0 != ra {
- contents = append(contents, fmt.Sprintf("%s: %.2f", key, ra))
- }
- }
- if len(contents) > 0 {
- logContent = fmt.Sprintf("%s, 计算参数:%s", logContent, strings.Join(contents, ", "))
- }
- }
- }
- other := make(map[string]interface{})
- if c != nil && c.Request != nil && c.Request.URL != nil {
- other["request_path"] = c.Request.URL.Path
- }
- other["model_price"] = modelPrice
- other["group_ratio"] = groupRatio
- if hasUserGroupRatio {
- other["user_group_ratio"] = userGroupRatio
- }
- model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{
- ChannelId: info.ChannelId,
- ModelName: modelName,
- TokenName: tokenName,
- Quota: quota,
- Content: logContent,
- TokenId: info.TokenId,
- Group: info.UsingGroup,
- Other: other,
- })
- model.UpdateUserUsedQuotaAndRequestCount(info.UserId, quota)
- model.UpdateChannelUsedQuota(info.ChannelId, quota)
- }
- }
- }()
-
- taskID, taskData, taskErr := adaptor.DoResponse(c, resp, info)
+ // 11. 解析响应
+ upstreamTaskID, taskData, taskErr := adaptor.DoResponse(c, resp, info)
if taskErr != nil {
- return
+ return nil, taskErr
}
- info.ConsumeQuota = true
- // insert task
- task := model.InitTask(platform, info)
- task.TaskID = taskID
- task.Quota = quota
- task.Data = taskData
- task.Action = info.Action
- err = task.Insert()
- if err != nil {
- taskErr = service.TaskErrorWrapper(err, "insert_task_failed", http.StatusInternalServerError)
- return
+
+ // 11. 提交后计费调整:让适配器根据上游实际返回调整 OtherRatios
+ finalQuota := info.PriceData.Quota
+ if adjustedRatios := adaptor.AdjustBillingOnSubmit(info, taskData); len(adjustedRatios) > 0 {
+ // 基于调整后的 ratios 重新计算 quota
+ finalQuota = recalcQuotaFromRatios(info, adjustedRatios)
+ info.PriceData.OtherRatios = adjustedRatios
+ info.PriceData.Quota = finalQuota
}
- return nil
+
+ return &TaskSubmitResult{
+ UpstreamTaskID: upstreamTaskID,
+ TaskData: taskData,
+ Platform: platform,
+ Quota: finalQuota,
+ }, nil
+}
+
+// recalcQuotaFromRatios 根据 adjustedRatios 重新计算 quota。
+// 公式: baseQuota × ∏(ratio) — 其中 baseQuota 是不含 OtherRatios 的基础额度。
+func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float64) int {
+ // 从 PriceData 获取不含 OtherRatios 的基础价格
+ baseQuota := info.PriceData.Quota
+ // 先除掉原有的 OtherRatios 恢复基础额度
+ for _, ra := range info.PriceData.OtherRatios {
+ if ra != 1.0 && ra > 0 {
+ baseQuota = int(float64(baseQuota) / ra)
+ }
+ }
+ // 应用新的 ratios
+ result := float64(baseQuota)
+ for _, ra := range ratios {
+ if ra != 1.0 {
+ result *= ra
+ }
+ }
+ return int(result)
}
var fetchRespBuilders = map[int]func(c *gin.Context) (respBody []byte, taskResp *dto.TaskError){
@@ -336,7 +331,7 @@ func sunoFetchRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.Ta
} else {
tasks = make([]any, 0)
}
- respBody, err = json.Marshal(dto.TaskResponse[[]any]{
+ respBody, err = common.Marshal(dto.TaskResponse[[]any]{
Code: "success",
Data: tasks,
})
@@ -357,7 +352,7 @@ func sunoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dt
return
}
- respBody, err = json.Marshal(dto.TaskResponse[any]{
+ respBody, err = common.Marshal(dto.TaskResponse[any]{
Code: "success",
Data: TaskModel2Dto(originTask),
})
@@ -381,97 +376,16 @@ func videoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *d
return
}
- func() {
- channelModel, err2 := model.GetChannelById(originTask.ChannelId, true)
- if err2 != nil {
- return
- }
- if channelModel.Type != constant.ChannelTypeVertexAi && channelModel.Type != constant.ChannelTypeGemini {
- return
- }
- baseURL := constant.ChannelBaseURLs[channelModel.Type]
- if channelModel.GetBaseURL() != "" {
- baseURL = channelModel.GetBaseURL()
- }
- proxy := channelModel.GetSetting().Proxy
- adaptor := GetTaskAdaptor(constant.TaskPlatform(strconv.Itoa(channelModel.Type)))
- if adaptor == nil {
- return
- }
- resp, err2 := adaptor.FetchTask(baseURL, channelModel.Key, map[string]any{
- "task_id": originTask.TaskID,
- "action": originTask.Action,
- }, proxy)
- if err2 != nil || resp == nil {
- return
- }
- defer resp.Body.Close()
- body, err2 := io.ReadAll(resp.Body)
- if err2 != nil {
- return
- }
- ti, err2 := adaptor.ParseTaskResult(body)
- if err2 == nil && ti != nil {
- if ti.Status != "" {
- originTask.Status = model.TaskStatus(ti.Status)
- }
- if ti.Progress != "" {
- originTask.Progress = ti.Progress
- }
- if ti.Url != "" {
- if strings.HasPrefix(ti.Url, "data:") {
- } else {
- originTask.FailReason = ti.Url
- }
- }
- _ = originTask.Update()
- var raw map[string]any
- _ = json.Unmarshal(body, &raw)
- format := "mp4"
- if respObj, ok := raw["response"].(map[string]any); ok {
- if vids, ok := respObj["videos"].([]any); ok && len(vids) > 0 {
- if v0, ok := vids[0].(map[string]any); ok {
- if mt, ok := v0["mimeType"].(string); ok && mt != "" {
- if strings.Contains(mt, "mp4") {
- format = "mp4"
- } else {
- format = mt
- }
- }
- }
- }
- }
- status := "processing"
- switch originTask.Status {
- case model.TaskStatusSuccess:
- status = "succeeded"
- case model.TaskStatusFailure:
- status = "failed"
- case model.TaskStatusQueued, model.TaskStatusSubmitted:
- status = "queued"
- }
- if !strings.HasPrefix(c.Request.RequestURI, "/v1/videos/") {
- out := map[string]any{
- "error": nil,
- "format": format,
- "metadata": nil,
- "status": status,
- "task_id": originTask.TaskID,
- "url": originTask.FailReason,
- }
- respBody, _ = json.Marshal(dto.TaskResponse[any]{
- Code: "success",
- Data: out,
- })
- }
- }
- }()
+ isOpenAIVideoAPI := strings.HasPrefix(c.Request.RequestURI, "/v1/videos/")
- if len(respBody) != 0 {
+ // Gemini/Vertex 支持实时查询:用户 fetch 时直接从上游拉取最新状态
+ if realtimeResp := tryRealtimeFetch(originTask, isOpenAIVideoAPI); len(realtimeResp) > 0 {
+ respBody = realtimeResp
return
}
- if strings.HasPrefix(c.Request.RequestURI, "/v1/videos/") {
+ // OpenAI Video API 格式: 走各 adaptor 的 ConvertToOpenAIVideo
+ if isOpenAIVideoAPI {
adaptor := GetTaskAdaptor(originTask.Platform)
if adaptor == nil {
taskResp = service.TaskErrorWrapperLocal(fmt.Errorf("invalid channel id: %d", originTask.ChannelId), "invalid_channel_id", http.StatusBadRequest)
@@ -486,10 +400,12 @@ func videoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *d
respBody = openAIVideoData
return
}
- taskResp = service.TaskErrorWrapperLocal(errors.New(fmt.Sprintf("not_implemented:%s", originTask.Platform)), "not_implemented", http.StatusNotImplemented)
+ taskResp = service.TaskErrorWrapperLocal(fmt.Errorf("not_implemented:%s", originTask.Platform), "not_implemented", http.StatusNotImplemented)
return
}
- respBody, err = json.Marshal(dto.TaskResponse[any]{
+
+ // 通用 TaskDto 格式
+ respBody, err = common.Marshal(dto.TaskResponse[any]{
Code: "success",
Data: TaskModel2Dto(originTask),
})
@@ -499,16 +415,150 @@ func videoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *d
return
}
+// tryRealtimeFetch 尝试从上游实时拉取 Gemini/Vertex 任务状态。
+// 仅当渠道类型为 Gemini 或 Vertex 时触发;其他渠道或出错时返回 nil。
+// 当非 OpenAI Video API 时,还会构建自定义格式的响应体。
+func tryRealtimeFetch(task *model.Task, isOpenAIVideoAPI bool) []byte {
+ channelModel, err := model.GetChannelById(task.ChannelId, true)
+ if err != nil {
+ return nil
+ }
+ if channelModel.Type != constant.ChannelTypeVertexAi && channelModel.Type != constant.ChannelTypeGemini {
+ return nil
+ }
+
+ baseURL := constant.ChannelBaseURLs[channelModel.Type]
+ if channelModel.GetBaseURL() != "" {
+ baseURL = channelModel.GetBaseURL()
+ }
+ proxy := channelModel.GetSetting().Proxy
+ adaptor := GetTaskAdaptor(constant.TaskPlatform(strconv.Itoa(channelModel.Type)))
+ if adaptor == nil {
+ return nil
+ }
+
+ resp, err := adaptor.FetchTask(baseURL, channelModel.Key, map[string]any{
+ "task_id": task.GetUpstreamTaskID(),
+ "action": task.Action,
+ }, proxy)
+ if err != nil || resp == nil {
+ return nil
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil
+ }
+
+ ti, err := adaptor.ParseTaskResult(body)
+ if err != nil || ti == nil {
+ return nil
+ }
+
+ snap := task.Snapshot()
+
+ // 将上游最新状态更新到 task
+ if ti.Status != "" {
+ task.Status = model.TaskStatus(ti.Status)
+ }
+ if ti.Progress != "" {
+ task.Progress = ti.Progress
+ }
+ if strings.HasPrefix(ti.Url, "data:") {
+ // data: URI — kept in Data, not ResultURL
+ } else if ti.Url != "" {
+ task.PrivateData.ResultURL = ti.Url
+ } else if task.Status == model.TaskStatusSuccess {
+ // No URL from adaptor — construct proxy URL using public task ID
+ task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
+ }
+
+ if !snap.Equal(task.Snapshot()) {
+ _, _ = task.UpdateWithStatus(snap.Status)
+ }
+
+ // OpenAI Video API 由调用者的 ConvertToOpenAIVideo 分支处理
+ if isOpenAIVideoAPI {
+ return nil
+ }
+
+ // 非 OpenAI Video API: 构建自定义格式响应
+ format := detectVideoFormat(body)
+ out := map[string]any{
+ "error": nil,
+ "format": format,
+ "metadata": nil,
+ "status": mapTaskStatusToSimple(task.Status),
+ "task_id": task.TaskID,
+ "url": task.GetResultURL(),
+ }
+ respBody, _ := common.Marshal(dto.TaskResponse[any]{
+ Code: "success",
+ Data: out,
+ })
+ return respBody
+}
+
+// detectVideoFormat 从 Gemini/Vertex 原始响应中探测视频格式
+func detectVideoFormat(rawBody []byte) string {
+ var raw map[string]any
+ if err := common.Unmarshal(rawBody, &raw); err != nil {
+ return "mp4"
+ }
+ respObj, ok := raw["response"].(map[string]any)
+ if !ok {
+ return "mp4"
+ }
+ vids, ok := respObj["videos"].([]any)
+ if !ok || len(vids) == 0 {
+ return "mp4"
+ }
+ v0, ok := vids[0].(map[string]any)
+ if !ok {
+ return "mp4"
+ }
+ mt, ok := v0["mimeType"].(string)
+ if !ok || mt == "" || strings.Contains(mt, "mp4") {
+ return "mp4"
+ }
+ return mt
+}
+
+// mapTaskStatusToSimple 将内部 TaskStatus 映射为简化状态字符串
+func mapTaskStatusToSimple(status model.TaskStatus) string {
+ switch status {
+ case model.TaskStatusSuccess:
+ return "succeeded"
+ case model.TaskStatusFailure:
+ return "failed"
+ case model.TaskStatusQueued, model.TaskStatusSubmitted:
+ return "queued"
+ default:
+ return "processing"
+ }
+}
+
func TaskModel2Dto(task *model.Task) *dto.TaskDto {
return &dto.TaskDto{
+ ID: task.ID,
+ CreatedAt: task.CreatedAt,
+ UpdatedAt: task.UpdatedAt,
TaskID: task.TaskID,
+ Platform: string(task.Platform),
+ UserId: task.UserId,
+ Group: task.Group,
+ ChannelId: task.ChannelId,
+ Quota: task.Quota,
Action: task.Action,
Status: string(task.Status),
FailReason: task.FailReason,
+ ResultURL: task.GetResultURL(),
SubmitTime: task.SubmitTime,
StartTime: task.StartTime,
FinishTime: task.FinishTime,
Progress: task.Progress,
+ Properties: task.Properties,
+ Username: task.Username,
Data: task.Data,
}
}
diff --git a/relay/rerank_handler.go b/relay/rerank_handler.go
index 35c66a2917..53cd6e47ad 100644
--- a/relay/rerank_handler.go
+++ b/relay/rerank_handler.go
@@ -43,11 +43,11 @@ func RerankHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
var requestBody io.Reader
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
}
- requestBody = bytes.NewBuffer(body)
+ requestBody = common.ReaderOnly(storage)
} else {
convertedRequest, err := adaptor.ConvertRerankRequest(c, info.RelayMode, *request)
if err != nil {
@@ -61,9 +61,9 @@ func RerankHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -96,6 +96,6 @@ func RerankHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
service.ResetStatusCode(newAPIError, statusCodeMappingStr)
return newAPIError
}
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usage.(*dto.Usage), nil)
return nil
}
diff --git a/relay/responses_handler.go b/relay/responses_handler.go
index 769437a1d2..09e490d9e3 100644
--- a/relay/responses_handler.go
+++ b/relay/responses_handler.go
@@ -8,8 +8,10 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
+ appconstant "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
relaycommon "github.com/QuantumNous/new-api/relay/common"
+ relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
@@ -20,10 +22,37 @@ import (
func ResponsesHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types.NewAPIError) {
info.InitChannelMeta(c)
+ if info.RelayMode == relayconstant.RelayModeResponsesCompact {
+ switch info.ApiType {
+ case appconstant.APITypeOpenAI, appconstant.APITypeCodex:
+ default:
+ return types.NewErrorWithStatusCode(
+ fmt.Errorf("unsupported endpoint %q for api type %d", "/v1/responses/compact", info.ApiType),
+ types.ErrorCodeInvalidRequest,
+ http.StatusBadRequest,
+ types.ErrOptionWithSkipRetry(),
+ )
+ }
+ }
- responsesReq, ok := info.Request.(*dto.OpenAIResponsesRequest)
- if !ok {
- return types.NewErrorWithStatusCode(fmt.Errorf("invalid request type, expected dto.OpenAIResponsesRequest, got %T", info.Request), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
+ var responsesReq *dto.OpenAIResponsesRequest
+ switch req := info.Request.(type) {
+ case *dto.OpenAIResponsesRequest:
+ responsesReq = req
+ case *dto.OpenAIResponsesCompactionRequest:
+ responsesReq = &dto.OpenAIResponsesRequest{
+ Model: req.Model,
+ Input: req.Input,
+ Instructions: req.Instructions,
+ PreviousResponseID: req.PreviousResponseID,
+ }
+ default:
+ return types.NewErrorWithStatusCode(
+ fmt.Errorf("invalid request type, expected dto.OpenAIResponsesRequest or dto.OpenAIResponsesCompactionRequest, got %T", info.Request),
+ types.ErrorCodeInvalidRequest,
+ http.StatusBadRequest,
+ types.ErrOptionWithSkipRetry(),
+ )
}
request, err := common.DeepCopy(responsesReq)
@@ -43,11 +72,11 @@ func ResponsesHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
adaptor.Init(info)
var requestBody io.Reader
if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
- body, err := common.GetRequestBody(c)
+ storage, err := common.GetBodyStorage(c)
if err != nil {
return types.NewError(err, types.ErrorCodeReadRequestBodyFailed, types.ErrOptionWithSkipRetry())
}
- requestBody = bytes.NewBuffer(body)
+ requestBody = common.ReaderOnly(storage)
} else {
convertedRequest, err := adaptor.ConvertOpenAIResponsesRequest(c, info, *request)
if err != nil {
@@ -60,16 +89,16 @@ func ResponsesHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
}
// remove disabled fields for OpenAI Responses API
- jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
+ jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
if err != nil {
return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
}
// apply param override
if len(info.ParamOverride) > 0 {
- jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
+ jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
if err != nil {
- return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
+ return newAPIErrorFromParamOverride(err)
}
}
@@ -105,10 +134,28 @@ func ResponsesHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
return newAPIError
}
+ usageDto := usage.(*dto.Usage)
+ if info.RelayMode == relayconstant.RelayModeResponsesCompact {
+ originModelName := info.OriginModelName
+ originPriceData := info.PriceData
+
+ _, err := helper.ModelPriceHelper(c, info, info.GetEstimatePromptTokens(), &types.TokenCountMeta{})
+ if err != nil {
+ info.OriginModelName = originModelName
+ info.PriceData = originPriceData
+ return types.NewError(err, types.ErrorCodeModelPriceError, types.ErrOptionWithSkipRetry())
+ }
+ service.PostTextConsumeQuota(c, info, usageDto, nil)
+
+ info.OriginModelName = originModelName
+ info.PriceData = originPriceData
+ return nil
+ }
+
if strings.HasPrefix(info.OriginModelName, "gpt-4o-audio") {
- service.PostAudioConsumeQuota(c, info, usage.(*dto.Usage), "")
+ service.PostAudioConsumeQuota(c, info, usageDto, "")
} else {
- postConsumeQuota(c, info, usage.(*dto.Usage))
+ service.PostTextConsumeQuota(c, info, usageDto, nil)
}
return nil
}
diff --git a/router/api-router.go b/router/api-router.go
index f3ae4d970d..acc2241b51 100644
--- a/router/api-router.go
+++ b/router/api-router.go
@@ -4,13 +4,18 @@ import (
"github.com/QuantumNous/new-api/controller"
"github.com/QuantumNous/new-api/middleware"
+ // Import oauth package to register providers via init()
+ _ "github.com/QuantumNous/new-api/oauth"
+
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
func SetApiRouter(router *gin.Engine) {
apiRouter := router.Group("/api")
+ apiRouter.Use(middleware.RouteTag("api"))
apiRouter.Use(gzip.Gzip(gzip.DefaultCompression))
+ apiRouter.Use(middleware.BodyStorageCleanup()) // 清理请求体存储
apiRouter.Use(middleware.GlobalAPIRateLimit())
{
apiRouter.GET("/setup", controller.GetSetup)
@@ -29,24 +34,24 @@ func SetApiRouter(router *gin.Engine) {
apiRouter.GET("/verification", middleware.EmailVerificationRateLimit(), middleware.TurnstileCheck(), controller.SendEmailVerification)
apiRouter.GET("/reset_password", middleware.CriticalRateLimit(), middleware.TurnstileCheck(), controller.SendPasswordResetEmail)
apiRouter.POST("/user/reset", middleware.CriticalRateLimit(), controller.ResetPassword)
- apiRouter.GET("/oauth/github", middleware.CriticalRateLimit(), controller.GitHubOAuth)
- apiRouter.GET("/oauth/discord", middleware.CriticalRateLimit(), controller.DiscordOAuth)
- apiRouter.GET("/oauth/oidc", middleware.CriticalRateLimit(), controller.OidcAuth)
- apiRouter.GET("/oauth/linuxdo", middleware.CriticalRateLimit(), controller.LinuxdoOAuth)
+ // OAuth routes - specific routes must come before :provider wildcard
apiRouter.GET("/oauth/state", middleware.CriticalRateLimit(), controller.GenerateOAuthCode)
+ apiRouter.POST("/oauth/email/bind", middleware.CriticalRateLimit(), controller.EmailBind)
+ // Non-standard OAuth (WeChat, Telegram) - keep original routes
apiRouter.GET("/oauth/wechat", middleware.CriticalRateLimit(), controller.WeChatAuth)
- apiRouter.GET("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind)
- apiRouter.GET("/oauth/email/bind", middleware.CriticalRateLimit(), controller.EmailBind)
+ apiRouter.POST("/oauth/wechat/bind", middleware.CriticalRateLimit(), controller.WeChatBind)
apiRouter.GET("/oauth/telegram/login", middleware.CriticalRateLimit(), controller.TelegramLogin)
apiRouter.GET("/oauth/telegram/bind", middleware.CriticalRateLimit(), controller.TelegramBind)
+ // Standard OAuth providers (GitHub, Discord, OIDC, LinuxDO) - unified route
+ apiRouter.GET("/oauth/:provider", middleware.CriticalRateLimit(), controller.HandleOAuth)
apiRouter.GET("/ratio_config", middleware.CriticalRateLimit(), controller.GetRatioConfig)
apiRouter.POST("/stripe/webhook", controller.StripeWebhook)
apiRouter.POST("/creem/webhook", controller.CreemWebhook)
+ apiRouter.POST("/waffo/webhook", controller.WaffoWebhook)
// Universal secure verification routes
apiRouter.POST("/verify", middleware.UserAuth(), middleware.CriticalRateLimit(), controller.UniversalVerify)
- apiRouter.GET("/verify/status", middleware.UserAuth(), controller.GetVerificationStatus)
userRoute := apiRouter.Group("/user")
{
@@ -57,6 +62,7 @@ func SetApiRouter(router *gin.Engine) {
userRoute.POST("/passkey/login/finish", middleware.CriticalRateLimit(), controller.PasskeyLoginFinish)
//userRoute.POST("/tokenlog", middleware.CriticalRateLimit(), controller.TokenLog)
userRoute.GET("/logout", controller.Logout)
+ userRoute.POST("/epay/notify", controller.EpayNotify)
userRoute.GET("/epay/notify", controller.EpayNotify)
userRoute.GET("/groups", controller.GetUserGroups)
@@ -84,6 +90,7 @@ func SetApiRouter(router *gin.Engine) {
selfRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.RequestStripePay)
selfRoute.POST("/stripe/amount", controller.RequestStripeAmount)
selfRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.RequestCreemPay)
+ selfRoute.POST("/waffo/pay", middleware.CriticalRateLimit(), controller.RequestWaffoPay)
selfRoute.POST("/aff_transfer", controller.TransferAffQuota)
selfRoute.PUT("/setting", controller.UpdateUserSetting)
@@ -97,6 +104,10 @@ func SetApiRouter(router *gin.Engine) {
// Check-in routes
selfRoute.GET("/checkin", controller.GetCheckinStatus)
selfRoute.POST("/checkin", middleware.TurnstileCheck(), controller.DoCheckin)
+
+ // Custom OAuth bindings
+ selfRoute.GET("/oauth/bindings", controller.GetUserOAuthBindings)
+ selfRoute.DELETE("/oauth/bindings/:provider_id", controller.UnbindCustomOAuth)
}
adminRoute := userRoute.Group("/")
@@ -106,6 +117,9 @@ func SetApiRouter(router *gin.Engine) {
adminRoute.GET("/topup", controller.GetAllTopUps)
adminRoute.POST("/topup/complete", controller.AdminCompleteTopUp)
adminRoute.GET("/search", controller.SearchUsers)
+ adminRoute.GET("/:id/oauth/bindings", controller.GetUserOAuthBindingsByAdmin)
+ adminRoute.DELETE("/:id/oauth/bindings/:provider_id", controller.UnbindCustomOAuthByAdmin)
+ adminRoute.DELETE("/:id/bindings/:binding_type", controller.AdminClearUserBinding)
adminRoute.GET("/:id", controller.GetUser)
adminRoute.POST("/", controller.CreateUser)
adminRoute.POST("/manage", controller.ManageUser)
@@ -118,14 +132,71 @@ func SetApiRouter(router *gin.Engine) {
adminRoute.DELETE("/:id/2fa", controller.AdminDisable2FA)
}
}
+
+ // Subscription billing (plans, purchase, admin management)
+ subscriptionRoute := apiRouter.Group("/subscription")
+ subscriptionRoute.Use(middleware.UserAuth())
+ {
+ subscriptionRoute.GET("/plans", controller.GetSubscriptionPlans)
+ subscriptionRoute.GET("/self", controller.GetSubscriptionSelf)
+ subscriptionRoute.PUT("/self/preference", controller.UpdateSubscriptionPreference)
+ subscriptionRoute.POST("/epay/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestEpay)
+ subscriptionRoute.POST("/stripe/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestStripePay)
+ subscriptionRoute.POST("/creem/pay", middleware.CriticalRateLimit(), controller.SubscriptionRequestCreemPay)
+ }
+ subscriptionAdminRoute := apiRouter.Group("/subscription/admin")
+ subscriptionAdminRoute.Use(middleware.AdminAuth())
+ {
+ subscriptionAdminRoute.GET("/plans", controller.AdminListSubscriptionPlans)
+ subscriptionAdminRoute.POST("/plans", controller.AdminCreateSubscriptionPlan)
+ subscriptionAdminRoute.PUT("/plans/:id", controller.AdminUpdateSubscriptionPlan)
+ subscriptionAdminRoute.PATCH("/plans/:id", controller.AdminUpdateSubscriptionPlanStatus)
+ subscriptionAdminRoute.POST("/bind", controller.AdminBindSubscription)
+
+ // User subscription management (admin)
+ subscriptionAdminRoute.GET("/users/:id/subscriptions", controller.AdminListUserSubscriptions)
+ subscriptionAdminRoute.POST("/users/:id/subscriptions", controller.AdminCreateUserSubscription)
+ subscriptionAdminRoute.POST("/user_subscriptions/:id/invalidate", controller.AdminInvalidateUserSubscription)
+ subscriptionAdminRoute.DELETE("/user_subscriptions/:id", controller.AdminDeleteUserSubscription)
+ }
+
+ // Subscription payment callbacks (no auth)
+ apiRouter.POST("/subscription/epay/notify", controller.SubscriptionEpayNotify)
+ apiRouter.GET("/subscription/epay/notify", controller.SubscriptionEpayNotify)
+ apiRouter.GET("/subscription/epay/return", controller.SubscriptionEpayReturn)
+ apiRouter.POST("/subscription/epay/return", controller.SubscriptionEpayReturn)
optionRoute := apiRouter.Group("/option")
optionRoute.Use(middleware.RootAuth())
{
optionRoute.GET("/", controller.GetOptions)
optionRoute.PUT("/", controller.UpdateOption)
+ optionRoute.GET("/channel_affinity_cache", controller.GetChannelAffinityCacheStats)
+ optionRoute.DELETE("/channel_affinity_cache", controller.ClearChannelAffinityCache)
optionRoute.POST("/rest_model_ratio", controller.ResetModelRatio)
optionRoute.POST("/migrate_console_setting", controller.MigrateConsoleSetting) // 用于迁移检测的旧键,下个版本会删除
}
+
+ // Custom OAuth provider management (root only)
+ customOAuthRoute := apiRouter.Group("/custom-oauth-provider")
+ customOAuthRoute.Use(middleware.RootAuth())
+ {
+ customOAuthRoute.POST("/discovery", controller.FetchCustomOAuthDiscovery)
+ customOAuthRoute.GET("/", controller.GetCustomOAuthProviders)
+ customOAuthRoute.GET("/:id", controller.GetCustomOAuthProvider)
+ customOAuthRoute.POST("/", controller.CreateCustomOAuthProvider)
+ customOAuthRoute.PUT("/:id", controller.UpdateCustomOAuthProvider)
+ customOAuthRoute.DELETE("/:id", controller.DeleteCustomOAuthProvider)
+ }
+ performanceRoute := apiRouter.Group("/performance")
+ performanceRoute.Use(middleware.RootAuth())
+ {
+ performanceRoute.GET("/stats", controller.GetPerformanceStats)
+ performanceRoute.DELETE("/disk_cache", controller.ClearDiskCache)
+ performanceRoute.POST("/reset_stats", controller.ResetPerformanceStats)
+ performanceRoute.POST("/gc", controller.ForceGC)
+ performanceRoute.GET("/logs", controller.GetLogFiles)
+ performanceRoute.DELETE("/logs", controller.CleanupLogFiles)
+ }
ratioSyncRoute := apiRouter.Group("/ratio_sync")
ratioSyncRoute.Use(middleware.RootAuth())
{
@@ -155,7 +226,7 @@ func SetApiRouter(router *gin.Engine) {
channelRoute.POST("/batch", controller.DeleteChannelBatch)
channelRoute.POST("/fix", controller.FixChannelsAbilities)
channelRoute.GET("/fetch_models/:id", controller.FetchUpstreamModels)
- channelRoute.POST("/fetch_models", controller.FetchModels)
+ channelRoute.POST("/fetch_models", middleware.RootAuth(), controller.FetchModels)
channelRoute.POST("/codex/oauth/start", controller.StartCodexOAuth)
channelRoute.POST("/codex/oauth/complete", controller.CompleteCodexOAuth)
channelRoute.POST("/:id/codex/oauth/start", controller.StartCodexOAuthForChannel)
@@ -170,24 +241,30 @@ func SetApiRouter(router *gin.Engine) {
channelRoute.GET("/tag/models", controller.GetTagModels)
channelRoute.POST("/copy/:id", controller.CopyChannel)
channelRoute.POST("/multi_key/manage", controller.ManageMultiKeys)
+ channelRoute.POST("/upstream_updates/apply", controller.ApplyChannelUpstreamModelUpdates)
+ channelRoute.POST("/upstream_updates/apply_all", controller.ApplyAllChannelUpstreamModelUpdates)
+ channelRoute.POST("/upstream_updates/detect", controller.DetectChannelUpstreamModelUpdates)
+ channelRoute.POST("/upstream_updates/detect_all", controller.DetectAllChannelUpstreamModelUpdates)
}
tokenRoute := apiRouter.Group("/token")
tokenRoute.Use(middleware.UserAuth())
{
tokenRoute.GET("/", controller.GetAllTokens)
- tokenRoute.GET("/search", controller.SearchTokens)
+ tokenRoute.GET("/search", middleware.SearchRateLimit(), controller.SearchTokens)
tokenRoute.GET("/:id", controller.GetToken)
+ tokenRoute.POST("/:id/key", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.GetTokenKey)
tokenRoute.POST("/", controller.AddToken)
tokenRoute.PUT("/", controller.UpdateToken)
tokenRoute.DELETE("/:id", controller.DeleteToken)
tokenRoute.POST("/batch", controller.DeleteTokenBatch)
+ tokenRoute.POST("/batch/keys", middleware.CriticalRateLimit(), middleware.DisableCache(), controller.GetTokenKeysBatch)
}
usageRoute := apiRouter.Group("/usage")
- usageRoute.Use(middleware.CriticalRateLimit())
+ usageRoute.Use(middleware.CORS(), middleware.CriticalRateLimit())
{
tokenUsageRoute := usageRoute.Group("/token")
- tokenUsageRoute.Use(middleware.TokenAuth())
+ tokenUsageRoute.Use(middleware.TokenAuthReadOnly())
{
tokenUsageRoute.GET("/", controller.GetTokenUsage)
}
@@ -209,17 +286,19 @@ func SetApiRouter(router *gin.Engine) {
logRoute.DELETE("/", middleware.AdminAuth(), controller.DeleteHistoryLogs)
logRoute.GET("/stat", middleware.AdminAuth(), controller.GetLogsStat)
logRoute.GET("/self/stat", middleware.UserAuth(), controller.GetLogsSelfStat)
+ logRoute.GET("/channel_affinity_usage_cache", middleware.AdminAuth(), controller.GetChannelAffinityUsageCacheStats)
logRoute.GET("/search", middleware.AdminAuth(), controller.SearchAllLogs)
logRoute.GET("/self", middleware.UserAuth(), controller.GetUserLogs)
- logRoute.GET("/self/search", middleware.UserAuth(), controller.SearchUserLogs)
+ logRoute.GET("/self/search", middleware.UserAuth(), middleware.SearchRateLimit(), controller.SearchUserLogs)
dataRoute := apiRouter.Group("/data")
dataRoute.GET("/", middleware.AdminAuth(), controller.GetAllQuotaDates)
+ dataRoute.GET("/users", middleware.AdminAuth(), controller.GetQuotaDatesByUser)
dataRoute.GET("/self", middleware.UserAuth(), controller.GetUserQuotaDates)
- logRoute.Use(middleware.CORS())
+ logRoute.Use(middleware.CORS(), middleware.CriticalRateLimit())
{
- logRoute.GET("/token", controller.GetLogByKey)
+ logRoute.GET("/token", middleware.TokenAuthReadOnly(), controller.GetLogByKey)
}
groupRoute := apiRouter.Group("/group")
groupRoute.Use(middleware.AdminAuth())
diff --git a/router/dashboard.go b/router/dashboard.go
index 17132dfb29..2e486156d9 100644
--- a/router/dashboard.go
+++ b/router/dashboard.go
@@ -9,6 +9,7 @@ import (
func SetDashboardRouter(router *gin.Engine) {
apiRouter := router.Group("/")
+ apiRouter.Use(middleware.RouteTag("old_api"))
apiRouter.Use(gzip.Gzip(gzip.DefaultCompression))
apiRouter.Use(middleware.GlobalAPIRateLimit())
apiRouter.Use(middleware.CORS())
diff --git a/router/main.go b/router/main.go
index 45b3080f28..ac9506fe45 100644
--- a/router/main.go
+++ b/router/main.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/middleware"
"github.com/gin-gonic/gin"
)
@@ -27,6 +28,7 @@ func SetRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
} else {
frontendBaseUrl = strings.TrimSuffix(frontendBaseUrl, "/")
router.NoRoute(func(c *gin.Context) {
+ c.Set(middleware.RouteTagKey, "web")
c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("%s%s", frontendBaseUrl, c.Request.RequestURI))
})
}
diff --git a/router/relay-router.go b/router/relay-router.go
index 267459e2c1..17a13cad7f 100644
--- a/router/relay-router.go
+++ b/router/relay-router.go
@@ -13,9 +13,11 @@ import (
func SetRelayRouter(router *gin.Engine) {
router.Use(middleware.CORS())
router.Use(middleware.DecompressRequestMiddleware())
+ router.Use(middleware.BodyStorageCleanup()) // 清理请求体存储
router.Use(middleware.StatsMiddleware())
// https://platform.openai.com/docs/api-reference/introduction
modelsRouter := router.Group("/v1/models")
+ modelsRouter.Use(middleware.RouteTag("relay"))
modelsRouter.Use(middleware.TokenAuth())
{
modelsRouter.GET("", func(c *gin.Context) {
@@ -40,6 +42,7 @@ func SetRelayRouter(router *gin.Engine) {
}
geminiRouter := router.Group("/v1beta/models")
+ geminiRouter.Use(middleware.RouteTag("relay"))
geminiRouter.Use(middleware.TokenAuth())
{
geminiRouter.GET("", func(c *gin.Context) {
@@ -48,6 +51,7 @@ func SetRelayRouter(router *gin.Engine) {
}
geminiCompatibleRouter := router.Group("/v1beta/openai/models")
+ geminiCompatibleRouter.Use(middleware.RouteTag("relay"))
geminiCompatibleRouter.Use(middleware.TokenAuth())
{
geminiCompatibleRouter.GET("", func(c *gin.Context) {
@@ -56,11 +60,15 @@ func SetRelayRouter(router *gin.Engine) {
}
playgroundRouter := router.Group("/pg")
+ playgroundRouter.Use(middleware.RouteTag("relay"))
+ playgroundRouter.Use(middleware.SystemPerformanceCheck())
playgroundRouter.Use(middleware.UserAuth(), middleware.Distribute())
{
playgroundRouter.POST("/chat/completions", controller.Playground)
}
relayV1Router := router.Group("/v1")
+ relayV1Router.Use(middleware.RouteTag("relay"))
+ relayV1Router.Use(middleware.SystemPerformanceCheck())
relayV1Router.Use(middleware.TokenAuth())
relayV1Router.Use(middleware.ModelRequestRateLimit())
{
@@ -93,6 +101,9 @@ func SetRelayRouter(router *gin.Engine) {
httpRouter.POST("/responses", func(c *gin.Context) {
controller.Relay(c, types.RelayFormatOpenAIResponses)
})
+ httpRouter.POST("/responses/compact", func(c *gin.Context) {
+ controller.Relay(c, types.RelayFormatOpenAIResponsesCompaction)
+ })
// image related routes
httpRouter.POST("/edits", func(c *gin.Context) {
@@ -155,21 +166,29 @@ func SetRelayRouter(router *gin.Engine) {
}
relayMjRouter := router.Group("/mj")
+ relayMjRouter.Use(middleware.RouteTag("relay"))
+ relayMjRouter.Use(middleware.SystemPerformanceCheck())
registerMjRouterGroup(relayMjRouter)
relayMjModeRouter := router.Group("/:mode/mj")
+ relayMjModeRouter.Use(middleware.RouteTag("relay"))
+ relayMjModeRouter.Use(middleware.SystemPerformanceCheck())
registerMjRouterGroup(relayMjModeRouter)
//relayMjRouter.Use()
relaySunoRouter := router.Group("/suno")
+ relaySunoRouter.Use(middleware.RouteTag("relay"))
+ relaySunoRouter.Use(middleware.SystemPerformanceCheck())
relaySunoRouter.Use(middleware.TokenAuth(), middleware.Distribute())
{
relaySunoRouter.POST("/submit/:action", controller.RelayTask)
- relaySunoRouter.POST("/fetch", controller.RelayTask)
- relaySunoRouter.GET("/fetch/:id", controller.RelayTask)
+ relaySunoRouter.POST("/fetch", controller.RelayTaskFetch)
+ relaySunoRouter.GET("/fetch/:id", controller.RelayTaskFetch)
}
relayGeminiRouter := router.Group("/v1beta")
+ relayGeminiRouter.Use(middleware.RouteTag("relay"))
+ relayGeminiRouter.Use(middleware.SystemPerformanceCheck())
relayGeminiRouter.Use(middleware.TokenAuth())
relayGeminiRouter.Use(middleware.ModelRequestRateLimit())
relayGeminiRouter.Use(middleware.Distribute())
@@ -195,7 +214,7 @@ func registerMjRouterGroup(relayMjRouter *gin.RouterGroup) {
relayMjRouter.POST("/submit/blend", controller.RelayMidjourney)
relayMjRouter.POST("/submit/edits", controller.RelayMidjourney)
relayMjRouter.POST("/submit/video", controller.RelayMidjourney)
- relayMjRouter.POST("/notify", controller.RelayMidjourney)
+ //relayMjRouter.POST("/notify", controller.RelayMidjourney)
relayMjRouter.GET("/task/:id/fetch", controller.RelayMidjourney)
relayMjRouter.GET("/task/:id/image-seed", controller.RelayMidjourney)
relayMjRouter.POST("/task/list-by-condition", controller.RelayMidjourney)
diff --git a/router/video-router.go b/router/video-router.go
index d5fed1d786..4614511045 100644
--- a/router/video-router.go
+++ b/router/video-router.go
@@ -8,32 +8,42 @@ import (
)
func SetVideoRouter(router *gin.Engine) {
+ // Video proxy: accepts either session auth (dashboard) or token auth (API clients)
+ videoProxyRouter := router.Group("/v1")
+ videoProxyRouter.Use(middleware.RouteTag("relay"))
+ videoProxyRouter.Use(middleware.TokenOrUserAuth())
+ {
+ videoProxyRouter.GET("/videos/:task_id/content", controller.VideoProxy)
+ }
+
videoV1Router := router.Group("/v1")
+ videoV1Router.Use(middleware.RouteTag("relay"))
videoV1Router.Use(middleware.TokenAuth(), middleware.Distribute())
{
- videoV1Router.GET("/videos/:task_id/content", controller.VideoProxy)
videoV1Router.POST("/video/generations", controller.RelayTask)
- videoV1Router.GET("/video/generations/:task_id", controller.RelayTask)
+ videoV1Router.GET("/video/generations/:task_id", controller.RelayTaskFetch)
videoV1Router.POST("/videos/:video_id/remix", controller.RelayTask)
}
// openai compatible API video routes
// docs: https://platform.openai.com/docs/api-reference/videos/create
{
videoV1Router.POST("/videos", controller.RelayTask)
- videoV1Router.GET("/videos/:task_id", controller.RelayTask)
+ videoV1Router.GET("/videos/:task_id", controller.RelayTaskFetch)
}
klingV1Router := router.Group("/kling/v1")
+ klingV1Router.Use(middleware.RouteTag("relay"))
klingV1Router.Use(middleware.KlingRequestConvert(), middleware.TokenAuth(), middleware.Distribute())
{
klingV1Router.POST("/videos/text2video", controller.RelayTask)
klingV1Router.POST("/videos/image2video", controller.RelayTask)
- klingV1Router.GET("/videos/text2video/:task_id", controller.RelayTask)
- klingV1Router.GET("/videos/image2video/:task_id", controller.RelayTask)
+ klingV1Router.GET("/videos/text2video/:task_id", controller.RelayTaskFetch)
+ klingV1Router.GET("/videos/image2video/:task_id", controller.RelayTaskFetch)
}
// Jimeng official API routes - direct mapping to official API format
jimengOfficialGroup := router.Group("jimeng")
+ jimengOfficialGroup.Use(middleware.RouteTag("relay"))
jimengOfficialGroup.Use(middleware.JimengRequestConvert(), middleware.TokenAuth(), middleware.Distribute())
{
// Maps to: /?Action=CVSync2AsyncSubmitTask&Version=2022-08-31 and /?Action=CVSync2AsyncGetResult&Version=2022-08-31
diff --git a/router/web-router.go b/router/web-router.go
index b053a3e63d..17a8378ddc 100644
--- a/router/web-router.go
+++ b/router/web-router.go
@@ -19,6 +19,7 @@ func SetWebRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
router.Use(middleware.Cache())
router.Use(static.Serve("/", common.EmbedFolder(buildFS, "web/dist")))
router.NoRoute(func(c *gin.Context) {
+ c.Set(middleware.RouteTagKey, "web")
if strings.HasPrefix(c.Request.RequestURI, "/v1") || strings.HasPrefix(c.Request.RequestURI, "/api") || strings.HasPrefix(c.Request.RequestURI, "/assets") {
controller.RelayNotFound(c)
return
diff --git a/service/billing.go b/service/billing.go
new file mode 100644
index 0000000000..81daeed82c
--- /dev/null
+++ b/service/billing.go
@@ -0,0 +1,78 @@
+package service
+
+import (
+ "fmt"
+
+ "github.com/QuantumNous/new-api/logger"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/gin-gonic/gin"
+)
+
+const (
+ BillingSourceWallet = "wallet"
+ BillingSourceSubscription = "subscription"
+)
+
+// PreConsumeBilling 根据用户计费偏好创建 BillingSession 并执行预扣费。
+// 会话存储在 relayInfo.Billing 上,供后续 Settle / Refund 使用。
+func PreConsumeBilling(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) *types.NewAPIError {
+ session, apiErr := NewBillingSession(c, relayInfo, preConsumedQuota)
+ if apiErr != nil {
+ return apiErr
+ }
+ relayInfo.Billing = session
+ return nil
+}
+
+// ---------------------------------------------------------------------------
+// SettleBilling — 后结算辅助函数
+// ---------------------------------------------------------------------------
+
+// SettleBilling 执行计费结算。如果 RelayInfo 上有 BillingSession 则通过 session 结算,
+// 否则回退到旧的 PostConsumeQuota 路径(兼容按次计费等场景)。
+func SettleBilling(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, actualQuota int) error {
+ if relayInfo.Billing != nil {
+ preConsumed := relayInfo.Billing.GetPreConsumedQuota()
+ delta := actualQuota - preConsumed
+
+ if delta > 0 {
+ logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
+ logger.FormatQuota(delta),
+ logger.FormatQuota(actualQuota),
+ logger.FormatQuota(preConsumed),
+ ))
+ } else if delta < 0 {
+ logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
+ logger.FormatQuota(-delta),
+ logger.FormatQuota(actualQuota),
+ logger.FormatQuota(preConsumed),
+ ))
+ } else {
+ logger.LogInfo(ctx, fmt.Sprintf("预扣费与实际消耗一致,无需调整:%s(按次计费)",
+ logger.FormatQuota(actualQuota),
+ ))
+ }
+
+ if err := relayInfo.Billing.Settle(actualQuota); err != nil {
+ return err
+ }
+
+ // 发送额度通知(订阅计费使用订阅剩余额度)
+ if actualQuota != 0 {
+ if relayInfo.BillingSource == BillingSourceSubscription {
+ checkAndSendSubscriptionQuotaNotify(relayInfo)
+ } else {
+ checkAndSendQuotaNotify(relayInfo, actualQuota-preConsumed, preConsumed)
+ }
+ }
+ return nil
+ }
+
+ // 回退:无 BillingSession 时使用旧路径
+ quotaDelta := actualQuota - relayInfo.FinalPreConsumedQuota
+ if quotaDelta != 0 {
+ return PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
+ }
+ return nil
+}
diff --git a/service/billing_session.go b/service/billing_session.go
new file mode 100644
index 0000000000..f24b68e55a
--- /dev/null
+++ b/service/billing_session.go
@@ -0,0 +1,347 @@
+package service
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+ "sync"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/bytedance/gopkg/util/gopool"
+ "github.com/gin-gonic/gin"
+)
+
+// ---------------------------------------------------------------------------
+// BillingSession — 统一计费会话
+// ---------------------------------------------------------------------------
+
+// BillingSession 封装单次请求的预扣费/结算/退款生命周期。
+// 实现 relaycommon.BillingSettler 接口。
+type BillingSession struct {
+ relayInfo *relaycommon.RelayInfo
+ funding FundingSource
+ preConsumedQuota int // 实际预扣额度(信任用户可能为 0)
+ tokenConsumed int // 令牌额度实际扣减量
+ fundingSettled bool // funding.Settle 已成功,资金来源已提交
+ settled bool // Settle 全部完成(资金 + 令牌)
+ refunded bool // Refund 已调用
+ mu sync.Mutex
+}
+
+// Settle 根据实际消耗额度进行结算。
+// 资金来源和令牌额度分两步提交:若资金来源已提交但令牌调整失败,
+// 会标记 fundingSettled 防止 Refund 对已提交的资金来源执行退款。
+func (s *BillingSession) Settle(actualQuota int) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.settled {
+ return nil
+ }
+ delta := actualQuota - s.preConsumedQuota
+ if delta == 0 {
+ s.settled = true
+ return nil
+ }
+ // 1) 调整资金来源(仅在尚未提交时执行,防止重复调用)
+ if !s.fundingSettled {
+ if err := s.funding.Settle(delta); err != nil {
+ return err
+ }
+ s.fundingSettled = true
+ }
+ // 2) 调整令牌额度
+ var tokenErr error
+ if !s.relayInfo.IsPlayground {
+ if delta > 0 {
+ tokenErr = model.DecreaseTokenQuota(s.relayInfo.TokenId, s.relayInfo.TokenKey, delta)
+ } else {
+ tokenErr = model.IncreaseTokenQuota(s.relayInfo.TokenId, s.relayInfo.TokenKey, -delta)
+ }
+ if tokenErr != nil {
+ // 资金来源已提交,令牌调整失败只能记录日志;标记 settled 防止 Refund 误退资金
+ common.SysLog(fmt.Sprintf("error adjusting token quota after funding settled (userId=%d, tokenId=%d, delta=%d): %s",
+ s.relayInfo.UserId, s.relayInfo.TokenId, delta, tokenErr.Error()))
+ }
+ }
+ // 3) 更新 relayInfo 上的订阅 PostDelta(用于日志)
+ if s.funding.Source() == BillingSourceSubscription {
+ s.relayInfo.SubscriptionPostDelta += int64(delta)
+ }
+ s.settled = true
+ return tokenErr
+}
+
+// Refund 退还所有预扣费,幂等安全,异步执行。
+func (s *BillingSession) Refund(c *gin.Context) {
+ s.mu.Lock()
+ if s.settled || s.refunded || !s.needsRefundLocked() {
+ s.mu.Unlock()
+ return
+ }
+ s.refunded = true
+ s.mu.Unlock()
+
+ logger.LogInfo(c, fmt.Sprintf("用户 %d 请求失败, 返还预扣费(token_quota=%s, funding=%s)",
+ s.relayInfo.UserId,
+ logger.FormatQuota(s.tokenConsumed),
+ s.funding.Source(),
+ ))
+
+ // 复制需要的值到闭包中
+ tokenId := s.relayInfo.TokenId
+ tokenKey := s.relayInfo.TokenKey
+ isPlayground := s.relayInfo.IsPlayground
+ tokenConsumed := s.tokenConsumed
+ funding := s.funding
+
+ gopool.Go(func() {
+ // 1) 退还资金来源
+ if err := funding.Refund(); err != nil {
+ common.SysLog("error refunding billing source: " + err.Error())
+ }
+ // 2) 退还令牌额度
+ if tokenConsumed > 0 && !isPlayground {
+ if err := model.IncreaseTokenQuota(tokenId, tokenKey, tokenConsumed); err != nil {
+ common.SysLog("error refunding token quota: " + err.Error())
+ }
+ }
+ })
+}
+
+// NeedsRefund 返回是否存在需要退还的预扣状态。
+func (s *BillingSession) NeedsRefund() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.needsRefundLocked()
+}
+
+func (s *BillingSession) needsRefundLocked() bool {
+ if s.settled || s.refunded || s.fundingSettled {
+ // fundingSettled 时资金来源已提交结算,不能再退预扣费
+ return false
+ }
+ if s.tokenConsumed > 0 {
+ return true
+ }
+ // 订阅可能在 tokenConsumed=0 时仍预扣了额度
+ if sub, ok := s.funding.(*SubscriptionFunding); ok && sub.preConsumed > 0 {
+ return true
+ }
+ return false
+}
+
+// GetPreConsumedQuota 返回实际预扣的额度。
+func (s *BillingSession) GetPreConsumedQuota() int {
+ return s.preConsumedQuota
+}
+
+// ---------------------------------------------------------------------------
+// PreConsume — 统一预扣费入口(含信任额度旁路)
+// ---------------------------------------------------------------------------
+
+// preConsume 执行预扣费:信任检查 -> 令牌预扣 -> 资金来源预扣。
+// 任一步骤失败时原子回滚已完成的步骤。
+func (s *BillingSession) preConsume(c *gin.Context, quota int) *types.NewAPIError {
+ effectiveQuota := quota
+
+ // ---- 信任额度旁路 ----
+ if s.shouldTrust(c) {
+ effectiveQuota = 0
+ logger.LogInfo(c, fmt.Sprintf("用户 %d 额度充足, 信任且不需要预扣费 (funding=%s)", s.relayInfo.UserId, s.funding.Source()))
+ } else if effectiveQuota > 0 {
+ logger.LogInfo(c, fmt.Sprintf("用户 %d 需要预扣费 %s (funding=%s)", s.relayInfo.UserId, logger.FormatQuota(effectiveQuota), s.funding.Source()))
+ }
+
+ // ---- 1) 预扣令牌额度 ----
+ if effectiveQuota > 0 {
+ if err := PreConsumeTokenQuota(s.relayInfo, effectiveQuota); err != nil {
+ return types.NewErrorWithStatusCode(err, types.ErrorCodePreConsumeTokenQuotaFailed, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
+ }
+ s.tokenConsumed = effectiveQuota
+ }
+
+ // ---- 2) 预扣资金来源 ----
+ if err := s.funding.PreConsume(effectiveQuota); err != nil {
+ // 预扣费失败,回滚令牌额度
+ if s.tokenConsumed > 0 && !s.relayInfo.IsPlayground {
+ if rollbackErr := model.IncreaseTokenQuota(s.relayInfo.TokenId, s.relayInfo.TokenKey, s.tokenConsumed); rollbackErr != nil {
+ common.SysLog(fmt.Sprintf("error rolling back token quota (userId=%d, tokenId=%d, amount=%d, fundingErr=%s): %s",
+ s.relayInfo.UserId, s.relayInfo.TokenId, s.tokenConsumed, err.Error(), rollbackErr.Error()))
+ }
+ s.tokenConsumed = 0
+ }
+ // TODO: model 层应定义哨兵错误(如 ErrNoActiveSubscription),用 errors.Is 替代字符串匹配
+ errMsg := err.Error()
+ if strings.Contains(errMsg, "no active subscription") || strings.Contains(errMsg, "subscription quota insufficient") {
+ return types.NewErrorWithStatusCode(fmt.Errorf("订阅额度不足或未配置订阅: %s", errMsg), types.ErrorCodeInsufficientUserQuota, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
+ }
+ return types.NewError(err, types.ErrorCodeUpdateDataError, types.ErrOptionWithSkipRetry())
+ }
+
+ s.preConsumedQuota = effectiveQuota
+
+ // ---- 同步 RelayInfo 兼容字段 ----
+ s.syncRelayInfo()
+
+ return nil
+}
+
+// shouldTrust 统一信任额度检查,适用于钱包和订阅。
+func (s *BillingSession) shouldTrust(c *gin.Context) bool {
+ // 异步任务(ForcePreConsume=true)必须预扣全额,不允许信任旁路
+ if s.relayInfo.ForcePreConsume {
+ return false
+ }
+
+ trustQuota := common.GetTrustQuota()
+ if trustQuota <= 0 {
+ return false
+ }
+
+ // 检查令牌是否充足
+ tokenTrusted := s.relayInfo.TokenUnlimited
+ if !tokenTrusted {
+ tokenQuota := c.GetInt("token_quota")
+ tokenTrusted = tokenQuota > trustQuota
+ }
+ if !tokenTrusted {
+ return false
+ }
+
+ switch s.funding.Source() {
+ case BillingSourceWallet:
+ return s.relayInfo.UserQuota > trustQuota
+ case BillingSourceSubscription:
+ // 订阅不能启用信任旁路。原因:
+ // 1. PreConsumeUserSubscription 要求 amount>0 来创建预扣记录并锁定订阅
+ // 2. SubscriptionFunding.PreConsume 忽略参数,始终用 s.amount 预扣
+ // 3. 若信任旁路将 effectiveQuota 设为 0,会导致 preConsumedQuota 与实际订阅预扣不一致
+ return false
+ default:
+ return false
+ }
+}
+
+// syncRelayInfo 将 BillingSession 的状态同步到 RelayInfo 的兼容字段上。
+func (s *BillingSession) syncRelayInfo() {
+ info := s.relayInfo
+ info.FinalPreConsumedQuota = s.preConsumedQuota
+ info.BillingSource = s.funding.Source()
+
+ if sub, ok := s.funding.(*SubscriptionFunding); ok {
+ info.SubscriptionId = sub.subscriptionId
+ info.SubscriptionPreConsumed = sub.preConsumed
+ info.SubscriptionPostDelta = 0
+ info.SubscriptionAmountTotal = sub.AmountTotal
+ info.SubscriptionAmountUsedAfterPreConsume = sub.AmountUsedAfter
+ info.SubscriptionPlanId = sub.PlanId
+ info.SubscriptionPlanTitle = sub.PlanTitle
+ } else {
+ info.SubscriptionId = 0
+ info.SubscriptionPreConsumed = 0
+ }
+}
+
+// ---------------------------------------------------------------------------
+// NewBillingSession 工厂 — 根据计费偏好创建会话并处理回退
+// ---------------------------------------------------------------------------
+
+// NewBillingSession 根据用户计费偏好创建 BillingSession,处理 subscription_first / wallet_first 的回退。
+func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preConsumedQuota int) (*BillingSession, *types.NewAPIError) {
+ if relayInfo == nil {
+ return nil, types.NewError(fmt.Errorf("relayInfo is nil"), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
+ }
+
+ pref := common.NormalizeBillingPreference(relayInfo.UserSetting.BillingPreference)
+
+ // 钱包路径需要先检查用户额度
+ tryWallet := func() (*BillingSession, *types.NewAPIError) {
+ userQuota, err := model.GetUserQuota(relayInfo.UserId, false)
+ if err != nil {
+ return nil, types.NewError(err, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry())
+ }
+ if userQuota <= 0 {
+ return nil, types.NewErrorWithStatusCode(
+ fmt.Errorf("用户额度不足, 剩余额度: %s", logger.FormatQuota(userQuota)),
+ types.ErrorCodeInsufficientUserQuota, http.StatusForbidden,
+ types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
+ }
+ if userQuota-preConsumedQuota < 0 {
+ return nil, types.NewErrorWithStatusCode(
+ fmt.Errorf("预扣费额度失败, 用户剩余额度: %s, 需要预扣费额度: %s", logger.FormatQuota(userQuota), logger.FormatQuota(preConsumedQuota)),
+ types.ErrorCodeInsufficientUserQuota, http.StatusForbidden,
+ types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog())
+ }
+ relayInfo.UserQuota = userQuota
+
+ session := &BillingSession{
+ relayInfo: relayInfo,
+ funding: &WalletFunding{userId: relayInfo.UserId},
+ }
+ if apiErr := session.preConsume(c, preConsumedQuota); apiErr != nil {
+ return nil, apiErr
+ }
+ return session, nil
+ }
+
+ trySubscription := func() (*BillingSession, *types.NewAPIError) {
+ subConsume := int64(preConsumedQuota)
+ if subConsume <= 0 {
+ subConsume = 1
+ }
+ session := &BillingSession{
+ relayInfo: relayInfo,
+ funding: &SubscriptionFunding{
+ requestId: relayInfo.RequestId,
+ userId: relayInfo.UserId,
+ modelName: relayInfo.OriginModelName,
+ amount: subConsume,
+ },
+ }
+ // 必须传 subConsume 而非 preConsumedQuota,保证 SubscriptionFunding.amount、
+ // preConsume 参数和 FinalPreConsumedQuota 三者一致,避免订阅多扣费。
+ if apiErr := session.preConsume(c, int(subConsume)); apiErr != nil {
+ return nil, apiErr
+ }
+ return session, nil
+ }
+
+ switch pref {
+ case "subscription_only":
+ return trySubscription()
+ case "wallet_only":
+ return tryWallet()
+ case "wallet_first":
+ session, err := tryWallet()
+ if err != nil {
+ if err.GetErrorCode() == types.ErrorCodeInsufficientUserQuota {
+ return trySubscription()
+ }
+ return nil, err
+ }
+ return session, nil
+ case "subscription_first":
+ fallthrough
+ default:
+ hasSub, subCheckErr := model.HasActiveUserSubscription(relayInfo.UserId)
+ if subCheckErr != nil {
+ return nil, types.NewError(subCheckErr, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry())
+ }
+ if !hasSub {
+ return tryWallet()
+ }
+ session, apiErr := trySubscription()
+ if apiErr != nil {
+ if apiErr.GetErrorCode() == types.ErrorCodeInsufficientUserQuota {
+ return tryWallet()
+ }
+ return nil, apiErr
+ }
+ return session, nil
+ }
+}
diff --git a/service/channel_affinity.go b/service/channel_affinity.go
new file mode 100644
index 0000000000..e09cb01f41
--- /dev/null
+++ b/service/channel_affinity.go
@@ -0,0 +1,966 @@
+package service
+
+import (
+ "fmt"
+ "hash/fnv"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/pkg/cachex"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/gin-gonic/gin"
+ "github.com/samber/hot"
+ "github.com/tidwall/gjson"
+)
+
+const (
+ ginKeyChannelAffinityCacheKey = "channel_affinity_cache_key"
+ ginKeyChannelAffinityTTLSeconds = "channel_affinity_ttl_seconds"
+ ginKeyChannelAffinityMeta = "channel_affinity_meta"
+ ginKeyChannelAffinityLogInfo = "channel_affinity_log_info"
+ ginKeyChannelAffinitySkipRetry = "channel_affinity_skip_retry_on_failure"
+
+ channelAffinityCacheNamespace = "new-api:channel_affinity:v1"
+ channelAffinityUsageCacheStatsNamespace = "new-api:channel_affinity_usage_cache_stats:v1"
+)
+
+var (
+ channelAffinityCacheOnce sync.Once
+ channelAffinityCache *cachex.HybridCache[int]
+
+ channelAffinityUsageCacheStatsOnce sync.Once
+ channelAffinityUsageCacheStatsCache *cachex.HybridCache[ChannelAffinityUsageCacheCounters]
+
+ channelAffinityRegexCache sync.Map // map[string]*regexp.Regexp
+)
+
+type channelAffinityMeta struct {
+ CacheKey string
+ TTLSeconds int
+ RuleName string
+ SkipRetry bool
+ ParamTemplate map[string]interface{}
+ KeySourceType string
+ KeySourceKey string
+ KeySourcePath string
+ KeyHint string
+ KeyFingerprint string
+ UsingGroup string
+ ModelName string
+ RequestPath string
+}
+
+type ChannelAffinityStatsContext struct {
+ RuleName string
+ UsingGroup string
+ KeyFingerprint string
+ TTLSeconds int64
+}
+
+const (
+ cacheTokenRateModeCachedOverPrompt = "cached_over_prompt"
+ cacheTokenRateModeCachedOverPromptPlusCached = "cached_over_prompt_plus_cached"
+ cacheTokenRateModeMixed = "mixed"
+)
+
+type ChannelAffinityCacheStats struct {
+ Enabled bool `json:"enabled"`
+ Total int `json:"total"`
+ Unknown int `json:"unknown"`
+ ByRuleName map[string]int `json:"by_rule_name"`
+ CacheCapacity int `json:"cache_capacity"`
+ CacheAlgo string `json:"cache_algo"`
+}
+
+func getChannelAffinityCache() *cachex.HybridCache[int] {
+ channelAffinityCacheOnce.Do(func() {
+ setting := operation_setting.GetChannelAffinitySetting()
+ capacity := setting.MaxEntries
+ if capacity <= 0 {
+ capacity = 100_000
+ }
+ defaultTTLSeconds := setting.DefaultTTLSeconds
+ if defaultTTLSeconds <= 0 {
+ defaultTTLSeconds = 3600
+ }
+
+ channelAffinityCache = cachex.NewHybridCache[int](cachex.HybridCacheConfig[int]{
+ Namespace: cachex.Namespace(channelAffinityCacheNamespace),
+ Redis: common.RDB,
+ RedisEnabled: func() bool {
+ return common.RedisEnabled && common.RDB != nil
+ },
+ RedisCodec: cachex.IntCodec{},
+ Memory: func() *hot.HotCache[string, int] {
+ return hot.NewHotCache[string, int](hot.LRU, capacity).
+ WithTTL(time.Duration(defaultTTLSeconds) * time.Second).
+ WithJanitor().
+ Build()
+ },
+ })
+ })
+ return channelAffinityCache
+}
+
+func GetChannelAffinityCacheStats() ChannelAffinityCacheStats {
+ setting := operation_setting.GetChannelAffinitySetting()
+ if setting == nil {
+ return ChannelAffinityCacheStats{
+ Enabled: false,
+ Total: 0,
+ Unknown: 0,
+ ByRuleName: map[string]int{},
+ }
+ }
+
+ cache := getChannelAffinityCache()
+ mainCap, _ := cache.Capacity()
+ mainAlgo, _ := cache.Algorithm()
+
+ rules := setting.Rules
+ ruleByName := make(map[string]operation_setting.ChannelAffinityRule, len(rules))
+ for _, r := range rules {
+ name := strings.TrimSpace(r.Name)
+ if name == "" {
+ continue
+ }
+ if !r.IncludeRuleName {
+ continue
+ }
+ ruleByName[name] = r
+ }
+
+ byRuleName := make(map[string]int, len(ruleByName))
+ for name := range ruleByName {
+ byRuleName[name] = 0
+ }
+
+ keys, err := cache.Keys()
+ if err != nil {
+ common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err))
+ keys = nil
+ }
+ total := len(keys)
+ unknown := 0
+ for _, k := range keys {
+ prefix := channelAffinityCacheNamespace + ":"
+ if !strings.HasPrefix(k, prefix) {
+ unknown++
+ continue
+ }
+ rest := strings.TrimPrefix(k, prefix)
+ parts := strings.Split(rest, ":")
+ if len(parts) < 2 {
+ unknown++
+ continue
+ }
+ ruleName := parts[0]
+ rule, ok := ruleByName[ruleName]
+ if !ok {
+ unknown++
+ continue
+ }
+ if rule.IncludeModelName {
+ if len(parts) < 3 {
+ unknown++
+ continue
+ }
+ }
+ if rule.IncludeUsingGroup {
+ minParts := 3
+ if rule.IncludeModelName {
+ minParts = 4
+ }
+ if len(parts) < minParts {
+ unknown++
+ continue
+ }
+ }
+ byRuleName[ruleName]++
+ }
+
+ return ChannelAffinityCacheStats{
+ Enabled: setting.Enabled,
+ Total: total,
+ Unknown: unknown,
+ ByRuleName: byRuleName,
+ CacheCapacity: mainCap,
+ CacheAlgo: mainAlgo,
+ }
+}
+
+func ClearChannelAffinityCacheAll() int {
+ cache := getChannelAffinityCache()
+ keys, err := cache.Keys()
+ if err != nil {
+ common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err))
+ keys = nil
+ }
+ if len(keys) > 0 {
+ if _, err := cache.DeleteMany(keys); err != nil {
+ common.SysError(fmt.Sprintf("channel affinity cache delete many failed: err=%v", err))
+ }
+ }
+ return len(keys)
+}
+
+func ClearChannelAffinityCacheByRuleName(ruleName string) (int, error) {
+ ruleName = strings.TrimSpace(ruleName)
+ if ruleName == "" {
+ return 0, fmt.Errorf("rule_name 不能为空")
+ }
+
+ setting := operation_setting.GetChannelAffinitySetting()
+ if setting == nil {
+ return 0, fmt.Errorf("channel_affinity_setting 未初始化")
+ }
+
+ var matchedRule *operation_setting.ChannelAffinityRule
+ for i := range setting.Rules {
+ r := &setting.Rules[i]
+ if strings.TrimSpace(r.Name) != ruleName {
+ continue
+ }
+ matchedRule = r
+ break
+ }
+ if matchedRule == nil {
+ return 0, fmt.Errorf("未知规则名称")
+ }
+ if !matchedRule.IncludeRuleName {
+ return 0, fmt.Errorf("该规则未启用 include_rule_name,无法按规则清空缓存")
+ }
+
+ cache := getChannelAffinityCache()
+ deleted, err := cache.DeleteByPrefix(ruleName)
+ if err != nil {
+ return 0, err
+ }
+ return deleted, nil
+}
+
+func matchAnyRegexCached(patterns []string, s string) bool {
+ if len(patterns) == 0 || s == "" {
+ return false
+ }
+ for _, pattern := range patterns {
+ if pattern == "" {
+ continue
+ }
+ re, ok := channelAffinityRegexCache.Load(pattern)
+ if !ok {
+ compiled, err := regexp.Compile(pattern)
+ if err != nil {
+ continue
+ }
+ re = compiled
+ channelAffinityRegexCache.Store(pattern, re)
+ }
+ if re.(*regexp.Regexp).MatchString(s) {
+ return true
+ }
+ }
+ return false
+}
+
+func matchAnyIncludeFold(patterns []string, s string) bool {
+ if len(patterns) == 0 || s == "" {
+ return false
+ }
+ sLower := strings.ToLower(s)
+ for _, p := range patterns {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ if strings.Contains(sLower, strings.ToLower(p)) {
+ return true
+ }
+ }
+ return false
+}
+
+func extractChannelAffinityValue(c *gin.Context, src operation_setting.ChannelAffinityKeySource) string {
+ switch src.Type {
+ case "context_int":
+ if src.Key == "" {
+ return ""
+ }
+ v := c.GetInt(src.Key)
+ if v <= 0 {
+ return ""
+ }
+ return strconv.Itoa(v)
+ case "context_string":
+ if src.Key == "" {
+ return ""
+ }
+ return strings.TrimSpace(c.GetString(src.Key))
+ case "gjson":
+ if src.Path == "" {
+ return ""
+ }
+ storage, err := common.GetBodyStorage(c)
+ if err != nil {
+ return ""
+ }
+ body, err := storage.Bytes()
+ if err != nil || len(body) == 0 {
+ return ""
+ }
+ res := gjson.GetBytes(body, src.Path)
+ if !res.Exists() {
+ return ""
+ }
+ switch res.Type {
+ case gjson.String, gjson.Number, gjson.True, gjson.False:
+ return strings.TrimSpace(res.String())
+ default:
+ return strings.TrimSpace(res.Raw)
+ }
+ default:
+ return ""
+ }
+}
+
+func buildChannelAffinityCacheKeySuffix(rule operation_setting.ChannelAffinityRule, modelName string, usingGroup string, affinityValue string) string {
+ parts := make([]string, 0, 4)
+ if rule.IncludeRuleName && rule.Name != "" {
+ parts = append(parts, rule.Name)
+ }
+ if rule.IncludeModelName && modelName != "" {
+ parts = append(parts, modelName)
+ }
+ if rule.IncludeUsingGroup && usingGroup != "" {
+ parts = append(parts, usingGroup)
+ }
+ parts = append(parts, affinityValue)
+ return strings.Join(parts, ":")
+}
+
+func setChannelAffinityContext(c *gin.Context, meta channelAffinityMeta) {
+ c.Set(ginKeyChannelAffinityCacheKey, meta.CacheKey)
+ c.Set(ginKeyChannelAffinityTTLSeconds, meta.TTLSeconds)
+ c.Set(ginKeyChannelAffinityMeta, meta)
+}
+
+func getChannelAffinityContext(c *gin.Context) (string, int, bool) {
+ keyAny, ok := c.Get(ginKeyChannelAffinityCacheKey)
+ if !ok {
+ return "", 0, false
+ }
+ key, ok := keyAny.(string)
+ if !ok || key == "" {
+ return "", 0, false
+ }
+ ttlAny, ok := c.Get(ginKeyChannelAffinityTTLSeconds)
+ if !ok {
+ return key, 0, true
+ }
+ ttlSeconds, _ := ttlAny.(int)
+ return key, ttlSeconds, true
+}
+
+func getChannelAffinityMeta(c *gin.Context) (channelAffinityMeta, bool) {
+ anyMeta, ok := c.Get(ginKeyChannelAffinityMeta)
+ if !ok {
+ return channelAffinityMeta{}, false
+ }
+ meta, ok := anyMeta.(channelAffinityMeta)
+ if !ok {
+ return channelAffinityMeta{}, false
+ }
+ return meta, true
+}
+
+func GetChannelAffinityStatsContext(c *gin.Context) (ChannelAffinityStatsContext, bool) {
+ if c == nil {
+ return ChannelAffinityStatsContext{}, false
+ }
+ meta, ok := getChannelAffinityMeta(c)
+ if !ok {
+ return ChannelAffinityStatsContext{}, false
+ }
+ ruleName := strings.TrimSpace(meta.RuleName)
+ keyFp := strings.TrimSpace(meta.KeyFingerprint)
+ usingGroup := strings.TrimSpace(meta.UsingGroup)
+ if ruleName == "" || keyFp == "" {
+ return ChannelAffinityStatsContext{}, false
+ }
+ ttlSeconds := int64(meta.TTLSeconds)
+ if ttlSeconds <= 0 {
+ return ChannelAffinityStatsContext{}, false
+ }
+ return ChannelAffinityStatsContext{
+ RuleName: ruleName,
+ UsingGroup: usingGroup,
+ KeyFingerprint: keyFp,
+ TTLSeconds: ttlSeconds,
+ }, true
+}
+
+func affinityFingerprint(s string) string {
+ if s == "" {
+ return ""
+ }
+ hex := common.Sha1([]byte(s))
+ if len(hex) >= 8 {
+ return hex[:8]
+ }
+ return hex
+}
+
+func buildChannelAffinityKeyHint(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return ""
+ }
+ s = strings.ReplaceAll(s, "\n", " ")
+ s = strings.ReplaceAll(s, "\r", " ")
+ if len(s) <= 12 {
+ return s
+ }
+ return s[:4] + "..." + s[len(s)-4:]
+}
+
+func cloneStringAnyMap(src map[string]interface{}) map[string]interface{} {
+ if len(src) == 0 {
+ return map[string]interface{}{}
+ }
+ dst := make(map[string]interface{}, len(src))
+ for k, v := range src {
+ dst[k] = v
+ }
+ return dst
+}
+
+func mergeChannelOverride(base map[string]interface{}, tpl map[string]interface{}) map[string]interface{} {
+ if len(base) == 0 && len(tpl) == 0 {
+ return map[string]interface{}{}
+ }
+ if len(tpl) == 0 {
+ return base
+ }
+ out := cloneStringAnyMap(base)
+ for k, v := range tpl {
+ if strings.EqualFold(strings.TrimSpace(k), "operations") {
+ baseOps, hasBaseOps := extractParamOperations(out[k])
+ tplOps, hasTplOps := extractParamOperations(v)
+ if hasTplOps {
+ if hasBaseOps {
+ out[k] = append(tplOps, baseOps...)
+ } else {
+ out[k] = tplOps
+ }
+ continue
+ }
+ }
+ if _, exists := out[k]; exists {
+ continue
+ }
+ out[k] = v
+ }
+ return out
+}
+
+func extractParamOperations(value interface{}) ([]interface{}, bool) {
+ switch ops := value.(type) {
+ case []interface{}:
+ if len(ops) == 0 {
+ return []interface{}{}, true
+ }
+ cloned := make([]interface{}, 0, len(ops))
+ cloned = append(cloned, ops...)
+ return cloned, true
+ case []map[string]interface{}:
+ cloned := make([]interface{}, 0, len(ops))
+ for _, op := range ops {
+ cloned = append(cloned, op)
+ }
+ return cloned, true
+ default:
+ return nil, false
+ }
+}
+
+func appendChannelAffinityTemplateAdminInfo(c *gin.Context, meta channelAffinityMeta) {
+ if c == nil {
+ return
+ }
+ if len(meta.ParamTemplate) == 0 {
+ return
+ }
+
+ templateInfo := map[string]interface{}{
+ "applied": true,
+ "rule_name": meta.RuleName,
+ "param_override_keys": len(meta.ParamTemplate),
+ }
+ if anyInfo, ok := c.Get(ginKeyChannelAffinityLogInfo); ok {
+ if info, ok := anyInfo.(map[string]interface{}); ok {
+ info["override_template"] = templateInfo
+ c.Set(ginKeyChannelAffinityLogInfo, info)
+ return
+ }
+ }
+ c.Set(ginKeyChannelAffinityLogInfo, map[string]interface{}{
+ "reason": meta.RuleName,
+ "rule_name": meta.RuleName,
+ "using_group": meta.UsingGroup,
+ "model": meta.ModelName,
+ "request_path": meta.RequestPath,
+ "key_source": meta.KeySourceType,
+ "key_key": meta.KeySourceKey,
+ "key_path": meta.KeySourcePath,
+ "key_hint": meta.KeyHint,
+ "key_fp": meta.KeyFingerprint,
+ "override_template": templateInfo,
+ })
+}
+
+// ApplyChannelAffinityOverrideTemplate merges per-rule channel override templates onto the selected channel override config.
+func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool) {
+ if c == nil {
+ return paramOverride, false
+ }
+ meta, ok := getChannelAffinityMeta(c)
+ if !ok {
+ return paramOverride, false
+ }
+ if len(meta.ParamTemplate) == 0 {
+ return paramOverride, false
+ }
+
+ mergedParam := mergeChannelOverride(paramOverride, meta.ParamTemplate)
+ appendChannelAffinityTemplateAdminInfo(c, meta)
+ return mergedParam, true
+}
+
+func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) {
+ setting := operation_setting.GetChannelAffinitySetting()
+ if setting == nil || !setting.Enabled {
+ return 0, false
+ }
+ path := ""
+ if c != nil && c.Request != nil && c.Request.URL != nil {
+ path = c.Request.URL.Path
+ }
+ userAgent := ""
+ if c != nil && c.Request != nil {
+ userAgent = c.Request.UserAgent()
+ }
+
+ for _, rule := range setting.Rules {
+ if !matchAnyRegexCached(rule.ModelRegex, modelName) {
+ continue
+ }
+ if len(rule.PathRegex) > 0 && !matchAnyRegexCached(rule.PathRegex, path) {
+ continue
+ }
+ if len(rule.UserAgentInclude) > 0 && !matchAnyIncludeFold(rule.UserAgentInclude, userAgent) {
+ continue
+ }
+ var affinityValue string
+ var usedSource operation_setting.ChannelAffinityKeySource
+ for _, src := range rule.KeySources {
+ affinityValue = extractChannelAffinityValue(c, src)
+ if affinityValue != "" {
+ usedSource = src
+ break
+ }
+ }
+ if affinityValue == "" {
+ continue
+ }
+ if rule.ValueRegex != "" && !matchAnyRegexCached([]string{rule.ValueRegex}, affinityValue) {
+ continue
+ }
+
+ ttlSeconds := rule.TTLSeconds
+ if ttlSeconds <= 0 {
+ ttlSeconds = setting.DefaultTTLSeconds
+ }
+ cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, modelName, usingGroup, affinityValue)
+ cacheKeyFull := channelAffinityCacheNamespace + ":" + cacheKeySuffix
+ setChannelAffinityContext(c, channelAffinityMeta{
+ CacheKey: cacheKeyFull,
+ TTLSeconds: ttlSeconds,
+ RuleName: rule.Name,
+ SkipRetry: rule.SkipRetryOnFailure,
+ ParamTemplate: cloneStringAnyMap(rule.ParamOverrideTemplate),
+ KeySourceType: strings.TrimSpace(usedSource.Type),
+ KeySourceKey: strings.TrimSpace(usedSource.Key),
+ KeySourcePath: strings.TrimSpace(usedSource.Path),
+ KeyHint: buildChannelAffinityKeyHint(affinityValue),
+ KeyFingerprint: affinityFingerprint(affinityValue),
+ UsingGroup: usingGroup,
+ ModelName: modelName,
+ RequestPath: path,
+ })
+
+ cache := getChannelAffinityCache()
+ channelID, found, err := cache.Get(cacheKeySuffix)
+ if err != nil {
+ common.SysError(fmt.Sprintf("channel affinity cache get failed: key=%s, err=%v", cacheKeyFull, err))
+ return 0, false
+ }
+ if found {
+ return channelID, true
+ }
+ return 0, false
+ }
+ return 0, false
+}
+
+func ShouldSkipRetryAfterChannelAffinityFailure(c *gin.Context) bool {
+ if c == nil {
+ return false
+ }
+ v, ok := c.Get(ginKeyChannelAffinitySkipRetry)
+ if ok {
+ b, ok := v.(bool)
+ if ok {
+ return b
+ }
+ }
+ meta, ok := getChannelAffinityMeta(c)
+ if !ok {
+ return false
+ }
+ return meta.SkipRetry
+}
+
+func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int) {
+ if c == nil || channelID <= 0 {
+ return
+ }
+ meta, ok := getChannelAffinityMeta(c)
+ if !ok {
+ return
+ }
+ c.Set(ginKeyChannelAffinitySkipRetry, meta.SkipRetry)
+ info := map[string]interface{}{
+ "reason": meta.RuleName,
+ "rule_name": meta.RuleName,
+ "using_group": meta.UsingGroup,
+ "selected_group": selectedGroup,
+ "model": meta.ModelName,
+ "request_path": meta.RequestPath,
+ "channel_id": channelID,
+ "key_source": meta.KeySourceType,
+ "key_key": meta.KeySourceKey,
+ "key_path": meta.KeySourcePath,
+ "key_hint": meta.KeyHint,
+ "key_fp": meta.KeyFingerprint,
+ }
+ c.Set(ginKeyChannelAffinityLogInfo, info)
+}
+
+func AppendChannelAffinityAdminInfo(c *gin.Context, adminInfo map[string]interface{}) {
+ if c == nil || adminInfo == nil {
+ return
+ }
+ anyInfo, ok := c.Get(ginKeyChannelAffinityLogInfo)
+ if !ok || anyInfo == nil {
+ return
+ }
+ adminInfo["channel_affinity"] = anyInfo
+}
+
+func RecordChannelAffinity(c *gin.Context, channelID int) {
+ if channelID <= 0 {
+ return
+ }
+ setting := operation_setting.GetChannelAffinitySetting()
+ if setting == nil || !setting.Enabled {
+ return
+ }
+ if setting.SwitchOnSuccess && c != nil {
+ if successChannelID := c.GetInt("channel_id"); successChannelID > 0 {
+ channelID = successChannelID
+ }
+ }
+ cacheKey, ttlSeconds, ok := getChannelAffinityContext(c)
+ if !ok {
+ return
+ }
+ if ttlSeconds <= 0 {
+ ttlSeconds = setting.DefaultTTLSeconds
+ }
+ if ttlSeconds <= 0 {
+ ttlSeconds = 3600
+ }
+ cache := getChannelAffinityCache()
+ if err := cache.SetWithTTL(cacheKey, channelID, time.Duration(ttlSeconds)*time.Second); err != nil {
+ common.SysError(fmt.Sprintf("channel affinity cache set failed: key=%s, err=%v", cacheKey, err))
+ }
+}
+
+type ChannelAffinityUsageCacheStats struct {
+ RuleName string `json:"rule_name"`
+ UsingGroup string `json:"using_group"`
+ KeyFingerprint string `json:"key_fp"`
+ CachedTokenRateMode string `json:"cached_token_rate_mode"`
+
+ Hit int64 `json:"hit"`
+ Total int64 `json:"total"`
+ WindowSeconds int64 `json:"window_seconds"`
+
+ PromptTokens int64 `json:"prompt_tokens"`
+ CompletionTokens int64 `json:"completion_tokens"`
+ TotalTokens int64 `json:"total_tokens"`
+ CachedTokens int64 `json:"cached_tokens"`
+ PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
+ LastSeenAt int64 `json:"last_seen_at"`
+}
+
+type ChannelAffinityUsageCacheCounters struct {
+ CachedTokenRateMode string `json:"cached_token_rate_mode"`
+
+ Hit int64 `json:"hit"`
+ Total int64 `json:"total"`
+ WindowSeconds int64 `json:"window_seconds"`
+
+ PromptTokens int64 `json:"prompt_tokens"`
+ CompletionTokens int64 `json:"completion_tokens"`
+ TotalTokens int64 `json:"total_tokens"`
+ CachedTokens int64 `json:"cached_tokens"`
+ PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
+ LastSeenAt int64 `json:"last_seen_at"`
+}
+
+var channelAffinityUsageCacheStatsLocks [64]sync.Mutex
+
+// ObserveChannelAffinityUsageCacheByRelayFormat records usage cache stats with a stable rate mode derived from relay format.
+func ObserveChannelAffinityUsageCacheByRelayFormat(c *gin.Context, usage *dto.Usage, relayFormat types.RelayFormat) {
+ ObserveChannelAffinityUsageCacheFromContext(c, usage, cachedTokenRateModeByRelayFormat(relayFormat))
+}
+
+func ObserveChannelAffinityUsageCacheFromContext(c *gin.Context, usage *dto.Usage, cachedTokenRateMode string) {
+ statsCtx, ok := GetChannelAffinityStatsContext(c)
+ if !ok {
+ return
+ }
+ observeChannelAffinityUsageCache(statsCtx, usage, cachedTokenRateMode)
+}
+
+func GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFp string) ChannelAffinityUsageCacheStats {
+ ruleName = strings.TrimSpace(ruleName)
+ usingGroup = strings.TrimSpace(usingGroup)
+ keyFp = strings.TrimSpace(keyFp)
+
+ entryKey := channelAffinityUsageCacheEntryKey(ruleName, usingGroup, keyFp)
+ if entryKey == "" {
+ return ChannelAffinityUsageCacheStats{
+ RuleName: ruleName,
+ UsingGroup: usingGroup,
+ KeyFingerprint: keyFp,
+ }
+ }
+
+ cache := getChannelAffinityUsageCacheStatsCache()
+ v, found, err := cache.Get(entryKey)
+ if err != nil || !found {
+ return ChannelAffinityUsageCacheStats{
+ RuleName: ruleName,
+ UsingGroup: usingGroup,
+ KeyFingerprint: keyFp,
+ }
+ }
+ return ChannelAffinityUsageCacheStats{
+ CachedTokenRateMode: v.CachedTokenRateMode,
+ RuleName: ruleName,
+ UsingGroup: usingGroup,
+ KeyFingerprint: keyFp,
+ Hit: v.Hit,
+ Total: v.Total,
+ WindowSeconds: v.WindowSeconds,
+ PromptTokens: v.PromptTokens,
+ CompletionTokens: v.CompletionTokens,
+ TotalTokens: v.TotalTokens,
+ CachedTokens: v.CachedTokens,
+ PromptCacheHitTokens: v.PromptCacheHitTokens,
+ LastSeenAt: v.LastSeenAt,
+ }
+}
+
+func observeChannelAffinityUsageCache(statsCtx ChannelAffinityStatsContext, usage *dto.Usage, cachedTokenRateMode string) {
+ entryKey := channelAffinityUsageCacheEntryKey(statsCtx.RuleName, statsCtx.UsingGroup, statsCtx.KeyFingerprint)
+ if entryKey == "" {
+ return
+ }
+
+ windowSeconds := statsCtx.TTLSeconds
+ if windowSeconds <= 0 {
+ return
+ }
+
+ cache := getChannelAffinityUsageCacheStatsCache()
+ ttl := time.Duration(windowSeconds) * time.Second
+
+ lock := channelAffinityUsageCacheStatsLock(entryKey)
+ lock.Lock()
+ defer lock.Unlock()
+
+ prev, found, err := cache.Get(entryKey)
+ if err != nil {
+ return
+ }
+ next := prev
+ if !found {
+ next = ChannelAffinityUsageCacheCounters{}
+ }
+ currentMode := normalizeCachedTokenRateMode(cachedTokenRateMode)
+ if currentMode != "" {
+ if next.CachedTokenRateMode == "" {
+ next.CachedTokenRateMode = currentMode
+ } else if next.CachedTokenRateMode != currentMode && next.CachedTokenRateMode != cacheTokenRateModeMixed {
+ next.CachedTokenRateMode = cacheTokenRateModeMixed
+ }
+ }
+ next.Total++
+ hit, cachedTokens, promptCacheHitTokens := usageCacheSignals(usage)
+ if hit {
+ next.Hit++
+ }
+ next.WindowSeconds = windowSeconds
+ next.LastSeenAt = time.Now().Unix()
+ next.CachedTokens += cachedTokens
+ next.PromptCacheHitTokens += promptCacheHitTokens
+ next.PromptTokens += int64(usagePromptTokens(usage))
+ next.CompletionTokens += int64(usageCompletionTokens(usage))
+ next.TotalTokens += int64(usageTotalTokens(usage))
+ _ = cache.SetWithTTL(entryKey, next, ttl)
+}
+
+func normalizeCachedTokenRateMode(mode string) string {
+ switch mode {
+ case cacheTokenRateModeCachedOverPrompt:
+ return cacheTokenRateModeCachedOverPrompt
+ case cacheTokenRateModeCachedOverPromptPlusCached:
+ return cacheTokenRateModeCachedOverPromptPlusCached
+ case cacheTokenRateModeMixed:
+ return cacheTokenRateModeMixed
+ default:
+ return ""
+ }
+}
+
+func cachedTokenRateModeByRelayFormat(relayFormat types.RelayFormat) string {
+ switch relayFormat {
+ case types.RelayFormatOpenAI, types.RelayFormatOpenAIResponses, types.RelayFormatOpenAIResponsesCompaction:
+ return cacheTokenRateModeCachedOverPrompt
+ case types.RelayFormatClaude:
+ return cacheTokenRateModeCachedOverPromptPlusCached
+ default:
+ return ""
+ }
+}
+
+func channelAffinityUsageCacheEntryKey(ruleName, usingGroup, keyFp string) string {
+ ruleName = strings.TrimSpace(ruleName)
+ usingGroup = strings.TrimSpace(usingGroup)
+ keyFp = strings.TrimSpace(keyFp)
+ if ruleName == "" || keyFp == "" {
+ return ""
+ }
+ return ruleName + "\n" + usingGroup + "\n" + keyFp
+}
+
+func usageCacheSignals(usage *dto.Usage) (hit bool, cachedTokens int64, promptCacheHitTokens int64) {
+ if usage == nil {
+ return false, 0, 0
+ }
+
+ cached := int64(0)
+ if usage.PromptTokensDetails.CachedTokens > 0 {
+ cached = int64(usage.PromptTokensDetails.CachedTokens)
+ } else if usage.InputTokensDetails != nil && usage.InputTokensDetails.CachedTokens > 0 {
+ cached = int64(usage.InputTokensDetails.CachedTokens)
+ }
+ pcht := int64(0)
+ if usage.PromptCacheHitTokens > 0 {
+ pcht = int64(usage.PromptCacheHitTokens)
+ }
+ return cached > 0 || pcht > 0, cached, pcht
+}
+
+func usagePromptTokens(usage *dto.Usage) int {
+ if usage == nil {
+ return 0
+ }
+ if usage.PromptTokens > 0 {
+ return usage.PromptTokens
+ }
+ return usage.InputTokens
+}
+
+func usageCompletionTokens(usage *dto.Usage) int {
+ if usage == nil {
+ return 0
+ }
+ if usage.CompletionTokens > 0 {
+ return usage.CompletionTokens
+ }
+ return usage.OutputTokens
+}
+
+func usageTotalTokens(usage *dto.Usage) int {
+ if usage == nil {
+ return 0
+ }
+ if usage.TotalTokens > 0 {
+ return usage.TotalTokens
+ }
+ pt := usagePromptTokens(usage)
+ ct := usageCompletionTokens(usage)
+ if pt > 0 || ct > 0 {
+ return pt + ct
+ }
+ return 0
+}
+
+func getChannelAffinityUsageCacheStatsCache() *cachex.HybridCache[ChannelAffinityUsageCacheCounters] {
+ channelAffinityUsageCacheStatsOnce.Do(func() {
+ setting := operation_setting.GetChannelAffinitySetting()
+ capacity := 100_000
+ defaultTTLSeconds := 3600
+ if setting != nil {
+ if setting.MaxEntries > 0 {
+ capacity = setting.MaxEntries
+ }
+ if setting.DefaultTTLSeconds > 0 {
+ defaultTTLSeconds = setting.DefaultTTLSeconds
+ }
+ }
+
+ channelAffinityUsageCacheStatsCache = cachex.NewHybridCache[ChannelAffinityUsageCacheCounters](cachex.HybridCacheConfig[ChannelAffinityUsageCacheCounters]{
+ Namespace: cachex.Namespace(channelAffinityUsageCacheStatsNamespace),
+ Redis: common.RDB,
+ RedisEnabled: func() bool {
+ return common.RedisEnabled && common.RDB != nil
+ },
+ RedisCodec: cachex.JSONCodec[ChannelAffinityUsageCacheCounters]{},
+ Memory: func() *hot.HotCache[string, ChannelAffinityUsageCacheCounters] {
+ return hot.NewHotCache[string, ChannelAffinityUsageCacheCounters](hot.LRU, capacity).
+ WithTTL(time.Duration(defaultTTLSeconds) * time.Second).
+ WithJanitor().
+ Build()
+ },
+ })
+ })
+ return channelAffinityUsageCacheStatsCache
+}
+
+func channelAffinityUsageCacheStatsLock(key string) *sync.Mutex {
+ h := fnv.New32a()
+ _, _ = h.Write([]byte(key))
+ idx := h.Sum32() % uint32(len(channelAffinityUsageCacheStatsLocks))
+ return &channelAffinityUsageCacheStatsLocks[idx]
+}
diff --git a/service/channel_affinity_template_test.go b/service/channel_affinity_template_test.go
new file mode 100644
index 0000000000..033cbd83aa
--- /dev/null
+++ b/service/channel_affinity_template_test.go
@@ -0,0 +1,247 @@
+package service
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func buildChannelAffinityTemplateContextForTest(meta channelAffinityMeta) *gin.Context {
+ rec := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(rec)
+ setChannelAffinityContext(ctx, meta)
+ return ctx
+}
+
+func TestApplyChannelAffinityOverrideTemplate_NoTemplate(t *testing.T) {
+ ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-no-template",
+ })
+ base := map[string]interface{}{
+ "temperature": 0.7,
+ }
+
+ merged, applied := ApplyChannelAffinityOverrideTemplate(ctx, base)
+ require.False(t, applied)
+ require.Equal(t, base, merged)
+}
+
+func TestApplyChannelAffinityOverrideTemplate_MergeTemplate(t *testing.T) {
+ ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-with-template",
+ ParamTemplate: map[string]interface{}{
+ "temperature": 0.2,
+ "top_p": 0.95,
+ },
+ UsingGroup: "default",
+ ModelName: "gpt-4.1",
+ RequestPath: "/v1/responses",
+ KeySourceType: "gjson",
+ KeySourcePath: "prompt_cache_key",
+ KeyHint: "abcd...wxyz",
+ KeyFingerprint: "abcd1234",
+ })
+ base := map[string]interface{}{
+ "temperature": 0.7,
+ "max_tokens": 2000,
+ }
+
+ merged, applied := ApplyChannelAffinityOverrideTemplate(ctx, base)
+ require.True(t, applied)
+ require.Equal(t, 0.7, merged["temperature"])
+ require.Equal(t, 0.95, merged["top_p"])
+ require.Equal(t, 2000, merged["max_tokens"])
+ require.Equal(t, 0.7, base["temperature"])
+
+ anyInfo, ok := ctx.Get(ginKeyChannelAffinityLogInfo)
+ require.True(t, ok)
+ info, ok := anyInfo.(map[string]interface{})
+ require.True(t, ok)
+ overrideInfoAny, ok := info["override_template"]
+ require.True(t, ok)
+ overrideInfo, ok := overrideInfoAny.(map[string]interface{})
+ require.True(t, ok)
+ require.Equal(t, true, overrideInfo["applied"])
+ require.Equal(t, "rule-with-template", overrideInfo["rule_name"])
+ require.EqualValues(t, 2, overrideInfo["param_override_keys"])
+}
+
+func TestApplyChannelAffinityOverrideTemplate_MergeOperations(t *testing.T) {
+ ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-with-ops-template",
+ ParamTemplate: map[string]interface{}{
+ "operations": []map[string]interface{}{
+ {
+ "mode": "pass_headers",
+ "value": []string{"Originator"},
+ },
+ },
+ },
+ })
+ base := map[string]interface{}{
+ "temperature": 0.7,
+ "operations": []map[string]interface{}{
+ {
+ "path": "model",
+ "mode": "trim_prefix",
+ "value": "openai/",
+ },
+ },
+ }
+
+ merged, applied := ApplyChannelAffinityOverrideTemplate(ctx, base)
+ require.True(t, applied)
+ require.Equal(t, 0.7, merged["temperature"])
+
+ opsAny, ok := merged["operations"]
+ require.True(t, ok)
+ ops, ok := opsAny.([]interface{})
+ require.True(t, ok)
+ require.Len(t, ops, 2)
+
+ firstOp, ok := ops[0].(map[string]interface{})
+ require.True(t, ok)
+ require.Equal(t, "pass_headers", firstOp["mode"])
+
+ secondOp, ok := ops[1].(map[string]interface{})
+ require.True(t, ok)
+ require.Equal(t, "trim_prefix", secondOp["mode"])
+}
+
+func TestShouldSkipRetryAfterChannelAffinityFailure(t *testing.T) {
+ tests := []struct {
+ name string
+ ctx func() *gin.Context
+ want bool
+ }{
+ {
+ name: "nil context",
+ ctx: func() *gin.Context {
+ return nil
+ },
+ want: false,
+ },
+ {
+ name: "explicit skip retry flag in context",
+ ctx: func() *gin.Context {
+ ctx := buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-explicit-flag",
+ SkipRetry: false,
+ UsingGroup: "default",
+ ModelName: "gpt-5",
+ })
+ ctx.Set(ginKeyChannelAffinitySkipRetry, true)
+ return ctx
+ },
+ want: true,
+ },
+ {
+ name: "fallback to matched rule meta",
+ ctx: func() *gin.Context {
+ return buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-skip-retry",
+ SkipRetry: true,
+ UsingGroup: "default",
+ ModelName: "gpt-5",
+ })
+ },
+ want: true,
+ },
+ {
+ name: "no flag and no skip retry meta",
+ ctx: func() *gin.Context {
+ return buildChannelAffinityTemplateContextForTest(channelAffinityMeta{
+ RuleName: "rule-no-skip-retry",
+ SkipRetry: false,
+ UsingGroup: "default",
+ ModelName: "gpt-5",
+ })
+ },
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ require.Equal(t, tt.want, ShouldSkipRetryAfterChannelAffinityFailure(tt.ctx()))
+ })
+ }
+}
+
+func TestChannelAffinityHitCodexTemplatePassHeadersEffective(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ setting := operation_setting.GetChannelAffinitySetting()
+ require.NotNil(t, setting)
+
+ var codexRule *operation_setting.ChannelAffinityRule
+ for i := range setting.Rules {
+ rule := &setting.Rules[i]
+ if strings.EqualFold(strings.TrimSpace(rule.Name), "codex cli trace") {
+ codexRule = rule
+ break
+ }
+ }
+ require.NotNil(t, codexRule)
+
+ affinityValue := fmt.Sprintf("pc-hit-%d", time.Now().UnixNano())
+ cacheKeySuffix := buildChannelAffinityCacheKeySuffix(*codexRule, "gpt-5", "default", affinityValue)
+
+ cache := getChannelAffinityCache()
+ require.NoError(t, cache.SetWithTTL(cacheKeySuffix, 9527, time.Minute))
+ t.Cleanup(func() {
+ _, _ = cache.DeleteMany([]string{cacheKeySuffix})
+ })
+
+ rec := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(rec)
+ ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(fmt.Sprintf(`{"prompt_cache_key":"%s"}`, affinityValue)))
+ ctx.Request.Header.Set("Content-Type", "application/json")
+
+ channelID, found := GetPreferredChannelByAffinity(ctx, "gpt-5", "default")
+ require.True(t, found)
+ require.Equal(t, 9527, channelID)
+
+ baseOverride := map[string]interface{}{
+ "temperature": 0.2,
+ }
+ mergedOverride, applied := ApplyChannelAffinityOverrideTemplate(ctx, baseOverride)
+ require.True(t, applied)
+ require.Equal(t, 0.2, mergedOverride["temperature"])
+
+ info := &relaycommon.RelayInfo{
+ RequestHeaders: map[string]string{
+ "Originator": "Codex CLI",
+ "Session_id": "sess-123",
+ "User-Agent": "codex-cli-test",
+ },
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ParamOverride: mergedOverride,
+ HeadersOverride: map[string]interface{}{
+ "X-Static": "legacy-static",
+ },
+ },
+ }
+
+ _, err := relaycommon.ApplyParamOverrideWithRelayInfo([]byte(`{"model":"gpt-5"}`), info)
+ require.NoError(t, err)
+ require.True(t, info.UseRuntimeHeadersOverride)
+
+ require.Equal(t, "legacy-static", info.RuntimeHeadersOverride["x-static"])
+ require.Equal(t, "Codex CLI", info.RuntimeHeadersOverride["originator"])
+ require.Equal(t, "sess-123", info.RuntimeHeadersOverride["session_id"])
+ require.Equal(t, "codex-cli-test", info.RuntimeHeadersOverride["user-agent"])
+
+ _, exists := info.RuntimeHeadersOverride["x-codex-beta-features"]
+ require.False(t, exists)
+ _, exists = info.RuntimeHeadersOverride["x-codex-turn-metadata"]
+ require.False(t, exists)
+}
diff --git a/service/channel_affinity_usage_cache_test.go b/service/channel_affinity_usage_cache_test.go
new file mode 100644
index 0000000000..64d3d715b5
--- /dev/null
+++ b/service/channel_affinity_usage_cache_test.go
@@ -0,0 +1,105 @@
+package service
+
+import (
+ "fmt"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/types"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP string) *gin.Context {
+ rec := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(rec)
+ setChannelAffinityContext(ctx, channelAffinityMeta{
+ CacheKey: fmt.Sprintf("test:%s:%s:%s", ruleName, usingGroup, keyFP),
+ TTLSeconds: 600,
+ RuleName: ruleName,
+ UsingGroup: usingGroup,
+ KeyFingerprint: keyFP,
+ })
+ return ctx
+}
+
+func TestObserveChannelAffinityUsageCacheByRelayFormat_ClaudeMode(t *testing.T) {
+ ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano())
+ usingGroup := "default"
+ keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano())
+ ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP)
+
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ CompletionTokens: 40,
+ TotalTokens: 140,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 30,
+ },
+ }
+
+ ObserveChannelAffinityUsageCacheByRelayFormat(ctx, usage, types.RelayFormatClaude)
+ stats := GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFP)
+
+ require.EqualValues(t, 1, stats.Total)
+ require.EqualValues(t, 1, stats.Hit)
+ require.EqualValues(t, 100, stats.PromptTokens)
+ require.EqualValues(t, 40, stats.CompletionTokens)
+ require.EqualValues(t, 140, stats.TotalTokens)
+ require.EqualValues(t, 30, stats.CachedTokens)
+ require.Equal(t, cacheTokenRateModeCachedOverPromptPlusCached, stats.CachedTokenRateMode)
+}
+
+func TestObserveChannelAffinityUsageCacheByRelayFormat_MixedMode(t *testing.T) {
+ ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano())
+ usingGroup := "default"
+ keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano())
+ ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP)
+
+ openAIUsage := &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 10,
+ },
+ }
+ claudeUsage := &dto.Usage{
+ PromptTokens: 80,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 20,
+ },
+ }
+
+ ObserveChannelAffinityUsageCacheByRelayFormat(ctx, openAIUsage, types.RelayFormatOpenAI)
+ ObserveChannelAffinityUsageCacheByRelayFormat(ctx, claudeUsage, types.RelayFormatClaude)
+ stats := GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFP)
+
+ require.EqualValues(t, 2, stats.Total)
+ require.EqualValues(t, 2, stats.Hit)
+ require.EqualValues(t, 180, stats.PromptTokens)
+ require.EqualValues(t, 30, stats.CachedTokens)
+ require.Equal(t, cacheTokenRateModeMixed, stats.CachedTokenRateMode)
+}
+
+func TestObserveChannelAffinityUsageCacheByRelayFormat_UnsupportedModeKeepsEmpty(t *testing.T) {
+ ruleName := fmt.Sprintf("rule_%d", time.Now().UnixNano())
+ usingGroup := "default"
+ keyFP := fmt.Sprintf("fp_%d", time.Now().UnixNano())
+ ctx := buildChannelAffinityStatsContextForTest(ruleName, usingGroup, keyFP)
+
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 25,
+ },
+ }
+
+ ObserveChannelAffinityUsageCacheByRelayFormat(ctx, usage, types.RelayFormatGemini)
+ stats := GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFP)
+
+ require.EqualValues(t, 1, stats.Total)
+ require.EqualValues(t, 1, stats.Hit)
+ require.EqualValues(t, 25, stats.CachedTokens)
+ require.Equal(t, "", stats.CachedTokenRateMode)
+}
diff --git a/service/codex_credential_refresh.go b/service/codex_credential_refresh.go
index 0290fe5160..2e681ee616 100644
--- a/service/codex_credential_refresh.go
+++ b/service/codex_credential_refresh.go
@@ -62,7 +62,7 @@ func RefreshCodexChannelCredential(ctx context.Context, channelID int, opts Code
refreshCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- res, err := RefreshCodexOAuthToken(refreshCtx, oauthKey.RefreshToken)
+ res, err := RefreshCodexOAuthTokenWithProxy(refreshCtx, oauthKey.RefreshToken, ch.GetSetting().Proxy)
if err != nil {
return nil, nil, err
}
diff --git a/service/codex_oauth.go b/service/codex_oauth.go
index 4c2dce1cc5..33ef1d60ac 100644
--- a/service/codex_oauth.go
+++ b/service/codex_oauth.go
@@ -12,6 +12,8 @@ import (
"net/url"
"strings"
"time"
+
+ "github.com/QuantumNous/new-api/common"
)
const (
@@ -38,12 +40,26 @@ type CodexOAuthAuthorizationFlow struct {
}
func RefreshCodexOAuthToken(ctx context.Context, refreshToken string) (*CodexOAuthTokenResult, error) {
- client := &http.Client{Timeout: defaultHTTPTimeout}
+ return RefreshCodexOAuthTokenWithProxy(ctx, refreshToken, "")
+}
+
+func RefreshCodexOAuthTokenWithProxy(ctx context.Context, refreshToken string, proxyURL string) (*CodexOAuthTokenResult, error) {
+ client, err := getCodexOAuthHTTPClient(proxyURL)
+ if err != nil {
+ return nil, err
+ }
return refreshCodexOAuthToken(ctx, client, codexOAuthTokenURL, codexOAuthClientID, refreshToken)
}
func ExchangeCodexAuthorizationCode(ctx context.Context, code string, verifier string) (*CodexOAuthTokenResult, error) {
- client := &http.Client{Timeout: defaultHTTPTimeout}
+ return ExchangeCodexAuthorizationCodeWithProxy(ctx, code, verifier, "")
+}
+
+func ExchangeCodexAuthorizationCodeWithProxy(ctx context.Context, code string, verifier string, proxyURL string) (*CodexOAuthTokenResult, error) {
+ client, err := getCodexOAuthHTTPClient(proxyURL)
+ if err != nil {
+ return nil, err
+ }
return exchangeCodexAuthorizationCode(ctx, client, codexOAuthTokenURL, codexOAuthClientID, code, verifier, codexOAuthRedirectURI)
}
@@ -104,7 +120,7 @@ func refreshCodexOAuthToken(
ExpiresIn int `json:"expires_in"`
}
- if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
+ if err := common.DecodeJson(resp.Body, &payload); err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@@ -165,7 +181,7 @@ func exchangeCodexAuthorizationCode(
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
}
- if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
+ if err := common.DecodeJson(resp.Body, &payload); err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@@ -181,6 +197,19 @@ func exchangeCodexAuthorizationCode(
}, nil
}
+func getCodexOAuthHTTPClient(proxyURL string) (*http.Client, error) {
+ baseClient, err := GetHttpClientWithProxy(strings.TrimSpace(proxyURL))
+ if err != nil {
+ return nil, err
+ }
+ if baseClient == nil {
+ return &http.Client{Timeout: defaultHTTPTimeout}, nil
+ }
+ clientCopy := *baseClient
+ clientCopy.Timeout = defaultHTTPTimeout
+ return &clientCopy, nil
+}
+
func buildCodexAuthorizeURL(state string, challenge string) (string, error) {
u, err := url.Parse(codexOAuthAuthorizeURL)
if err != nil {
diff --git a/service/convert.go b/service/convert.go
index f357f6842a..95acf835ee 100644
--- a/service/convert.go
+++ b/service/convert.go
@@ -10,35 +10,58 @@ import (
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/relay/channel/openrouter"
relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/relay/reasonmap"
+ "github.com/samber/lo"
)
func ClaudeToOpenAIRequest(claudeRequest dto.ClaudeRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error) {
openAIRequest := dto.GeneralOpenAIRequest{
Model: claudeRequest.Model,
- MaxTokens: claudeRequest.MaxTokens,
Temperature: claudeRequest.Temperature,
- TopP: claudeRequest.TopP,
- Stream: claudeRequest.Stream,
+ }
+ if claudeRequest.MaxTokens != nil {
+ openAIRequest.MaxTokens = lo.ToPtr(lo.FromPtr(claudeRequest.MaxTokens))
+ }
+ if claudeRequest.TopP != nil {
+ openAIRequest.TopP = lo.ToPtr(lo.FromPtr(claudeRequest.TopP))
+ }
+ if claudeRequest.TopK != nil {
+ openAIRequest.TopK = lo.ToPtr(lo.FromPtr(claudeRequest.TopK))
+ }
+ if claudeRequest.Stream != nil {
+ openAIRequest.Stream = lo.ToPtr(lo.FromPtr(claudeRequest.Stream))
}
isOpenRouter := info.ChannelType == constant.ChannelTypeOpenRouter
- if claudeRequest.Thinking != nil && claudeRequest.Thinking.Type == "enabled" {
- if isOpenRouter {
- reasoning := openrouter.RequestReasoning{
- MaxTokens: claudeRequest.Thinking.GetBudgetTokens(),
+ if isOpenRouter {
+ if effort := claudeRequest.GetEfforts(); effort != "" {
+ effortBytes, _ := json.Marshal(effort)
+ openAIRequest.Verbosity = effortBytes
+ }
+ if claudeRequest.Thinking != nil {
+ var reasoning openrouter.RequestReasoning
+ if claudeRequest.Thinking.Type == "enabled" {
+ reasoning = openrouter.RequestReasoning{
+ Enabled: true,
+ MaxTokens: claudeRequest.Thinking.GetBudgetTokens(),
+ }
+ } else if claudeRequest.Thinking.Type == "adaptive" {
+ reasoning = openrouter.RequestReasoning{
+ Enabled: true,
+ }
}
reasoningJSON, err := json.Marshal(reasoning)
if err != nil {
return nil, fmt.Errorf("failed to marshal reasoning: %w", err)
}
openAIRequest.Reasoning = reasoningJSON
- } else {
- thinkingSuffix := "-thinking"
- if strings.HasSuffix(info.OriginModelName, thinkingSuffix) &&
- !strings.HasSuffix(openAIRequest.Model, thinkingSuffix) {
- openAIRequest.Model = openAIRequest.Model + thinkingSuffix
- }
+ }
+ } else {
+ thinkingSuffix := "-thinking"
+ if strings.HasSuffix(info.OriginModelName, thinkingSuffix) &&
+ !strings.HasSuffix(openAIRequest.Model, thinkingSuffix) {
+ openAIRequest.Model = openAIRequest.Model + thinkingSuffix
}
}
@@ -126,7 +149,7 @@ func ClaudeToOpenAIRequest(claudeRequest dto.ClaudeRequest, info *relaycommon.Re
for _, mediaMsg := range contents {
switch mediaMsg.Type {
- case "text":
+ case "text", "input_text":
message := dto.MediaContent{
Type: "text",
Text: mediaMsg.GetText(),
@@ -200,12 +223,79 @@ func generateStopBlock(index int) *dto.ClaudeResponse {
}
}
+func buildClaudeUsageFromOpenAIUsage(oaiUsage *dto.Usage) *dto.ClaudeUsage {
+ if oaiUsage == nil {
+ return nil
+ }
+ cacheCreation5m, cacheCreation1h := NormalizeCacheCreationSplit(
+ oaiUsage.PromptTokensDetails.CachedCreationTokens,
+ oaiUsage.ClaudeCacheCreation5mTokens,
+ oaiUsage.ClaudeCacheCreation1hTokens,
+ )
+ usage := &dto.ClaudeUsage{
+ InputTokens: oaiUsage.PromptTokens,
+ OutputTokens: oaiUsage.CompletionTokens,
+ CacheCreationInputTokens: oaiUsage.PromptTokensDetails.CachedCreationTokens,
+ CacheReadInputTokens: oaiUsage.PromptTokensDetails.CachedTokens,
+ }
+ if cacheCreation5m > 0 || cacheCreation1h > 0 {
+ usage.CacheCreation = &dto.ClaudeCacheCreationUsage{
+ Ephemeral5mInputTokens: cacheCreation5m,
+ Ephemeral1hInputTokens: cacheCreation1h,
+ }
+ }
+ return usage
+}
+
+func NormalizeCacheCreationSplit(totalTokens int, tokens5m int, tokens1h int) (int, int) {
+ remainder := lo.Max([]int{totalTokens - tokens5m - tokens1h, 0})
+ return tokens5m + remainder, tokens1h
+}
+
func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) []*dto.ClaudeResponse {
if info.ClaudeConvertInfo.Done {
return nil
}
var claudeResponses []*dto.ClaudeResponse
+ // stopOpenBlocks emits the required content_block_stop event(s) for the currently open block(s)
+ // according to Anthropic's SSE streaming state machine:
+ // content_block_start -> content_block_delta* -> content_block_stop (per index).
+ //
+ // For text/thinking, there is at most one open block at info.ClaudeConvertInfo.Index.
+ // For tools, OpenAI tool_calls can stream multiple parallel tool_use blocks (indexed from 0),
+ // so we may have multiple open blocks and must stop each one explicitly.
+ stopOpenBlocks := func() {
+ switch info.ClaudeConvertInfo.LastMessagesType {
+ case relaycommon.LastMessageTypeText, relaycommon.LastMessageTypeThinking:
+ claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
+ case relaycommon.LastMessageTypeTools:
+ base := info.ClaudeConvertInfo.ToolCallBaseIndex
+ for offset := 0; offset <= info.ClaudeConvertInfo.ToolCallMaxIndexOffset; offset++ {
+ claudeResponses = append(claudeResponses, generateStopBlock(base+offset))
+ }
+ }
+ }
+ // stopOpenBlocksAndAdvance closes the currently open block(s) and advances the content block index
+ // to the next available slot for subsequent content_block_start events.
+ //
+ // This prevents invalid streams where a content_block_delta (e.g. thinking_delta) is emitted for an
+ // index whose active content_block type is different (the typical cause of "Mismatched content block type").
+ stopOpenBlocksAndAdvance := func() {
+ if info.ClaudeConvertInfo.LastMessagesType == relaycommon.LastMessageTypeNone {
+ return
+ }
+ stopOpenBlocks()
+ switch info.ClaudeConvertInfo.LastMessagesType {
+ case relaycommon.LastMessageTypeTools:
+ info.ClaudeConvertInfo.Index = info.ClaudeConvertInfo.ToolCallBaseIndex + info.ClaudeConvertInfo.ToolCallMaxIndexOffset + 1
+ info.ClaudeConvertInfo.ToolCallBaseIndex = 0
+ info.ClaudeConvertInfo.ToolCallMaxIndexOffset = 0
+ default:
+ info.ClaudeConvertInfo.Index++
+ }
+ info.ClaudeConvertInfo.LastMessagesType = relaycommon.LastMessageTypeNone
+ }
if info.SendResponseCount == 1 {
msg := &dto.ClaudeMediaMessage{
Id: openAIResponse.Id,
@@ -227,6 +317,8 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
//})
if openAIResponse.IsToolCall() {
info.ClaudeConvertInfo.LastMessagesType = relaycommon.LastMessageTypeTools
+ info.ClaudeConvertInfo.ToolCallBaseIndex = 0
+ info.ClaudeConvertInfo.ToolCallMaxIndexOffset = 0
var toolCall dto.ToolCallResponse
if len(openAIResponse.Choices) > 0 && len(openAIResponse.Choices[0].Delta.ToolCalls) > 0 {
toolCall = openAIResponse.Choices[0].Delta.ToolCalls[0]
@@ -251,8 +343,9 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
claudeResponses = append(claudeResponses, resp)
// 首块包含工具 delta,则追加 input_json_delta
if toolCall.Function.Arguments != "" {
+ idx := 0
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx,
Type: "content_block_delta",
Delta: &dto.ClaudeMediaMessage{
Type: "input_json_delta",
@@ -269,16 +362,21 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
content := openAIResponse.Choices[0].Delta.GetContentString()
if reasoning != "" {
+ if info.ClaudeConvertInfo.LastMessagesType != relaycommon.LastMessageTypeThinking {
+ stopOpenBlocksAndAdvance()
+ }
+ idx := info.ClaudeConvertInfo.Index
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx,
Type: "content_block_start",
ContentBlock: &dto.ClaudeMediaMessage{
Type: "thinking",
Thinking: common.GetPointer[string](""),
},
})
+ idx2 := idx
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx2,
Type: "content_block_delta",
Delta: &dto.ClaudeMediaMessage{
Type: "thinking_delta",
@@ -287,16 +385,21 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
})
info.ClaudeConvertInfo.LastMessagesType = relaycommon.LastMessageTypeThinking
} else if content != "" {
+ if info.ClaudeConvertInfo.LastMessagesType != relaycommon.LastMessageTypeText {
+ stopOpenBlocksAndAdvance()
+ }
+ idx := info.ClaudeConvertInfo.Index
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx,
Type: "content_block_start",
ContentBlock: &dto.ClaudeMediaMessage{
Type: "text",
Text: common.GetPointer[string](""),
},
})
+ idx2 := idx
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx2,
Type: "content_block_delta",
Delta: &dto.ClaudeMediaMessage{
Type: "text_delta",
@@ -310,20 +413,15 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
// 如果首块就带 finish_reason,需要立即发送停止块
if len(openAIResponse.Choices) > 0 && openAIResponse.Choices[0].FinishReason != nil && *openAIResponse.Choices[0].FinishReason != "" {
info.FinishReason = *openAIResponse.Choices[0].FinishReason
- claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
+ stopOpenBlocks()
oaiUsage := openAIResponse.Usage
if oaiUsage == nil {
oaiUsage = info.ClaudeConvertInfo.Usage
}
if oaiUsage != nil {
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Type: "message_delta",
- Usage: &dto.ClaudeUsage{
- InputTokens: oaiUsage.PromptTokens,
- OutputTokens: oaiUsage.CompletionTokens,
- CacheCreationInputTokens: oaiUsage.PromptTokensDetails.CachedCreationTokens,
- CacheReadInputTokens: oaiUsage.PromptTokensDetails.CachedTokens,
- },
+ Type: "message_delta",
+ Usage: buildClaudeUsageFromOpenAIUsage(oaiUsage),
Delta: &dto.ClaudeMediaMessage{
StopReason: common.GetPointer[string](stopReasonOpenAI2Claude(info.FinishReason)),
},
@@ -338,28 +436,28 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
}
if len(openAIResponse.Choices) == 0 {
- // no choices
- // 可能为非标准的 OpenAI 响应,判断是否已经完成
- if info.ClaudeConvertInfo.Done {
- claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
- oaiUsage := info.ClaudeConvertInfo.Usage
- if oaiUsage != nil {
- claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Type: "message_delta",
- Usage: &dto.ClaudeUsage{
- InputTokens: oaiUsage.PromptTokens,
- OutputTokens: oaiUsage.CompletionTokens,
- CacheCreationInputTokens: oaiUsage.PromptTokensDetails.CachedCreationTokens,
- CacheReadInputTokens: oaiUsage.PromptTokensDetails.CachedTokens,
- },
- Delta: &dto.ClaudeMediaMessage{
- StopReason: common.GetPointer[string](stopReasonOpenAI2Claude(info.FinishReason)),
- },
- })
+ // Some OpenAI-compatible upstreams end with a usage-only SSE chunk.
+ oaiUsage := openAIResponse.Usage
+ if oaiUsage == nil {
+ oaiUsage = info.ClaudeConvertInfo.Usage
+ }
+ if oaiUsage != nil {
+ stopOpenBlocks()
+ stopReason := stopReasonOpenAI2Claude(info.FinishReason)
+ if stopReason == "" {
+ stopReason = "end_turn"
}
+ claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
+ Type: "message_delta",
+ Usage: buildClaudeUsageFromOpenAIUsage(oaiUsage),
+ Delta: &dto.ClaudeMediaMessage{
+ StopReason: common.GetPointer[string](stopReason),
+ },
+ })
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
Type: "message_stop",
})
+ info.ClaudeConvertInfo.Done = true
}
return claudeResponses
} else {
@@ -367,6 +465,13 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
doneChunk := chosenChoice.FinishReason != nil && *chosenChoice.FinishReason != ""
if doneChunk {
info.FinishReason = *chosenChoice.FinishReason
+ oaiUsage := openAIResponse.Usage
+ if oaiUsage == nil {
+ oaiUsage = info.ClaudeConvertInfo.Usage
+ // Some upstreams emit finish_reason first, then send a final usage-only chunk.
+ // Defer closing until usage is available so the final message_delta carries it.
+ return claudeResponses
+ }
}
var claudeResponse dto.ClaudeResponse
@@ -375,18 +480,25 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
if len(chosenChoice.Delta.ToolCalls) > 0 {
toolCalls := chosenChoice.Delta.ToolCalls
if info.ClaudeConvertInfo.LastMessagesType != relaycommon.LastMessageTypeTools {
- claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
- info.ClaudeConvertInfo.Index++
+ stopOpenBlocksAndAdvance()
+ info.ClaudeConvertInfo.ToolCallBaseIndex = info.ClaudeConvertInfo.Index
+ info.ClaudeConvertInfo.ToolCallMaxIndexOffset = 0
}
info.ClaudeConvertInfo.LastMessagesType = relaycommon.LastMessageTypeTools
+ base := info.ClaudeConvertInfo.ToolCallBaseIndex
+ maxOffset := info.ClaudeConvertInfo.ToolCallMaxIndexOffset
for i, toolCall := range toolCalls {
- blockIndex := info.ClaudeConvertInfo.Index
+ offset := 0
if toolCall.Index != nil {
- blockIndex = *toolCall.Index
- } else if len(toolCalls) > 1 {
- blockIndex = info.ClaudeConvertInfo.Index + i
+ offset = *toolCall.Index
+ } else {
+ offset = i
}
+ if offset > maxOffset {
+ maxOffset = offset
+ }
+ blockIndex := base + offset
idx := blockIndex
if toolCall.Function.Name != "" {
@@ -412,17 +524,19 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
},
})
}
-
- info.ClaudeConvertInfo.Index = blockIndex
}
+ info.ClaudeConvertInfo.ToolCallMaxIndexOffset = maxOffset
+ info.ClaudeConvertInfo.Index = base + maxOffset
} else {
reasoning := chosenChoice.Delta.GetReasoningContent()
textContent := chosenChoice.Delta.GetContentString()
if reasoning != "" || textContent != "" {
if reasoning != "" {
if info.ClaudeConvertInfo.LastMessagesType != relaycommon.LastMessageTypeThinking {
+ stopOpenBlocksAndAdvance()
+ idx := info.ClaudeConvertInfo.Index
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx,
Type: "content_block_start",
ContentBlock: &dto.ClaudeMediaMessage{
Type: "thinking",
@@ -437,12 +551,10 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
}
} else {
if info.ClaudeConvertInfo.LastMessagesType != relaycommon.LastMessageTypeText {
- if info.ClaudeConvertInfo.LastMessagesType == relaycommon.LastMessageTypeThinking || info.ClaudeConvertInfo.LastMessagesType == relaycommon.LastMessageTypeTools {
- claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
- info.ClaudeConvertInfo.Index++
- }
+ stopOpenBlocksAndAdvance()
+ idx := info.ClaudeConvertInfo.Index
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Index: &info.ClaudeConvertInfo.Index,
+ Index: &idx,
Type: "content_block_start",
ContentBlock: &dto.ClaudeMediaMessage{
Type: "text",
@@ -461,26 +573,21 @@ func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamRespon
}
}
- claudeResponse.Index = &info.ClaudeConvertInfo.Index
+ claudeResponse.Index = common.GetPointer[int](info.ClaudeConvertInfo.Index)
if !isEmpty && claudeResponse.Delta != nil {
claudeResponses = append(claudeResponses, &claudeResponse)
}
if doneChunk || info.ClaudeConvertInfo.Done {
- claudeResponses = append(claudeResponses, generateStopBlock(info.ClaudeConvertInfo.Index))
+ stopOpenBlocks()
oaiUsage := openAIResponse.Usage
if oaiUsage == nil {
oaiUsage = info.ClaudeConvertInfo.Usage
}
if oaiUsage != nil {
claudeResponses = append(claudeResponses, &dto.ClaudeResponse{
- Type: "message_delta",
- Usage: &dto.ClaudeUsage{
- InputTokens: oaiUsage.PromptTokens,
- OutputTokens: oaiUsage.CompletionTokens,
- CacheCreationInputTokens: oaiUsage.PromptTokensDetails.CachedCreationTokens,
- CacheReadInputTokens: oaiUsage.PromptTokensDetails.CachedTokens,
- },
+ Type: "message_delta",
+ Usage: buildClaudeUsageFromOpenAIUsage(oaiUsage),
Delta: &dto.ClaudeMediaMessage{
StopReason: common.GetPointer[string](stopReasonOpenAI2Claude(info.FinishReason)),
},
@@ -531,29 +638,13 @@ func ResponseOpenAI2Claude(openAIResponse *dto.OpenAITextResponse, info *relayco
}
claudeResponse.Content = contents
claudeResponse.StopReason = stopReason
- claudeResponse.Usage = &dto.ClaudeUsage{
- InputTokens: openAIResponse.PromptTokens,
- OutputTokens: openAIResponse.CompletionTokens,
- }
+ claudeResponse.Usage = buildClaudeUsageFromOpenAIUsage(&openAIResponse.Usage)
return claudeResponse
}
func stopReasonOpenAI2Claude(reason string) string {
- switch reason {
- case "stop":
- return "end_turn"
- case "stop_sequence":
- return "stop_sequence"
- case "length":
- fallthrough
- case "max_tokens":
- return "max_tokens"
- case "tool_calls":
- return "tool_use"
- default:
- return reason
- }
+ return reasonmap.OpenAIFinishReasonToClaudeStopReason(reason)
}
func toJSONString(v interface{}) string {
@@ -567,7 +658,7 @@ func toJSONString(v interface{}) string {
func GeminiToOpenAIRequest(geminiRequest *dto.GeminiChatRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error) {
openaiRequest := &dto.GeneralOpenAIRequest{
Model: info.UpstreamModelName,
- Stream: info.IsStream,
+ Stream: lo.ToPtr(info.IsStream),
}
// 转换 messages
@@ -652,21 +743,21 @@ func GeminiToOpenAIRequest(geminiRequest *dto.GeminiChatRequest, info *relaycomm
if geminiRequest.GenerationConfig.Temperature != nil {
openaiRequest.Temperature = geminiRequest.GenerationConfig.Temperature
}
- if geminiRequest.GenerationConfig.TopP > 0 {
- openaiRequest.TopP = geminiRequest.GenerationConfig.TopP
+ if geminiRequest.GenerationConfig.TopP != nil && *geminiRequest.GenerationConfig.TopP > 0 {
+ openaiRequest.TopP = lo.ToPtr(*geminiRequest.GenerationConfig.TopP)
}
- if geminiRequest.GenerationConfig.TopK > 0 {
- openaiRequest.TopK = int(geminiRequest.GenerationConfig.TopK)
+ if geminiRequest.GenerationConfig.TopK != nil && *geminiRequest.GenerationConfig.TopK > 0 {
+ openaiRequest.TopK = lo.ToPtr(int(*geminiRequest.GenerationConfig.TopK))
}
- if geminiRequest.GenerationConfig.MaxOutputTokens > 0 {
- openaiRequest.MaxTokens = geminiRequest.GenerationConfig.MaxOutputTokens
+ if geminiRequest.GenerationConfig.MaxOutputTokens != nil && *geminiRequest.GenerationConfig.MaxOutputTokens > 0 {
+ openaiRequest.MaxTokens = lo.ToPtr(*geminiRequest.GenerationConfig.MaxOutputTokens)
}
// gemini stop sequences 最多 5 个,openai stop 最多 4 个
if len(geminiRequest.GenerationConfig.StopSequences) > 0 {
openaiRequest.Stop = geminiRequest.GenerationConfig.StopSequences[:4]
}
- if geminiRequest.GenerationConfig.CandidateCount > 0 {
- openaiRequest.N = geminiRequest.GenerationConfig.CandidateCount
+ if geminiRequest.GenerationConfig.CandidateCount != nil && *geminiRequest.GenerationConfig.CandidateCount > 0 {
+ openaiRequest.N = lo.ToPtr(*geminiRequest.GenerationConfig.CandidateCount)
}
// 转换工具调用
diff --git a/service/error.go b/service/error.go
index 889964beb7..a2ff0aad79 100644
--- a/service/error.go
+++ b/service/error.go
@@ -2,9 +2,11 @@ package service
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
+ "math"
"net/http"
"strconv"
"strings"
@@ -127,10 +129,13 @@ func RelayErrorHandler(ctx context.Context, resp *http.Response, showBodyWhenFai
}
func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string) {
+ if newApiErr == nil {
+ return
+ }
if statusCodeMappingStr == "" || statusCodeMappingStr == "{}" {
return
}
- statusCodeMapping := make(map[string]string)
+ statusCodeMapping := make(map[string]any)
err := common.Unmarshal([]byte(statusCodeMappingStr), &statusCodeMapping)
if err != nil {
return
@@ -139,12 +144,44 @@ func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string)
return
}
codeStr := strconv.Itoa(newApiErr.StatusCode)
- if _, ok := statusCodeMapping[codeStr]; ok {
- intCode, _ := strconv.Atoi(statusCodeMapping[codeStr])
+ if value, ok := statusCodeMapping[codeStr]; ok {
+ intCode, ok := parseStatusCodeMappingValue(value)
+ if !ok {
+ return
+ }
newApiErr.StatusCode = intCode
}
}
+func parseStatusCodeMappingValue(value any) (int, bool) {
+ switch v := value.(type) {
+ case string:
+ if v == "" {
+ return 0, false
+ }
+ statusCode, err := strconv.Atoi(v)
+ if err != nil {
+ return 0, false
+ }
+ return statusCode, true
+ case float64:
+ if v != math.Trunc(v) {
+ return 0, false
+ }
+ return int(v), true
+ case int:
+ return v, true
+ case json.Number:
+ statusCode, err := strconv.Atoi(v.String())
+ if err != nil {
+ return 0, false
+ }
+ return statusCode, true
+ default:
+ return 0, false
+ }
+}
+
func TaskErrorWrapperLocal(err error, code string, statusCode int) *dto.TaskError {
openaiErr := TaskErrorWrapper(err, code, statusCode)
openaiErr.LocalError = true
@@ -169,3 +206,16 @@ func TaskErrorWrapper(err error, code string, statusCode int) *dto.TaskError {
return taskError
}
+
+// TaskErrorFromAPIError 将 PreConsumeBilling 返回的 NewAPIError 转换为 TaskError。
+func TaskErrorFromAPIError(apiErr *types.NewAPIError) *dto.TaskError {
+ if apiErr == nil {
+ return nil
+ }
+ return &dto.TaskError{
+ Code: string(apiErr.GetErrorCode()),
+ Message: apiErr.Err.Error(),
+ StatusCode: apiErr.StatusCode,
+ Error: apiErr.Err,
+ }
+}
diff --git a/service/error_test.go b/service/error_test.go
new file mode 100644
index 0000000000..2303e8f4a1
--- /dev/null
+++ b/service/error_test.go
@@ -0,0 +1,57 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/QuantumNous/new-api/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestResetStatusCode(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ statusCode int
+ statusCodeConfig string
+ expectedCode int
+ }{
+ {
+ name: "map string value",
+ statusCode: 429,
+ statusCodeConfig: `{"429":"503"}`,
+ expectedCode: 503,
+ },
+ {
+ name: "map int value",
+ statusCode: 429,
+ statusCodeConfig: `{"429":503}`,
+ expectedCode: 503,
+ },
+ {
+ name: "skip invalid string value",
+ statusCode: 429,
+ statusCodeConfig: `{"429":"bad-code"}`,
+ expectedCode: 429,
+ },
+ {
+ name: "skip status code 200",
+ statusCode: 200,
+ statusCodeConfig: `{"200":503}`,
+ expectedCode: 200,
+ },
+ }
+
+ for _, tc := range testCases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ newAPIError := &types.NewAPIError{
+ StatusCode: tc.statusCode,
+ }
+ ResetStatusCode(newAPIError, tc.statusCodeConfig)
+ require.Equal(t, tc.expectedCode, newAPIError.StatusCode)
+ })
+ }
+}
diff --git a/service/file_decoder.go b/service/file_decoder.go
index 4ca139794a..57898af7d7 100644
--- a/service/file_decoder.go
+++ b/service/file_decoder.go
@@ -2,7 +2,6 @@ package service
import (
"bytes"
- "encoding/base64"
"fmt"
"image"
_ "image/gif"
@@ -13,7 +12,6 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
- "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/types"
@@ -106,6 +104,11 @@ func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, e
return sniffed, nil
}
+ // Try HEIF/HEIC detection (Go standard library doesn't recognize it)
+ if heifMime := detectHEIF(readData); heifMime != "" {
+ return heifMime, nil
+ }
+
if _, format, err := image.DecodeConfig(bytes.NewReader(readData)); err == nil {
switch strings.ToLower(format) {
case "jpeg", "jpg":
@@ -130,90 +133,27 @@ func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, e
return "application/octet-stream", nil
}
+// GetFileBase64FromUrl 从 URL 获取文件的 base64 编码数据
+// Deprecated: 请使用 GetBase64Data 配合 types.NewURLFileSource 替代
+// 此函数保留用于向后兼容,内部已重构为调用统一的文件服务
func GetFileBase64FromUrl(c *gin.Context, url string, reason ...string) (*types.LocalFileData, error) {
- contextKey := fmt.Sprintf("file_download_%s", common.GenerateHMAC(url))
-
- // Check if the file has already been downloaded in this request
- if cachedData, exists := c.Get(contextKey); exists {
- if common.DebugEnabled {
- logger.LogDebug(c, fmt.Sprintf("Using cached file data for URL: %s", url))
- }
- return cachedData.(*types.LocalFileData), nil
- }
-
- var maxFileSize = constant.MaxFileDownloadMB * 1024 * 1024
-
- resp, err := DoDownloadRequest(url, reason...)
+ source := types.NewURLFileSource(url)
+ cachedData, err := LoadFileSource(c, source, reason...)
if err != nil {
return nil, err
}
- defer resp.Body.Close()
- // Always use LimitReader to prevent oversized downloads
- fileBytes, err := io.ReadAll(io.LimitReader(resp.Body, int64(maxFileSize+1)))
+ // 转换为旧的 LocalFileData 格式以保持兼容
+ base64Data, err := cachedData.GetBase64Data()
if err != nil {
return nil, err
}
- // Check actual size after reading
- if len(fileBytes) > maxFileSize {
- return nil, fmt.Errorf("file size exceeds maximum allowed size: %dMB", constant.MaxFileDownloadMB)
- }
-
- // Convert to base64
- base64Data := base64.StdEncoding.EncodeToString(fileBytes)
-
- mimeType := resp.Header.Get("Content-Type")
- if len(strings.Split(mimeType, ";")) > 1 {
- // If Content-Type has parameters, take the first part
- mimeType = strings.Split(mimeType, ";")[0]
- }
- if mimeType == "application/octet-stream" {
- logger.LogDebug(c, fmt.Sprintf("MIME type is application/octet-stream for URL: %s", url))
- // try to guess the MIME type from the url last segment
- urlParts := strings.Split(url, "/")
- if len(urlParts) > 0 {
- lastSegment := urlParts[len(urlParts)-1]
- if strings.Contains(lastSegment, ".") {
- // Extract the file extension
- filename := strings.Split(lastSegment, ".")
- if len(filename) > 1 {
- ext := strings.ToLower(filename[len(filename)-1])
- // Guess MIME type based on file extension
- mimeType = GetMimeTypeByExtension(ext)
- }
- }
- } else {
- // try to guess the MIME type from the file extension
- fileName := resp.Header.Get("Content-Disposition")
- if fileName != "" {
- // Extract the filename from the Content-Disposition header
- parts := strings.Split(fileName, ";")
- for _, part := range parts {
- if strings.HasPrefix(strings.TrimSpace(part), "filename=") {
- fileName = strings.TrimSpace(strings.TrimPrefix(part, "filename="))
- // Remove quotes if present
- if len(fileName) > 2 && fileName[0] == '"' && fileName[len(fileName)-1] == '"' {
- fileName = fileName[1 : len(fileName)-1]
- }
- // Guess MIME type based on file extension
- if ext := strings.ToLower(strings.TrimPrefix(fileName, ".")); ext != "" {
- mimeType = GetMimeTypeByExtension(ext)
- }
- break
- }
- }
- }
- }
- }
- data := &types.LocalFileData{
+ return &types.LocalFileData{
Base64Data: base64Data,
- MimeType: mimeType,
- Size: int64(len(fileBytes)),
- }
- // Store the file data in the context to avoid re-downloading
- c.Set(contextKey, data)
-
- return data, nil
+ MimeType: cachedData.MimeType,
+ Size: cachedData.Size,
+ Url: url,
+ }, nil
}
func GetMimeTypeByExtension(ext string) string {
@@ -231,6 +171,12 @@ func GetMimeTypeByExtension(ext string) string {
return "image/png"
case "gif":
return "image/gif"
+ case "jfif":
+ return "image/jpeg"
+ case "heic":
+ return "image/heic"
+ case "heif":
+ return "image/heif"
// Audio files
case "mp3":
diff --git a/service/file_service.go b/service/file_service.go
new file mode 100644
index 0000000000..bcf4744224
--- /dev/null
+++ b/service/file_service.go
@@ -0,0 +1,607 @@
+package service
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/binary"
+ "fmt"
+ "image"
+ _ "image/gif"
+ _ "image/jpeg"
+ _ "image/png"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+ "golang.org/x/image/webp"
+)
+
+// FileService 统一的文件处理服务
+// 提供文件下载、解码、缓存等功能的统一入口
+
+// getContextCacheKey 生成 URL context 缓存的 key
+func getContextCacheKey(url string) string {
+ return fmt.Sprintf("file_cache_%s", common.GenerateHMAC(url))
+}
+
+// getBase64ContextCacheKey 生成 base64 context 缓存的 key
+// 使用 length + MIME + 前 128 字符作为输入,避免对整个 base64 数据做 hash
+func getBase64ContextCacheKey(data string, mimeType string) string {
+ keyMaterial := fmt.Sprintf("%d:%s:", len(data), mimeType)
+ if len(data) > 128 {
+ keyMaterial += data[:128]
+ } else {
+ keyMaterial += data
+ }
+ return fmt.Sprintf("b64_cache_%s", common.GenerateHMAC(keyMaterial))
+}
+
+// LoadFileSource 加载文件源数据
+// 这是统一的入口,会自动处理缓存和不同的来源类型
+func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (*types.CachedFileData, error) {
+ if source == nil {
+ return nil, fmt.Errorf("file source is nil")
+ }
+
+ if common.DebugEnabled {
+ logger.LogDebug(c, fmt.Sprintf("LoadFileSource starting for: %s", source.GetIdentifier()))
+ }
+
+ // 1. 快速检查内部缓存
+ if source.HasCache() {
+ if c != nil {
+ registerSourceForCleanup(c, source)
+ }
+ return source.GetCache(), nil
+ }
+
+ // 2. 加锁保护加载过程
+ source.Mu().Lock()
+ defer source.Mu().Unlock()
+
+ // 3. 双重检查
+ if source.HasCache() {
+ if c != nil {
+ registerSourceForCleanup(c, source)
+ }
+ return source.GetCache(), nil
+ }
+
+ // 4. 根据来源类型加载(含 URL context 缓存查找)
+ var cachedData *types.CachedFileData
+ var contextKey string
+ var err error
+
+ switch s := source.(type) {
+ case *types.URLSource:
+ if c != nil {
+ contextKey = getContextCacheKey(s.URL)
+ if cached, exists := c.Get(contextKey); exists {
+ data := cached.(*types.CachedFileData)
+ source.SetCache(data)
+ registerSourceForCleanup(c, source)
+ return data, nil
+ }
+ }
+ cachedData, err = loadFromURL(c, s.URL, reason...)
+ case *types.Base64Source:
+ if c != nil {
+ contextKey = getBase64ContextCacheKey(s.Base64Data, s.MimeType)
+ if cached, exists := c.Get(contextKey); exists {
+ data := cached.(*types.CachedFileData)
+ source.SetCache(data)
+ registerSourceForCleanup(c, source)
+ return data, nil
+ }
+ }
+ cachedData, err = loadFromBase64(s.Base64Data, s.MimeType)
+ default:
+ return nil, fmt.Errorf("unsupported file source type: %T", source)
+ }
+
+ if err != nil {
+ return nil, err
+ }
+
+ // 5. 设置缓存
+ source.SetCache(cachedData)
+ if contextKey != "" && c != nil {
+ c.Set(contextKey, cachedData)
+ }
+
+ // 6. 注册到 context 以便请求结束时自动清理
+ if c != nil {
+ registerSourceForCleanup(c, source)
+ }
+
+ return cachedData, nil
+}
+
+// registerSourceForCleanup 注册 FileSource 到 context 以便请求结束时清理
+func registerSourceForCleanup(c *gin.Context, source types.FileSource) {
+ if source.IsRegistered() {
+ return
+ }
+
+ key := string(constant.ContextKeyFileSourcesToCleanup)
+ var sources []types.FileSource
+ if existing, exists := c.Get(key); exists {
+ sources = existing.([]types.FileSource)
+ }
+ sources = append(sources, source)
+ c.Set(key, sources)
+ source.SetRegistered(true)
+}
+
+// CleanupFileSources 清理请求中所有注册的 FileSource
+// 应在请求结束时调用(通常由中间件自动调用)
+func CleanupFileSources(c *gin.Context) {
+ key := string(constant.ContextKeyFileSourcesToCleanup)
+ if sources, exists := c.Get(key); exists {
+ for _, source := range sources.([]types.FileSource) {
+ if cache := source.GetCache(); cache != nil {
+ cache.Close()
+ }
+ }
+ c.Set(key, nil)
+ }
+}
+
+// loadFromURL 从 URL 加载文件
+func loadFromURL(c *gin.Context, url string, reason ...string) (*types.CachedFileData, error) {
+ // 下载文件
+ var maxFileSize = constant.MaxFileDownloadMB * 1024 * 1024
+
+ if common.DebugEnabled {
+ logger.LogDebug(c, "loadFromURL: initiating download")
+ }
+ resp, err := DoDownloadRequest(url, reason...)
+ if err != nil {
+ return nil, fmt.Errorf("failed to download file from %s: %w", url, err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != 200 {
+ return nil, fmt.Errorf("failed to download file, status code: %d", resp.StatusCode)
+ }
+
+ // 读取文件内容(限制大小)
+ if common.DebugEnabled {
+ logger.LogDebug(c, "loadFromURL: reading response body")
+ }
+ fileBytes, err := io.ReadAll(io.LimitReader(resp.Body, int64(maxFileSize+1)))
+ if err != nil {
+ return nil, fmt.Errorf("failed to read file content: %w", err)
+ }
+ if len(fileBytes) > maxFileSize {
+ return nil, fmt.Errorf("file size exceeds maximum allowed size: %dMB", constant.MaxFileDownloadMB)
+ }
+
+ // 转换为 base64
+ base64Data := base64.StdEncoding.EncodeToString(fileBytes)
+
+ // 智能获取 MIME 类型
+ mimeType := smartDetectMimeType(resp, url, fileBytes)
+
+ // 判断是否使用磁盘缓存
+ base64Size := int64(len(base64Data))
+ var cachedData *types.CachedFileData
+
+ if shouldUseDiskCache(base64Size) {
+ // 使用磁盘缓存
+ diskPath, err := writeToDiskCache(base64Data)
+ if err != nil {
+ // 磁盘缓存失败,回退到内存
+ logger.LogWarn(c, fmt.Sprintf("Failed to write to disk cache, falling back to memory: %v", err))
+ cachedData = types.NewMemoryCachedData(base64Data, mimeType, int64(len(fileBytes)))
+ } else {
+ cachedData = types.NewDiskCachedData(diskPath, mimeType, int64(len(fileBytes)))
+ cachedData.DiskSize = base64Size
+ cachedData.OnClose = func(size int64) {
+ common.DecrementDiskFiles(size)
+ }
+ common.IncrementDiskFiles(base64Size)
+ if common.DebugEnabled {
+ logger.LogDebug(c, fmt.Sprintf("File cached to disk: %s, size: %d bytes", diskPath, base64Size))
+ }
+ }
+ } else {
+ // 使用内存缓存
+ cachedData = types.NewMemoryCachedData(base64Data, mimeType, int64(len(fileBytes)))
+ }
+
+ // 如果是图片,尝试获取图片配置
+ if strings.HasPrefix(mimeType, "image/") {
+ if common.DebugEnabled {
+ logger.LogDebug(c, "loadFromURL: decoding image config")
+ }
+ config, format, err := decodeImageConfig(fileBytes)
+ if err == nil {
+ cachedData.ImageConfig = &config
+ cachedData.ImageFormat = format
+ // 如果通过图片解码获取了更准确的格式,更新 MIME 类型
+ if mimeType == "application/octet-stream" || mimeType == "" {
+ cachedData.MimeType = "image/" + format
+ }
+ }
+ }
+
+ return cachedData, nil
+}
+
+// shouldUseDiskCache 判断是否应该使用磁盘缓存
+func shouldUseDiskCache(dataSize int64) bool {
+ return common.ShouldUseDiskCache(dataSize)
+}
+
+// writeToDiskCache 将数据写入磁盘缓存
+func writeToDiskCache(base64Data string) (string, error) {
+ return common.WriteDiskCacheFileString(common.DiskCacheTypeFile, base64Data)
+}
+
+// smartDetectMimeType 智能检测 MIME 类型
+func smartDetectMimeType(resp *http.Response, url string, fileBytes []byte) string {
+ // 1. 尝试从 Content-Type header 获取
+ mimeType := resp.Header.Get("Content-Type")
+ if idx := strings.Index(mimeType, ";"); idx != -1 {
+ mimeType = strings.TrimSpace(mimeType[:idx])
+ }
+ if mimeType != "" && mimeType != "application/octet-stream" {
+ return mimeType
+ }
+
+ // 2. 尝试从 Content-Disposition header 的 filename 获取
+ if cd := resp.Header.Get("Content-Disposition"); cd != "" {
+ parts := strings.Split(cd, ";")
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+ if strings.HasPrefix(strings.ToLower(part), "filename=") {
+ name := strings.TrimSpace(strings.TrimPrefix(part, "filename="))
+ // 移除引号
+ if len(name) > 2 && name[0] == '"' && name[len(name)-1] == '"' {
+ name = name[1 : len(name)-1]
+ }
+ if dot := strings.LastIndex(name, "."); dot != -1 && dot+1 < len(name) {
+ ext := strings.ToLower(name[dot+1:])
+ if ext != "" {
+ mt := GetMimeTypeByExtension(ext)
+ if mt != "application/octet-stream" {
+ return mt
+ }
+ }
+ }
+ break
+ }
+ }
+ }
+
+ // 3. 尝试从 URL 路径获取扩展名
+ mt := guessMimeTypeFromURL(url)
+ if mt != "application/octet-stream" {
+ return mt
+ }
+
+ // 4. 使用 http.DetectContentType 内容嗅探
+ if len(fileBytes) > 0 {
+ sniffed := http.DetectContentType(fileBytes)
+ if sniffed != "" && sniffed != "application/octet-stream" {
+ // 去除可能的 charset 参数
+ if idx := strings.Index(sniffed, ";"); idx != -1 {
+ sniffed = strings.TrimSpace(sniffed[:idx])
+ }
+ return sniffed
+ }
+
+ // 4.5 尝试 HEIF/HEIC 检测(Go 标准库不识别)
+ if heifMime := detectHEIF(fileBytes); heifMime != "" {
+ return heifMime
+ }
+ }
+
+ // 5. 尝试作为图片解码获取格式
+ if len(fileBytes) > 0 {
+ if _, format, err := decodeImageConfig(fileBytes); err == nil && format != "" {
+ return "image/" + strings.ToLower(format)
+ }
+ }
+
+ // 最终回退
+ return "application/octet-stream"
+}
+
+// loadFromBase64 从 base64 字符串加载文件
+func loadFromBase64(base64String string, providedMimeType string) (*types.CachedFileData, error) {
+ var mimeType string
+ var cleanBase64 string
+
+ // 处理 data: 前缀
+ if strings.HasPrefix(base64String, "data:") {
+ idx := strings.Index(base64String, ",")
+ if idx != -1 {
+ header := base64String[:idx]
+ cleanBase64 = base64String[idx+1:]
+
+ if strings.Contains(header, ":") && strings.Contains(header, ";") {
+ mimeStart := strings.Index(header, ":") + 1
+ mimeEnd := strings.Index(header, ";")
+ if mimeStart < mimeEnd {
+ mimeType = header[mimeStart:mimeEnd]
+ }
+ }
+ } else {
+ cleanBase64 = base64String
+ }
+ } else {
+ cleanBase64 = base64String
+ }
+
+ if providedMimeType != "" {
+ mimeType = providedMimeType
+ }
+
+ decodedData, err := base64.StdEncoding.DecodeString(cleanBase64)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode base64 data: %w", err)
+ }
+
+ base64Size := int64(len(cleanBase64))
+ var cachedData *types.CachedFileData
+
+ if shouldUseDiskCache(base64Size) {
+ diskPath, err := writeToDiskCache(cleanBase64)
+ if err != nil {
+ cachedData = types.NewMemoryCachedData(cleanBase64, mimeType, int64(len(decodedData)))
+ } else {
+ cachedData = types.NewDiskCachedData(diskPath, mimeType, int64(len(decodedData)))
+ cachedData.DiskSize = base64Size
+ cachedData.OnClose = func(size int64) {
+ common.DecrementDiskFiles(size)
+ }
+ common.IncrementDiskFiles(base64Size)
+ }
+ } else {
+ cachedData = types.NewMemoryCachedData(cleanBase64, mimeType, int64(len(decodedData)))
+ }
+
+ if mimeType == "" || strings.HasPrefix(mimeType, "image/") {
+ config, format, err := decodeImageConfig(decodedData)
+ if err == nil {
+ cachedData.ImageConfig = &config
+ cachedData.ImageFormat = format
+ if mimeType == "" {
+ cachedData.MimeType = "image/" + format
+ }
+ }
+ }
+
+ return cachedData, nil
+}
+
+// GetImageConfig 获取图片配置
+func GetImageConfig(c *gin.Context, source types.FileSource) (image.Config, string, error) {
+ cachedData, err := LoadFileSource(c, source, "get_image_config")
+ if err != nil {
+ return image.Config{}, "", err
+ }
+
+ if cachedData.ImageConfig != nil {
+ return *cachedData.ImageConfig, cachedData.ImageFormat, nil
+ }
+
+ base64Str, err := cachedData.GetBase64Data()
+ if err != nil {
+ return image.Config{}, "", fmt.Errorf("failed to get base64 data: %w", err)
+ }
+ decodedData, err := base64.StdEncoding.DecodeString(base64Str)
+ if err != nil {
+ return image.Config{}, "", fmt.Errorf("failed to decode base64 for image config: %w", err)
+ }
+
+ config, format, err := decodeImageConfig(decodedData)
+ if err != nil {
+ return image.Config{}, "", err
+ }
+
+ cachedData.ImageConfig = &config
+ cachedData.ImageFormat = format
+
+ return config, format, nil
+}
+
+// GetBase64Data 获取 base64 编码的数据
+func GetBase64Data(c *gin.Context, source types.FileSource, reason ...string) (string, string, error) {
+ cachedData, err := LoadFileSource(c, source, reason...)
+ if err != nil {
+ return "", "", err
+ }
+ base64Str, err := cachedData.GetBase64Data()
+ if err != nil {
+ return "", "", fmt.Errorf("failed to get base64 data: %w", err)
+ }
+ return base64Str, cachedData.MimeType, nil
+}
+
+// GetMimeType 获取文件的 MIME 类型
+func GetMimeType(c *gin.Context, source types.FileSource) (string, error) {
+ if source.HasCache() {
+ return source.GetCache().MimeType, nil
+ }
+
+ if urlSource, ok := source.(*types.URLSource); ok {
+ mimeType, err := GetFileTypeFromUrl(c, urlSource.URL, "get_mime_type")
+ if err == nil && mimeType != "" && mimeType != "application/octet-stream" {
+ return mimeType, nil
+ }
+ }
+
+ cachedData, err := LoadFileSource(c, source, "get_mime_type")
+ if err != nil {
+ return "", err
+ }
+ return cachedData.MimeType, nil
+}
+
+// DetectFileType 检测文件类型
+func DetectFileType(mimeType string) types.FileType {
+ if strings.HasPrefix(mimeType, "image/") {
+ return types.FileTypeImage
+ }
+ if strings.HasPrefix(mimeType, "audio/") {
+ return types.FileTypeAudio
+ }
+ if strings.HasPrefix(mimeType, "video/") {
+ return types.FileTypeVideo
+ }
+ return types.FileTypeFile
+}
+
+// decodeImageConfig 从字节数据解码图片配置
+func decodeImageConfig(data []byte) (image.Config, string, error) {
+ reader := bytes.NewReader(data)
+
+ config, format, err := image.DecodeConfig(reader)
+ if err == nil {
+ return config, format, nil
+ }
+
+ reader.Seek(0, io.SeekStart)
+ config, err = webp.DecodeConfig(reader)
+ if err == nil {
+ return config, "webp", nil
+ }
+
+ // Try HEIF/HEIC: parse ISOBMFF ispe box for dimensions
+ if heifMime := detectHEIF(data); heifMime != "" {
+ formatName := "heif"
+ if heifMime == "image/heic" {
+ formatName = "heic"
+ }
+ if w, h, ok := parseHEIFDimensions(data); ok {
+ return image.Config{Width: w, Height: h}, formatName, nil
+ }
+ return image.Config{}, "", fmt.Errorf("failed to decode HEIF/HEIC image dimensions")
+ }
+
+ return image.Config{}, "", fmt.Errorf("failed to decode image config: unsupported format")
+}
+
+// detectHEIF checks ISOBMFF magic bytes to detect HEIC/HEIF files.
+// Returns "image/heic", "image/heif", or "" if not recognized.
+func detectHEIF(data []byte) string {
+ if len(data) < 12 {
+ return ""
+ }
+ // ISOBMFF: bytes[4:8] must be "ftyp"
+ if string(data[4:8]) != "ftyp" {
+ return ""
+ }
+ brand := string(data[8:12])
+ switch brand {
+ case "heic", "heix", "hevc", "hevx", "heim", "heis":
+ return "image/heic"
+ case "mif1", "msf1":
+ return "image/heif"
+ default:
+ return ""
+ }
+}
+
+// parseHEIFDimensions parses ISOBMFF box tree to find the ispe box
+// and extract image width/height. Returns (width, height, ok).
+func parseHEIFDimensions(data []byte) (int, int, bool) {
+ size := len(data)
+ if size < 12 {
+ return 0, 0, false
+ }
+
+ // Walk top-level boxes to find "meta"
+ offset := 0
+ for offset+8 <= size {
+ boxSize := int(binary.BigEndian.Uint32(data[offset : offset+4]))
+ boxType := string(data[offset+4 : offset+8])
+ headerLen := 8
+
+ if boxSize == 1 {
+ // 64-bit extended size
+ if offset+16 > size {
+ break
+ }
+ boxSize = int(binary.BigEndian.Uint64(data[offset+8 : offset+16]))
+ headerLen = 16
+ } else if boxSize == 0 {
+ // box extends to end of data
+ boxSize = size - offset
+ }
+
+ if boxSize < headerLen || offset+boxSize > size {
+ break
+ }
+
+ if boxType == "meta" {
+ // meta is a full box: 4 bytes version/flags after header
+ metaData := data[offset+headerLen : offset+boxSize]
+ if len(metaData) < 4 {
+ return 0, 0, false
+ }
+ return findISPE(metaData[4:])
+ }
+ offset += boxSize
+ }
+ return 0, 0, false
+}
+
+// findISPE recursively searches for the ispe box within container boxes.
+// Path: meta -> iprp -> ipco -> ispe
+func findISPE(data []byte) (int, int, bool) {
+ offset := 0
+ size := len(data)
+ for offset+8 <= size {
+ boxSize := int(binary.BigEndian.Uint32(data[offset : offset+4]))
+ boxType := string(data[offset+4 : offset+8])
+ if boxSize < 8 || offset+boxSize > size {
+ break
+ }
+ content := data[offset+8 : offset+boxSize]
+ switch boxType {
+ case "iprp", "ipco":
+ if w, h, ok := findISPE(content); ok {
+ return w, h, true
+ }
+ case "ispe":
+ // ispe is a full box: 4 bytes version/flags, then 4 bytes width, 4 bytes height
+ if len(content) >= 12 {
+ w := int(binary.BigEndian.Uint32(content[4:8]))
+ h := int(binary.BigEndian.Uint32(content[8:12]))
+ if w > 0 && h > 0 {
+ return w, h, true
+ }
+ }
+ }
+ offset += boxSize
+ }
+ return 0, 0, false
+}
+
+// guessMimeTypeFromURL 从 URL 猜测 MIME 类型
+func guessMimeTypeFromURL(url string) string {
+ cleanedURL := url
+ if q := strings.Index(cleanedURL, "?"); q != -1 {
+ cleanedURL = cleanedURL[:q]
+ }
+
+ if slash := strings.LastIndex(cleanedURL, "/"); slash != -1 && slash+1 < len(cleanedURL) {
+ last := cleanedURL[slash+1:]
+ if dot := strings.LastIndex(last, "."); dot != -1 && dot+1 < len(last) {
+ ext := strings.ToLower(last[dot+1:])
+ return GetMimeTypeByExtension(ext)
+ }
+ }
+
+ return "application/octet-stream"
+}
diff --git a/service/funding_source.go b/service/funding_source.go
new file mode 100644
index 0000000000..98f5e874d8
--- /dev/null
+++ b/service/funding_source.go
@@ -0,0 +1,139 @@
+package service
+
+import (
+ "time"
+
+ "github.com/QuantumNous/new-api/model"
+)
+
+// ---------------------------------------------------------------------------
+// FundingSource — 资金来源接口(钱包 or 订阅)
+// ---------------------------------------------------------------------------
+
+// FundingSource 抽象了预扣费的资金来源。
+type FundingSource interface {
+ // Source 返回资金来源标识:"wallet" 或 "subscription"
+ Source() string
+ // PreConsume 从该资金来源预扣 amount 额度
+ PreConsume(amount int) error
+ // Settle 根据差额调整资金来源(正数补扣,负数退还)
+ Settle(delta int) error
+ // Refund 退还所有预扣费
+ Refund() error
+}
+
+// ---------------------------------------------------------------------------
+// WalletFunding — 钱包资金来源实现
+// ---------------------------------------------------------------------------
+
+type WalletFunding struct {
+ userId int
+ consumed int // 实际预扣的用户额度
+}
+
+func (w *WalletFunding) Source() string { return BillingSourceWallet }
+
+func (w *WalletFunding) PreConsume(amount int) error {
+ if amount <= 0 {
+ return nil
+ }
+ if err := model.DecreaseUserQuota(w.userId, amount); err != nil {
+ return err
+ }
+ w.consumed = amount
+ return nil
+}
+
+func (w *WalletFunding) Settle(delta int) error {
+ if delta == 0 {
+ return nil
+ }
+ if delta > 0 {
+ return model.DecreaseUserQuota(w.userId, delta)
+ }
+ return model.IncreaseUserQuota(w.userId, -delta, false)
+}
+
+func (w *WalletFunding) Refund() error {
+ if w.consumed <= 0 {
+ return nil
+ }
+ // IncreaseUserQuota 是 quota += N 的非幂等操作,不能重试,否则会多退额度。
+ // 订阅的 RefundSubscriptionPreConsume 有 requestId 幂等保护所以可以重试。
+ return model.IncreaseUserQuota(w.userId, w.consumed, false)
+}
+
+// ---------------------------------------------------------------------------
+// SubscriptionFunding — 订阅资金来源实现
+// ---------------------------------------------------------------------------
+
+type SubscriptionFunding struct {
+ requestId string
+ userId int
+ modelName string
+ amount int64 // 预扣的订阅额度(subConsume)
+ subscriptionId int
+ preConsumed int64
+ // 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用
+ AmountTotal int64
+ AmountUsedAfter int64
+ PlanId int
+ PlanTitle string
+}
+
+func (s *SubscriptionFunding) Source() string { return BillingSourceSubscription }
+
+func (s *SubscriptionFunding) PreConsume(_ int) error {
+ // amount 参数被忽略,使用内部 s.amount(已在构造时根据 preConsumedQuota 计算)
+ res, err := model.PreConsumeUserSubscription(s.requestId, s.userId, s.modelName, 0, s.amount)
+ if err != nil {
+ return err
+ }
+ s.subscriptionId = res.UserSubscriptionId
+ s.preConsumed = res.PreConsumed
+ s.AmountTotal = res.AmountTotal
+ s.AmountUsedAfter = res.AmountUsedAfter
+ // 获取订阅计划信息
+ if planInfo, err := model.GetSubscriptionPlanInfoByUserSubscriptionId(res.UserSubscriptionId); err == nil && planInfo != nil {
+ s.PlanId = planInfo.PlanId
+ s.PlanTitle = planInfo.PlanTitle
+ }
+ return nil
+}
+
+func (s *SubscriptionFunding) Settle(delta int) error {
+ if delta == 0 {
+ return nil
+ }
+ return model.PostConsumeUserSubscriptionDelta(s.subscriptionId, int64(delta))
+}
+
+func (s *SubscriptionFunding) Refund() error {
+ if s.preConsumed <= 0 {
+ return nil
+ }
+ return refundWithRetry(func() error {
+ return model.RefundSubscriptionPreConsume(s.requestId)
+ })
+}
+
+// refundWithRetry 尝试多次执行退款操作以提高成功率,只能用于基于事务的退款函数!!!!!!
+// try to refund with retries, only for refund functions based on transactions!!!
+func refundWithRetry(fn func() error) error {
+ if fn == nil {
+ return nil
+ }
+ const maxAttempts = 3
+ var lastErr error
+ for i := 0; i < maxAttempts; i++ {
+ if err := fn(); err == nil {
+ return nil
+ } else {
+ lastErr = err
+ }
+ if i < maxAttempts-1 {
+ time.Sleep(time.Duration(200*(i+1)) * time.Millisecond)
+ }
+ }
+ return lastErr
+}
diff --git a/service/image.go b/service/image.go
index fa5c175bca..66181f6c7c 100644
--- a/service/image.go
+++ b/service/image.go
@@ -159,20 +159,36 @@ func DecodeUrlImageData(imageUrl string) (image.Config, string, error) {
}
func getImageConfig(reader io.Reader) (image.Config, string, error) {
+ // Read all data so we can retry with different decoders
+ data, readErr := io.ReadAll(reader)
+ if readErr != nil {
+ return image.Config{}, "", fmt.Errorf("failed to read image data: %w", readErr)
+ }
+
// 读取图片的头部信息来获取图片尺寸
- config, format, err := image.DecodeConfig(reader)
- if err != nil {
- err = errors.New(fmt.Sprintf("fail to decode image config(gif, jpg, png): %s", err.Error()))
- common.SysLog(err.Error())
- config, err = webp.DecodeConfig(reader)
- if err != nil {
- err = errors.New(fmt.Sprintf("fail to decode image config(webp): %s", err.Error()))
- common.SysLog(err.Error())
+ config, format, err := image.DecodeConfig(bytes.NewReader(data))
+ if err == nil {
+ return config, format, nil
+ }
+ common.SysLog(fmt.Sprintf("fail to decode image config(gif, jpg, png): %s", err.Error()))
+
+ config, err = webp.DecodeConfig(bytes.NewReader(data))
+ if err == nil {
+ return config, "webp", nil
+ }
+ common.SysLog(fmt.Sprintf("fail to decode image config(webp): %s", err.Error()))
+
+ // Try HEIF/HEIC: parse ISOBMFF ispe box for dimensions
+ if heifMime := detectHEIF(data); heifMime != "" {
+ formatName := "heif"
+ if heifMime == "image/heic" {
+ formatName = "heic"
}
- format = "webp"
+ if w, h, ok := parseHEIFDimensions(data); ok {
+ return image.Config{Width: w, Height: h}, formatName, nil
+ }
+ return image.Config{}, "", fmt.Errorf("failed to decode HEIF/HEIC image dimensions")
}
- if err != nil {
- return image.Config{}, "", err
- }
- return config, format, nil
+
+ return image.Config{}, "", err
}
diff --git a/service/log_info_generate.go b/service/log_info_generate.go
index 71a6bd32a5..75e6fb1d49 100644
--- a/service/log_info_generate.go
+++ b/service/log_info_generate.go
@@ -68,12 +68,106 @@ func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, m
adminInfo["local_count_tokens"] = isLocalCountTokens
}
+ AppendChannelAffinityAdminInfo(ctx, adminInfo)
+
other["admin_info"] = adminInfo
appendRequestPath(ctx, relayInfo, other)
appendRequestConversionChain(relayInfo, other)
+ appendFinalRequestFormat(relayInfo, other)
+ appendBillingInfo(relayInfo, other)
+ appendParamOverrideInfo(relayInfo, other)
+ appendStreamStatus(relayInfo, other)
return other
}
+func appendParamOverrideInfo(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
+ if relayInfo == nil || other == nil || len(relayInfo.ParamOverrideAudit) == 0 {
+ return
+ }
+ other["po"] = relayInfo.ParamOverrideAudit
+}
+
+func appendStreamStatus(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
+ if relayInfo == nil || other == nil || !relayInfo.IsStream || relayInfo.StreamStatus == nil {
+ return
+ }
+ ss := relayInfo.StreamStatus
+ status := "ok"
+ if !ss.IsNormalEnd() || ss.HasErrors() {
+ status = "error"
+ }
+ streamInfo := map[string]interface{}{
+ "status": status,
+ "end_reason": string(ss.EndReason),
+ }
+ if ss.EndError != nil {
+ streamInfo["end_error"] = ss.EndError.Error()
+ }
+ if ss.ErrorCount > 0 {
+ streamInfo["error_count"] = ss.ErrorCount
+ messages := make([]string, 0, len(ss.Errors))
+ for _, e := range ss.Errors {
+ messages = append(messages, e.Message)
+ }
+ streamInfo["errors"] = messages
+ }
+ other["stream_status"] = streamInfo
+}
+
+func appendBillingInfo(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
+ if relayInfo == nil || other == nil {
+ return
+ }
+ // billing_source: "wallet" or "subscription"
+ if relayInfo.BillingSource != "" {
+ other["billing_source"] = relayInfo.BillingSource
+ }
+ if relayInfo.UserSetting.BillingPreference != "" {
+ other["billing_preference"] = relayInfo.UserSetting.BillingPreference
+ }
+ if relayInfo.BillingSource == "subscription" {
+ if relayInfo.SubscriptionId != 0 {
+ other["subscription_id"] = relayInfo.SubscriptionId
+ }
+ if relayInfo.SubscriptionPreConsumed > 0 {
+ other["subscription_pre_consumed"] = relayInfo.SubscriptionPreConsumed
+ }
+ // post_delta: settlement delta applied after actual usage is known (can be negative for refund)
+ if relayInfo.SubscriptionPostDelta != 0 {
+ other["subscription_post_delta"] = relayInfo.SubscriptionPostDelta
+ }
+ if relayInfo.SubscriptionPlanId != 0 {
+ other["subscription_plan_id"] = relayInfo.SubscriptionPlanId
+ }
+ if relayInfo.SubscriptionPlanTitle != "" {
+ other["subscription_plan_title"] = relayInfo.SubscriptionPlanTitle
+ }
+ // Compute "this request" subscription consumed + remaining
+ consumed := relayInfo.SubscriptionPreConsumed + relayInfo.SubscriptionPostDelta
+ usedFinal := relayInfo.SubscriptionAmountUsedAfterPreConsume + relayInfo.SubscriptionPostDelta
+ if consumed < 0 {
+ consumed = 0
+ }
+ if usedFinal < 0 {
+ usedFinal = 0
+ }
+ if relayInfo.SubscriptionAmountTotal > 0 {
+ remain := relayInfo.SubscriptionAmountTotal - usedFinal
+ if remain < 0 {
+ remain = 0
+ }
+ other["subscription_total"] = relayInfo.SubscriptionAmountTotal
+ other["subscription_used"] = usedFinal
+ other["subscription_remain"] = remain
+ }
+ if consumed > 0 {
+ other["subscription_consumed"] = consumed
+ }
+ // Wallet quota is not deducted when billed from subscription.
+ other["wallet_quota_deducted"] = 0
+ }
+}
+
func appendRequestConversionChain(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
if relayInfo == nil || other == nil {
return
@@ -102,6 +196,17 @@ func appendRequestConversionChain(relayInfo *relaycommon.RelayInfo, other map[st
other["request_conversion"] = chain
}
+func appendFinalRequestFormat(relayInfo *relaycommon.RelayInfo, other map[string]interface{}) {
+ if relayInfo == nil || other == nil {
+ return
+ }
+ if relayInfo.GetFinalRequestRelayFormat() == types.RelayFormatClaude {
+ // claude indicates the final upstream request format is Claude Messages.
+ // Frontend log rendering uses this to keep the original Claude input display.
+ other["claude"] = true
+ }
+}
+
func GenerateWssOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage, modelRatio, groupRatio, completionRatio, audioRatio, audioCompletionRatio, modelPrice, userGroupRatio float64) map[string]interface{} {
info := GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, 0, 0.0, modelPrice, userGroupRatio)
info["ws"] = true
@@ -147,7 +252,7 @@ func GenerateClaudeOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo,
return info
}
-func GenerateMjOtherInfo(relayInfo *relaycommon.RelayInfo, priceData types.PerCallPriceData) map[string]interface{} {
+func GenerateMjOtherInfo(relayInfo *relaycommon.RelayInfo, priceData types.PriceData) map[string]interface{} {
other := make(map[string]interface{})
other["model_price"] = priceData.ModelPrice
other["group_ratio"] = priceData.GroupRatioInfo.GroupRatio
diff --git a/service/midjourney.go b/service/midjourney.go
index 9b2eb5ca75..bdb0fe50a9 100644
--- a/service/midjourney.go
+++ b/service/midjourney.go
@@ -19,7 +19,7 @@ import (
"github.com/gin-gonic/gin"
)
-func CoverActionToModelName(mjAction string) string {
+func CovertMjpActionToModelName(mjAction string) string {
modelName := "mj_" + strings.ToLower(mjAction)
if mjAction == constant.MjActionSwapFace {
modelName = "swap_face"
@@ -70,7 +70,7 @@ func GetMjRequestModel(relayMode int, midjRequest *dto.MidjourneyRequest) (strin
return "", MidjourneyErrorWrapper(constant.MjRequestError, "unknown_relay_action"), false
}
}
- modelName := CoverActionToModelName(action)
+ modelName := CovertMjpActionToModelName(action)
return modelName, nil, true
}
diff --git a/service/openai_chat_responses_mode.go b/service/openai_chat_responses_mode.go
index a655a38be0..c66c33c9dc 100644
--- a/service/openai_chat_responses_mode.go
+++ b/service/openai_chat_responses_mode.go
@@ -5,10 +5,10 @@ import (
"github.com/QuantumNous/new-api/setting/model_setting"
)
-func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, model string) bool {
- return openaicompat.ShouldChatCompletionsUseResponsesPolicy(policy, channelID, model)
+func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, channelType int, model string) bool {
+ return openaicompat.ShouldChatCompletionsUseResponsesPolicy(policy, channelID, channelType, model)
}
-func ShouldChatCompletionsUseResponsesGlobal(channelID int, model string) bool {
- return openaicompat.ShouldChatCompletionsUseResponsesGlobal(channelID, model)
+func ShouldChatCompletionsUseResponsesGlobal(channelID int, channelType int, model string) bool {
+ return openaicompat.ShouldChatCompletionsUseResponsesGlobal(channelID, channelType, model)
}
diff --git a/service/openaicompat/chat_to_responses.go b/service/openaicompat/chat_to_responses.go
index 3779db934f..16096b88f5 100644
--- a/service/openaicompat/chat_to_responses.go
+++ b/service/openaicompat/chat_to_responses.go
@@ -8,6 +8,7 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto"
+ "github.com/samber/lo"
)
func normalizeChatImageURLToString(v any) any {
@@ -34,6 +35,44 @@ func normalizeChatImageURLToString(v any) any {
}
}
+func convertChatResponseFormatToResponsesText(reqFormat *dto.ResponseFormat) json.RawMessage {
+ if reqFormat == nil || strings.TrimSpace(reqFormat.Type) == "" {
+ return nil
+ }
+
+ format := map[string]any{
+ "type": reqFormat.Type,
+ }
+
+ if reqFormat.Type == "json_schema" && len(reqFormat.JsonSchema) > 0 {
+ var chatSchema map[string]any
+ if err := common.Unmarshal(reqFormat.JsonSchema, &chatSchema); err == nil {
+ for key, value := range chatSchema {
+ if key == "type" {
+ continue
+ }
+ format[key] = value
+ }
+
+ if nested, ok := format["json_schema"].(map[string]any); ok {
+ for key, value := range nested {
+ if _, exists := format[key]; !exists {
+ format[key] = value
+ }
+ }
+ delete(format, "json_schema")
+ }
+ } else {
+ format["json_schema"] = reqFormat.JsonSchema
+ }
+ }
+
+ textRaw, _ := common.Marshal(map[string]any{
+ "format": format,
+ })
+ return textRaw
+}
+
func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*dto.OpenAIResponsesRequest, error) {
if req == nil {
return nil, errors.New("request is nil")
@@ -41,7 +80,7 @@ func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*d
if req.Model == "" {
return nil, errors.New("model is required")
}
- if req.N > 1 {
+ if lo.FromPtrOr(req.N, 1) > 1 {
return nil, fmt.Errorf("n>1 is not supported in responses compatibility mode")
}
@@ -176,8 +215,12 @@ func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*d
for _, part := range parts {
switch part.Type {
case dto.ContentTypeText:
+ textType := "input_text"
+ if role == "assistant" {
+ textType = "output_text"
+ }
contentParts = append(contentParts, map[string]any{
- "type": "input_text",
+ "type": textType,
"text": part.Text,
})
case dto.ContentTypeImageURL:
@@ -312,28 +355,27 @@ func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*d
parallelToolCallsRaw, _ = common.Marshal(*req.ParallelTooCalls)
}
- var textRaw json.RawMessage
- if req.ResponseFormat != nil && req.ResponseFormat.Type != "" {
- textRaw, _ = common.Marshal(map[string]any{
- "format": req.ResponseFormat,
- })
- }
+ textRaw := convertChatResponseFormatToResponsesText(req.ResponseFormat)
- maxOutputTokens := req.MaxTokens
- if req.MaxCompletionTokens > maxOutputTokens {
- maxOutputTokens = req.MaxCompletionTokens
+ maxOutputTokens := lo.FromPtrOr(req.MaxTokens, uint(0))
+ maxCompletionTokens := lo.FromPtrOr(req.MaxCompletionTokens, uint(0))
+ if maxCompletionTokens > maxOutputTokens {
+ maxOutputTokens = maxCompletionTokens
}
+ // OpenAI Responses API rejects max_output_tokens < 16 when explicitly provided.
+ //if maxOutputTokens > 0 && maxOutputTokens < 16 {
+ // maxOutputTokens = 16
+ //}
var topP *float64
- if req.TopP != 0 {
- topP = common.GetPointer(req.TopP)
+ if req.TopP != nil {
+ topP = common.GetPointer(lo.FromPtr(req.TopP))
}
out := &dto.OpenAIResponsesRequest{
Model: req.Model,
Input: inputRaw,
Instructions: instructionsRaw,
- MaxOutputTokens: maxOutputTokens,
Stream: req.Stream,
Temperature: req.Temperature,
Text: textRaw,
@@ -345,10 +387,14 @@ func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*d
Store: req.Store,
Metadata: req.Metadata,
}
+ if req.MaxTokens != nil || req.MaxCompletionTokens != nil {
+ out.MaxOutputTokens = lo.ToPtr(maxOutputTokens)
+ }
- if req.ReasoningEffort != "" && req.ReasoningEffort != "none" {
+ if req.ReasoningEffort != "" {
out.Reasoning = &dto.Reasoning{
- Effort: req.ReasoningEffort,
+ Effort: req.ReasoningEffort,
+ Summary: "detailed",
}
}
diff --git a/service/openaicompat/policy.go b/service/openaicompat/policy.go
index 39b11ce5d8..b600b0fdc7 100644
--- a/service/openaicompat/policy.go
+++ b/service/openaicompat/policy.go
@@ -2,17 +2,18 @@ package openaicompat
import "github.com/QuantumNous/new-api/setting/model_setting"
-func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, model string) bool {
- if !policy.IsChannelEnabled(channelID) {
+func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, channelType int, model string) bool {
+ if !policy.IsChannelEnabled(channelID, channelType) {
return false
}
return matchAnyRegex(policy.ModelPatterns, model)
}
-func ShouldChatCompletionsUseResponsesGlobal(channelID int, model string) bool {
+func ShouldChatCompletionsUseResponsesGlobal(channelID int, channelType int, model string) bool {
return ShouldChatCompletionsUseResponsesPolicy(
model_setting.GetGlobalSettings().ChatCompletionsToResponsesPolicy,
channelID,
+ channelType,
model,
)
}
diff --git a/service/quota.go b/service/quota.go
index 23ae60c1f0..9dc84ab4be 100644
--- a/service/quota.go
+++ b/service/quota.go
@@ -235,124 +235,6 @@ func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, mod
})
}
-func PostClaudeConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage) {
-
- useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
- promptTokens := usage.PromptTokens
- completionTokens := usage.CompletionTokens
- modelName := relayInfo.OriginModelName
-
- tokenName := ctx.GetString("token_name")
- completionRatio := relayInfo.PriceData.CompletionRatio
- modelRatio := relayInfo.PriceData.ModelRatio
- groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
- modelPrice := relayInfo.PriceData.ModelPrice
- cacheRatio := relayInfo.PriceData.CacheRatio
- cacheTokens := usage.PromptTokensDetails.CachedTokens
-
- cacheCreationRatio := relayInfo.PriceData.CacheCreationRatio
- cacheCreationRatio5m := relayInfo.PriceData.CacheCreation5mRatio
- cacheCreationRatio1h := relayInfo.PriceData.CacheCreation1hRatio
- cacheCreationTokens := usage.PromptTokensDetails.CachedCreationTokens
- cacheCreationTokens5m := usage.ClaudeCacheCreation5mTokens
- cacheCreationTokens1h := usage.ClaudeCacheCreation1hTokens
-
- if relayInfo.ChannelType == constant.ChannelTypeOpenRouter {
- promptTokens -= cacheTokens
- isUsingCustomSettings := relayInfo.PriceData.UsePrice || hasCustomModelRatio(modelName, relayInfo.PriceData.ModelRatio)
- if cacheCreationTokens == 0 && relayInfo.PriceData.CacheCreationRatio != 1 && usage.Cost != 0 && !isUsingCustomSettings {
- maybeCacheCreationTokens := CalcOpenRouterCacheCreateTokens(*usage, relayInfo.PriceData)
- if maybeCacheCreationTokens >= 0 && promptTokens >= maybeCacheCreationTokens {
- cacheCreationTokens = maybeCacheCreationTokens
- }
- }
- promptTokens -= cacheCreationTokens
- }
-
- calculateQuota := 0.0
- if !relayInfo.PriceData.UsePrice {
- calculateQuota = float64(promptTokens)
- calculateQuota += float64(cacheTokens) * cacheRatio
- calculateQuota += float64(cacheCreationTokens5m) * cacheCreationRatio5m
- calculateQuota += float64(cacheCreationTokens1h) * cacheCreationRatio1h
- remainingCacheCreationTokens := cacheCreationTokens - cacheCreationTokens5m - cacheCreationTokens1h
- if remainingCacheCreationTokens > 0 {
- calculateQuota += float64(remainingCacheCreationTokens) * cacheCreationRatio
- }
- calculateQuota += float64(completionTokens) * completionRatio
- calculateQuota = calculateQuota * groupRatio * modelRatio
- } else {
- calculateQuota = modelPrice * common.QuotaPerUnit * groupRatio
- }
-
- if modelRatio != 0 && calculateQuota <= 0 {
- calculateQuota = 1
- }
-
- quota := int(calculateQuota)
-
- totalTokens := promptTokens + completionTokens
-
- var logContent string
- // record all the consume log even if quota is 0
- if totalTokens == 0 {
- // in this case, must be some error happened
- // we cannot just return, because we may have to return the pre-consumed quota
- quota = 0
- logContent += fmt.Sprintf("(可能是上游出错)")
- logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
- "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
- } else {
- model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
- model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
- }
-
- quotaDelta := quota - relayInfo.FinalPreConsumedQuota
-
- if quotaDelta > 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- } else if quotaDelta < 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(-quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- }
-
- if quotaDelta != 0 {
- err := PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
- if err != nil {
- logger.LogError(ctx, "error consuming token remain quota: "+err.Error())
- }
- }
-
- other := GenerateClaudeOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio,
- cacheTokens, cacheRatio,
- cacheCreationTokens, cacheCreationRatio,
- cacheCreationTokens5m, cacheCreationRatio5m,
- cacheCreationTokens1h, cacheCreationRatio1h,
- modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
- model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
- ChannelId: relayInfo.ChannelId,
- PromptTokens: promptTokens,
- CompletionTokens: completionTokens,
- ModelName: modelName,
- TokenName: tokenName,
- Quota: quota,
- Content: logContent,
- TokenId: relayInfo.TokenId,
- UseTimeSeconds: int(useTimeSeconds),
- IsStream: relayInfo.IsStream,
- Group: relayInfo.UsingGroup,
- Other: other,
- })
-
-}
-
func CalcOpenRouterCacheCreateTokens(usage dto.Usage, priceData types.PriceData) int {
if priceData.CacheCreationRatio == 1 {
return 0
@@ -432,27 +314,8 @@ func PostAudioConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, u
model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
}
- quotaDelta := quota - relayInfo.FinalPreConsumedQuota
-
- if quotaDelta > 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- } else if quotaDelta < 0 {
- logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
- logger.FormatQuota(-quotaDelta),
- logger.FormatQuota(quota),
- logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
- ))
- }
-
- if quotaDelta != 0 {
- err := PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
- if err != nil {
- logger.LogError(ctx, "error consuming token remain quota: "+err.Error())
- }
+ if err := SettleBilling(ctx, relayInfo, quota); err != nil {
+ logger.LogError(ctx, "error settling billing: "+err.Error())
}
logModel := relayInfo.OriginModelName
@@ -503,13 +366,28 @@ func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error {
func PostConsumeQuota(relayInfo *relaycommon.RelayInfo, quota int, preConsumedQuota int, sendEmail bool) (err error) {
- if quota > 0 {
- err = model.DecreaseUserQuota(relayInfo.UserId, quota)
+ // 1) Consume from wallet quota OR subscription item
+ if relayInfo != nil && relayInfo.BillingSource == BillingSourceSubscription {
+ if relayInfo.SubscriptionId == 0 {
+ return errors.New("subscription id is missing")
+ }
+ delta := int64(quota)
+ if delta != 0 {
+ if err := model.PostConsumeUserSubscriptionDelta(relayInfo.SubscriptionId, delta); err != nil {
+ return err
+ }
+ relayInfo.SubscriptionPostDelta += delta
+ }
} else {
- err = model.IncreaseUserQuota(relayInfo.UserId, -quota, false)
- }
- if err != nil {
- return err
+ // Wallet
+ if quota > 0 {
+ err = model.DecreaseUserQuota(relayInfo.UserId, quota)
+ } else {
+ err = model.IncreaseUserQuota(relayInfo.UserId, -quota, false)
+ }
+ if err != nil {
+ return err
+ }
}
if !relayInfo.IsPlayground {
@@ -579,3 +457,51 @@ func checkAndSendQuotaNotify(relayInfo *relaycommon.RelayInfo, quota int, preCon
}
})
}
+
+func checkAndSendSubscriptionQuotaNotify(relayInfo *relaycommon.RelayInfo) {
+ gopool.Go(func() {
+ if relayInfo == nil {
+ return
+ }
+ if relayInfo.SubscriptionId == 0 || relayInfo.SubscriptionAmountTotal <= 0 {
+ return
+ }
+
+ userSetting := relayInfo.UserSetting
+ threshold := common.QuotaRemindThreshold
+ if userSetting.QuotaWarningThreshold != 0 {
+ threshold = int(userSetting.QuotaWarningThreshold)
+ }
+
+ usedAfter := relayInfo.SubscriptionAmountUsedAfterPreConsume + relayInfo.SubscriptionPostDelta
+ remaining := relayInfo.SubscriptionAmountTotal - usedAfter
+ if remaining >= int64(threshold) {
+ return
+ }
+
+ prompt := "您的订阅额度即将用尽"
+ topUpLink := fmt.Sprintf("%s/console/topup", system_setting.ServerAddress)
+
+ var content string
+ var values []interface{}
+ notifyType := userSetting.NotifyType
+ if notifyType == "" {
+ notifyType = dto.NotifyTypeEmail
+ }
+
+ if notifyType == dto.NotifyTypeBark {
+ content = "{{value}},剩余额度:{{value}},请及时充值"
+ values = []interface{}{prompt, logger.FormatQuota(int(remaining))}
+ } else if notifyType == dto.NotifyTypeGotify {
+ content = "{{value}},当前剩余额度为 {{value}},请及时充值。"
+ values = []interface{}{prompt, logger.FormatQuota(int(remaining))}
+ } else {
+ content = "{{value}},当前剩余额度为 {{value}},为了不影响您的使用,请及时充值。 充值链接:{{value}} "
+ values = []interface{}{prompt, logger.FormatQuota(int(remaining)), topUpLink, topUpLink}
+ }
+
+ if err := NotifyUser(relayInfo.UserId, relayInfo.UserEmail, relayInfo.UserSetting, dto.NewNotify(dto.NotifyTypeQuotaExceed, prompt, content, values)); err != nil {
+ common.SysError(fmt.Sprintf("failed to send subscription quota notify to user %d: %s", relayInfo.UserId, err.Error()))
+ }
+ })
+}
diff --git a/service/subscription_reset_task.go b/service/subscription_reset_task.go
new file mode 100644
index 0000000000..9dcd373068
--- /dev/null
+++ b/service/subscription_reset_task.go
@@ -0,0 +1,93 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+
+ "github.com/bytedance/gopkg/util/gopool"
+)
+
+const (
+ subscriptionResetTickInterval = 1 * time.Minute
+ subscriptionResetBatchSize = 300
+ subscriptionCleanupInterval = 30 * time.Minute
+)
+
+var (
+ subscriptionResetOnce sync.Once
+ subscriptionResetRunning atomic.Bool
+ subscriptionCleanupLast atomic.Int64
+)
+
+func StartSubscriptionQuotaResetTask() {
+ subscriptionResetOnce.Do(func() {
+ if !common.IsMasterNode {
+ return
+ }
+ gopool.Go(func() {
+ logger.LogInfo(context.Background(), fmt.Sprintf("subscription quota reset task started: tick=%s", subscriptionResetTickInterval))
+ ticker := time.NewTicker(subscriptionResetTickInterval)
+ defer ticker.Stop()
+
+ runSubscriptionQuotaResetOnce()
+ for range ticker.C {
+ runSubscriptionQuotaResetOnce()
+ }
+ })
+ })
+}
+
+func runSubscriptionQuotaResetOnce() {
+ if !subscriptionResetRunning.CompareAndSwap(false, true) {
+ return
+ }
+ defer subscriptionResetRunning.Store(false)
+
+ ctx := context.Background()
+ totalReset := 0
+ totalExpired := 0
+ for {
+ n, err := model.ExpireDueSubscriptions(subscriptionResetBatchSize)
+ if err != nil {
+ logger.LogWarn(ctx, fmt.Sprintf("subscription expire task failed: %v", err))
+ return
+ }
+ if n == 0 {
+ break
+ }
+ totalExpired += n
+ if n < subscriptionResetBatchSize {
+ break
+ }
+ }
+ for {
+ n, err := model.ResetDueSubscriptions(subscriptionResetBatchSize)
+ if err != nil {
+ logger.LogWarn(ctx, fmt.Sprintf("subscription quota reset task failed: %v", err))
+ return
+ }
+ if n == 0 {
+ break
+ }
+ totalReset += n
+ if n < subscriptionResetBatchSize {
+ break
+ }
+ }
+ lastCleanup := time.Unix(subscriptionCleanupLast.Load(), 0)
+ if time.Since(lastCleanup) >= subscriptionCleanupInterval {
+ if _, err := model.CleanupSubscriptionPreConsumeRecords(7 * 24 * 3600); err == nil {
+ subscriptionCleanupLast.Store(time.Now().Unix())
+ }
+ }
+ if common.DebugEnabled && (totalReset > 0 || totalExpired > 0) {
+ logger.LogDebug(ctx, "subscription maintenance: reset_count=%d, expired_count=%d", totalReset, totalExpired)
+ }
+}
diff --git a/service/task_billing.go b/service/task_billing.go
new file mode 100644
index 0000000000..e5c406ddc2
--- /dev/null
+++ b/service/task_billing.go
@@ -0,0 +1,301 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/ratio_setting"
+ "github.com/gin-gonic/gin"
+)
+
+// LogTaskConsumption 记录任务消费日志和统计信息(仅记录,不涉及实际扣费)。
+// 实际扣费已由 BillingSession(PreConsumeBilling + SettleBilling)完成。
+func LogTaskConsumption(c *gin.Context, info *relaycommon.RelayInfo) {
+ tokenName := c.GetString("token_name")
+ logContent := fmt.Sprintf("操作 %s", info.Action)
+ // 支持任务仅按次计费
+ if common.StringsContains(constant.TaskPricePatches, info.OriginModelName) {
+ logContent = fmt.Sprintf("%s,按次计费", logContent)
+ } else {
+ if len(info.PriceData.OtherRatios) > 0 {
+ var contents []string
+ for key, ra := range info.PriceData.OtherRatios {
+ if 1.0 != ra {
+ contents = append(contents, fmt.Sprintf("%s: %.2f", key, ra))
+ }
+ }
+ if len(contents) > 0 {
+ logContent = fmt.Sprintf("%s, 计算参数:%s", logContent, strings.Join(contents, ", "))
+ }
+ }
+ }
+ other := make(map[string]interface{})
+ other["is_task"] = true
+ other["request_path"] = c.Request.URL.Path
+ other["model_price"] = info.PriceData.ModelPrice
+ if info.PriceData.ModelRatio > 0 {
+ other["model_ratio"] = info.PriceData.ModelRatio
+ }
+ other["group_ratio"] = info.PriceData.GroupRatioInfo.GroupRatio
+ if info.PriceData.GroupRatioInfo.HasSpecialRatio {
+ other["user_group_ratio"] = info.PriceData.GroupRatioInfo.GroupSpecialRatio
+ }
+ if info.IsModelMapped {
+ other["is_model_mapped"] = true
+ other["upstream_model_name"] = info.UpstreamModelName
+ }
+ model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{
+ ChannelId: info.ChannelId,
+ ModelName: info.OriginModelName,
+ TokenName: tokenName,
+ Quota: info.PriceData.Quota,
+ Content: logContent,
+ TokenId: info.TokenId,
+ Group: info.UsingGroup,
+ Other: other,
+ })
+ model.UpdateUserUsedQuotaAndRequestCount(info.UserId, info.PriceData.Quota)
+ model.UpdateChannelUsedQuota(info.ChannelId, info.PriceData.Quota)
+}
+
+// ---------------------------------------------------------------------------
+// 异步任务计费辅助函数
+// ---------------------------------------------------------------------------
+
+// resolveTokenKey 通过 TokenId 运行时获取令牌 Key(用于 Redis 缓存操作)。
+// 如果令牌已被删除或查询失败,返回空字符串。
+func resolveTokenKey(ctx context.Context, tokenId int, taskID string) string {
+ token, err := model.GetTokenById(tokenId)
+ if err != nil {
+ logger.LogWarn(ctx, fmt.Sprintf("获取令牌 key 失败 (tokenId=%d, task=%s): %s", tokenId, taskID, err.Error()))
+ return ""
+ }
+ return token.Key
+}
+
+// taskIsSubscription 判断任务是否通过订阅计费。
+func taskIsSubscription(task *model.Task) bool {
+ return task.PrivateData.BillingSource == BillingSourceSubscription && task.PrivateData.SubscriptionId > 0
+}
+
+// taskAdjustFunding 调整任务的资金来源(钱包或订阅),delta > 0 表示扣费,delta < 0 表示退还。
+func taskAdjustFunding(task *model.Task, delta int) error {
+ if taskIsSubscription(task) {
+ return model.PostConsumeUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
+ }
+ if delta > 0 {
+ return model.DecreaseUserQuota(task.UserId, delta)
+ }
+ return model.IncreaseUserQuota(task.UserId, -delta, false)
+}
+
+// taskAdjustTokenQuota 调整任务的令牌额度,delta > 0 表示扣费,delta < 0 表示退还。
+// 需要通过 resolveTokenKey 运行时获取 key(不从 PrivateData 中读取)。
+func taskAdjustTokenQuota(ctx context.Context, task *model.Task, delta int) {
+ if task.PrivateData.TokenId <= 0 || delta == 0 {
+ return
+ }
+ tokenKey := resolveTokenKey(ctx, task.PrivateData.TokenId, task.TaskID)
+ if tokenKey == "" {
+ return
+ }
+ var err error
+ if delta > 0 {
+ err = model.DecreaseTokenQuota(task.PrivateData.TokenId, tokenKey, delta)
+ } else {
+ err = model.IncreaseTokenQuota(task.PrivateData.TokenId, tokenKey, -delta)
+ }
+ if err != nil {
+ logger.LogWarn(ctx, fmt.Sprintf("调整令牌额度失败 (delta=%d, task=%s): %s", delta, task.TaskID, err.Error()))
+ }
+}
+
+// taskBillingOther 从 task 的 BillingContext 构建日志 Other 字段。
+func taskBillingOther(task *model.Task) map[string]interface{} {
+ other := make(map[string]interface{})
+ if bc := task.PrivateData.BillingContext; bc != nil {
+ other["model_price"] = bc.ModelPrice
+ if bc.ModelRatio > 0 {
+ other["model_ratio"] = bc.ModelRatio
+ }
+ other["group_ratio"] = bc.GroupRatio
+ if len(bc.OtherRatios) > 0 {
+ for k, v := range bc.OtherRatios {
+ other[k] = v
+ }
+ }
+ }
+ props := task.Properties
+ if props.UpstreamModelName != "" && props.UpstreamModelName != props.OriginModelName {
+ other["is_model_mapped"] = true
+ other["upstream_model_name"] = props.UpstreamModelName
+ }
+ return other
+}
+
+// taskModelName 从 BillingContext 或 Properties 中获取模型名称。
+func taskModelName(task *model.Task) string {
+ if bc := task.PrivateData.BillingContext; bc != nil && bc.OriginModelName != "" {
+ return bc.OriginModelName
+ }
+ return task.Properties.OriginModelName
+}
+
+// RefundTaskQuota 统一的任务失败退款逻辑。
+// 当异步任务失败时,将预扣的 quota 退还给用户(支持钱包和订阅),并退还令牌额度。
+func RefundTaskQuota(ctx context.Context, task *model.Task, reason string) {
+ quota := task.Quota
+ if quota == 0 {
+ return
+ }
+
+ // 1. 退还资金来源(钱包或订阅)
+ if err := taskAdjustFunding(task, -quota); err != nil {
+ logger.LogWarn(ctx, fmt.Sprintf("退还资金来源失败 task %s: %s", task.TaskID, err.Error()))
+ return
+ }
+
+ // 2. 退还令牌额度
+ taskAdjustTokenQuota(ctx, task, -quota)
+
+ // 3. 记录日志
+ other := taskBillingOther(task)
+ other["task_id"] = task.TaskID
+ other["reason"] = reason
+ model.RecordTaskBillingLog(model.RecordTaskBillingLogParams{
+ UserId: task.UserId,
+ LogType: model.LogTypeRefund,
+ Content: "",
+ ChannelId: task.ChannelId,
+ ModelName: taskModelName(task),
+ Quota: quota,
+ TokenId: task.PrivateData.TokenId,
+ Group: task.Group,
+ Other: other,
+ })
+}
+
+// RecalculateTaskQuota 通用的异步差额结算。
+// actualQuota 是任务完成后的实际应扣额度,与预扣额度 (task.Quota) 做差额结算。
+// reason 用于日志记录(例如 "token重算" 或 "adaptor调整")。
+func RecalculateTaskQuota(ctx context.Context, task *model.Task, actualQuota int, reason string) {
+ if actualQuota <= 0 {
+ return
+ }
+ preConsumedQuota := task.Quota
+ quotaDelta := actualQuota - preConsumedQuota
+
+ if quotaDelta == 0 {
+ logger.LogInfo(ctx, fmt.Sprintf("任务 %s 预扣费准确(%s,%s)",
+ task.TaskID, logger.LogQuota(actualQuota), reason))
+ return
+ }
+
+ logger.LogInfo(ctx, fmt.Sprintf("任务 %s 差额结算:delta=%s(实际:%s,预扣:%s,%s)",
+ task.TaskID,
+ logger.LogQuota(quotaDelta),
+ logger.LogQuota(actualQuota),
+ logger.LogQuota(preConsumedQuota),
+ reason,
+ ))
+
+ // 调整资金来源
+ if err := taskAdjustFunding(task, quotaDelta); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("差额结算资金调整失败 task %s: %s", task.TaskID, err.Error()))
+ return
+ }
+
+ // 调整令牌额度
+ taskAdjustTokenQuota(ctx, task, quotaDelta)
+
+ task.Quota = actualQuota
+
+ var logType int
+ var logQuota int
+ if quotaDelta > 0 {
+ logType = model.LogTypeConsume
+ logQuota = quotaDelta
+ model.UpdateUserUsedQuotaAndRequestCount(task.UserId, quotaDelta)
+ model.UpdateChannelUsedQuota(task.ChannelId, quotaDelta)
+ } else {
+ logType = model.LogTypeRefund
+ logQuota = -quotaDelta
+ }
+ other := taskBillingOther(task)
+ other["task_id"] = task.TaskID
+ other["pre_consumed_quota"] = preConsumedQuota
+ other["actual_quota"] = actualQuota
+ model.RecordTaskBillingLog(model.RecordTaskBillingLogParams{
+ UserId: task.UserId,
+ LogType: logType,
+ Content: reason,
+ ChannelId: task.ChannelId,
+ ModelName: taskModelName(task),
+ Quota: logQuota,
+ TokenId: task.PrivateData.TokenId,
+ Group: task.Group,
+ Other: other,
+ })
+}
+
+// RecalculateTaskQuotaByTokens 根据实际 token 消耗重新计费(异步差额结算)。
+// 当任务成功且返回了 totalTokens 时,根据模型倍率和分组倍率重新计算实际扣费额度,
+// 与预扣费的差额进行补扣或退还。支持钱包和订阅计费来源。
+func RecalculateTaskQuotaByTokens(ctx context.Context, task *model.Task, totalTokens int) {
+ if totalTokens <= 0 {
+ return
+ }
+
+ modelName := taskModelName(task)
+
+ // 获取模型价格和倍率
+ modelRatio, hasRatioSetting, _ := ratio_setting.GetModelRatio(modelName)
+ // 只有配置了倍率(非固定价格)时才按 token 重新计费
+ if !hasRatioSetting || modelRatio <= 0 {
+ return
+ }
+
+ // 获取用户和组的倍率信息
+ group := task.Group
+ if group == "" {
+ user, err := model.GetUserById(task.UserId, false)
+ if err == nil {
+ group = user.Group
+ }
+ }
+ if group == "" {
+ return
+ }
+
+ groupRatio := ratio_setting.GetGroupRatio(group)
+ userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(group, group)
+
+ var finalGroupRatio float64
+ if hasUserGroupRatio {
+ finalGroupRatio = userGroupRatio
+ } else {
+ finalGroupRatio = groupRatio
+ }
+
+ // 计算 OtherRatios 乘积(视频折扣、时长等)
+ otherMultiplier := 1.0
+ if bc := task.PrivateData.BillingContext; bc != nil {
+ for _, r := range bc.OtherRatios {
+ if r != 1.0 && r > 0 {
+ otherMultiplier *= r
+ }
+ }
+ }
+
+ // 计算实际应扣费额度: totalTokens * modelRatio * groupRatio * otherMultiplier
+ actualQuota := int(float64(totalTokens) * modelRatio * finalGroupRatio * otherMultiplier)
+
+ reason := fmt.Sprintf("token重算:tokens=%d, modelRatio=%.2f, groupRatio=%.2f, otherMultiplier=%.4f", totalTokens, modelRatio, finalGroupRatio, otherMultiplier)
+ RecalculateTaskQuota(ctx, task, actualQuota, reason)
+}
diff --git a/service/task_billing_test.go b/service/task_billing_test.go
new file mode 100644
index 0000000000..79c8c49eb4
--- /dev/null
+++ b/service/task_billing_test.go
@@ -0,0 +1,714 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/model"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/glebarez/sqlite"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func TestMain(m *testing.M) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
+ if err != nil {
+ panic("failed to open test db: " + err.Error())
+ }
+ sqlDB, err := db.DB()
+ if err != nil {
+ panic("failed to get sql.DB: " + err.Error())
+ }
+ sqlDB.SetMaxOpenConns(1)
+
+ model.DB = db
+ model.LOG_DB = db
+
+ common.UsingSQLite = true
+ common.RedisEnabled = false
+ common.BatchUpdateEnabled = false
+ common.LogConsumeEnabled = true
+
+ if err := db.AutoMigrate(
+ &model.Task{},
+ &model.User{},
+ &model.Token{},
+ &model.Log{},
+ &model.Channel{},
+ &model.UserSubscription{},
+ ); err != nil {
+ panic("failed to migrate: " + err.Error())
+ }
+
+ os.Exit(m.Run())
+}
+
+// ---------------------------------------------------------------------------
+// Seed helpers
+// ---------------------------------------------------------------------------
+
+func truncate(t *testing.T) {
+ t.Helper()
+ t.Cleanup(func() {
+ model.DB.Exec("DELETE FROM tasks")
+ model.DB.Exec("DELETE FROM users")
+ model.DB.Exec("DELETE FROM tokens")
+ model.DB.Exec("DELETE FROM logs")
+ model.DB.Exec("DELETE FROM channels")
+ model.DB.Exec("DELETE FROM user_subscriptions")
+ })
+}
+
+func seedUser(t *testing.T, id int, quota int) {
+ t.Helper()
+ user := &model.User{Id: id, Username: "test_user", Quota: quota, Status: common.UserStatusEnabled}
+ require.NoError(t, model.DB.Create(user).Error)
+}
+
+func seedToken(t *testing.T, id int, userId int, key string, remainQuota int) {
+ t.Helper()
+ token := &model.Token{
+ Id: id,
+ UserId: userId,
+ Key: key,
+ Name: "test_token",
+ Status: common.TokenStatusEnabled,
+ RemainQuota: remainQuota,
+ UsedQuota: 0,
+ }
+ require.NoError(t, model.DB.Create(token).Error)
+}
+
+func seedSubscription(t *testing.T, id int, userId int, amountTotal int64, amountUsed int64) {
+ t.Helper()
+ sub := &model.UserSubscription{
+ Id: id,
+ UserId: userId,
+ AmountTotal: amountTotal,
+ AmountUsed: amountUsed,
+ Status: "active",
+ StartTime: time.Now().Unix(),
+ EndTime: time.Now().Add(30 * 24 * time.Hour).Unix(),
+ }
+ require.NoError(t, model.DB.Create(sub).Error)
+}
+
+func seedChannel(t *testing.T, id int) {
+ t.Helper()
+ ch := &model.Channel{Id: id, Name: "test_channel", Key: "sk-test", Status: common.ChannelStatusEnabled}
+ require.NoError(t, model.DB.Create(ch).Error)
+}
+
+func makeTask(userId, channelId, quota, tokenId int, billingSource string, subscriptionId int) *model.Task {
+ return &model.Task{
+ TaskID: "task_" + time.Now().Format("150405.000"),
+ UserId: userId,
+ ChannelId: channelId,
+ Quota: quota,
+ Status: model.TaskStatus(model.TaskStatusInProgress),
+ Group: "default",
+ Data: json.RawMessage(`{}`),
+ CreatedAt: time.Now().Unix(),
+ UpdatedAt: time.Now().Unix(),
+ Properties: model.Properties{
+ OriginModelName: "test-model",
+ },
+ PrivateData: model.TaskPrivateData{
+ BillingSource: billingSource,
+ SubscriptionId: subscriptionId,
+ TokenId: tokenId,
+ BillingContext: &model.TaskBillingContext{
+ ModelPrice: 0.02,
+ GroupRatio: 1.0,
+ OriginModelName: "test-model",
+ },
+ },
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Read-back helpers
+// ---------------------------------------------------------------------------
+
+func getUserQuota(t *testing.T, id int) int {
+ t.Helper()
+ var user model.User
+ require.NoError(t, model.DB.Select("quota").Where("id = ?", id).First(&user).Error)
+ return user.Quota
+}
+
+func getTokenRemainQuota(t *testing.T, id int) int {
+ t.Helper()
+ var token model.Token
+ require.NoError(t, model.DB.Select("remain_quota").Where("id = ?", id).First(&token).Error)
+ return token.RemainQuota
+}
+
+func getTokenUsedQuota(t *testing.T, id int) int {
+ t.Helper()
+ var token model.Token
+ require.NoError(t, model.DB.Select("used_quota").Where("id = ?", id).First(&token).Error)
+ return token.UsedQuota
+}
+
+func getSubscriptionUsed(t *testing.T, id int) int64 {
+ t.Helper()
+ var sub model.UserSubscription
+ require.NoError(t, model.DB.Select("amount_used").Where("id = ?", id).First(&sub).Error)
+ return sub.AmountUsed
+}
+
+func getLastLog(t *testing.T) *model.Log {
+ t.Helper()
+ var log model.Log
+ err := model.LOG_DB.Order("id desc").First(&log).Error
+ if err != nil {
+ return nil
+ }
+ return &log
+}
+
+func countLogs(t *testing.T) int64 {
+ t.Helper()
+ var count int64
+ model.LOG_DB.Model(&model.Log{}).Count(&count)
+ return count
+}
+
+// ===========================================================================
+// RefundTaskQuota tests
+// ===========================================================================
+
+func TestRefundTaskQuota_Wallet(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 1, 1, 1
+ const initQuota, preConsumed = 10000, 3000
+ const tokenRemain = 5000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-test-key", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+
+ RefundTaskQuota(ctx, task, "task failed: upstream error")
+
+ // User quota should increase by preConsumed
+ assert.Equal(t, initQuota+preConsumed, getUserQuota(t, userID))
+
+ // Token remain_quota should increase, used_quota should decrease
+ assert.Equal(t, tokenRemain+preConsumed, getTokenRemainQuota(t, tokenID))
+ assert.Equal(t, -preConsumed, getTokenUsedQuota(t, tokenID))
+
+ // A refund log should be created
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+ assert.Equal(t, preConsumed, log.Quota)
+ assert.Equal(t, "test-model", log.ModelName)
+}
+
+func TestRefundTaskQuota_Subscription(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID, subID = 2, 2, 2, 1
+ const preConsumed = 2000
+ const subTotal, subUsed int64 = 100000, 50000
+ const tokenRemain = 8000
+
+ seedUser(t, userID, 0)
+ seedToken(t, tokenID, userID, "sk-sub-key", tokenRemain)
+ seedChannel(t, channelID)
+ seedSubscription(t, subID, userID, subTotal, subUsed)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceSubscription, subID)
+
+ RefundTaskQuota(ctx, task, "subscription task failed")
+
+ // Subscription used should decrease by preConsumed
+ assert.Equal(t, subUsed-int64(preConsumed), getSubscriptionUsed(t, subID))
+
+ // Token should also be refunded
+ assert.Equal(t, tokenRemain+preConsumed, getTokenRemainQuota(t, tokenID))
+
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+}
+
+func TestRefundTaskQuota_ZeroQuota(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID = 3
+ seedUser(t, userID, 5000)
+
+ task := makeTask(userID, 0, 0, 0, BillingSourceWallet, 0)
+
+ RefundTaskQuota(ctx, task, "zero quota task")
+
+ // No change to user quota
+ assert.Equal(t, 5000, getUserQuota(t, userID))
+
+ // No log created
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestRefundTaskQuota_NoToken(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, channelID = 4, 4
+ const initQuota, preConsumed = 10000, 1500
+
+ seedUser(t, userID, initQuota)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, 0, BillingSourceWallet, 0) // TokenId=0
+
+ RefundTaskQuota(ctx, task, "no token task failed")
+
+ // User quota refunded
+ assert.Equal(t, initQuota+preConsumed, getUserQuota(t, userID))
+
+ // Log created
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+}
+
+// ===========================================================================
+// RecalculateTaskQuota tests
+// ===========================================================================
+
+func TestRecalculate_PositiveDelta(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 10, 10, 10
+ const initQuota, preConsumed = 10000, 2000
+ const actualQuota = 3000 // under-charged by 1000
+ const tokenRemain = 5000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-recalc-pos", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+
+ RecalculateTaskQuota(ctx, task, actualQuota, "adaptor adjustment")
+
+ // User quota should decrease by the delta (1000 additional charge)
+ assert.Equal(t, initQuota-(actualQuota-preConsumed), getUserQuota(t, userID))
+
+ // Token should also be charged the delta
+ assert.Equal(t, tokenRemain-(actualQuota-preConsumed), getTokenRemainQuota(t, tokenID))
+
+ // task.Quota should be updated to actualQuota
+ assert.Equal(t, actualQuota, task.Quota)
+
+ // Log type should be Consume (additional charge)
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeConsume, log.Type)
+ assert.Equal(t, actualQuota-preConsumed, log.Quota)
+}
+
+func TestRecalculate_NegativeDelta(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 11, 11, 11
+ const initQuota, preConsumed = 10000, 5000
+ const actualQuota = 3000 // over-charged by 2000
+ const tokenRemain = 5000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-recalc-neg", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+
+ RecalculateTaskQuota(ctx, task, actualQuota, "adaptor adjustment")
+
+ // User quota should increase by abs(delta) = 2000 (refund overpayment)
+ assert.Equal(t, initQuota+(preConsumed-actualQuota), getUserQuota(t, userID))
+
+ // Token should be refunded the difference
+ assert.Equal(t, tokenRemain+(preConsumed-actualQuota), getTokenRemainQuota(t, tokenID))
+
+ // task.Quota updated
+ assert.Equal(t, actualQuota, task.Quota)
+
+ // Log type should be Refund
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+ assert.Equal(t, preConsumed-actualQuota, log.Quota)
+}
+
+func TestRecalculate_ZeroDelta(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID = 12
+ const initQuota, preConsumed = 10000, 3000
+
+ seedUser(t, userID, initQuota)
+
+ task := makeTask(userID, 0, preConsumed, 0, BillingSourceWallet, 0)
+
+ RecalculateTaskQuota(ctx, task, preConsumed, "exact match")
+
+ // No change to user quota
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+
+ // No log created (delta is zero)
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestRecalculate_ActualQuotaZero(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID = 13
+ const initQuota = 10000
+
+ seedUser(t, userID, initQuota)
+
+ task := makeTask(userID, 0, 5000, 0, BillingSourceWallet, 0)
+
+ RecalculateTaskQuota(ctx, task, 0, "zero actual")
+
+ // No change (early return)
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestRecalculate_Subscription_NegativeDelta(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID, subID = 14, 14, 14, 2
+ const preConsumed = 5000
+ const actualQuota = 2000 // over-charged by 3000
+ const subTotal, subUsed int64 = 100000, 50000
+ const tokenRemain = 8000
+
+ seedUser(t, userID, 0)
+ seedToken(t, tokenID, userID, "sk-sub-recalc", tokenRemain)
+ seedChannel(t, channelID)
+ seedSubscription(t, subID, userID, subTotal, subUsed)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceSubscription, subID)
+
+ RecalculateTaskQuota(ctx, task, actualQuota, "subscription over-charge")
+
+ // Subscription used should decrease by delta (refund 3000)
+ assert.Equal(t, subUsed-int64(preConsumed-actualQuota), getSubscriptionUsed(t, subID))
+
+ // Token refunded
+ assert.Equal(t, tokenRemain+(preConsumed-actualQuota), getTokenRemainQuota(t, tokenID))
+
+ assert.Equal(t, actualQuota, task.Quota)
+
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+}
+
+// ===========================================================================
+// CAS + Billing integration tests
+// Simulates the flow in updateVideoSingleTask (service/task_polling.go)
+// ===========================================================================
+
+// simulatePollBilling reproduces the CAS + billing logic from updateVideoSingleTask.
+// It takes a persisted task (already in DB), applies the new status, and performs
+// the conditional update + billing exactly as the polling loop does.
+func simulatePollBilling(ctx context.Context, task *model.Task, newStatus model.TaskStatus, actualQuota int) {
+ snap := task.Snapshot()
+
+ shouldRefund := false
+ shouldSettle := false
+ quota := task.Quota
+
+ task.Status = newStatus
+ switch string(newStatus) {
+ case model.TaskStatusSuccess:
+ task.Progress = "100%"
+ task.FinishTime = 9999
+ shouldSettle = true
+ case model.TaskStatusFailure:
+ task.Progress = "100%"
+ task.FinishTime = 9999
+ task.FailReason = "upstream error"
+ if quota != 0 {
+ shouldRefund = true
+ }
+ default:
+ task.Progress = "50%"
+ }
+
+ isDone := task.Status == model.TaskStatus(model.TaskStatusSuccess) || task.Status == model.TaskStatus(model.TaskStatusFailure)
+ if isDone && snap.Status != task.Status {
+ won, err := task.UpdateWithStatus(snap.Status)
+ if err != nil {
+ shouldRefund = false
+ shouldSettle = false
+ } else if !won {
+ shouldRefund = false
+ shouldSettle = false
+ }
+ } else if !snap.Equal(task.Snapshot()) {
+ _, _ = task.UpdateWithStatus(snap.Status)
+ }
+
+ if shouldSettle && actualQuota > 0 {
+ RecalculateTaskQuota(ctx, task, actualQuota, "test settle")
+ }
+ if shouldRefund {
+ RefundTaskQuota(ctx, task, task.FailReason)
+ }
+}
+
+func TestCASGuardedRefund_Win(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 20, 20, 20
+ const initQuota, preConsumed = 10000, 4000
+ const tokenRemain = 6000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-cas-refund-win", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ task.Status = model.TaskStatus(model.TaskStatusInProgress)
+ require.NoError(t, model.DB.Create(task).Error)
+
+ simulatePollBilling(ctx, task, model.TaskStatus(model.TaskStatusFailure), 0)
+
+ // CAS wins: task in DB should now be FAILURE
+ var reloaded model.Task
+ require.NoError(t, model.DB.First(&reloaded, task.ID).Error)
+ assert.EqualValues(t, model.TaskStatusFailure, reloaded.Status)
+
+ // Refund should have happened
+ assert.Equal(t, initQuota+preConsumed, getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain+preConsumed, getTokenRemainQuota(t, tokenID))
+
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+}
+
+func TestCASGuardedRefund_Lose(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 21, 21, 21
+ const initQuota, preConsumed = 10000, 4000
+ const tokenRemain = 6000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-cas-refund-lose", tokenRemain)
+ seedChannel(t, channelID)
+
+ // Create task with IN_PROGRESS in DB
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ task.Status = model.TaskStatus(model.TaskStatusInProgress)
+ require.NoError(t, model.DB.Create(task).Error)
+
+ // Simulate another process already transitioning to FAILURE
+ model.DB.Model(&model.Task{}).Where("id = ?", task.ID).Update("status", model.TaskStatusFailure)
+
+ // Our process still has the old in-memory state (IN_PROGRESS) and tries to transition
+ // task.Status is still IN_PROGRESS in the snapshot
+ simulatePollBilling(ctx, task, model.TaskStatus(model.TaskStatusFailure), 0)
+
+ // CAS lost: user quota should NOT change (no double refund)
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
+
+ // No billing log should be created
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestCASGuardedSettle_Win(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 22, 22, 22
+ const initQuota, preConsumed = 10000, 5000
+ const actualQuota = 3000 // over-charged, should get partial refund
+ const tokenRemain = 8000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-cas-settle-win", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ task.Status = model.TaskStatus(model.TaskStatusInProgress)
+ require.NoError(t, model.DB.Create(task).Error)
+
+ simulatePollBilling(ctx, task, model.TaskStatus(model.TaskStatusSuccess), actualQuota)
+
+ // CAS wins: task should be SUCCESS
+ var reloaded model.Task
+ require.NoError(t, model.DB.First(&reloaded, task.ID).Error)
+ assert.EqualValues(t, model.TaskStatusSuccess, reloaded.Status)
+
+ // Settlement should refund the over-charge (5000 - 3000 = 2000 back to user)
+ assert.Equal(t, initQuota+(preConsumed-actualQuota), getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain+(preConsumed-actualQuota), getTokenRemainQuota(t, tokenID))
+
+ // task.Quota should be updated to actualQuota
+ assert.Equal(t, actualQuota, task.Quota)
+}
+
+func TestNonTerminalUpdate_NoBilling(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, channelID = 23, 23
+ const initQuota, preConsumed = 10000, 3000
+
+ seedUser(t, userID, initQuota)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, 0, BillingSourceWallet, 0)
+ task.Status = model.TaskStatus(model.TaskStatusInProgress)
+ task.Progress = "20%"
+ require.NoError(t, model.DB.Create(task).Error)
+
+ // Simulate a non-terminal poll update (still IN_PROGRESS, progress changed)
+ simulatePollBilling(ctx, task, model.TaskStatus(model.TaskStatusInProgress), 0)
+
+ // User quota should NOT change
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+
+ // No billing log
+ assert.Equal(t, int64(0), countLogs(t))
+
+ // Task progress should be updated in DB
+ var reloaded model.Task
+ require.NoError(t, model.DB.First(&reloaded, task.ID).Error)
+ assert.Equal(t, "50%", reloaded.Progress)
+}
+
+// ===========================================================================
+// Mock adaptor for settleTaskBillingOnComplete tests
+// ===========================================================================
+
+type mockAdaptor struct {
+ adjustReturn int
+}
+
+func (m *mockAdaptor) Init(_ *relaycommon.RelayInfo) {}
+func (m *mockAdaptor) FetchTask(string, string, map[string]any, string) (*http.Response, error) {
+ return nil, nil
+}
+func (m *mockAdaptor) ParseTaskResult([]byte) (*relaycommon.TaskInfo, error) { return nil, nil }
+func (m *mockAdaptor) AdjustBillingOnComplete(_ *model.Task, _ *relaycommon.TaskInfo) int {
+ return m.adjustReturn
+}
+
+// ===========================================================================
+// PerCallBilling tests — settleTaskBillingOnComplete
+// ===========================================================================
+
+func TestSettle_PerCallBilling_SkipsAdaptorAdjust(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 30, 30, 30
+ const initQuota, preConsumed = 10000, 5000
+ const tokenRemain = 8000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-percall-adaptor", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ task.PrivateData.BillingContext.PerCallBilling = true
+
+ adaptor := &mockAdaptor{adjustReturn: 2000}
+ taskResult := &relaycommon.TaskInfo{Status: model.TaskStatusSuccess}
+
+ settleTaskBillingOnComplete(ctx, adaptor, task, taskResult)
+
+ // Per-call: no adjustment despite adaptor returning 2000
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
+ assert.Equal(t, preConsumed, task.Quota)
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestSettle_PerCallBilling_SkipsTotalTokens(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 31, 31, 31
+ const initQuota, preConsumed = 10000, 4000
+ const tokenRemain = 7000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-percall-tokens", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ task.PrivateData.BillingContext.PerCallBilling = true
+
+ adaptor := &mockAdaptor{adjustReturn: 0}
+ taskResult := &relaycommon.TaskInfo{Status: model.TaskStatusSuccess, TotalTokens: 9999}
+
+ settleTaskBillingOnComplete(ctx, adaptor, task, taskResult)
+
+ // Per-call: no recalculation by tokens
+ assert.Equal(t, initQuota, getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain, getTokenRemainQuota(t, tokenID))
+ assert.Equal(t, preConsumed, task.Quota)
+ assert.Equal(t, int64(0), countLogs(t))
+}
+
+func TestSettle_NonPerCall_AdaptorAdjustWorks(t *testing.T) {
+ truncate(t)
+ ctx := context.Background()
+
+ const userID, tokenID, channelID = 32, 32, 32
+ const initQuota, preConsumed = 10000, 5000
+ const adaptorQuota = 3000
+ const tokenRemain = 8000
+
+ seedUser(t, userID, initQuota)
+ seedToken(t, tokenID, userID, "sk-nonpercall-adj", tokenRemain)
+ seedChannel(t, channelID)
+
+ task := makeTask(userID, channelID, preConsumed, tokenID, BillingSourceWallet, 0)
+ // PerCallBilling defaults to false
+
+ adaptor := &mockAdaptor{adjustReturn: adaptorQuota}
+ taskResult := &relaycommon.TaskInfo{Status: model.TaskStatusSuccess}
+
+ settleTaskBillingOnComplete(ctx, adaptor, task, taskResult)
+
+ // Non-per-call: adaptor adjustment applies (refund 2000)
+ assert.Equal(t, initQuota+(preConsumed-adaptorQuota), getUserQuota(t, userID))
+ assert.Equal(t, tokenRemain+(preConsumed-adaptorQuota), getTokenRemainQuota(t, tokenID))
+ assert.Equal(t, adaptorQuota, task.Quota)
+
+ log := getLastLog(t)
+ require.NotNil(t, log)
+ assert.Equal(t, model.LogTypeRefund, log.Type)
+}
diff --git a/service/task_polling.go b/service/task_polling.go
new file mode 100644
index 0000000000..dc85e579e8
--- /dev/null
+++ b/service/task_polling.go
@@ -0,0 +1,560 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+
+ "github.com/samber/lo"
+)
+
+// TaskPollingAdaptor 定义轮询所需的最小适配器接口,避免 service -> relay 的循环依赖
+type TaskPollingAdaptor interface {
+ Init(info *relaycommon.RelayInfo)
+ FetchTask(baseURL string, key string, body map[string]any, proxy string) (*http.Response, error)
+ ParseTaskResult(body []byte) (*relaycommon.TaskInfo, error)
+ // AdjustBillingOnComplete 在任务到达终态(成功/失败)时由轮询循环调用。
+ // 返回正数触发差额结算(补扣/退还),返回 0 保持预扣费金额不变。
+ AdjustBillingOnComplete(task *model.Task, taskResult *relaycommon.TaskInfo) int
+}
+
+// GetTaskAdaptorFunc 由 main 包注入,用于获取指定平台的任务适配器。
+// 打破 service -> relay -> relay/channel -> service 的循环依赖。
+var GetTaskAdaptorFunc func(platform constant.TaskPlatform) TaskPollingAdaptor
+
+// sweepTimedOutTasks 在主轮询之前独立清理超时任务。
+// 每次最多处理 100 条,剩余的下个周期继续处理。
+// 使用 per-task CAS (UpdateWithStatus) 防止覆盖被正常轮询已推进的任务。
+func sweepTimedOutTasks(ctx context.Context) {
+ if constant.TaskTimeoutMinutes <= 0 {
+ return
+ }
+ cutoff := time.Now().Unix() - int64(constant.TaskTimeoutMinutes)*60
+ tasks := model.GetTimedOutUnfinishedTasks(cutoff, 100)
+ if len(tasks) == 0 {
+ return
+ }
+
+ const legacyTaskCutoff int64 = 1740182400 // 2026-02-22 00:00:00 UTC
+ reason := fmt.Sprintf("任务超时(%d分钟)", constant.TaskTimeoutMinutes)
+ legacyReason := "任务超时(旧系统遗留任务,不进行退款,请联系管理员)"
+ now := time.Now().Unix()
+ timedOutCount := 0
+
+ for _, task := range tasks {
+ isLegacy := task.SubmitTime > 0 && task.SubmitTime < legacyTaskCutoff
+
+ oldStatus := task.Status
+ task.Status = model.TaskStatusFailure
+ task.Progress = "100%"
+ task.FinishTime = now
+ if isLegacy {
+ task.FailReason = legacyReason
+ } else {
+ task.FailReason = reason
+ }
+
+ won, err := task.UpdateWithStatus(oldStatus)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("sweepTimedOutTasks CAS update error for task %s: %v", task.TaskID, err))
+ continue
+ }
+ if !won {
+ logger.LogInfo(ctx, fmt.Sprintf("sweepTimedOutTasks: task %s already transitioned, skip", task.TaskID))
+ continue
+ }
+ timedOutCount++
+ if !isLegacy && task.Quota != 0 {
+ RefundTaskQuota(ctx, task, reason)
+ }
+ }
+
+ if timedOutCount > 0 {
+ logger.LogInfo(ctx, fmt.Sprintf("sweepTimedOutTasks: timed out %d tasks", timedOutCount))
+ }
+}
+
+// TaskPollingLoop 主轮询循环,每 15 秒检查一次未完成的任务
+func TaskPollingLoop() {
+ for {
+ time.Sleep(time.Duration(15) * time.Second)
+ common.SysLog("任务进度轮询开始")
+ ctx := context.TODO()
+ sweepTimedOutTasks(ctx)
+ allTasks := model.GetAllUnFinishSyncTasks(constant.TaskQueryLimit)
+ platformTask := make(map[constant.TaskPlatform][]*model.Task)
+ for _, t := range allTasks {
+ platformTask[t.Platform] = append(platformTask[t.Platform], t)
+ }
+ for platform, tasks := range platformTask {
+ if len(tasks) == 0 {
+ continue
+ }
+ taskChannelM := make(map[int][]string)
+ taskM := make(map[string]*model.Task)
+ nullTaskIds := make([]int64, 0)
+ for _, task := range tasks {
+ upstreamID := task.GetUpstreamTaskID()
+ if upstreamID == "" {
+ // 统计失败的未完成任务
+ nullTaskIds = append(nullTaskIds, task.ID)
+ continue
+ }
+ taskM[upstreamID] = task
+ taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], upstreamID)
+ }
+ if len(nullTaskIds) > 0 {
+ err := model.TaskBulkUpdateByID(nullTaskIds, map[string]any{
+ "status": "FAILURE",
+ "progress": "100%",
+ })
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("Fix null task_id task error: %v", err))
+ } else {
+ logger.LogInfo(ctx, fmt.Sprintf("Fix null task_id task success: %v", nullTaskIds))
+ }
+ }
+ if len(taskChannelM) == 0 {
+ continue
+ }
+
+ DispatchPlatformUpdate(platform, taskChannelM, taskM)
+ }
+ common.SysLog("任务进度轮询完成")
+ }
+}
+
+// DispatchPlatformUpdate 按平台分发轮询更新
+func DispatchPlatformUpdate(platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) {
+ switch platform {
+ case constant.TaskPlatformMidjourney:
+ // MJ 轮询由其自身处理,这里预留入口
+ case constant.TaskPlatformSuno:
+ _ = UpdateSunoTasks(context.Background(), taskChannelM, taskM)
+ default:
+ if err := UpdateVideoTasks(context.Background(), platform, taskChannelM, taskM); err != nil {
+ common.SysLog(fmt.Sprintf("UpdateVideoTasks fail: %s", err))
+ }
+ }
+}
+
+// UpdateSunoTasks 按渠道更新所有 Suno 任务
+func UpdateSunoTasks(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
+ for channelId, taskIds := range taskChannelM {
+ err := updateSunoTasks(ctx, channelId, taskIds, taskM)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("渠道 #%d 更新异步任务失败: %s", channelId, err.Error()))
+ }
+ }
+ return nil
+}
+
+func updateSunoTasks(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error {
+ logger.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
+ if len(taskIds) == 0 {
+ return nil
+ }
+ ch, err := model.CacheGetChannel(channelId)
+ if err != nil {
+ common.SysLog(fmt.Sprintf("CacheGetChannel: %v", err))
+ // Collect DB primary key IDs for bulk update (taskIds are upstream IDs, not task_id column values)
+ var failedIDs []int64
+ for _, upstreamID := range taskIds {
+ if t, ok := taskM[upstreamID]; ok {
+ failedIDs = append(failedIDs, t.ID)
+ }
+ }
+ err = model.TaskBulkUpdateByID(failedIDs, map[string]any{
+ "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
+ "status": "FAILURE",
+ "progress": "100%",
+ })
+ if err != nil {
+ common.SysLog(fmt.Sprintf("UpdateSunoTask error: %v", err))
+ }
+ return err
+ }
+ adaptor := GetTaskAdaptorFunc(constant.TaskPlatformSuno)
+ if adaptor == nil {
+ return errors.New("adaptor not found")
+ }
+ proxy := ch.GetSetting().Proxy
+ resp, err := adaptor.FetchTask(*ch.BaseURL, ch.Key, map[string]any{
+ "ids": taskIds,
+ }, proxy)
+ if err != nil {
+ common.SysLog(fmt.Sprintf("Get Task Do req error: %v", err))
+ return err
+ }
+ if resp.StatusCode != http.StatusOK {
+ logger.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
+ return fmt.Errorf("Get Task status code: %d", resp.StatusCode)
+ }
+ defer resp.Body.Close()
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ common.SysLog(fmt.Sprintf("Get Suno Task parse body error: %v", err))
+ return err
+ }
+ var responseItems dto.TaskResponse[[]dto.SunoDataResponse]
+ err = common.Unmarshal(responseBody, &responseItems)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("Get Suno Task parse body error2: %v, body: %s", err, string(responseBody)))
+ return err
+ }
+ if !responseItems.IsSuccess() {
+ common.SysLog(fmt.Sprintf("渠道 #%d 未完成的任务有: %d, 成功获取到任务数: %s", channelId, len(taskIds), string(responseBody)))
+ return err
+ }
+
+ for _, responseItem := range responseItems.Data {
+ task := taskM[responseItem.TaskID]
+ if !taskNeedsUpdate(task, responseItem) {
+ continue
+ }
+
+ task.Status = lo.If(model.TaskStatus(responseItem.Status) != "", model.TaskStatus(responseItem.Status)).Else(task.Status)
+ task.FailReason = lo.If(responseItem.FailReason != "", responseItem.FailReason).Else(task.FailReason)
+ task.SubmitTime = lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime)
+ task.StartTime = lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime)
+ task.FinishTime = lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime)
+ if responseItem.FailReason != "" || task.Status == model.TaskStatusFailure {
+ logger.LogInfo(ctx, task.TaskID+" 构建失败,"+task.FailReason)
+ task.Progress = "100%"
+ RefundTaskQuota(ctx, task, task.FailReason)
+ }
+ if responseItem.Status == model.TaskStatusSuccess {
+ task.Progress = "100%"
+ }
+ task.Data = responseItem.Data
+
+ err = task.Update()
+ if err != nil {
+ common.SysLog("UpdateSunoTask task error: " + err.Error())
+ }
+ }
+ return nil
+}
+
+// taskNeedsUpdate 检查 Suno 任务是否需要更新
+func taskNeedsUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool {
+ if oldTask.SubmitTime != newTask.SubmitTime {
+ return true
+ }
+ if oldTask.StartTime != newTask.StartTime {
+ return true
+ }
+ if oldTask.FinishTime != newTask.FinishTime {
+ return true
+ }
+ if string(oldTask.Status) != newTask.Status {
+ return true
+ }
+ if oldTask.FailReason != newTask.FailReason {
+ return true
+ }
+
+ if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != "100%" {
+ return true
+ }
+
+ oldData, _ := common.Marshal(oldTask.Data)
+ newData, _ := common.Marshal(newTask.Data)
+
+ sort.Slice(oldData, func(i, j int) bool {
+ return oldData[i] < oldData[j]
+ })
+ sort.Slice(newData, func(i, j int) bool {
+ return newData[i] < newData[j]
+ })
+
+ if string(oldData) != string(newData) {
+ return true
+ }
+ return false
+}
+
+// UpdateVideoTasks 按渠道更新所有视频任务
+func UpdateVideoTasks(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
+ for channelId, taskIds := range taskChannelM {
+ if err := updateVideoTasks(ctx, platform, channelId, taskIds, taskM); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("Channel #%d failed to update video async tasks: %s", channelId, err.Error()))
+ }
+ }
+ return nil
+}
+
+func updateVideoTasks(ctx context.Context, platform constant.TaskPlatform, channelId int, taskIds []string, taskM map[string]*model.Task) error {
+ logger.LogInfo(ctx, fmt.Sprintf("Channel #%d pending video tasks: %d", channelId, len(taskIds)))
+ if len(taskIds) == 0 {
+ return nil
+ }
+ cacheGetChannel, err := model.CacheGetChannel(channelId)
+ if err != nil {
+ // Collect DB primary key IDs for bulk update (taskIds are upstream IDs, not task_id column values)
+ var failedIDs []int64
+ for _, upstreamID := range taskIds {
+ if t, ok := taskM[upstreamID]; ok {
+ failedIDs = append(failedIDs, t.ID)
+ }
+ }
+ errUpdate := model.TaskBulkUpdateByID(failedIDs, map[string]any{
+ "fail_reason": fmt.Sprintf("Failed to get channel info, channel ID: %d", channelId),
+ "status": "FAILURE",
+ "progress": "100%",
+ })
+ if errUpdate != nil {
+ common.SysLog(fmt.Sprintf("UpdateVideoTask error: %v", errUpdate))
+ }
+ return fmt.Errorf("CacheGetChannel failed: %w", err)
+ }
+ adaptor := GetTaskAdaptorFunc(platform)
+ if adaptor == nil {
+ return fmt.Errorf("video adaptor not found")
+ }
+ info := &relaycommon.RelayInfo{}
+ info.ChannelMeta = &relaycommon.ChannelMeta{
+ ChannelBaseUrl: cacheGetChannel.GetBaseURL(),
+ }
+ info.ApiKey = cacheGetChannel.Key
+ adaptor.Init(info)
+ for _, taskId := range taskIds {
+ if err := updateVideoSingleTask(ctx, adaptor, cacheGetChannel, taskId, taskM); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("Failed to update video task %s: %s", taskId, err.Error()))
+ }
+ // sleep 1 second between each task to avoid hitting rate limits of upstream platforms
+ time.Sleep(1 * time.Second)
+ }
+ return nil
+}
+
+func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *model.Channel, taskId string, taskM map[string]*model.Task) error {
+ baseURL := constant.ChannelBaseURLs[ch.Type]
+ if ch.GetBaseURL() != "" {
+ baseURL = ch.GetBaseURL()
+ }
+ proxy := ch.GetSetting().Proxy
+
+ task := taskM[taskId]
+ if task == nil {
+ logger.LogError(ctx, fmt.Sprintf("Task %s not found in taskM", taskId))
+ return fmt.Errorf("task %s not found", taskId)
+ }
+ key := ch.Key
+
+ privateData := task.PrivateData
+ if privateData.Key != "" {
+ key = privateData.Key
+ }
+ resp, err := adaptor.FetchTask(baseURL, key, map[string]any{
+ "task_id": task.GetUpstreamTaskID(),
+ "action": task.Action,
+ }, proxy)
+ if err != nil {
+ return fmt.Errorf("fetchTask failed for task %s: %w", taskId, err)
+ }
+ defer resp.Body.Close()
+ responseBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("readAll failed for task %s: %w", taskId, err)
+ }
+
+ logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask response: %s", string(responseBody)))
+
+ snap := task.Snapshot()
+
+ taskResult := &relaycommon.TaskInfo{}
+ // try parse as New API response format
+ var responseItems dto.TaskResponse[model.Task]
+ if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() {
+ logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask parsed as new api response format: %+v", responseItems))
+ t := responseItems.Data
+ taskResult.TaskID = t.TaskID
+ taskResult.Status = string(t.Status)
+ taskResult.Url = t.GetResultURL()
+ taskResult.Progress = t.Progress
+ taskResult.Reason = t.FailReason
+ task.Data = t.Data
+ } else if taskResult, err = adaptor.ParseTaskResult(responseBody); err != nil {
+ return fmt.Errorf("parseTaskResult failed for task %s: %w", taskId, err)
+ }
+
+ task.Data = redactVideoResponseBody(responseBody)
+
+ logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask taskResult: %+v", taskResult))
+
+ now := time.Now().Unix()
+ if taskResult.Status == "" {
+ //taskResult = relaycommon.FailTaskInfo("upstream returned empty status")
+ errorResult := &dto.GeneralErrorResponse{}
+ if err = common.Unmarshal(responseBody, &errorResult); err == nil {
+ openaiError := errorResult.TryToOpenAIError()
+ if openaiError != nil {
+ // 返回规范的 OpenAI 错误格式,提取错误信息,判断错误是否为任务失败
+ if openaiError.Code == "429" {
+ // 429 错误通常表示请求过多或速率限制,暂时不认为是任务失败,保持原状态等待下一轮轮询
+ return nil
+ }
+
+ // 其他错误认为是任务失败,记录错误信息并更新任务状态
+ taskResult = relaycommon.FailTaskInfo("upstream returned error")
+ } else {
+ // unknown error format, log original response
+ logger.LogError(ctx, fmt.Sprintf("Task %s returned empty status with unrecognized error format, response: %s", taskId, string(responseBody)))
+ taskResult = relaycommon.FailTaskInfo("upstream returned unrecognized message")
+ }
+ }
+ }
+
+ shouldRefund := false
+ shouldSettle := false
+ quota := task.Quota
+
+ task.Status = model.TaskStatus(taskResult.Status)
+ switch taskResult.Status {
+ case model.TaskStatusSubmitted:
+ task.Progress = taskcommon.ProgressSubmitted
+ case model.TaskStatusQueued:
+ task.Progress = taskcommon.ProgressQueued
+ case model.TaskStatusInProgress:
+ task.Progress = taskcommon.ProgressInProgress
+ if task.StartTime == 0 {
+ task.StartTime = now
+ }
+ case model.TaskStatusSuccess:
+ task.Progress = taskcommon.ProgressComplete
+ if task.FinishTime == 0 {
+ task.FinishTime = now
+ }
+ if strings.HasPrefix(taskResult.Url, "data:") {
+ // data: URI (e.g. Vertex base64 encoded video) — keep in Data, not in ResultURL
+ task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
+ } else if taskResult.Url != "" {
+ // Direct upstream URL (e.g. Kling, Ali, Doubao, etc.)
+ task.PrivateData.ResultURL = taskResult.Url
+ } else {
+ // No URL from adaptor — construct proxy URL using public task ID
+ task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
+ }
+ shouldSettle = true
+ case model.TaskStatusFailure:
+ logger.LogJson(ctx, fmt.Sprintf("Task %s failed", taskId), task)
+ task.Status = model.TaskStatusFailure
+ task.Progress = taskcommon.ProgressComplete
+ if task.FinishTime == 0 {
+ task.FinishTime = now
+ }
+ task.FailReason = taskResult.Reason
+ logger.LogInfo(ctx, fmt.Sprintf("Task %s failed: %s", task.TaskID, task.FailReason))
+ taskResult.Progress = taskcommon.ProgressComplete
+ if quota != 0 {
+ shouldRefund = true
+ }
+ default:
+ return fmt.Errorf("unknown task status %s for task %s", taskResult.Status, task.TaskID)
+ }
+ if taskResult.Progress != "" {
+ task.Progress = taskResult.Progress
+ }
+
+ isDone := task.Status == model.TaskStatusSuccess || task.Status == model.TaskStatusFailure
+ if isDone && snap.Status != task.Status {
+ won, err := task.UpdateWithStatus(snap.Status)
+ if err != nil {
+ logger.LogError(ctx, fmt.Sprintf("UpdateWithStatus failed for task %s: %s", task.TaskID, err.Error()))
+ shouldRefund = false
+ shouldSettle = false
+ } else if !won {
+ logger.LogWarn(ctx, fmt.Sprintf("Task %s already transitioned by another process, skip billing", task.TaskID))
+ shouldRefund = false
+ shouldSettle = false
+ }
+ } else if !snap.Equal(task.Snapshot()) {
+ if _, err := task.UpdateWithStatus(snap.Status); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("Failed to update task %s: %s", task.TaskID, err.Error()))
+ }
+ } else {
+ // No changes, skip update
+ logger.LogDebug(ctx, fmt.Sprintf("No update needed for task %s", task.TaskID))
+ }
+
+ if shouldSettle {
+ settleTaskBillingOnComplete(ctx, adaptor, task, taskResult)
+ }
+ if shouldRefund {
+ RefundTaskQuota(ctx, task, task.FailReason)
+ }
+
+ return nil
+}
+
+func redactVideoResponseBody(body []byte) []byte {
+ var m map[string]any
+ if err := common.Unmarshal(body, &m); err != nil {
+ return body
+ }
+ resp, _ := m["response"].(map[string]any)
+ if resp != nil {
+ delete(resp, "bytesBase64Encoded")
+ if v, ok := resp["video"].(string); ok {
+ resp["video"] = truncateBase64(v)
+ }
+ if vs, ok := resp["videos"].([]any); ok {
+ for i := range vs {
+ if vm, ok := vs[i].(map[string]any); ok {
+ delete(vm, "bytesBase64Encoded")
+ }
+ }
+ }
+ }
+ b, err := common.Marshal(m)
+ if err != nil {
+ return body
+ }
+ return b
+}
+
+func truncateBase64(s string) string {
+ const maxKeep = 256
+ if len(s) <= maxKeep {
+ return s
+ }
+ return s[:maxKeep] + "..."
+}
+
+// settleTaskBillingOnComplete 任务完成时的统一计费调整。
+// 优先级:1. adaptor.AdjustBillingOnComplete 返回正数 → 使用 adaptor 计算的额度
+//
+// 2. taskResult.TotalTokens > 0 → 按 token 重算
+// 3. 都不满足 → 保持预扣额度不变
+func settleTaskBillingOnComplete(ctx context.Context, adaptor TaskPollingAdaptor, task *model.Task, taskResult *relaycommon.TaskInfo) {
+ // 0. 按次计费的任务不做差额结算
+ if bc := task.PrivateData.BillingContext; bc != nil && bc.PerCallBilling {
+ logger.LogInfo(ctx, fmt.Sprintf("任务 %s 按次计费,跳过差额结算", task.TaskID))
+ return
+ }
+ // 1. 优先让 adaptor 决定最终额度
+ if actualQuota := adaptor.AdjustBillingOnComplete(task, taskResult); actualQuota > 0 {
+ RecalculateTaskQuota(ctx, task, actualQuota, "adaptor计费调整")
+ return
+ }
+ // 2. 回退到 token 重算
+ if taskResult.TotalTokens > 0 {
+ RecalculateTaskQuotaByTokens(ctx, task, taskResult.TotalTokens)
+ return
+ }
+ // 3. 无调整,保持预扣额度
+}
diff --git a/service/text_quota.go b/service/text_quota.go
new file mode 100644
index 0000000000..8caee8f287
--- /dev/null
+++ b/service/text_quota.go
@@ -0,0 +1,430 @@
+package service
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+ "github.com/shopspring/decimal"
+)
+
+type textQuotaSummary struct {
+ PromptTokens int
+ CompletionTokens int
+ TotalTokens int
+ CacheTokens int
+ CacheCreationTokens int
+ CacheCreationTokens5m int
+ CacheCreationTokens1h int
+ ImageTokens int
+ AudioTokens int
+ ModelName string
+ TokenName string
+ UseTimeSeconds int64
+ CompletionRatio float64
+ CacheRatio float64
+ ImageRatio float64
+ ModelRatio float64
+ GroupRatio float64
+ ModelPrice float64
+ CacheCreationRatio float64
+ CacheCreationRatio5m float64
+ CacheCreationRatio1h float64
+ Quota int
+ IsClaudeUsageSemantic bool
+ UsageSemantic string
+ WebSearchPrice float64
+ WebSearchCallCount int
+ ClaudeWebSearchPrice float64
+ ClaudeWebSearchCallCount int
+ FileSearchPrice float64
+ FileSearchCallCount int
+ AudioInputPrice float64
+ ImageGenerationCallPrice float64
+}
+
+func cacheWriteTokensTotal(summary textQuotaSummary) int {
+ if summary.CacheCreationTokens5m > 0 || summary.CacheCreationTokens1h > 0 {
+ splitCacheWriteTokens := summary.CacheCreationTokens5m + summary.CacheCreationTokens1h
+ if summary.CacheCreationTokens > splitCacheWriteTokens {
+ return summary.CacheCreationTokens
+ }
+ return splitCacheWriteTokens
+ }
+ return summary.CacheCreationTokens
+}
+
+func isLegacyClaudeDerivedOpenAIUsage(relayInfo *relaycommon.RelayInfo, usage *dto.Usage) bool {
+ if relayInfo == nil || usage == nil {
+ return false
+ }
+ if relayInfo.GetFinalRequestRelayFormat() == types.RelayFormatClaude {
+ return false
+ }
+ if usage.UsageSource != "" || usage.UsageSemantic != "" {
+ return false
+ }
+ return usage.ClaudeCacheCreation5mTokens > 0 || usage.ClaudeCacheCreation1hTokens > 0
+}
+
+func calculateTextQuotaSummary(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage) textQuotaSummary {
+ summary := textQuotaSummary{
+ ModelName: relayInfo.OriginModelName,
+ TokenName: ctx.GetString("token_name"),
+ UseTimeSeconds: time.Now().Unix() - relayInfo.StartTime.Unix(),
+ CompletionRatio: relayInfo.PriceData.CompletionRatio,
+ CacheRatio: relayInfo.PriceData.CacheRatio,
+ ImageRatio: relayInfo.PriceData.ImageRatio,
+ ModelRatio: relayInfo.PriceData.ModelRatio,
+ GroupRatio: relayInfo.PriceData.GroupRatioInfo.GroupRatio,
+ ModelPrice: relayInfo.PriceData.ModelPrice,
+ CacheCreationRatio: relayInfo.PriceData.CacheCreationRatio,
+ CacheCreationRatio5m: relayInfo.PriceData.CacheCreation5mRatio,
+ CacheCreationRatio1h: relayInfo.PriceData.CacheCreation1hRatio,
+ UsageSemantic: usageSemanticFromUsage(relayInfo, usage),
+ }
+ summary.IsClaudeUsageSemantic = summary.UsageSemantic == "anthropic"
+
+ if usage == nil {
+ usage = &dto.Usage{
+ PromptTokens: relayInfo.GetEstimatePromptTokens(),
+ CompletionTokens: 0,
+ TotalTokens: relayInfo.GetEstimatePromptTokens(),
+ }
+ }
+
+ summary.PromptTokens = usage.PromptTokens
+ summary.CompletionTokens = usage.CompletionTokens
+ summary.TotalTokens = usage.PromptTokens + usage.CompletionTokens
+ summary.CacheTokens = usage.PromptTokensDetails.CachedTokens
+ summary.CacheCreationTokens = usage.PromptTokensDetails.CachedCreationTokens
+ summary.CacheCreationTokens5m = usage.ClaudeCacheCreation5mTokens
+ summary.CacheCreationTokens1h = usage.ClaudeCacheCreation1hTokens
+ summary.ImageTokens = usage.PromptTokensDetails.ImageTokens
+ summary.AudioTokens = usage.PromptTokensDetails.AudioTokens
+ legacyClaudeDerived := isLegacyClaudeDerivedOpenAIUsage(relayInfo, usage)
+ isOpenRouterClaudeBilling := relayInfo.ChannelMeta != nil &&
+ relayInfo.ChannelType == constant.ChannelTypeOpenRouter &&
+ summary.IsClaudeUsageSemantic
+
+ if isOpenRouterClaudeBilling {
+ summary.PromptTokens -= summary.CacheTokens
+ isUsingCustomSettings := relayInfo.PriceData.UsePrice || hasCustomModelRatio(summary.ModelName, relayInfo.PriceData.ModelRatio)
+ if summary.CacheCreationTokens == 0 && relayInfo.PriceData.CacheCreationRatio != 1 && usage.Cost != 0 && !isUsingCustomSettings {
+ maybeCacheCreationTokens := CalcOpenRouterCacheCreateTokens(*usage, relayInfo.PriceData)
+ if maybeCacheCreationTokens >= 0 && summary.PromptTokens >= maybeCacheCreationTokens {
+ summary.CacheCreationTokens = maybeCacheCreationTokens
+ }
+ }
+ summary.PromptTokens -= summary.CacheCreationTokens
+ }
+
+ dPromptTokens := decimal.NewFromInt(int64(summary.PromptTokens))
+ dCacheTokens := decimal.NewFromInt(int64(summary.CacheTokens))
+ dImageTokens := decimal.NewFromInt(int64(summary.ImageTokens))
+ dAudioTokens := decimal.NewFromInt(int64(summary.AudioTokens))
+ dCompletionTokens := decimal.NewFromInt(int64(summary.CompletionTokens))
+ dCachedCreationTokens := decimal.NewFromInt(int64(summary.CacheCreationTokens))
+ dCompletionRatio := decimal.NewFromFloat(summary.CompletionRatio)
+ dCacheRatio := decimal.NewFromFloat(summary.CacheRatio)
+ dImageRatio := decimal.NewFromFloat(summary.ImageRatio)
+ dModelRatio := decimal.NewFromFloat(summary.ModelRatio)
+ dGroupRatio := decimal.NewFromFloat(summary.GroupRatio)
+ dModelPrice := decimal.NewFromFloat(summary.ModelPrice)
+ dCacheCreationRatio := decimal.NewFromFloat(summary.CacheCreationRatio)
+ dCacheCreationRatio5m := decimal.NewFromFloat(summary.CacheCreationRatio5m)
+ dCacheCreationRatio1h := decimal.NewFromFloat(summary.CacheCreationRatio1h)
+ dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
+
+ ratio := dModelRatio.Mul(dGroupRatio)
+
+ var dWebSearchQuota decimal.Decimal
+ if relayInfo.ResponsesUsageInfo != nil {
+ if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
+ summary.WebSearchCallCount = webSearchTool.CallCount
+ summary.WebSearchPrice = operation_setting.GetWebSearchPricePerThousand(summary.ModelName, webSearchTool.SearchContextSize)
+ dWebSearchQuota = decimal.NewFromFloat(summary.WebSearchPrice).
+ Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
+ Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
+ }
+ } else if strings.HasSuffix(summary.ModelName, "search-preview") {
+ searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
+ if searchContextSize == "" {
+ searchContextSize = "medium"
+ }
+ summary.WebSearchCallCount = 1
+ summary.WebSearchPrice = operation_setting.GetWebSearchPricePerThousand(summary.ModelName, searchContextSize)
+ dWebSearchQuota = decimal.NewFromFloat(summary.WebSearchPrice).
+ Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
+ }
+
+ var dClaudeWebSearchQuota decimal.Decimal
+ summary.ClaudeWebSearchCallCount = ctx.GetInt("claude_web_search_requests")
+ if summary.ClaudeWebSearchCallCount > 0 {
+ summary.ClaudeWebSearchPrice = operation_setting.GetClaudeWebSearchPricePerThousand()
+ dClaudeWebSearchQuota = decimal.NewFromFloat(summary.ClaudeWebSearchPrice).
+ Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit).
+ Mul(decimal.NewFromInt(int64(summary.ClaudeWebSearchCallCount)))
+ }
+
+ var dFileSearchQuota decimal.Decimal
+ if relayInfo.ResponsesUsageInfo != nil {
+ if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
+ summary.FileSearchCallCount = fileSearchTool.CallCount
+ summary.FileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
+ dFileSearchQuota = decimal.NewFromFloat(summary.FileSearchPrice).
+ Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
+ Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
+ }
+ }
+
+ var dImageGenerationCallQuota decimal.Decimal
+ if ctx.GetBool("image_generation_call") {
+ summary.ImageGenerationCallPrice = operation_setting.GetGPTImage1PriceOnceCall(ctx.GetString("image_generation_call_quality"), ctx.GetString("image_generation_call_size"))
+ dImageGenerationCallQuota = decimal.NewFromFloat(summary.ImageGenerationCallPrice).Mul(dGroupRatio).Mul(dQuotaPerUnit)
+ }
+
+ var audioInputQuota decimal.Decimal
+ if !relayInfo.PriceData.UsePrice {
+ baseTokens := dPromptTokens
+
+ var cachedTokensWithRatio decimal.Decimal
+ if !dCacheTokens.IsZero() {
+ if !summary.IsClaudeUsageSemantic && !legacyClaudeDerived {
+ baseTokens = baseTokens.Sub(dCacheTokens)
+ }
+ cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
+ }
+
+ var cachedCreationTokensWithRatio decimal.Decimal
+ hasSplitCacheCreationTokens := summary.CacheCreationTokens5m > 0 || summary.CacheCreationTokens1h > 0
+ if !dCachedCreationTokens.IsZero() || hasSplitCacheCreationTokens {
+ if !summary.IsClaudeUsageSemantic && !legacyClaudeDerived {
+ baseTokens = baseTokens.Sub(dCachedCreationTokens)
+ cachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCacheCreationRatio)
+ } else {
+ remaining := summary.CacheCreationTokens - summary.CacheCreationTokens5m - summary.CacheCreationTokens1h
+ if remaining < 0 {
+ remaining = 0
+ }
+ cachedCreationTokensWithRatio = decimal.NewFromInt(int64(remaining)).Mul(dCacheCreationRatio)
+ cachedCreationTokensWithRatio = cachedCreationTokensWithRatio.Add(decimal.NewFromInt(int64(summary.CacheCreationTokens5m)).Mul(dCacheCreationRatio5m))
+ cachedCreationTokensWithRatio = cachedCreationTokensWithRatio.Add(decimal.NewFromInt(int64(summary.CacheCreationTokens1h)).Mul(dCacheCreationRatio1h))
+ }
+ }
+
+ var imageTokensWithRatio decimal.Decimal
+ if !dImageTokens.IsZero() {
+ baseTokens = baseTokens.Sub(dImageTokens)
+ imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
+ }
+
+ if !dAudioTokens.IsZero() {
+ summary.AudioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(summary.ModelName)
+ if summary.AudioInputPrice > 0 {
+ baseTokens = baseTokens.Sub(dAudioTokens)
+ audioInputQuota = decimal.NewFromFloat(summary.AudioInputPrice).
+ Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
+ }
+ }
+
+ promptQuota := baseTokens.Add(cachedTokensWithRatio).Add(imageTokensWithRatio).Add(cachedCreationTokensWithRatio)
+ completionQuota := dCompletionTokens.Mul(dCompletionRatio)
+ quotaCalculateDecimal := promptQuota.Add(completionQuota).Mul(ratio)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dClaudeWebSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dImageGenerationCallQuota)
+
+ if len(relayInfo.PriceData.OtherRatios) > 0 {
+ for _, otherRatio := range relayInfo.PriceData.OtherRatios {
+ quotaCalculateDecimal = quotaCalculateDecimal.Mul(decimal.NewFromFloat(otherRatio))
+ }
+ }
+
+ if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
+ quotaCalculateDecimal = decimal.NewFromInt(1)
+ }
+ summary.Quota = int(quotaCalculateDecimal.Round(0).IntPart())
+ } else {
+ quotaCalculateDecimal := dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dClaudeWebSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
+ quotaCalculateDecimal = quotaCalculateDecimal.Add(dImageGenerationCallQuota)
+ if len(relayInfo.PriceData.OtherRatios) > 0 {
+ for _, otherRatio := range relayInfo.PriceData.OtherRatios {
+ quotaCalculateDecimal = quotaCalculateDecimal.Mul(decimal.NewFromFloat(otherRatio))
+ }
+ }
+ summary.Quota = int(quotaCalculateDecimal.Round(0).IntPart())
+ }
+
+ if summary.TotalTokens == 0 {
+ summary.Quota = 0
+ } else if !ratio.IsZero() && summary.Quota == 0 {
+ summary.Quota = 1
+ }
+
+ return summary
+}
+
+func usageSemanticFromUsage(relayInfo *relaycommon.RelayInfo, usage *dto.Usage) string {
+ if usage != nil && usage.UsageSemantic != "" {
+ return usage.UsageSemantic
+ }
+ if relayInfo != nil && relayInfo.GetFinalRequestRelayFormat() == types.RelayFormatClaude {
+ return "anthropic"
+ }
+ return "openai"
+}
+
+func PostTextConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, extraContent []string) {
+ originUsage := usage
+ if usage == nil {
+ extraContent = append(extraContent, "上游无计费信息")
+ }
+ if originUsage != nil {
+ ObserveChannelAffinityUsageCacheByRelayFormat(ctx, usage, relayInfo.GetFinalRequestRelayFormat())
+ }
+
+ adminRejectReason := common.GetContextKeyString(ctx, constant.ContextKeyAdminRejectReason)
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ if summary.WebSearchCallCount > 0 {
+ extraContent = append(extraContent, fmt.Sprintf("Web Search 调用 %d 次,调用花费 %s", summary.WebSearchCallCount, decimal.NewFromFloat(summary.WebSearchPrice).Mul(decimal.NewFromInt(int64(summary.WebSearchCallCount))).Div(decimal.NewFromInt(1000)).Mul(decimal.NewFromFloat(summary.GroupRatio)).Mul(decimal.NewFromFloat(common.QuotaPerUnit)).String()))
+ }
+ if summary.ClaudeWebSearchCallCount > 0 {
+ extraContent = append(extraContent, fmt.Sprintf("Claude Web Search 调用 %d 次,调用花费 %s", summary.ClaudeWebSearchCallCount, decimal.NewFromFloat(summary.ClaudeWebSearchPrice).Div(decimal.NewFromInt(1000)).Mul(decimal.NewFromFloat(summary.GroupRatio)).Mul(decimal.NewFromFloat(common.QuotaPerUnit)).Mul(decimal.NewFromInt(int64(summary.ClaudeWebSearchCallCount))).String()))
+ }
+ if summary.FileSearchCallCount > 0 {
+ extraContent = append(extraContent, fmt.Sprintf("File Search 调用 %d 次,调用花费 %s", summary.FileSearchCallCount, decimal.NewFromFloat(summary.FileSearchPrice).Mul(decimal.NewFromInt(int64(summary.FileSearchCallCount))).Div(decimal.NewFromInt(1000)).Mul(decimal.NewFromFloat(summary.GroupRatio)).Mul(decimal.NewFromFloat(common.QuotaPerUnit)).String()))
+ }
+ if summary.AudioInputPrice > 0 && summary.AudioTokens > 0 {
+ extraContent = append(extraContent, fmt.Sprintf("Audio Input 花费 %s", decimal.NewFromFloat(summary.AudioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(decimal.NewFromInt(int64(summary.AudioTokens))).Mul(decimal.NewFromFloat(summary.GroupRatio)).Mul(decimal.NewFromFloat(common.QuotaPerUnit)).String()))
+ }
+ if summary.ImageGenerationCallPrice > 0 {
+ extraContent = append(extraContent, fmt.Sprintf("Image Generation Call 花费 %s", decimal.NewFromFloat(summary.ImageGenerationCallPrice).Mul(decimal.NewFromFloat(summary.GroupRatio)).Mul(decimal.NewFromFloat(common.QuotaPerUnit)).String()))
+ }
+
+ if summary.TotalTokens == 0 {
+ extraContent = append(extraContent, "上游没有返回计费信息,无法扣费(可能是上游超时)")
+ logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, summary.ModelName, relayInfo.FinalPreConsumedQuota))
+ } else {
+ model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, summary.Quota)
+ model.UpdateChannelUsedQuota(relayInfo.ChannelId, summary.Quota)
+ }
+
+ if err := SettleBilling(ctx, relayInfo, summary.Quota); err != nil {
+ logger.LogError(ctx, "error settling billing: "+err.Error())
+ }
+
+ logModel := summary.ModelName
+ if strings.HasPrefix(logModel, "gpt-4-gizmo") {
+ logModel = "gpt-4-gizmo-*"
+ extraContent = append(extraContent, fmt.Sprintf("模型 %s", summary.ModelName))
+ }
+ if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
+ logModel = "gpt-4o-gizmo-*"
+ extraContent = append(extraContent, fmt.Sprintf("模型 %s", summary.ModelName))
+ }
+
+ logContent := strings.Join(extraContent, ", ")
+ var other map[string]interface{}
+ if summary.IsClaudeUsageSemantic {
+ other = GenerateClaudeOtherInfo(ctx, relayInfo,
+ summary.ModelRatio, summary.GroupRatio, summary.CompletionRatio,
+ summary.CacheTokens, summary.CacheRatio,
+ summary.CacheCreationTokens, summary.CacheCreationRatio,
+ summary.CacheCreationTokens5m, summary.CacheCreationRatio5m,
+ summary.CacheCreationTokens1h, summary.CacheCreationRatio1h,
+ summary.ModelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
+ other["usage_semantic"] = "anthropic"
+ } else {
+ other = GenerateTextOtherInfo(ctx, relayInfo, summary.ModelRatio, summary.GroupRatio, summary.CompletionRatio, summary.CacheTokens, summary.CacheRatio, summary.ModelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
+ }
+ if adminRejectReason != "" {
+ other["reject_reason"] = adminRejectReason
+ }
+ if summary.ImageTokens != 0 {
+ other["image"] = true
+ other["image_ratio"] = summary.ImageRatio
+ other["image_output"] = summary.ImageTokens
+ }
+ if summary.WebSearchCallCount > 0 {
+ other["web_search"] = true
+ other["web_search_call_count"] = summary.WebSearchCallCount
+ other["web_search_price"] = summary.WebSearchPrice
+ } else if summary.ClaudeWebSearchCallCount > 0 {
+ other["web_search"] = true
+ other["web_search_call_count"] = summary.ClaudeWebSearchCallCount
+ other["web_search_price"] = summary.ClaudeWebSearchPrice
+ }
+ if summary.FileSearchCallCount > 0 {
+ other["file_search"] = true
+ other["file_search_call_count"] = summary.FileSearchCallCount
+ other["file_search_price"] = summary.FileSearchPrice
+ }
+ if summary.AudioInputPrice > 0 && summary.AudioTokens > 0 {
+ other["audio_input_seperate_price"] = true
+ other["audio_input_token_count"] = summary.AudioTokens
+ other["audio_input_price"] = summary.AudioInputPrice
+ }
+ if summary.ImageGenerationCallPrice > 0 {
+ other["image_generation_call"] = true
+ other["image_generation_call_price"] = summary.ImageGenerationCallPrice
+ }
+ if summary.CacheCreationTokens > 0 {
+ other["cache_creation_tokens"] = summary.CacheCreationTokens
+ other["cache_creation_ratio"] = summary.CacheCreationRatio
+ }
+ if summary.CacheCreationTokens5m > 0 {
+ other["cache_creation_tokens_5m"] = summary.CacheCreationTokens5m
+ other["cache_creation_ratio_5m"] = summary.CacheCreationRatio5m
+ }
+ if summary.CacheCreationTokens1h > 0 {
+ other["cache_creation_tokens_1h"] = summary.CacheCreationTokens1h
+ other["cache_creation_ratio_1h"] = summary.CacheCreationRatio1h
+ }
+ cacheWriteTokens := cacheWriteTokensTotal(summary)
+ if cacheWriteTokens > 0 {
+ // cache_write_tokens: normalized cache creation total for UI display.
+ // If split 5m/1h values are present, this is their sum; otherwise it falls back
+ // to cache_creation_tokens.
+ other["cache_write_tokens"] = cacheWriteTokens
+ }
+ if relayInfo.GetFinalRequestRelayFormat() != types.RelayFormatClaude && usage != nil && usage.UsageSource != "" && usage.InputTokens > 0 {
+ // input_tokens_total: explicit normalized total input used by the usage log UI.
+ // Only write this field when upstream/current conversion has already provided a
+ // reliable total input value and tagged the usage source. Do not infer it from
+ // prompt/cache fields here, otherwise old upstream payloads may be double-counted.
+ other["input_tokens_total"] = usage.InputTokens
+ }
+
+ model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
+ ChannelId: relayInfo.ChannelId,
+ PromptTokens: summary.PromptTokens,
+ CompletionTokens: summary.CompletionTokens,
+ ModelName: logModel,
+ TokenName: summary.TokenName,
+ Quota: summary.Quota,
+ Content: logContent,
+ TokenId: relayInfo.TokenId,
+ UseTimeSeconds: int(summary.UseTimeSeconds),
+ IsStream: relayInfo.IsStream,
+ Group: relayInfo.UsingGroup,
+ Other: other,
+ })
+}
diff --git a/service/text_quota_test.go b/service/text_quota_test.go
new file mode 100644
index 0000000000..e995de17ae
--- /dev/null
+++ b/service/text_quota_test.go
@@ -0,0 +1,318 @@
+package service
+
+import (
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/QuantumNous/new-api/constant"
+ "github.com/QuantumNous/new-api/dto"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCalculateTextQuotaSummaryUnifiedForClaudeSemantic(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ usage := &dto.Usage{
+ PromptTokens: 1000,
+ CompletionTokens: 200,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 100,
+ CachedCreationTokens: 50,
+ },
+ ClaudeCacheCreation5mTokens: 10,
+ ClaudeCacheCreation1hTokens: 20,
+ }
+
+ priceData := types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 2,
+ CacheRatio: 0.1,
+ CacheCreationRatio: 1.25,
+ CacheCreation5mRatio: 1.25,
+ CacheCreation1hRatio: 2,
+ GroupRatioInfo: types.GroupRatioInfo{
+ GroupRatio: 1,
+ },
+ }
+
+ chatRelayInfo := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ FinalRequestRelayFormat: types.RelayFormatClaude,
+ OriginModelName: "claude-3-7-sonnet",
+ PriceData: priceData,
+ StartTime: time.Now(),
+ }
+ messageRelayInfo := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatClaude,
+ FinalRequestRelayFormat: types.RelayFormatClaude,
+ OriginModelName: "claude-3-7-sonnet",
+ PriceData: priceData,
+ StartTime: time.Now(),
+ }
+
+ chatSummary := calculateTextQuotaSummary(ctx, chatRelayInfo, usage)
+ messageSummary := calculateTextQuotaSummary(ctx, messageRelayInfo, usage)
+
+ require.Equal(t, messageSummary.Quota, chatSummary.Quota)
+ require.Equal(t, messageSummary.CacheCreationTokens5m, chatSummary.CacheCreationTokens5m)
+ require.Equal(t, messageSummary.CacheCreationTokens1h, chatSummary.CacheCreationTokens1h)
+ require.True(t, chatSummary.IsClaudeUsageSemantic)
+ require.Equal(t, 1488, chatSummary.Quota)
+}
+
+func TestCalculateTextQuotaSummaryUsesSplitClaudeCacheCreationRatios(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ FinalRequestRelayFormat: types.RelayFormatClaude,
+ OriginModelName: "claude-3-7-sonnet",
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 1,
+ CacheRatio: 0,
+ CacheCreationRatio: 1,
+ CacheCreation5mRatio: 2,
+ CacheCreation1hRatio: 3,
+ GroupRatioInfo: types.GroupRatioInfo{
+ GroupRatio: 1,
+ },
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 100,
+ CompletionTokens: 0,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedCreationTokens: 10,
+ },
+ ClaudeCacheCreation5mTokens: 2,
+ ClaudeCacheCreation1hTokens: 3,
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ // 100 + remaining(5)*1 + 2*2 + 3*3 = 118
+ require.Equal(t, 118, summary.Quota)
+}
+
+func TestCalculateTextQuotaSummaryUsesAnthropicUsageSemanticFromUpstreamUsage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ OriginModelName: "claude-3-7-sonnet",
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 2,
+ CacheRatio: 0.1,
+ CacheCreationRatio: 1.25,
+ CacheCreation5mRatio: 1.25,
+ CacheCreation1hRatio: 2,
+ GroupRatioInfo: types.GroupRatioInfo{
+ GroupRatio: 1,
+ },
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 1000,
+ CompletionTokens: 200,
+ UsageSemantic: "anthropic",
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 100,
+ CachedCreationTokens: 50,
+ },
+ ClaudeCacheCreation5mTokens: 10,
+ ClaudeCacheCreation1hTokens: 20,
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ require.True(t, summary.IsClaudeUsageSemantic)
+ require.Equal(t, "anthropic", summary.UsageSemantic)
+ require.Equal(t, 1488, summary.Quota)
+}
+
+func TestCacheWriteTokensTotal(t *testing.T) {
+ t.Run("split cache creation", func(t *testing.T) {
+ summary := textQuotaSummary{
+ CacheCreationTokens: 50,
+ CacheCreationTokens5m: 10,
+ CacheCreationTokens1h: 20,
+ }
+ require.Equal(t, 50, cacheWriteTokensTotal(summary))
+ })
+
+ t.Run("legacy cache creation", func(t *testing.T) {
+ summary := textQuotaSummary{CacheCreationTokens: 50}
+ require.Equal(t, 50, cacheWriteTokensTotal(summary))
+ })
+
+ t.Run("split cache creation without aggregate remainder", func(t *testing.T) {
+ summary := textQuotaSummary{
+ CacheCreationTokens5m: 10,
+ CacheCreationTokens1h: 20,
+ }
+ require.Equal(t, 30, cacheWriteTokensTotal(summary))
+ })
+}
+
+func TestCalculateTextQuotaSummaryHandlesLegacyClaudeDerivedOpenAIUsage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ RelayFormat: types.RelayFormatOpenAI,
+ OriginModelName: "claude-3-7-sonnet",
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 5,
+ CacheRatio: 0.1,
+ CacheCreationRatio: 1.25,
+ CacheCreation5mRatio: 1.25,
+ CacheCreation1hRatio: 2,
+ GroupRatioInfo: types.GroupRatioInfo{GroupRatio: 1},
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 62,
+ CompletionTokens: 95,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 3544,
+ },
+ ClaudeCacheCreation5mTokens: 586,
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ // 62 + 3544*0.1 + 586*1.25 + 95*5 = 1624.9 => 1624
+ require.Equal(t, 1624, summary.Quota)
+}
+
+func TestCalculateTextQuotaSummarySeparatesOpenRouterCacheReadFromPromptBilling(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ OriginModelName: "openai/gpt-4.1",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ChannelType: constant.ChannelTypeOpenRouter,
+ },
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 1,
+ CacheRatio: 0.1,
+ CacheCreationRatio: 1.25,
+ GroupRatioInfo: types.GroupRatioInfo{GroupRatio: 1},
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 2604,
+ CompletionTokens: 383,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 2432,
+ },
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ // OpenRouter OpenAI-format display keeps prompt_tokens as total input,
+ // but billing still separates normal input from cache read tokens.
+ // quota = (2604 - 2432) + 2432*0.1 + 383 = 798.2 => 798
+ require.Equal(t, 2604, summary.PromptTokens)
+ require.Equal(t, 798, summary.Quota)
+}
+
+func TestCalculateTextQuotaSummarySeparatesOpenRouterCacheCreationFromPromptBilling(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ OriginModelName: "openai/gpt-4.1",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ChannelType: constant.ChannelTypeOpenRouter,
+ },
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 1,
+ CacheCreationRatio: 1.25,
+ GroupRatioInfo: types.GroupRatioInfo{GroupRatio: 1},
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 2604,
+ CompletionTokens: 383,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedCreationTokens: 100,
+ },
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ // prompt_tokens is still logged as total input, but cache creation is billed separately.
+ // quota = (2604 - 100) + 100*1.25 + 383 = 3012
+ require.Equal(t, 2604, summary.PromptTokens)
+ require.Equal(t, 3012, summary.Quota)
+}
+
+func TestCalculateTextQuotaSummaryKeepsPrePRClaudeOpenRouterBilling(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(w)
+
+ relayInfo := &relaycommon.RelayInfo{
+ FinalRequestRelayFormat: types.RelayFormatClaude,
+ OriginModelName: "anthropic/claude-3.7-sonnet",
+ ChannelMeta: &relaycommon.ChannelMeta{
+ ChannelType: constant.ChannelTypeOpenRouter,
+ },
+ PriceData: types.PriceData{
+ ModelRatio: 1,
+ CompletionRatio: 1,
+ CacheRatio: 0.1,
+ CacheCreationRatio: 1.25,
+ GroupRatioInfo: types.GroupRatioInfo{GroupRatio: 1},
+ },
+ StartTime: time.Now(),
+ }
+
+ usage := &dto.Usage{
+ PromptTokens: 2604,
+ CompletionTokens: 383,
+ PromptTokensDetails: dto.InputTokenDetails{
+ CachedTokens: 2432,
+ },
+ }
+
+ summary := calculateTextQuotaSummary(ctx, relayInfo, usage)
+
+ // Pre-PR PostClaudeConsumeQuota behavior for OpenRouter:
+ // prompt = 2604 - 2432 = 172
+ // quota = 172 + 2432*0.1 + 383 = 798.2 => 798
+ require.True(t, summary.IsClaudeUsageSemantic)
+ require.Equal(t, 172, summary.PromptTokens)
+ require.Equal(t, 798, summary.Quota)
+}
diff --git a/service/token_counter.go b/service/token_counter.go
index c70c54a88a..63b76d978a 100644
--- a/service/token_counter.go
+++ b/service/token_counter.go
@@ -3,10 +3,6 @@ package service
import (
"errors"
"fmt"
- "image"
- _ "image/gif"
- _ "image/jpeg"
- _ "image/png"
"log"
"math"
"path/filepath"
@@ -23,8 +19,8 @@ import (
"github.com/gin-gonic/gin"
)
-func getImageToken(fileMeta *types.FileMeta, model string, stream bool) (int, error) {
- if fileMeta == nil {
+func getImageToken(c *gin.Context, fileMeta *types.FileMeta, model string, stream bool) (int, error) {
+ if fileMeta == nil || fileMeta.Source == nil {
return 0, fmt.Errorf("image_url_is_nil")
}
@@ -99,35 +95,18 @@ func getImageToken(fileMeta *types.FileMeta, model string, stream bool) (int, er
fileMeta.Detail = "high"
}
- // Decode image to get dimensions
- var config image.Config
- var err error
- var format string
- var b64str string
-
- if fileMeta.ParsedData != nil {
- config, format, b64str, err = DecodeBase64ImageData(fileMeta.ParsedData.Base64Data)
- } else {
- if strings.HasPrefix(fileMeta.OriginData, "http") {
- config, format, err = DecodeUrlImageData(fileMeta.OriginData)
- } else {
- common.SysLog(fmt.Sprintf("decoding image"))
- config, format, b64str, err = DecodeBase64ImageData(fileMeta.OriginData)
- }
- fileMeta.MimeType = format
- }
-
+ // 使用统一的文件服务获取图片配置
+ config, format, err := GetImageConfig(c, fileMeta.Source)
if err != nil {
return 0, err
}
-
if config.Width == 0 || config.Height == 0 {
- // not an image
- if format != "" && b64str != "" {
+ // not an image, but might be a valid file
+ if format != "" {
// file type
return 3 * baseTokens, nil
}
- return 0, errors.New(fmt.Sprintf("fail to decode base64 config: %s", fileMeta.OriginData))
+ return 0, errors.New(fmt.Sprintf("fail to decode image config: %s", fileMeta.GetIdentifier()))
}
width := config.Width
@@ -269,48 +248,25 @@ func EstimateRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *rela
shouldFetchFiles = false
}
+ // 使用统一的文件服务获取文件类型
for _, file := range meta.Files {
- if strings.HasPrefix(file.OriginData, "http") {
- if shouldFetchFiles {
- mineType, err := GetFileTypeFromUrl(c, file.OriginData, "token_counter")
- if err != nil {
- return 0, fmt.Errorf("error getting file base64 from url: %v", err)
- }
- if strings.HasPrefix(mineType, "image/") {
- file.FileType = types.FileTypeImage
- } else if strings.HasPrefix(mineType, "video/") {
- file.FileType = types.FileTypeVideo
- } else if strings.HasPrefix(mineType, "audio/") {
- file.FileType = types.FileTypeAudio
- } else {
- file.FileType = types.FileTypeFile
- }
- file.MimeType = mineType
- }
- } else if strings.HasPrefix(file.OriginData, "data:") {
- // get mime type from base64 header
- parts := strings.SplitN(file.OriginData, ",", 2)
- if len(parts) >= 1 {
- header := parts[0]
- // Extract mime type from "data:mime/type;base64" format
- if strings.Contains(header, ":") && strings.Contains(header, ";") {
- mimeStart := strings.Index(header, ":") + 1
- mimeEnd := strings.Index(header, ";")
- if mimeStart < mimeEnd {
- mineType := header[mimeStart:mimeEnd]
- if strings.HasPrefix(mineType, "image/") {
- file.FileType = types.FileTypeImage
- } else if strings.HasPrefix(mineType, "video/") {
- file.FileType = types.FileTypeVideo
- } else if strings.HasPrefix(mineType, "audio/") {
- file.FileType = types.FileTypeAudio
- } else {
- file.FileType = types.FileTypeFile
- }
- file.MimeType = mineType
- }
+ if file.Source == nil {
+ continue
+ }
+
+ // 如果文件类型未知且需要获取,通过 MIME 类型检测
+ if file.FileType == "" || (file.Source.IsURL() && shouldFetchFiles) {
+ // 注意:这里我们直接调用 LoadFileSource 而不是 GetMimeType
+ // 因为 GetMimeType 内部可能会调用 GetFileTypeFromUrl (HEAD 请求)
+ // 而我们这里既然要计算 token,通常需要完整数据
+ cachedData, err := LoadFileSource(c, file.Source, "token_counter")
+ if err != nil {
+ if shouldFetchFiles {
+ return 0, fmt.Errorf("error getting file type: %v", err)
}
+ continue
}
+ file.FileType = DetectFileType(cachedData.MimeType)
}
}
@@ -318,9 +274,9 @@ func EstimateRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *rela
switch file.FileType {
case types.FileTypeImage:
if common.IsOpenAITextModel(model) {
- token, err := getImageToken(file, model, info.IsStream)
+ token, err := getImageToken(c, file, model, info.IsStream)
if err != nil {
- return 0, fmt.Errorf("error counting image token, media index[%d], original data[%s], err: %v", i, file.OriginData, err)
+ return 0, fmt.Errorf("error counting image token, media index[%d], identifier[%s], err: %v", i, file.GetIdentifier(), err)
}
tkm += token
} else {
diff --git a/service/user_notify.go b/service/user_notify.go
index cecf46cade..27a72b8be4 100644
--- a/service/user_notify.go
+++ b/service/user_notify.go
@@ -22,6 +22,32 @@ func NotifyRootUser(t string, subject string, content string) {
}
}
+func NotifyUpstreamModelUpdateWatchers(subject string, content string) {
+ var users []model.User
+ if err := model.DB.
+ Select("id", "email", "role", "status", "setting").
+ Where("status = ? AND role >= ?", common.UserStatusEnabled, common.RoleAdminUser).
+ Find(&users).Error; err != nil {
+ common.SysLog(fmt.Sprintf("failed to query upstream update notification users: %s", err.Error()))
+ return
+ }
+
+ notification := dto.NewNotify(dto.NotifyTypeChannelUpdate, subject, content, nil)
+ sentCount := 0
+ for _, user := range users {
+ userSetting := user.GetSetting()
+ if !userSetting.UpstreamModelUpdateNotifyEnabled {
+ continue
+ }
+ if err := NotifyUser(user.Id, user.Email, userSetting, notification); err != nil {
+ common.SysLog(fmt.Sprintf("failed to notify user %d for upstream model update: %s", user.Id, err.Error()))
+ continue
+ }
+ sentCount++
+ }
+ common.SysLog(fmt.Sprintf("upstream model update notifications sent: %d", sentCount))
+}
+
func NotifyUser(userId int, userEmail string, userSetting dto.UserSetting, data dto.Notify) error {
notifyType := userSetting.NotifyType
if notifyType == "" {
diff --git a/service/violation_fee.go b/service/violation_fee.go
new file mode 100644
index 0000000000..4550885613
--- /dev/null
+++ b/service/violation_fee.go
@@ -0,0 +1,164 @@
+package service
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/logger"
+ "github.com/QuantumNous/new-api/model"
+ relaycommon "github.com/QuantumNous/new-api/relay/common"
+ "github.com/QuantumNous/new-api/setting/model_setting"
+ "github.com/QuantumNous/new-api/types"
+
+ "github.com/shopspring/decimal"
+
+ "github.com/gin-gonic/gin"
+)
+
+const (
+ ViolationFeeCodePrefix = "violation_fee."
+ CSAMViolationMarker = "Failed check: SAFETY_CHECK_TYPE"
+ ContentViolatesUsageMarker = "Content violates usage guidelines"
+)
+
+func IsViolationFeeCode(code types.ErrorCode) bool {
+ return strings.HasPrefix(string(code), ViolationFeeCodePrefix)
+}
+
+func HasCSAMViolationMarker(err *types.NewAPIError) bool {
+ if err == nil {
+ return false
+ }
+ if strings.Contains(err.Error(), CSAMViolationMarker) || strings.Contains(err.Error(), ContentViolatesUsageMarker) {
+ return true
+ }
+ msg := err.ToOpenAIError().Message
+ return strings.Contains(msg, CSAMViolationMarker) || strings.Contains(err.Error(), ContentViolatesUsageMarker)
+}
+
+func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError {
+ if err == nil {
+ return nil
+ }
+ oai := err.ToOpenAIError()
+ oai.Type = string(types.ErrorCodeViolationFeeGrokCSAM)
+ oai.Code = string(types.ErrorCodeViolationFeeGrokCSAM)
+ return types.WithOpenAIError(oai, err.StatusCode, types.ErrOptionWithSkipRetry())
+}
+
+// NormalizeViolationFeeError ensures:
+// - if the CSAM marker is present, error.code is set to a stable violation-fee code and skip-retry is enabled.
+// - if error.code already has the violation-fee prefix, skip-retry is enabled.
+//
+// It must be called before retry decision logic.
+func NormalizeViolationFeeError(err *types.NewAPIError) *types.NewAPIError {
+ if err == nil {
+ return nil
+ }
+
+ if HasCSAMViolationMarker(err) {
+ return WrapAsViolationFeeGrokCSAM(err)
+ }
+
+ if IsViolationFeeCode(err.GetErrorCode()) {
+ oai := err.ToOpenAIError()
+ return types.WithOpenAIError(oai, err.StatusCode, types.ErrOptionWithSkipRetry())
+ }
+
+ return err
+}
+
+func shouldChargeViolationFee(err *types.NewAPIError) bool {
+ if err == nil {
+ return false
+ }
+ if err.GetErrorCode() == types.ErrorCodeViolationFeeGrokCSAM {
+ return true
+ }
+ // In case some callers didn't normalize, keep a safety net.
+ return HasCSAMViolationMarker(err)
+}
+
+func calcViolationFeeQuota(amount, groupRatio float64) int {
+ if amount <= 0 {
+ return 0
+ }
+ if groupRatio <= 0 {
+ return 0
+ }
+ quota := decimal.NewFromFloat(amount).
+ Mul(decimal.NewFromFloat(common.QuotaPerUnit)).
+ Mul(decimal.NewFromFloat(groupRatio)).
+ Round(0).
+ IntPart()
+ if quota <= 0 {
+ return 0
+ }
+ return int(quota)
+}
+
+// ChargeViolationFeeIfNeeded charges an additional fee after the normal flow finishes (including refund).
+// It uses Grok fee settings as the fee policy.
+func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, apiErr *types.NewAPIError) bool {
+ if ctx == nil || relayInfo == nil || apiErr == nil {
+ return false
+ }
+ //if relayInfo.IsPlayground {
+ // return false
+ //}
+ if !shouldChargeViolationFee(apiErr) {
+ return false
+ }
+
+ settings := model_setting.GetGrokSettings()
+ if settings == nil || !settings.ViolationDeductionEnabled {
+ return false
+ }
+
+ groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
+ feeQuota := calcViolationFeeQuota(settings.ViolationDeductionAmount, groupRatio)
+ if feeQuota <= 0 {
+ return false
+ }
+
+ if err := PostConsumeQuota(relayInfo, feeQuota, 0, true); err != nil {
+ logger.LogError(ctx, fmt.Sprintf("failed to charge violation fee: %s", err.Error()))
+ return false
+ }
+
+ model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, feeQuota)
+ model.UpdateChannelUsedQuota(relayInfo.ChannelId, feeQuota)
+
+ useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
+ tokenName := ctx.GetString("token_name")
+ oai := apiErr.ToOpenAIError()
+
+ other := map[string]any{
+ "violation_fee": true,
+ "violation_fee_code": string(types.ErrorCodeViolationFeeGrokCSAM),
+ "fee_quota": feeQuota,
+ "base_amount": settings.ViolationDeductionAmount,
+ "group_ratio": groupRatio,
+ "status_code": apiErr.StatusCode,
+ "upstream_error_type": oai.Type,
+ "upstream_error_code": fmt.Sprintf("%v", oai.Code),
+ "violation_fee_marker": CSAMViolationMarker,
+ }
+
+ model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
+ ChannelId: relayInfo.ChannelId,
+ ModelName: relayInfo.OriginModelName,
+ TokenName: tokenName,
+ Quota: feeQuota,
+ Content: "Violation fee charged",
+ TokenId: relayInfo.TokenId,
+ UseTimeSeconds: int(useTimeSeconds),
+ IsStream: relayInfo.IsStream,
+ Group: relayInfo.UsingGroup,
+ Other: other,
+ })
+
+ return true
+}
diff --git a/setting/chat.go b/setting/chat.go
index 9be08268a8..417ee85d79 100644
--- a/setting/chat.go
+++ b/setting/chat.go
@@ -13,9 +13,15 @@ var Chats = []map[string]string{
{
"Cherry Studio": "cherrystudio://providers/api-keys?v=1&data={cherryConfig}",
},
+ {
+ "AionUI": "aionui://provider/add?v=1&data={aionuiConfig}",
+ },
{
"流畅阅读": "fluentread",
},
+ {
+ "CC Switch": "ccswitch",
+ },
{
"Lobe Chat 官方示例": "https://chat-preview.lobehub.com/?settings={\"keyVaults\":{\"openai\":{\"apiKey\":\"{key}\",\"baseURL\":\"{address}/v1\"}}}",
},
diff --git a/setting/config/config.go b/setting/config/config.go
index 6c6abe9d4a..8b3d051392 100644
--- a/setting/config/config.go
+++ b/setting/config/config.go
@@ -212,13 +212,23 @@ func updateConfigFromMap(config interface{}, configMap map[string]string) error
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
intValue, err := strconv.ParseInt(strValue, 10, 64)
if err != nil {
- continue
+ // 兼容 float 格式的字符串(如 "2.000000")
+ floatValue, fErr := strconv.ParseFloat(strValue, 64)
+ if fErr != nil {
+ continue
+ }
+ intValue = int64(floatValue)
}
field.SetInt(intValue)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
uintValue, err := strconv.ParseUint(strValue, 10, 64)
if err != nil {
- continue
+ // 兼容 float 格式的字符串
+ floatValue, fErr := strconv.ParseFloat(strValue, 64)
+ if fErr != nil || floatValue < 0 {
+ continue
+ }
+ uintValue = uint64(floatValue)
}
field.SetUint(uintValue)
case reflect.Float32, reflect.Float64:
diff --git a/setting/model_setting/claude.go b/setting/model_setting/claude.go
index aa010c07aa..3173bda2ee 100644
--- a/setting/model_setting/claude.go
+++ b/setting/model_setting/claude.go
@@ -2,6 +2,7 @@ package model_setting
import (
"net/http"
+ "strings"
"github.com/QuantumNous/new-api/setting/config"
)
@@ -50,23 +51,36 @@ func GetClaudeSettings() *ClaudeSettings {
func (c *ClaudeSettings) WriteHeaders(originModel string, httpHeader *http.Header) {
if headers, ok := c.HeadersSettings[originModel]; ok {
for headerKey, headerValues := range headers {
- // get existing values for this header key
- existingValues := httpHeader.Values(headerKey)
- existingValuesMap := make(map[string]bool)
- for _, v := range existingValues {
- existingValuesMap[v] = true
- }
-
- // add only values that don't already exist
- for _, headerValue := range headerValues {
- if !existingValuesMap[headerValue] {
- httpHeader.Add(headerKey, headerValue)
- }
+ mergedValues := normalizeHeaderListValues(
+ append(append([]string(nil), httpHeader.Values(headerKey)...), headerValues...),
+ )
+ if len(mergedValues) == 0 {
+ continue
}
+ httpHeader.Set(headerKey, strings.Join(mergedValues, ","))
}
}
}
+func normalizeHeaderListValues(values []string) []string {
+ normalizedValues := make([]string, 0, len(values))
+ seenValues := make(map[string]struct{}, len(values))
+ for _, value := range values {
+ for _, item := range strings.Split(value, ",") {
+ normalizedItem := strings.TrimSpace(item)
+ if normalizedItem == "" {
+ continue
+ }
+ if _, exists := seenValues[normalizedItem]; exists {
+ continue
+ }
+ seenValues[normalizedItem] = struct{}{}
+ normalizedValues = append(normalizedValues, normalizedItem)
+ }
+ }
+ return normalizedValues
+}
+
func (c *ClaudeSettings) GetDefaultMaxTokens(model string) int {
if maxTokens, ok := c.DefaultMaxTokens[model]; ok {
return maxTokens
diff --git a/setting/model_setting/gemini.go b/setting/model_setting/gemini.go
index 30d56e345d..dea7131b9b 100644
--- a/setting/model_setting/gemini.go
+++ b/setting/model_setting/gemini.go
@@ -27,6 +27,9 @@ var defaultGeminiSettings = GeminiSettings{
SupportedImagineModels: []string{
"gemini-2.0-flash-exp-image-generation",
"gemini-2.0-flash-exp",
+ "gemini-3-pro-image-preview",
+ "gemini-2.5-flash-image",
+ "gemini-3.1-flash-image-preview",
},
ThinkingAdapterEnabled: false,
ThinkingAdapterBudgetTokensPercentage: 0.6,
diff --git a/setting/model_setting/global.go b/setting/model_setting/global.go
index 5801711712..d0c4d31289 100644
--- a/setting/model_setting/global.go
+++ b/setting/model_setting/global.go
@@ -11,20 +11,25 @@ type ChatCompletionsToResponsesPolicy struct {
Enabled bool `json:"enabled"`
AllChannels bool `json:"all_channels"`
ChannelIDs []int `json:"channel_ids,omitempty"`
+ ChannelTypes []int `json:"channel_types,omitempty"`
ModelPatterns []string `json:"model_patterns,omitempty"`
}
-func (p ChatCompletionsToResponsesPolicy) IsChannelEnabled(channelID int) bool {
+func (p ChatCompletionsToResponsesPolicy) IsChannelEnabled(channelID int, channelType int) bool {
if !p.Enabled {
return false
}
if p.AllChannels {
return true
}
- if channelID == 0 || len(p.ChannelIDs) == 0 {
- return false
+
+ if channelID > 0 && len(p.ChannelIDs) > 0 && slices.Contains(p.ChannelIDs, channelID) {
+ return true
}
- return slices.Contains(p.ChannelIDs, channelID)
+ if channelType > 0 && len(p.ChannelTypes) > 0 && slices.Contains(p.ChannelTypes, channelType) {
+ return true
+ }
+ return false
}
type GlobalSettings struct {
diff --git a/setting/model_setting/grok.go b/setting/model_setting/grok.go
new file mode 100644
index 0000000000..d558679bf7
--- /dev/null
+++ b/setting/model_setting/grok.go
@@ -0,0 +1,24 @@
+package model_setting
+
+import "github.com/QuantumNous/new-api/setting/config"
+
+// GrokSettings defines Grok model configuration.
+type GrokSettings struct {
+ ViolationDeductionEnabled bool `json:"violation_deduction_enabled"`
+ ViolationDeductionAmount float64 `json:"violation_deduction_amount"`
+}
+
+var defaultGrokSettings = GrokSettings{
+ ViolationDeductionEnabled: true,
+ ViolationDeductionAmount: 0.05,
+}
+
+var grokSettings = defaultGrokSettings
+
+func init() {
+ config.GlobalConfig.Register("grok", &grokSettings)
+}
+
+func GetGrokSettings() *GrokSettings {
+ return &grokSettings
+}
diff --git a/setting/model_setting/qwen.go b/setting/model_setting/qwen.go
index ccab575945..ffbcd9d2ec 100644
--- a/setting/model_setting/qwen.go
+++ b/setting/model_setting/qwen.go
@@ -17,6 +17,7 @@ var defaultQwenSettings = QwenSettings{
"z-image",
"qwen-image",
"wan2.6",
+ "wan2.7",
"qwen-image-edit",
"qwen-image-edit-max",
"qwen-image-edit-max-2026-01-16",
diff --git a/setting/operation_setting/channel_affinity_setting.go b/setting/operation_setting/channel_affinity_setting.go
new file mode 100644
index 0000000000..8cd605c035
--- /dev/null
+++ b/setting/operation_setting/channel_affinity_setting.go
@@ -0,0 +1,121 @@
+package operation_setting
+
+import "github.com/QuantumNous/new-api/setting/config"
+
+type ChannelAffinityKeySource struct {
+ Type string `json:"type"` // context_int, context_string, gjson
+ Key string `json:"key,omitempty"`
+ Path string `json:"path,omitempty"`
+}
+
+type ChannelAffinityRule struct {
+ Name string `json:"name"`
+ ModelRegex []string `json:"model_regex"`
+ PathRegex []string `json:"path_regex"`
+ UserAgentInclude []string `json:"user_agent_include,omitempty"`
+ KeySources []ChannelAffinityKeySource `json:"key_sources"`
+
+ ValueRegex string `json:"value_regex"`
+ TTLSeconds int `json:"ttl_seconds"`
+
+ ParamOverrideTemplate map[string]interface{} `json:"param_override_template,omitempty"`
+
+ SkipRetryOnFailure bool `json:"skip_retry_on_failure"`
+
+ IncludeUsingGroup bool `json:"include_using_group"`
+ IncludeModelName bool `json:"include_model_name"`
+ IncludeRuleName bool `json:"include_rule_name"`
+}
+
+type ChannelAffinitySetting struct {
+ Enabled bool `json:"enabled"`
+ SwitchOnSuccess bool `json:"switch_on_success"`
+ MaxEntries int `json:"max_entries"`
+ DefaultTTLSeconds int `json:"default_ttl_seconds"`
+ Rules []ChannelAffinityRule `json:"rules"`
+}
+
+var codexCliPassThroughHeaders = []string{
+ "Originator",
+ "Session_id",
+ "User-Agent",
+ "X-Codex-Beta-Features",
+ "X-Codex-Turn-Metadata",
+}
+
+var claudeCliPassThroughHeaders = []string{
+ "X-Stainless-Arch",
+ "X-Stainless-Lang",
+ "X-Stainless-Os",
+ "X-Stainless-Package-Version",
+ "X-Stainless-Retry-Count",
+ "X-Stainless-Runtime",
+ "X-Stainless-Runtime-Version",
+ "X-Stainless-Timeout",
+ "User-Agent",
+ "X-App",
+ "Anthropic-Beta",
+ "Anthropic-Dangerous-Direct-Browser-Access",
+ "Anthropic-Version",
+}
+
+func buildPassHeaderTemplate(headers []string) map[string]interface{} {
+ clonedHeaders := make([]string, 0, len(headers))
+ clonedHeaders = append(clonedHeaders, headers...)
+ return map[string]interface{}{
+ "operations": []map[string]interface{}{
+ {
+ "mode": "pass_headers",
+ "value": clonedHeaders,
+ "keep_origin": true,
+ },
+ },
+ }
+}
+
+var channelAffinitySetting = ChannelAffinitySetting{
+ Enabled: true,
+ SwitchOnSuccess: true,
+ MaxEntries: 100_000,
+ DefaultTTLSeconds: 3600,
+ Rules: []ChannelAffinityRule{
+ {
+ Name: "codex cli trace",
+ ModelRegex: []string{"^gpt-.*$"},
+ PathRegex: []string{"/v1/responses"},
+ KeySources: []ChannelAffinityKeySource{
+ {Type: "gjson", Path: "prompt_cache_key"},
+ },
+ ValueRegex: "",
+ TTLSeconds: 0,
+ ParamOverrideTemplate: buildPassHeaderTemplate(codexCliPassThroughHeaders),
+ SkipRetryOnFailure: true,
+ IncludeUsingGroup: true,
+ IncludeRuleName: true,
+ UserAgentInclude: nil,
+ },
+ {
+ Name: "claude cli trace",
+ ModelRegex: []string{"^claude-.*$"},
+ PathRegex: []string{"/v1/messages"},
+ KeySources: []ChannelAffinityKeySource{
+ {Type: "gjson", Path: "metadata.user_id"},
+ },
+ ValueRegex: "",
+ TTLSeconds: 0,
+ ParamOverrideTemplate: buildPassHeaderTemplate(claudeCliPassThroughHeaders),
+ SkipRetryOnFailure: true,
+ IncludeUsingGroup: true,
+ IncludeRuleName: true,
+ UserAgentInclude: nil,
+ },
+ },
+}
+
+func init() {
+ config.GlobalConfig.Register("channel_affinity_setting", &channelAffinitySetting)
+}
+
+func GetChannelAffinitySetting() *ChannelAffinitySetting {
+ return &channelAffinitySetting
+}
diff --git a/setting/operation_setting/status_code_ranges.go b/setting/operation_setting/status_code_ranges.go
index 698c87c914..14cfacad71 100644
--- a/setting/operation_setting/status_code_ranges.go
+++ b/setting/operation_setting/status_code_ranges.go
@@ -5,6 +5,8 @@ import (
"sort"
"strconv"
"strings"
+
+ "github.com/QuantumNous/new-api/types"
)
type StatusCodeRange struct {
@@ -26,6 +28,15 @@ var AutomaticRetryStatusCodeRanges = []StatusCodeRange{
{Start: 525, End: 599},
}
+var alwaysSkipRetryStatusCodes = map[int]struct{}{
+ 504: {},
+ 524: {},
+}
+
+var alwaysSkipRetryCodes = map[types.ErrorCode]struct{}{
+ types.ErrorCodeBadResponseBody: {},
+}
+
func AutomaticDisableStatusCodesToString() string {
return statusCodeRangesToString(AutomaticDisableStatusCodeRanges)
}
@@ -56,7 +67,20 @@ func AutomaticRetryStatusCodesFromString(s string) error {
return nil
}
+func IsAlwaysSkipRetryStatusCode(code int) bool {
+ _, exists := alwaysSkipRetryStatusCodes[code]
+ return exists
+}
+
+func IsAlwaysSkipRetryCode(errorCode types.ErrorCode) bool {
+ _, exists := alwaysSkipRetryCodes[errorCode]
+ return exists
+}
+
func ShouldRetryByStatusCode(code int) bool {
+ if IsAlwaysSkipRetryStatusCode(code) {
+ return false
+ }
return shouldMatchStatusCodeRanges(AutomaticRetryStatusCodeRanges, code)
}
diff --git a/setting/operation_setting/status_code_ranges_test.go b/setting/operation_setting/status_code_ranges_test.go
index 5801824acf..4e292a3681 100644
--- a/setting/operation_setting/status_code_ranges_test.go
+++ b/setting/operation_setting/status_code_ranges_test.go
@@ -62,6 +62,8 @@ func TestShouldRetryByStatusCode(t *testing.T) {
require.True(t, ShouldRetryByStatusCode(429))
require.True(t, ShouldRetryByStatusCode(500))
+ require.False(t, ShouldRetryByStatusCode(504))
+ require.False(t, ShouldRetryByStatusCode(524))
require.False(t, ShouldRetryByStatusCode(400))
require.False(t, ShouldRetryByStatusCode(200))
}
@@ -77,3 +79,9 @@ func TestShouldRetryByStatusCode_DefaultMatchesLegacyBehavior(t *testing.T) {
require.False(t, ShouldRetryByStatusCode(524))
require.True(t, ShouldRetryByStatusCode(599))
}
+
+func TestIsAlwaysSkipRetryStatusCode(t *testing.T) {
+ require.True(t, IsAlwaysSkipRetryStatusCode(504))
+ require.True(t, IsAlwaysSkipRetryStatusCode(524))
+ require.False(t, IsAlwaysSkipRetryStatusCode(500))
+}
diff --git a/setting/operation_setting/token_setting.go b/setting/operation_setting/token_setting.go
new file mode 100644
index 0000000000..0d4c4e2f24
--- /dev/null
+++ b/setting/operation_setting/token_setting.go
@@ -0,0 +1,28 @@
+package operation_setting
+
+import "github.com/QuantumNous/new-api/setting/config"
+
+// TokenSetting 令牌相关配置
+type TokenSetting struct {
+ MaxUserTokens int `json:"max_user_tokens"` // 每用户最大令牌数量
+}
+
+// 默认配置
+var tokenSetting = TokenSetting{
+ MaxUserTokens: 1000, // 默认每用户最多 1000 个令牌
+}
+
+func init() {
+ // 注册到全局配置管理器
+ config.GlobalConfig.Register("token_setting", &tokenSetting)
+}
+
+// GetTokenSetting 获取令牌配置
+func GetTokenSetting() *TokenSetting {
+ return &tokenSetting
+}
+
+// GetMaxUserTokens 获取每用户最大令牌数量
+func GetMaxUserTokens() int {
+ return GetTokenSetting().MaxUserTokens
+}
diff --git a/setting/payment_waffo.go b/setting/payment_waffo.go
new file mode 100644
index 0000000000..c27ca6f24f
--- /dev/null
+++ b/setting/payment_waffo.go
@@ -0,0 +1,67 @@
+package setting
+
+import (
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/constant"
+)
+
+var (
+ WaffoEnabled bool
+ WaffoApiKey string
+ WaffoPrivateKey string
+ WaffoPublicCert string
+ WaffoSandboxPublicCert string
+ WaffoSandboxApiKey string
+ WaffoSandboxPrivateKey string
+ WaffoSandbox bool
+ WaffoMerchantId string
+ WaffoNotifyUrl string
+ WaffoReturnUrl string
+ WaffoSubscriptionReturnUrl string
+ WaffoCurrency string
+ WaffoUnitPrice float64 = 1.0
+ WaffoMinTopUp int = 1
+)
+
+// GetWaffoPayMethods 从 options 读取 Waffo 支付方式配置
+func GetWaffoPayMethods() []constant.WaffoPayMethod {
+ common.OptionMapRWMutex.RLock()
+ jsonStr := common.OptionMap["WaffoPayMethods"]
+ common.OptionMapRWMutex.RUnlock()
+
+ if jsonStr == "" {
+ return copyDefaultWaffoPayMethods()
+ }
+ var methods []constant.WaffoPayMethod
+ if err := common.UnmarshalJsonStr(jsonStr, &methods); err != nil {
+ return copyDefaultWaffoPayMethods()
+ }
+ return methods
+}
+
+// SetWaffoPayMethods 序列化 Waffo 支付方式配置并更新 OptionMap
+func SetWaffoPayMethods(methods []constant.WaffoPayMethod) error {
+ jsonBytes, err := common.Marshal(methods)
+ if err != nil {
+ return err
+ }
+ common.OptionMapRWMutex.Lock()
+ common.OptionMap["WaffoPayMethods"] = string(jsonBytes)
+ common.OptionMapRWMutex.Unlock()
+ return nil
+}
+
+func copyDefaultWaffoPayMethods() []constant.WaffoPayMethod {
+ cp := make([]constant.WaffoPayMethod, len(constant.DefaultWaffoPayMethods))
+ copy(cp, constant.DefaultWaffoPayMethods)
+ return cp
+}
+
+// WaffoPayMethods2JsonString 将默认 WaffoPayMethods 序列化为 JSON 字符串(供 InitOptionMap 使用)
+func WaffoPayMethods2JsonString() string {
+ jsonBytes, err := common.Marshal(constant.DefaultWaffoPayMethods)
+ if err != nil {
+ return "[]"
+ }
+ return string(jsonBytes)
+}
diff --git a/setting/performance_setting/config.go b/setting/performance_setting/config.go
new file mode 100644
index 0000000000..4f02dc7bdd
--- /dev/null
+++ b/setting/performance_setting/config.go
@@ -0,0 +1,85 @@
+package performance_setting
+
+import (
+ "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/setting/config"
+)
+
+// PerformanceSetting 性能设置配置
+type PerformanceSetting struct {
+ // DiskCacheEnabled 是否启用磁盘缓存(磁盘换内存)
+ DiskCacheEnabled bool `json:"disk_cache_enabled"`
+ // DiskCacheThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
+ DiskCacheThresholdMB int `json:"disk_cache_threshold_mb"`
+ // DiskCacheMaxSizeMB 磁盘缓存最大总大小(MB)
+ DiskCacheMaxSizeMB int `json:"disk_cache_max_size_mb"`
+ // DiskCachePath 磁盘缓存目录
+ DiskCachePath string `json:"disk_cache_path"`
+
+ // MonitorEnabled 是否启用性能监控
+ MonitorEnabled bool `json:"monitor_enabled"`
+ // MonitorCPUThreshold CPU 使用率阈值(%)
+ MonitorCPUThreshold int `json:"monitor_cpu_threshold"`
+ // MonitorMemoryThreshold 内存使用率阈值(%)
+ MonitorMemoryThreshold int `json:"monitor_memory_threshold"`
+ // MonitorDiskThreshold 磁盘使用率阈值(%)
+ MonitorDiskThreshold int `json:"monitor_disk_threshold"`
+}
+
+// 默认配置
+var performanceSetting = PerformanceSetting{
+ DiskCacheEnabled: false,
+ DiskCacheThresholdMB: 10, // 超过 10MB 使用磁盘缓存
+ DiskCacheMaxSizeMB: 1024, // 最大 1GB 磁盘缓存
+ DiskCachePath: "", // 空表示使用系统临时目录
+
+ MonitorEnabled: true,
+ MonitorCPUThreshold: 90,
+ MonitorMemoryThreshold: 90,
+ MonitorDiskThreshold: 95,
+}
+
+func init() {
+ // 注册到全局配置管理器
+ config.GlobalConfig.Register("performance_setting", &performanceSetting)
+ // 同步初始配置到 common 包
+ syncToCommon()
+}
+
+// syncToCommon 将配置同步到 common 包
+func syncToCommon() {
+ common.SetDiskCacheConfig(common.DiskCacheConfig{
+ Enabled: performanceSetting.DiskCacheEnabled,
+ ThresholdMB: performanceSetting.DiskCacheThresholdMB,
+ MaxSizeMB: performanceSetting.DiskCacheMaxSizeMB,
+ Path: performanceSetting.DiskCachePath,
+ })
+
+ common.SetPerformanceMonitorConfig(common.PerformanceMonitorConfig{
+ Enabled: performanceSetting.MonitorEnabled,
+ CPUThreshold: performanceSetting.MonitorCPUThreshold,
+ MemoryThreshold: performanceSetting.MonitorMemoryThreshold,
+ DiskThreshold: performanceSetting.MonitorDiskThreshold,
+ })
+}
+
+// GetPerformanceSetting 获取性能设置
+func GetPerformanceSetting() *PerformanceSetting {
+ return &performanceSetting
+}
+
+// UpdateAndSync 更新配置并同步到 common 包
+// 当配置从数据库加载后,需要调用此函数同步
+func UpdateAndSync() {
+ syncToCommon()
+}
+
+// GetCacheStats 获取缓存统计信息(代理到 common 包)
+func GetCacheStats() common.DiskCacheStats {
+ return common.GetDiskCacheStats()
+}
+
+// ResetStats 重置统计信息
+func ResetStats() {
+ common.ResetDiskCacheStats()
+}
diff --git a/setting/ratio_setting/cache_ratio.go b/setting/ratio_setting/cache_ratio.go
index cf54cb3139..2c75ab482f 100644
--- a/setting/ratio_setting/cache_ratio.go
+++ b/setting/ratio_setting/cache_ratio.go
@@ -1,13 +1,13 @@
package ratio_setting
import (
- "encoding/json"
- "sync"
-
- "github.com/QuantumNous/new-api/common"
+ "github.com/QuantumNous/new-api/types"
)
var defaultCacheRatio = map[string]float64{
+ "gemini-3-flash-preview": 0.1,
+ "gemini-3-pro-preview": 0.1,
+ "gemini-3.1-pro-preview": 0.1,
"gpt-4": 0.5,
"o1": 0.5,
"o1-2024-12-17": 0.5,
@@ -58,6 +58,12 @@ var defaultCacheRatio = map[string]float64{
"claude-sonnet-4-5-20250929-thinking": 0.1,
"claude-opus-4-5-20251101": 0.1,
"claude-opus-4-5-20251101-thinking": 0.1,
+ "claude-opus-4-6": 0.1,
+ "claude-opus-4-6-thinking": 0.1,
+ "claude-opus-4-6-max": 0.1,
+ "claude-opus-4-6-high": 0.1,
+ "claude-opus-4-6-medium": 0.1,
+ "claude-opus-4-6-low": 0.1,
}
var defaultCreateCacheRatio = map[string]float64{
@@ -80,48 +86,47 @@ var defaultCreateCacheRatio = map[string]float64{
"claude-sonnet-4-5-20250929-thinking": 1.25,
"claude-opus-4-5-20251101": 1.25,
"claude-opus-4-5-20251101-thinking": 1.25,
+ "claude-opus-4-6": 1.25,
+ "claude-opus-4-6-thinking": 1.25,
+ "claude-opus-4-6-max": 1.25,
+ "claude-opus-4-6-high": 1.25,
+ "claude-opus-4-6-medium": 1.25,
+ "claude-opus-4-6-low": 1.25,
}
//var defaultCreateCacheRatio = map[string]float64{}
-var cacheRatioMap map[string]float64
-var cacheRatioMapMutex sync.RWMutex
+var cacheRatioMap = types.NewRWMap[string, float64]()
+var createCacheRatioMap = types.NewRWMap[string, float64]()
-// GetCacheRatioMap returns the cache ratio map
+// GetCacheRatioMap returns a copy of the cache ratio map
func GetCacheRatioMap() map[string]float64 {
- cacheRatioMapMutex.RLock()
- defer cacheRatioMapMutex.RUnlock()
- return cacheRatioMap
+ return cacheRatioMap.ReadAll()
}
// CacheRatio2JSONString converts the cache ratio map to a JSON string
func CacheRatio2JSONString() string {
- cacheRatioMapMutex.RLock()
- defer cacheRatioMapMutex.RUnlock()
- jsonBytes, err := json.Marshal(cacheRatioMap)
- if err != nil {
- common.SysLog("error marshalling cache ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return cacheRatioMap.MarshalJSONString()
+}
+
+// CreateCacheRatio2JSONString converts the create cache ratio map to a JSON string
+func CreateCacheRatio2JSONString() string {
+ return createCacheRatioMap.MarshalJSONString()
}
// UpdateCacheRatioByJSONString updates the cache ratio map from a JSON string
func UpdateCacheRatioByJSONString(jsonStr string) error {
- cacheRatioMapMutex.Lock()
- defer cacheRatioMapMutex.Unlock()
- cacheRatioMap = make(map[string]float64)
- err := json.Unmarshal([]byte(jsonStr), &cacheRatioMap)
- if err == nil {
- InvalidateExposedDataCache()
- }
- return err
+ return types.LoadFromJsonStringWithCallback(cacheRatioMap, jsonStr, InvalidateExposedDataCache)
+}
+
+// UpdateCreateCacheRatioByJSONString updates the create cache ratio map from a JSON string
+func UpdateCreateCacheRatioByJSONString(jsonStr string) error {
+ return types.LoadFromJsonStringWithCallback(createCacheRatioMap, jsonStr, InvalidateExposedDataCache)
}
// GetCacheRatio returns the cache ratio for a model
func GetCacheRatio(name string) (float64, bool) {
- cacheRatioMapMutex.RLock()
- defer cacheRatioMapMutex.RUnlock()
- ratio, ok := cacheRatioMap[name]
+ ratio, ok := cacheRatioMap.Get(name)
if !ok {
return 1, false // Default to 1 if not found
}
@@ -129,7 +134,7 @@ func GetCacheRatio(name string) (float64, bool) {
}
func GetCreateCacheRatio(name string) (float64, bool) {
- ratio, ok := defaultCreateCacheRatio[name]
+ ratio, ok := createCacheRatioMap.Get(name)
if !ok {
return 1.25, false // Default to 1.25 if not found
}
@@ -137,11 +142,9 @@ func GetCreateCacheRatio(name string) (float64, bool) {
}
func GetCacheRatioCopy() map[string]float64 {
- cacheRatioMapMutex.RLock()
- defer cacheRatioMapMutex.RUnlock()
- copyMap := make(map[string]float64, len(cacheRatioMap))
- for k, v := range cacheRatioMap {
- copyMap[k] = v
- }
- return copyMap
+ return cacheRatioMap.ReadAll()
+}
+
+func GetCreateCacheRatioCopy() map[string]float64 {
+ return createCacheRatioMap.ReadAll()
}
diff --git a/setting/ratio_setting/compact_suffix.go b/setting/ratio_setting/compact_suffix.go
new file mode 100644
index 0000000000..2d2fe3c34b
--- /dev/null
+++ b/setting/ratio_setting/compact_suffix.go
@@ -0,0 +1,13 @@
+package ratio_setting
+
+import "strings"
+
+const CompactModelSuffix = "-openai-compact"
+const CompactWildcardModelKey = "*" + CompactModelSuffix
+
+func WithCompactModelSuffix(modelName string) string {
+ if strings.HasSuffix(modelName, CompactModelSuffix) {
+ return modelName
+ }
+ return modelName + CompactModelSuffix
+}
diff --git a/setting/ratio_setting/exposed_cache.go b/setting/ratio_setting/exposed_cache.go
index 2fe2cd09b4..c88216fcb0 100644
--- a/setting/ratio_setting/exposed_cache.go
+++ b/setting/ratio_setting/exposed_cache.go
@@ -42,10 +42,11 @@ func GetExposedData() gin.H {
return cloneGinH(c.data)
}
newData := gin.H{
- "model_ratio": GetModelRatioCopy(),
- "completion_ratio": GetCompletionRatioCopy(),
- "cache_ratio": GetCacheRatioCopy(),
- "model_price": GetModelPriceCopy(),
+ "model_ratio": GetModelRatioCopy(),
+ "completion_ratio": GetCompletionRatioCopy(),
+ "cache_ratio": GetCacheRatioCopy(),
+ "create_cache_ratio": GetCreateCacheRatioCopy(),
+ "model_price": GetModelPriceCopy(),
}
exposedData.Store(&exposedCache{
data: newData,
diff --git a/setting/ratio_setting/group_ratio.go b/setting/ratio_setting/group_ratio.go
index 9bb26557b9..637aef62b3 100644
--- a/setting/ratio_setting/group_ratio.go
+++ b/setting/ratio_setting/group_ratio.go
@@ -3,29 +3,27 @@ package ratio_setting
import (
"encoding/json"
"errors"
- "sync"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/config"
"github.com/QuantumNous/new-api/types"
)
-var groupRatio = map[string]float64{
+var defaultGroupRatio = map[string]float64{
"default": 1,
"vip": 1,
"svip": 1,
}
-var groupRatioMutex sync.RWMutex
+var groupRatioMap = types.NewRWMap[string, float64]()
-var (
- GroupGroupRatio = map[string]map[string]float64{
- "vip": {
- "edit_this": 0.9,
- },
- }
- groupGroupRatioMutex sync.RWMutex
-)
+var defaultGroupGroupRatio = map[string]map[string]float64{
+ "vip": {
+ "edit_this": 0.9,
+ },
+}
+
+var groupGroupRatioMap = types.NewRWMap[string, map[string]float64]()
var defaultGroupSpecialUsableGroup = map[string]map[string]string{
"vip": {
@@ -35,9 +33,9 @@ var defaultGroupSpecialUsableGroup = map[string]map[string]string{
}
type GroupRatioSetting struct {
- GroupRatio map[string]float64 `json:"group_ratio"`
- GroupGroupRatio map[string]map[string]float64 `json:"group_group_ratio"`
- GroupSpecialUsableGroup *types.RWMap[string, map[string]string] `json:"group_special_usable_group"`
+ GroupRatio *types.RWMap[string, float64] `json:"group_ratio"`
+ GroupGroupRatio *types.RWMap[string, map[string]float64] `json:"group_group_ratio"`
+ GroupSpecialUsableGroup *types.RWMap[string, map[string]string] `json:"group_special_usable_group"`
}
var groupRatioSetting GroupRatioSetting
@@ -46,10 +44,13 @@ func init() {
groupSpecialUsableGroup := types.NewRWMap[string, map[string]string]()
groupSpecialUsableGroup.AddAll(defaultGroupSpecialUsableGroup)
+ groupRatioMap.AddAll(defaultGroupRatio)
+ groupGroupRatioMap.AddAll(defaultGroupGroupRatio)
+
groupRatioSetting = GroupRatioSetting{
GroupSpecialUsableGroup: groupSpecialUsableGroup,
- GroupRatio: groupRatio,
- GroupGroupRatio: GroupGroupRatio,
+ GroupRatio: groupRatioMap,
+ GroupGroupRatio: groupGroupRatioMap,
}
config.GlobalConfig.Register("group_ratio_setting", &groupRatioSetting)
@@ -64,48 +65,24 @@ func GetGroupRatioSetting() *GroupRatioSetting {
}
func GetGroupRatioCopy() map[string]float64 {
- groupRatioMutex.RLock()
- defer groupRatioMutex.RUnlock()
-
- groupRatioCopy := make(map[string]float64)
- for k, v := range groupRatio {
- groupRatioCopy[k] = v
- }
- return groupRatioCopy
+ return groupRatioMap.ReadAll()
}
func ContainsGroupRatio(name string) bool {
- groupRatioMutex.RLock()
- defer groupRatioMutex.RUnlock()
-
- _, ok := groupRatio[name]
+ _, ok := groupRatioMap.Get(name)
return ok
}
func GroupRatio2JSONString() string {
- groupRatioMutex.RLock()
- defer groupRatioMutex.RUnlock()
-
- jsonBytes, err := json.Marshal(groupRatio)
- if err != nil {
- common.SysLog("error marshalling model ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return groupRatioMap.MarshalJSONString()
}
func UpdateGroupRatioByJSONString(jsonStr string) error {
- groupRatioMutex.Lock()
- defer groupRatioMutex.Unlock()
-
- groupRatio = make(map[string]float64)
- return json.Unmarshal([]byte(jsonStr), &groupRatio)
+ return types.LoadFromJsonString(groupRatioMap, jsonStr)
}
func GetGroupRatio(name string) float64 {
- groupRatioMutex.RLock()
- defer groupRatioMutex.RUnlock()
-
- ratio, ok := groupRatio[name]
+ ratio, ok := groupRatioMap.Get(name)
if !ok {
common.SysLog("group ratio not found: " + name)
return 1
@@ -114,10 +91,7 @@ func GetGroupRatio(name string) float64 {
}
func GetGroupGroupRatio(userGroup, usingGroup string) (float64, bool) {
- groupGroupRatioMutex.RLock()
- defer groupGroupRatioMutex.RUnlock()
-
- gp, ok := GroupGroupRatio[userGroup]
+ gp, ok := groupGroupRatioMap.Get(userGroup)
if !ok {
return -1, false
}
@@ -129,22 +103,11 @@ func GetGroupGroupRatio(userGroup, usingGroup string) (float64, bool) {
}
func GroupGroupRatio2JSONString() string {
- groupGroupRatioMutex.RLock()
- defer groupGroupRatioMutex.RUnlock()
-
- jsonBytes, err := json.Marshal(GroupGroupRatio)
- if err != nil {
- common.SysLog("error marshalling group-group ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return groupGroupRatioMap.MarshalJSONString()
}
func UpdateGroupGroupRatioByJSONString(jsonStr string) error {
- groupGroupRatioMutex.Lock()
- defer groupGroupRatioMutex.Unlock()
-
- GroupGroupRatio = make(map[string]map[string]float64)
- return json.Unmarshal([]byte(jsonStr), &GroupGroupRatio)
+ return types.LoadFromJsonString(groupGroupRatioMap, jsonStr)
}
func CheckGroupRatio(jsonStr string) error {
diff --git a/setting/ratio_setting/model_ratio.go b/setting/ratio_setting/model_ratio.go
index 039d4a0211..62fc8b3e10 100644
--- a/setting/ratio_setting/model_ratio.go
+++ b/setting/ratio_setting/model_ratio.go
@@ -1,12 +1,11 @@
package ratio_setting
import (
- "encoding/json"
"strings"
- "sync"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/operation_setting"
+ "github.com/QuantumNous/new-api/types"
)
// from songquanpeng/one-api
@@ -131,9 +130,6 @@ var defaultModelRatio = map[string]float64{
"text-search-ada-doc-001": 10,
"text-moderation-stable": 0.1,
"text-moderation-latest": 0.1,
- "claude-instant-1": 0.4, // $0.8 / 1M tokens
- "claude-2.0": 4, // $8 / 1M tokens
- "claude-2.1": 4, // $8 / 1M tokens
"claude-3-haiku-20240307": 0.125, // $0.25 / 1M tokens
"claude-3-5-haiku-20241022": 0.5, // $1 / 1M tokens
"claude-haiku-4-5-20251001": 0.5, // $1 / 1M tokens
@@ -145,6 +141,11 @@ var defaultModelRatio = map[string]float64{
"claude-sonnet-4-20250514": 1.5,
"claude-sonnet-4-5-20250929": 1.5,
"claude-opus-4-5-20251101": 2.5,
+ "claude-opus-4-6": 2.5,
+ "claude-opus-4-6-max": 2.5,
+ "claude-opus-4-6-high": 2.5,
+ "claude-opus-4-6-medium": 2.5,
+ "claude-opus-4-6-low": 2.5,
"claude-3-opus-20240229": 7.5, // $15 / 1M tokens
"claude-opus-4-20250514": 7.5,
"claude-opus-4-1-20250805": 7.5,
@@ -297,6 +298,10 @@ var defaultModelPrice = map[string]float64{
"sora-2": 0.3,
"sora-2-pro": 0.5,
"gpt-4o-mini-tts": 0.3,
+ "veo-3.0-generate-001": 0.4,
+ "veo-3.0-fast-generate-001": 0.15,
+ "veo-3.1-generate-preview": 0.4,
+ "veo-3.1-fast-generate-preview": 0.15,
}
var defaultAudioRatio = map[string]float64{
@@ -317,19 +322,9 @@ var defaultAudioCompletionRatio = map[string]float64{
"tts-1-hd-1106": 0,
}
-var (
- modelPriceMap map[string]float64 = nil
- modelPriceMapMutex = sync.RWMutex{}
-)
-var (
- modelRatioMap map[string]float64 = nil
- modelRatioMapMutex = sync.RWMutex{}
-)
-
-var (
- CompletionRatio map[string]float64 = nil
- CompletionRatioMutex = sync.RWMutex{}
-)
+var modelPriceMap = types.NewRWMap[string, float64]()
+var modelRatioMap = types.NewRWMap[string, float64]()
+var completionRatioMap = types.NewRWMap[string, float64]()
var defaultCompletionRatio = map[string]float64{
"gpt-4-gizmo-*": 2,
@@ -340,78 +335,44 @@ var defaultCompletionRatio = map[string]float64{
// InitRatioSettings initializes all model related settings maps
func InitRatioSettings() {
- // Initialize modelPriceMap
- modelPriceMapMutex.Lock()
- modelPriceMap = defaultModelPrice
- modelPriceMapMutex.Unlock()
-
- // Initialize modelRatioMap
- modelRatioMapMutex.Lock()
- modelRatioMap = defaultModelRatio
- modelRatioMapMutex.Unlock()
-
- // Initialize CompletionRatio
- CompletionRatioMutex.Lock()
- CompletionRatio = defaultCompletionRatio
- CompletionRatioMutex.Unlock()
-
- // Initialize cacheRatioMap
- cacheRatioMapMutex.Lock()
- cacheRatioMap = defaultCacheRatio
- cacheRatioMapMutex.Unlock()
-
- // initialize imageRatioMap
- imageRatioMapMutex.Lock()
- imageRatioMap = defaultImageRatio
- imageRatioMapMutex.Unlock()
-
- // initialize audioRatioMap
- audioRatioMapMutex.Lock()
- audioRatioMap = defaultAudioRatio
- audioRatioMapMutex.Unlock()
-
- // initialize audioCompletionRatioMap
- audioCompletionRatioMapMutex.Lock()
- audioCompletionRatioMap = defaultAudioCompletionRatio
- audioCompletionRatioMapMutex.Unlock()
+ modelPriceMap.AddAll(defaultModelPrice)
+ modelRatioMap.AddAll(defaultModelRatio)
+ completionRatioMap.AddAll(defaultCompletionRatio)
+ cacheRatioMap.AddAll(defaultCacheRatio)
+ createCacheRatioMap.AddAll(defaultCreateCacheRatio)
+ imageRatioMap.AddAll(defaultImageRatio)
+ audioRatioMap.AddAll(defaultAudioRatio)
+ audioCompletionRatioMap.AddAll(defaultAudioCompletionRatio)
}
func GetModelPriceMap() map[string]float64 {
- modelPriceMapMutex.RLock()
- defer modelPriceMapMutex.RUnlock()
- return modelPriceMap
+ return modelPriceMap.ReadAll()
}
func ModelPrice2JSONString() string {
- modelPriceMapMutex.RLock()
- defer modelPriceMapMutex.RUnlock()
-
- jsonBytes, err := common.Marshal(modelPriceMap)
- if err != nil {
- common.SysError("error marshalling model price: " + err.Error())
- }
- return string(jsonBytes)
+ return modelPriceMap.MarshalJSONString()
}
func UpdateModelPriceByJSONString(jsonStr string) error {
- modelPriceMapMutex.Lock()
- defer modelPriceMapMutex.Unlock()
- modelPriceMap = make(map[string]float64)
- err := json.Unmarshal([]byte(jsonStr), &modelPriceMap)
- if err == nil {
- InvalidateExposedDataCache()
- }
- return err
+ return types.LoadFromJsonStringWithCallback(modelPriceMap, jsonStr, InvalidateExposedDataCache)
}
// GetModelPrice 返回模型的价格,如果模型不存在则返回-1,false
func GetModelPrice(name string, printErr bool) (float64, bool) {
- modelPriceMapMutex.RLock()
- defer modelPriceMapMutex.RUnlock()
-
name = FormatMatchingModelName(name)
- price, ok := modelPriceMap[name]
+ if strings.HasSuffix(name, CompactModelSuffix) {
+ price, ok := modelPriceMap.Get(CompactWildcardModelKey)
+ if !ok {
+ if printErr {
+ common.SysError("model price not found: " + name)
+ }
+ return -1, false
+ }
+ return price, true
+ }
+
+ price, ok := modelPriceMap.Get(name)
if !ok {
if printErr {
common.SysError("model price not found: " + name)
@@ -422,14 +383,7 @@ func GetModelPrice(name string, printErr bool) (float64, bool) {
}
func UpdateModelRatioByJSONString(jsonStr string) error {
- modelRatioMapMutex.Lock()
- defer modelRatioMapMutex.Unlock()
- modelRatioMap = make(map[string]float64)
- err := common.Unmarshal([]byte(jsonStr), &modelRatioMap)
- if err == nil {
- InvalidateExposedDataCache()
- }
- return err
+ return types.LoadFromJsonStringWithCallback(modelRatioMap, jsonStr, InvalidateExposedDataCache)
}
// 处理带有思考预算的模型名称,方便统一定价
@@ -441,13 +395,16 @@ func handleThinkingBudgetModel(name, prefix, wildcard string) string {
}
func GetModelRatio(name string) (float64, bool, string) {
- modelRatioMapMutex.RLock()
- defer modelRatioMapMutex.RUnlock()
-
name = FormatMatchingModelName(name)
- ratio, ok := modelRatioMap[name]
+ ratio, ok := modelRatioMap.Get(name)
if !ok {
+ if strings.HasSuffix(name, CompactModelSuffix) {
+ if wildcardRatio, ok := modelRatioMap.Get(CompactWildcardModelKey); ok {
+ return wildcardRatio, true, name
+ }
+ //return 0, true, name
+ }
return 37.5, operation_setting.SelfUseModeEnabled, name
}
return ratio, true, name
@@ -469,54 +426,19 @@ func GetDefaultModelPriceMap() map[string]float64 {
return defaultModelPrice
}
-func GetDefaultImageRatioMap() map[string]float64 {
- return defaultImageRatio
-}
-
-func GetDefaultAudioRatioMap() map[string]float64 {
- return defaultAudioRatio
-}
-
-func GetDefaultAudioCompletionRatioMap() map[string]float64 {
- return defaultAudioCompletionRatio
-}
-
-func GetCompletionRatioMap() map[string]float64 {
- CompletionRatioMutex.RLock()
- defer CompletionRatioMutex.RUnlock()
- return CompletionRatio
-}
-
func CompletionRatio2JSONString() string {
- CompletionRatioMutex.RLock()
- defer CompletionRatioMutex.RUnlock()
-
- jsonBytes, err := json.Marshal(CompletionRatio)
- if err != nil {
- common.SysError("error marshalling completion ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return completionRatioMap.MarshalJSONString()
}
func UpdateCompletionRatioByJSONString(jsonStr string) error {
- CompletionRatioMutex.Lock()
- defer CompletionRatioMutex.Unlock()
- CompletionRatio = make(map[string]float64)
- err := common.Unmarshal([]byte(jsonStr), &CompletionRatio)
- if err == nil {
- InvalidateExposedDataCache()
- }
- return err
+ return types.LoadFromJsonStringWithCallback(completionRatioMap, jsonStr, InvalidateExposedDataCache)
}
func GetCompletionRatio(name string) float64 {
- CompletionRatioMutex.RLock()
- defer CompletionRatioMutex.RUnlock()
-
name = FormatMatchingModelName(name)
if strings.Contains(name, "/") {
- if ratio, ok := CompletionRatio[name]; ok {
+ if ratio, ok := completionRatioMap.Get(name); ok {
return ratio
}
}
@@ -524,12 +446,50 @@ func GetCompletionRatio(name string) float64 {
if contain {
return hardCodedRatio
}
- if ratio, ok := CompletionRatio[name]; ok {
+ if ratio, ok := completionRatioMap.Get(name); ok {
return ratio
}
return hardCodedRatio
}
+type CompletionRatioInfo struct {
+ Ratio float64 `json:"ratio"`
+ Locked bool `json:"locked"`
+}
+
+func GetCompletionRatioInfo(name string) CompletionRatioInfo {
+ name = FormatMatchingModelName(name)
+
+ if strings.Contains(name, "/") {
+ if ratio, ok := completionRatioMap.Get(name); ok {
+ return CompletionRatioInfo{
+ Ratio: ratio,
+ Locked: false,
+ }
+ }
+ }
+
+ hardCodedRatio, locked := getHardcodedCompletionModelRatio(name)
+ if locked {
+ return CompletionRatioInfo{
+ Ratio: hardCodedRatio,
+ Locked: true,
+ }
+ }
+
+ if ratio, ok := completionRatioMap.Get(name); ok {
+ return CompletionRatioInfo{
+ Ratio: ratio,
+ Locked: false,
+ }
+ }
+
+ return CompletionRatioInfo{
+ Ratio: hardCodedRatio,
+ Locked: false,
+ }
+}
+
func getHardcodedCompletionModelRatio(name string) (float64, bool) {
isReservedModel := strings.HasSuffix(name, "-all") || strings.HasSuffix(name, "-gizmo-*")
@@ -549,6 +509,12 @@ func getHardcodedCompletionModelRatio(name string) (float64, bool) {
}
// gpt-5 匹配
if strings.HasPrefix(name, "gpt-5") {
+ if strings.HasPrefix(name, "gpt-5.4") {
+ if strings.HasPrefix(name, "gpt-5.4-nano") {
+ return 6.25, true
+ }
+ return 6, true
+ }
return 8, true
}
// gpt-4.5-preview匹配
@@ -572,8 +538,6 @@ func getHardcodedCompletionModelRatio(name string) (float64, bool) {
return 5, true
} else if strings.Contains(name, "claude-sonnet-4") || strings.Contains(name, "claude-opus-4") || strings.Contains(name, "claude-haiku-4") {
return 5, true
- } else if strings.Contains(name, "claude-instant-1") || strings.Contains(name, "claude-2") {
- return 3, true
}
if strings.HasPrefix(name, "gpt-3.5") {
@@ -654,88 +618,54 @@ func getHardcodedCompletionModelRatio(name string) (float64, bool) {
}
func GetAudioRatio(name string) float64 {
- audioRatioMapMutex.RLock()
- defer audioRatioMapMutex.RUnlock()
name = FormatMatchingModelName(name)
- if ratio, ok := audioRatioMap[name]; ok {
+ if ratio, ok := audioRatioMap.Get(name); ok {
return ratio
}
return 1
}
func GetAudioCompletionRatio(name string) float64 {
- audioCompletionRatioMapMutex.RLock()
- defer audioCompletionRatioMapMutex.RUnlock()
name = FormatMatchingModelName(name)
- if ratio, ok := audioCompletionRatioMap[name]; ok {
-
+ if ratio, ok := audioCompletionRatioMap.Get(name); ok {
return ratio
}
return 1
}
func ContainsAudioRatio(name string) bool {
- audioRatioMapMutex.RLock()
- defer audioRatioMapMutex.RUnlock()
name = FormatMatchingModelName(name)
- _, ok := audioRatioMap[name]
+ _, ok := audioRatioMap.Get(name)
return ok
}
func ContainsAudioCompletionRatio(name string) bool {
- audioCompletionRatioMapMutex.RLock()
- defer audioCompletionRatioMapMutex.RUnlock()
name = FormatMatchingModelName(name)
- _, ok := audioCompletionRatioMap[name]
+ _, ok := audioCompletionRatioMap.Get(name)
return ok
}
func ModelRatio2JSONString() string {
- modelRatioMapMutex.RLock()
- defer modelRatioMapMutex.RUnlock()
-
- jsonBytes, err := common.Marshal(modelRatioMap)
- if err != nil {
- common.SysError("error marshalling model ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return modelRatioMap.MarshalJSONString()
}
var defaultImageRatio = map[string]float64{
"gpt-image-1": 2,
}
-var imageRatioMap map[string]float64
-var imageRatioMapMutex sync.RWMutex
-var (
- audioRatioMap map[string]float64 = nil
- audioRatioMapMutex = sync.RWMutex{}
-)
-var (
- audioCompletionRatioMap map[string]float64 = nil
- audioCompletionRatioMapMutex = sync.RWMutex{}
-)
+var imageRatioMap = types.NewRWMap[string, float64]()
+var audioRatioMap = types.NewRWMap[string, float64]()
+var audioCompletionRatioMap = types.NewRWMap[string, float64]()
func ImageRatio2JSONString() string {
- imageRatioMapMutex.RLock()
- defer imageRatioMapMutex.RUnlock()
- jsonBytes, err := common.Marshal(imageRatioMap)
- if err != nil {
- common.SysError("error marshalling cache ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return imageRatioMap.MarshalJSONString()
}
func UpdateImageRatioByJSONString(jsonStr string) error {
- imageRatioMapMutex.Lock()
- defer imageRatioMapMutex.Unlock()
- imageRatioMap = make(map[string]float64)
- return common.Unmarshal([]byte(jsonStr), &imageRatioMap)
+ return types.LoadFromJsonString(imageRatioMap, jsonStr)
}
func GetImageRatio(name string) (float64, bool) {
- imageRatioMapMutex.RLock()
- defer imageRatioMapMutex.RUnlock()
- ratio, ok := imageRatioMap[name]
+ ratio, ok := imageRatioMap.Get(name)
if !ok {
return 1, false // Default to 1 if not found
}
@@ -743,78 +673,31 @@ func GetImageRatio(name string) (float64, bool) {
}
func AudioRatio2JSONString() string {
- audioRatioMapMutex.RLock()
- defer audioRatioMapMutex.RUnlock()
- jsonBytes, err := common.Marshal(audioRatioMap)
- if err != nil {
- common.SysError("error marshalling audio ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return audioRatioMap.MarshalJSONString()
}
func UpdateAudioRatioByJSONString(jsonStr string) error {
-
- tmp := make(map[string]float64)
- if err := common.Unmarshal([]byte(jsonStr), &tmp); err != nil {
- return err
- }
- audioRatioMapMutex.Lock()
- audioRatioMap = tmp
- audioRatioMapMutex.Unlock()
- InvalidateExposedDataCache()
- return nil
+ return types.LoadFromJsonStringWithCallback(audioRatioMap, jsonStr, InvalidateExposedDataCache)
}
func AudioCompletionRatio2JSONString() string {
- audioCompletionRatioMapMutex.RLock()
- defer audioCompletionRatioMapMutex.RUnlock()
- jsonBytes, err := common.Marshal(audioCompletionRatioMap)
- if err != nil {
- common.SysError("error marshalling audio completion ratio: " + err.Error())
- }
- return string(jsonBytes)
+ return audioCompletionRatioMap.MarshalJSONString()
}
func UpdateAudioCompletionRatioByJSONString(jsonStr string) error {
- tmp := make(map[string]float64)
- if err := common.Unmarshal([]byte(jsonStr), &tmp); err != nil {
- return err
- }
- audioCompletionRatioMapMutex.Lock()
- audioCompletionRatioMap = tmp
- audioCompletionRatioMapMutex.Unlock()
- InvalidateExposedDataCache()
- return nil
+ return types.LoadFromJsonStringWithCallback(audioCompletionRatioMap, jsonStr, InvalidateExposedDataCache)
}
func GetModelRatioCopy() map[string]float64 {
- modelRatioMapMutex.RLock()
- defer modelRatioMapMutex.RUnlock()
- copyMap := make(map[string]float64, len(modelRatioMap))
- for k, v := range modelRatioMap {
- copyMap[k] = v
- }
- return copyMap
+ return modelRatioMap.ReadAll()
}
func GetModelPriceCopy() map[string]float64 {
- modelPriceMapMutex.RLock()
- defer modelPriceMapMutex.RUnlock()
- copyMap := make(map[string]float64, len(modelPriceMap))
- for k, v := range modelPriceMap {
- copyMap[k] = v
- }
- return copyMap
+ return modelPriceMap.ReadAll()
}
func GetCompletionRatioCopy() map[string]float64 {
- CompletionRatioMutex.RLock()
- defer CompletionRatioMutex.RUnlock()
- copyMap := make(map[string]float64, len(CompletionRatio))
- for k, v := range CompletionRatio {
- copyMap[k] = v
- }
- return copyMap
+ return completionRatioMap.ReadAll()
}
// 转换模型名,减少渠道必须配置各种带参数模型
diff --git a/setting/reasoning/suffix.go b/setting/reasoning/suffix.go
index da3bdc7d3e..fb66c6019a 100644
--- a/setting/reasoning/suffix.go
+++ b/setting/reasoning/suffix.go
@@ -6,7 +6,7 @@ import (
"github.com/samber/lo"
)
-var EffortSuffixes = []string{"-high", "-medium", "-low", "-minimal"}
+var EffortSuffixes = []string{"-max", "-high", "-medium", "-low", "-minimal"}
// TrimEffortSuffix -> modelName level(low) exists
func TrimEffortSuffix(modelName string) (string, string, bool) {
diff --git a/setting/system_setting/fetch_setting.go b/setting/system_setting/fetch_setting.go
index 078696195f..c71be03c50 100644
--- a/setting/system_setting/fetch_setting.go
+++ b/setting/system_setting/fetch_setting.go
@@ -21,7 +21,7 @@ var defaultFetchSetting = FetchSetting{
DomainList: []string{},
IpList: []string{},
AllowedPorts: []string{"80", "443", "8080", "8443"},
- ApplyIPFilterForDomain: false,
+ ApplyIPFilterForDomain: true,
}
func init() {
diff --git a/types/error.go b/types/error.go
index e112eeefbe..6af39f7e9f 100644
--- a/types/error.go
+++ b/types/error.go
@@ -40,6 +40,7 @@ type ErrorCode string
const (
ErrorCodeInvalidRequest ErrorCode = "invalid_request"
ErrorCodeSensitiveWordsDetected ErrorCode = "sensitive_words_detected"
+ ErrorCodeViolationFeeGrokCSAM ErrorCode = "violation_fee.grok.csam"
// new api error
ErrorCodeCountTokenFailed ErrorCode = "count_token_failed"
diff --git a/types/file_source.go b/types/file_source.go
new file mode 100644
index 0000000000..86ef25e1b0
--- /dev/null
+++ b/types/file_source.go
@@ -0,0 +1,232 @@
+package types
+
+import (
+ "fmt"
+ "image"
+ "os"
+ "strings"
+ "sync"
+)
+
+// FileSource 统一的文件来源抽象接口
+// 支持 URL 和 base64 两种来源,提供懒加载和缓存机制
+type FileSource interface {
+ IsURL() bool
+ GetIdentifier() string
+ GetRawData() string
+ ClearRawData()
+
+ SetCache(data *CachedFileData)
+ GetCache() *CachedFileData
+ HasCache() bool
+ ClearCache()
+
+ IsRegistered() bool
+ SetRegistered(registered bool)
+ Mu() *sync.Mutex
+}
+
+// baseFileSource 共享的缓存/锁/清理注册状态
+type baseFileSource struct {
+ cachedData *CachedFileData
+ cacheLoaded bool
+ registered bool
+ mu sync.Mutex
+}
+
+func (b *baseFileSource) SetCache(data *CachedFileData) {
+ b.cachedData = data
+ b.cacheLoaded = true
+}
+
+func (b *baseFileSource) GetCache() *CachedFileData {
+ return b.cachedData
+}
+
+func (b *baseFileSource) HasCache() bool {
+ return b.cacheLoaded && b.cachedData != nil
+}
+
+func (b *baseFileSource) ClearCache() {
+ if b.cachedData != nil {
+ b.cachedData.Close()
+ }
+ b.cachedData = nil
+ b.cacheLoaded = false
+}
+
+func (b *baseFileSource) IsRegistered() bool {
+ return b.registered
+}
+
+func (b *baseFileSource) SetRegistered(registered bool) {
+ b.registered = registered
+}
+
+func (b *baseFileSource) Mu() *sync.Mutex {
+ return &b.mu
+}
+
+// ---------------------------------------------------------------------------
+// URLSource — URL 来源的 FileSource 实现
+// ---------------------------------------------------------------------------
+
+type URLSource struct {
+ baseFileSource
+ URL string
+}
+
+func (u *URLSource) IsURL() bool { return true }
+
+func (u *URLSource) GetIdentifier() string {
+ if len(u.URL) > 100 {
+ return u.URL[:100] + "..."
+ }
+ return u.URL
+}
+
+func (u *URLSource) GetRawData() string { return u.URL }
+
+func (u *URLSource) ClearRawData() {}
+
+// ---------------------------------------------------------------------------
+// Base64Source — Base64 内联数据来源的 FileSource 实现
+// ---------------------------------------------------------------------------
+
+type Base64Source struct {
+ baseFileSource
+ Base64Data string
+ MimeType string
+}
+
+func (b *Base64Source) IsURL() bool { return false }
+
+func (b *Base64Source) GetIdentifier() string {
+ if len(b.Base64Data) > 50 {
+ return "base64:" + b.Base64Data[:50] + "..."
+ }
+ return "base64:" + b.Base64Data
+}
+
+func (b *Base64Source) GetRawData() string { return b.Base64Data }
+
+func (b *Base64Source) ClearRawData() {
+ if len(b.Base64Data) > 1024 {
+ b.Base64Data = ""
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Constructors
+// ---------------------------------------------------------------------------
+
+func NewURLFileSource(url string) *URLSource {
+ return &URLSource{URL: url}
+}
+
+func NewBase64FileSource(base64Data string, mimeType string) *Base64Source {
+ return &Base64Source{
+ Base64Data: base64Data,
+ MimeType: mimeType,
+ }
+}
+
+func NewFileSourceFromData(data string, mimeType string) FileSource {
+ if strings.HasPrefix(data, "http://") || strings.HasPrefix(data, "https://") {
+ return NewURLFileSource(data)
+ }
+ return NewBase64FileSource(data, mimeType)
+}
+
+// ---------------------------------------------------------------------------
+// CachedFileData — 缓存的文件数据(支持内存和磁盘两种模式)
+// ---------------------------------------------------------------------------
+
+type CachedFileData struct {
+ base64Data string // 内存中的 base64 数据(小文件)
+ MimeType string // MIME 类型
+ Size int64 // 文件大小(字节)
+ DiskSize int64 // 磁盘缓存实际占用大小(字节,通常是 base64 长度)
+ ImageConfig *image.Config // 图片配置(如果是图片)
+ ImageFormat string // 图片格式(如果是图片)
+
+ diskPath string // 磁盘缓存文件路径(大文件)
+ isDisk bool // 是否使用磁盘缓存
+ diskMu sync.Mutex // 磁盘操作锁(保护磁盘文件的读取和删除)
+ diskClosed bool // 是否已关闭/清理
+ statDecremented bool // 是否已扣减统计
+
+ OnClose func(size int64)
+}
+
+func NewMemoryCachedData(base64Data string, mimeType string, size int64) *CachedFileData {
+ return &CachedFileData{
+ base64Data: base64Data,
+ MimeType: mimeType,
+ Size: size,
+ isDisk: false,
+ }
+}
+
+func NewDiskCachedData(diskPath string, mimeType string, size int64) *CachedFileData {
+ return &CachedFileData{
+ diskPath: diskPath,
+ MimeType: mimeType,
+ Size: size,
+ isDisk: true,
+ }
+}
+
+func (c *CachedFileData) GetBase64Data() (string, error) {
+ if !c.isDisk {
+ return c.base64Data, nil
+ }
+
+ c.diskMu.Lock()
+ defer c.diskMu.Unlock()
+
+ if c.diskClosed {
+ return "", fmt.Errorf("disk cache already closed")
+ }
+
+ data, err := os.ReadFile(c.diskPath)
+ if err != nil {
+ return "", fmt.Errorf("failed to read from disk cache: %w", err)
+ }
+ return string(data), nil
+}
+
+func (c *CachedFileData) SetBase64Data(data string) {
+ if !c.isDisk {
+ c.base64Data = data
+ }
+}
+
+func (c *CachedFileData) IsDisk() bool {
+ return c.isDisk
+}
+
+func (c *CachedFileData) Close() error {
+ if !c.isDisk {
+ c.base64Data = ""
+ return nil
+ }
+
+ c.diskMu.Lock()
+ defer c.diskMu.Unlock()
+
+ if c.diskClosed {
+ return nil
+ }
+
+ c.diskClosed = true
+ if c.diskPath != "" {
+ err := os.Remove(c.diskPath)
+ if err == nil && !c.statDecremented && c.OnClose != nil {
+ c.OnClose(c.DiskSize)
+ c.statDecremented = true
+ }
+ return err
+ }
+ return nil
+}
diff --git a/types/price_data.go b/types/price_data.go
index 3f7121b8c7..93bc6ae8d1 100644
--- a/types/price_data.go
+++ b/types/price_data.go
@@ -22,7 +22,8 @@ type PriceData struct {
AudioCompletionRatio float64
OtherRatios map[string]float64
UsePrice bool
- QuotaToPreConsume int // 预消耗额度
+ Quota int // 按次计费的最终额度(MJ / Task)
+ QuotaToPreConsume int // 按量计费的预消耗额度
GroupRatioInfo GroupRatioInfo
}
@@ -36,12 +37,6 @@ func (p *PriceData) AddOtherRatio(key string, ratio float64) {
p.OtherRatios[key] = ratio
}
-type PerCallPriceData struct {
- ModelPrice float64
- Quota int
- GroupRatioInfo GroupRatioInfo
-}
-
func (p *PriceData) ToSetting() string {
return fmt.Sprintf("ModelPrice: %f, ModelRatio: %f, CompletionRatio: %f, CacheRatio: %f, GroupRatio: %f, UsePrice: %t, CacheCreationRatio: %f, CacheCreation5mRatio: %f, CacheCreation1hRatio: %f, QuotaToPreConsume: %d, ImageRatio: %f, AudioRatio: %f, AudioCompletionRatio: %f", p.ModelPrice, p.ModelRatio, p.CompletionRatio, p.CacheRatio, p.GroupRatioInfo.GroupRatio, p.UsePrice, p.CacheCreationRatio, p.CacheCreation5mRatio, p.CacheCreation1hRatio, p.QuotaToPreConsume, p.ImageRatio, p.AudioRatio, p.AudioCompletionRatio)
}
diff --git a/types/relay_format.go b/types/relay_format.go
index 6d94a70bca..9b4c86f249 100644
--- a/types/relay_format.go
+++ b/types/relay_format.go
@@ -3,15 +3,16 @@ package types
type RelayFormat string
const (
- RelayFormatOpenAI RelayFormat = "openai"
- RelayFormatClaude = "claude"
- RelayFormatGemini = "gemini"
- RelayFormatOpenAIResponses = "openai_responses"
- RelayFormatOpenAIAudio = "openai_audio"
- RelayFormatOpenAIImage = "openai_image"
- RelayFormatOpenAIRealtime = "openai_realtime"
- RelayFormatRerank = "rerank"
- RelayFormatEmbedding = "embedding"
+ RelayFormatOpenAI RelayFormat = "openai"
+ RelayFormatClaude = "claude"
+ RelayFormatGemini = "gemini"
+ RelayFormatOpenAIResponses = "openai_responses"
+ RelayFormatOpenAIResponsesCompaction = "openai_responses_compaction"
+ RelayFormatOpenAIAudio = "openai_audio"
+ RelayFormatOpenAIImage = "openai_image"
+ RelayFormatOpenAIRealtime = "openai_realtime"
+ RelayFormatRerank = "rerank"
+ RelayFormatEmbedding = "embedding"
RelayFormatTask = "task"
RelayFormatMjProxy = "mj_proxy"
diff --git a/types/request_meta.go b/types/request_meta.go
index 18f80832be..476ea0524d 100644
--- a/types/request_meta.go
+++ b/types/request_meta.go
@@ -32,10 +32,47 @@ type TokenCountMeta struct {
type FileMeta struct {
FileType
- MimeType string
- OriginData string // url or base64 data
- Detail string
- ParsedData *LocalFileData
+ Source FileSource // 统一的文件来源(URL 或 base64)
+ Detail string // 图片细节级别(low/high/auto)
+}
+
+// NewFileMeta 创建新的 FileMeta
+func NewFileMeta(fileType FileType, source FileSource) *FileMeta {
+ return &FileMeta{
+ FileType: fileType,
+ Source: source,
+ }
+}
+
+// NewImageFileMeta 创建图片类型的 FileMeta
+func NewImageFileMeta(source FileSource, detail string) *FileMeta {
+ return &FileMeta{
+ FileType: FileTypeImage,
+ Source: source,
+ Detail: detail,
+ }
+}
+
+// GetIdentifier 获取文件标识符(用于日志)
+func (f *FileMeta) GetIdentifier() string {
+ if f.Source != nil {
+ return f.Source.GetIdentifier()
+ }
+ return "unknown"
+}
+
+// IsURL 判断是否是 URL 来源
+func (f *FileMeta) IsURL() bool {
+ return f.Source != nil && f.Source.IsURL()
+}
+
+// GetRawData 获取原始数据(兼容旧代码)
+// Deprecated: 请使用 Source.GetRawData()
+func (f *FileMeta) GetRawData() string {
+ if f.Source != nil {
+ return f.Source.GetRawData()
+ }
+ return ""
}
type RequestMeta struct {
diff --git a/types/rw_map.go b/types/rw_map.go
index 12c9cbc7fe..3d296816f2 100644
--- a/types/rw_map.go
+++ b/types/rw_map.go
@@ -80,3 +80,24 @@ func LoadFromJsonString[K comparable, V any](m *RWMap[K, V], jsonStr string) err
m.data = make(map[K]V)
return common.Unmarshal([]byte(jsonStr), &m.data)
}
+
+// LoadFromJsonStringWithCallback loads a JSON string into the RWMap and calls the callback on success.
+func LoadFromJsonStringWithCallback[K comparable, V any](m *RWMap[K, V], jsonStr string, onSuccess func()) error {
+ m.mutex.Lock()
+ defer m.mutex.Unlock()
+ m.data = make(map[K]V)
+ err := common.Unmarshal([]byte(jsonStr), &m.data)
+ if err == nil && onSuccess != nil {
+ onSuccess()
+ }
+ return err
+}
+
+// MarshalJSONString returns the JSON string representation of the RWMap.
+func (m *RWMap[K, V]) MarshalJSONString() string {
+ bytes, err := m.MarshalJSON()
+ if err != nil {
+ return "{}"
+ }
+ return string(bytes)
+}
diff --git a/web/old/bun.lock b/web/old/bun.lock
index f9a60229b3..9a8419226a 100644
--- a/web/old/bun.lock
+++ b/web/old/bun.lock
@@ -11,9 +11,8 @@
"@visactor/react-vchart": "~1.8.8",
"@visactor/vchart": "~1.8.8",
"@visactor/vchart-semi-theme": "~1.8.8",
- "axios": "1.12.0",
+ "axios": "1.13.5",
"clsx": "^2.1.1",
- "country-flag-icons": "^1.5.19",
"dayjs": "^1.11.11",
"history": "^5.3.0",
"i18next": "^23.16.8",
@@ -778,7 +777,7 @@
"autoprefixer": ["autoprefixer@10.4.21", "", { "dependencies": { "browserslist": "^4.24.4", "caniuse-lite": "^1.0.30001702", "fraction.js": "^4.3.7", "normalize-range": "^0.1.2", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": { "autoprefixer": "bin/autoprefixer" } }, "sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ=="],
- "axios": ["axios@1.12.0", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg=="],
+ "axios": ["axios@1.13.5", "", { "dependencies": { "follow-redirects": "^1.15.11", "form-data": "^4.0.5", "proxy-from-env": "^1.1.0" } }, "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q=="],
"babel-plugin-macros": ["babel-plugin-macros@3.1.0", "", { "dependencies": { "@babel/runtime": "^7.12.5", "cosmiconfig": "^7.0.0", "resolve": "^1.19.0" } }, "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg=="],
@@ -884,8 +883,6 @@
"cosmiconfig": ["cosmiconfig@7.1.0", "", { "dependencies": { "@types/parse-json": "^4.0.0", "import-fresh": "^3.2.1", "parse-json": "^5.0.0", "path-type": "^4.0.0", "yaml": "^1.10.0" } }, "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA=="],
- "country-flag-icons": ["country-flag-icons@1.5.19", "", {}, "sha512-D/ZkRyj+ywJC6b2IrAN3/tpbReMUqmuRLlcKFoY/o0+EPQN9Ev/e8tV+D3+9scvu/tarxwLErNwS73C3yzxs/g=="],
-
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
@@ -1108,13 +1105,13 @@
"flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="],
- "follow-redirects": ["follow-redirects@1.15.9", "", {}, "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ=="],
+ "follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
"for-in": ["for-in@1.0.2", "", {}, "sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ=="],
"foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="],
- "form-data": ["form-data@4.0.4", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow=="],
+ "form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
"fraction.js": ["fraction.js@4.3.7", "", {}, "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew=="],
diff --git a/web/old/i18next.config.js b/web/old/i18next.config.js
index 4e138bdfc5..fc4767ee6b 100644
--- a/web/old/i18next.config.js
+++ b/web/old/i18next.config.js
@@ -21,77 +21,66 @@ import { defineConfig } from 'i18next-cli';
/** @type {import('i18next-cli').I18nextToolkitConfig} */
export default defineConfig({
- locales: [
- "zh",
- "en",
- "fr",
- "ru",
- "ja",
- "vi"
- ],
+ locales: ['zh-CN', 'zh-TW', 'en', 'fr', 'ru', 'ja', 'vi'],
extract: {
- input: [
- "src/**/*.{js,jsx,ts,tsx}"
- ],
- ignore: [
- "src/i18n/**/*"
- ],
- output: "src/i18n/locales/{{language}}.json",
+ input: ['src/**/*.{js,jsx,ts,tsx}'],
+ ignore: ['src/i18n/**/*'],
+ output: 'src/i18n/locales/{{language}}.json',
ignoredAttributes: [
- "accept",
- "align",
- "aria-label",
- "autoComplete",
- "className",
- "clipRule",
- "color",
- "crossOrigin",
- "data-index",
- "data-name",
- "data-testid",
- "data-type",
- "defaultActiveKey",
- "direction",
- "editorType",
- "field",
- "fill",
- "fillRule",
- "height",
- "hoverStyle",
- "htmlType",
- "id",
- "itemKey",
- "key",
- "keyPrefix",
- "layout",
- "margin",
- "maxHeight",
- "mode",
- "name",
- "overflow",
- "placement",
- "position",
- "rel",
- "role",
- "rowKey",
- "searchPosition",
- "selectedStyle",
- "shape",
- "size",
- "style",
- "theme",
- "trigger",
- "uploadTrigger",
- "validateStatus",
- "value",
- "viewBox",
- "width"
+ 'accept',
+ 'align',
+ 'aria-label',
+ 'autoComplete',
+ 'className',
+ 'clipRule',
+ 'color',
+ 'crossOrigin',
+ 'data-index',
+ 'data-name',
+ 'data-testid',
+ 'data-type',
+ 'defaultActiveKey',
+ 'direction',
+ 'editorType',
+ 'field',
+ 'fill',
+ 'fillRule',
+ 'height',
+ 'hoverStyle',
+ 'htmlType',
+ 'id',
+ 'itemKey',
+ 'key',
+ 'keyPrefix',
+ 'layout',
+ 'margin',
+ 'maxHeight',
+ 'mode',
+ 'name',
+ 'overflow',
+ 'placement',
+ 'position',
+ 'rel',
+ 'role',
+ 'rowKey',
+ 'searchPosition',
+ 'selectedStyle',
+ 'shape',
+ 'size',
+ 'style',
+ 'theme',
+ 'trigger',
+ 'uploadTrigger',
+ 'validateStatus',
+ 'value',
+ 'viewBox',
+ 'width',
],
sort: true,
disablePlurals: false,
removeUnusedKeys: false,
nsSeparator: false,
keySeparator: false,
- mergeNamespaces: true
- }
-});
\ No newline at end of file
+ mergeNamespaces: true,
+ },
+});
diff --git a/web/old/index.html b/web/old/index.html
index b1bcf1713e..d6bd2433ea 100644
--- a/web/old/index.html
+++ b/web/old/index.html
@@ -7,8 +7,15 @@
+
+
New API
diff --git a/web/old/package.json b/web/old/package.json
index 9ac8e266eb..97c7c821fe 100644
--- a/web/old/package.json
+++ b/web/old/package.json
@@ -10,9 +10,8 @@
"@visactor/react-vchart": "~1.8.8",
"@visactor/vchart": "~1.8.8",
"@visactor/vchart-semi-theme": "~1.8.8",
- "axios": "1.12.0",
+ "axios": "1.13.5",
"clsx": "^2.1.1",
- "country-flag-icons": "^1.5.19",
"dayjs": "^1.11.11",
"history": "^5.3.0",
"i18next": "^23.16.8",
diff --git a/web/old/public/pay-apple.png b/web/old/public/pay-apple.png
new file mode 100644
index 0000000000..b040f6e89f
Binary files /dev/null and b/web/old/public/pay-apple.png differ
diff --git a/web/old/public/pay-card.png b/web/old/public/pay-card.png
new file mode 100644
index 0000000000..98c4146185
Binary files /dev/null and b/web/old/public/pay-card.png differ
diff --git a/web/old/public/pay-google.png b/web/old/public/pay-google.png
new file mode 100644
index 0000000000..bd31bb92fa
Binary files /dev/null and b/web/old/public/pay-google.png differ
diff --git a/web/old/src/App.jsx b/web/old/src/App.jsx
index 995c644996..a5d1ebc00b 100644
--- a/web/old/src/App.jsx
+++ b/web/old/src/App.jsx
@@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { lazy, Suspense, useContext, useMemo } from 'react';
-import { Route, Routes, useLocation } from 'react-router-dom';
+import { Route, Routes, useLocation, useParams } from 'react-router-dom';
import Loading from './components/common/ui/Loading';
import User from './pages/User';
import { AuthRedirect, PrivateRoute, AdminRoute } from './helpers';
@@ -44,6 +44,7 @@ import Task from './pages/Task';
import ModelPage from './pages/Model';
import ModelDeploymentPage from './pages/ModelDeployment';
import Playground from './pages/Playground';
+import Subscription from './pages/Subscription';
import OAuth2Callback from './components/auth/OAuth2Callback';
import PersonalSetting from './components/settings/PersonalSetting';
import Setup from './pages/Setup';
@@ -55,6 +56,11 @@ const About = lazy(() => import('./pages/About'));
const UserAgreement = lazy(() => import('./pages/UserAgreement'));
const PrivacyPolicy = lazy(() => import('./pages/PrivacyPolicy'));
+function DynamicOAuth2Callback() {
+ const { provider } = useParams();
+ return ;
+}
+
function App() {
const location = useLocation();
const [statusState] = useContext(StatusContext);
@@ -117,6 +123,14 @@ function App() {
}
/>
+
+
+
+ }
+ />
}
/>
+ } key={location.pathname}>
+
+
+ }
+ />
{
let navigate = useNavigate();
@@ -101,6 +111,7 @@ const LoginForm = () => {
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
const githubTimeoutRef = useRef(null);
const githubButtonText = t(githubButtonTextKeyByState[githubButtonState]);
+ const [customOAuthLoading, setCustomOAuthLoading] = useState({});
const logo = getLogo();
const systemName = getSystemName();
@@ -120,13 +131,24 @@ const LoginForm = () => {
return {};
}
}, [statusState?.status]);
+ const hasCustomOAuthProviders =
+ (status.custom_oauth_providers || []).length > 0;
+ const hasOAuthLoginOptions = Boolean(
+ status.github_oauth ||
+ status.discord_oauth ||
+ status.oidc_enabled ||
+ status.wechat_login ||
+ status.linuxdo_oauth ||
+ status.telegram_oauth ||
+ hasCustomOAuthProviders,
+ );
useEffect(() => {
if (status?.turnstile_check) {
setTurnstileEnabled(true);
setTurnstileSiteKey(status.turnstile_site_key);
}
-
+
// 从 status 获取用户协议和隐私政策的启用状态
setHasUserAgreement(status?.user_agreement_enabled || false);
setHasPrivacyPolicy(status?.privacy_policy_enabled || false);
@@ -365,6 +387,23 @@ const LoginForm = () => {
}
};
+ // 包装的自定义OAuth登录点击处理
+ const handleCustomOAuthClick = (provider) => {
+ if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
+ showInfo(t('请先阅读并同意用户协议和隐私政策'));
+ return;
+ }
+ setCustomOAuthLoading((prev) => ({ ...prev, [provider.slug]: true }));
+ try {
+ onCustomOAuthClicked(provider, { shouldLogout: true });
+ } finally {
+ // 由于重定向,这里不会执行到,但为了完整性添加
+ setTimeout(() => {
+ setCustomOAuthLoading((prev) => ({ ...prev, [provider.slug]: false }));
+ }, 3000);
+ }
+ };
+
// 包装的邮箱登录选项点击处理
const handleEmailLoginClick = () => {
setEmailLoginLoading(true);
@@ -514,7 +553,15 @@ const LoginForm = () => {
theme='outline'
className='w-full h-12 flex items-center justify-center !rounded-full border border-gray-200 hover:bg-gray-50 transition-colors'
type='tertiary'
- icon={ }
+ icon={
+
+ }
onClick={handleDiscordClick}
loading={discordLoading}
>
@@ -556,6 +603,23 @@ const LoginForm = () => {
)}
+ {status.custom_oauth_providers &&
+ status.custom_oauth_providers.map((provider) => (
+ handleCustomOAuthClick(provider)}
+ loading={customOAuthLoading[provider.slug]}
+ >
+
+ {t('使用 {{name}} 继续', { name: provider.name })}
+
+
+ ))}
+
{status.telegram_oauth && (
{
{t('隐私政策')}
>
- )}
-
-
-
- )}
+ )}
+
+
+
+ )}
{!status.self_use_mode_enabled && (
@@ -746,7 +810,9 @@ const LoginForm = () => {
htmlType='submit'
onClick={handleSubmit}
loading={loginLoading}
- disabled={(hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms}
+ disabled={
+ (hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms
+ }
>
{t('继续')}
@@ -763,12 +829,7 @@ const LoginForm = () => {
- {(status.github_oauth ||
- status.discord_oauth ||
- status.oidc_enabled ||
- status.wechat_login ||
- status.linuxdo_oauth ||
- status.telegram_oauth) && (
+ {hasOAuthLoginOptions && (
<>