mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-04 23:51:08 +00:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c40edb4070 | ||
|
|
7bb9c0ed7d | ||
|
|
5f43696a9a | ||
|
|
847c0c4526 | ||
|
|
4a02d80543 | ||
|
|
bd17411d0e | ||
|
|
c4ae3550dd | ||
|
|
2f43e72bb9 | ||
|
|
b8651947c3 | ||
|
|
96b160d9a0 | ||
|
|
6f972145b7 | ||
|
|
695ebede70 | ||
|
|
269a409241 | ||
|
|
73aabc861c | ||
|
|
3b81776429 | ||
|
|
cbe258fd12 | ||
|
|
1591477a3e | ||
|
|
e457f0fa22 | ||
|
|
c0c3e1cb47 | ||
|
|
f06bf181d2 | ||
|
|
7075ae0d82 | ||
|
|
a177b88e52 | ||
|
|
cfecc8d113 | ||
|
|
c416467882 | ||
|
|
f19095f96d | ||
|
|
625f1693cb | ||
|
|
f25f399be0 | ||
|
|
748b84a15a | ||
|
|
fa42c3d706 | ||
|
|
fb01f5df2c | ||
|
|
8238956799 | ||
|
|
e00a8abdd5 | ||
|
|
a52665d079 | ||
|
|
ba5b861ec0 | ||
|
|
817fd1214c | ||
|
|
41f6e63799 | ||
|
|
b07d85c497 | ||
|
|
cc894ef578 | ||
|
|
83d4eb6a43 | ||
|
|
ecce0769c0 | ||
|
|
377d1230fc | ||
|
|
6466978d2f | ||
|
|
3b8a148bcf | ||
|
|
3e45d4e030 | ||
|
|
f82d32207f | ||
|
|
3fd66a33be | ||
|
|
4a1da29509 | ||
|
|
243921dc0a | ||
|
|
616df479e8 | ||
|
|
75faedda95 | ||
|
|
4eadee1074 | ||
|
|
31d5b67baa | ||
|
|
913ec5d74b | ||
|
|
77e0409f7c | ||
|
|
6a1efda0cc | ||
|
|
7498d8fdc8 | ||
|
|
cd05772e91 | ||
|
|
7a09a2eaf7 | ||
|
|
d493ce0bb2 | ||
|
|
5dfad32b87 | ||
|
|
ee62dfbaf1 | ||
|
|
e2263d2565 | ||
|
|
10081a8127 | ||
|
|
9f2f2738fd |
No files matched your search
@@ -17,6 +17,7 @@ jobs:
|
||||
/bin/bash -n deploy/apple-container.sh
|
||||
/bin/bash deploy/tests/apple-container-test.sh
|
||||
/bin/sh deploy/tests/docker-compose-security-test.sh
|
||||
/bin/sh deploy/tests/docker-compose-gateway-env-test.sh
|
||||
/bin/sh deploy/tests/docker-runtime-resources-test.sh
|
||||
/bin/sh deploy/test-caddyfile-cache.sh
|
||||
|
||||
@@ -32,7 +33,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.6'
|
||||
go version | grep -q 'go1.27.0'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -72,10 +73,10 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.6'
|
||||
go version | grep -q 'go1.27.0'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.9
|
||||
version: v2.13
|
||||
args: --timeout=30m
|
||||
working-directory: backend
|
||||
@@ -115,7 +115,7 @@ jobs:
|
||||
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.6'
|
||||
go version | grep -q 'go1.27.0'
|
||||
|
||||
# Docker setup for GoReleaser
|
||||
- name: Set up QEMU
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.6'
|
||||
go version | grep -q 'go1.27.0'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
|
||||
+5
-5
@@ -34,8 +34,8 @@
|
||||
### 开发工具
|
||||
|
||||
```bash
|
||||
# golangci-lint(CI 用 v2.9,本地建议装同一版以免版本差异带来的噪音)
|
||||
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.9
|
||||
# golangci-lint(CI 用 v2.13,本地建议装同一版以免版本差异带来的噪音)
|
||||
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.13
|
||||
|
||||
# pnpm (前端包管理)
|
||||
npm install -g pnpm
|
||||
@@ -47,13 +47,13 @@ npm install -g pnpm
|
||||
|
||||
| Workflow | 触发条件 | 检查内容 |
|
||||
|----------|----------|----------|
|
||||
| **backend-ci.yml** | push, pull_request | 单元测试 + 集成测试 + golangci-lint v2.9 |
|
||||
| **backend-ci.yml** | push, pull_request | 单元测试 + 集成测试 + golangci-lint v2.13 |
|
||||
| **security-scan.yml** | push, pull_request, 每周一 | govulncheck + gosec + pnpm audit |
|
||||
| **release.yml** | tag `v*` | 构建发布(PR 不触发) |
|
||||
|
||||
### CI 要求
|
||||
|
||||
- Go 版本必须是 **1.26.6**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.26.6'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml`
|
||||
|
||||
### 本地测试命令
|
||||
@@ -203,7 +203,7 @@ go test -tags=integration ./...
|
||||
**解决**:
|
||||
```bash
|
||||
cd backend
|
||||
go generate ./ent # 重新生成 ent 代码
|
||||
go generate ./ent # 重新生成 ent 代码(json.RawMessage 字段会生成为同类型的 jsontext.Value,属预期)
|
||||
git add ent/ # 生成的文件也要提交
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.26.6-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.0-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
# Sub2API
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
@@ -194,7 +194,7 @@ Community projects that extend or integrate with Sub2API:
|
||||
|
||||
| Component | Technology |
|
||||
|-----------|------------|
|
||||
| Backend | Go 1.26.5, Gin, Ent |
|
||||
| Backend | Go 1.27.0, Gin, Ent |
|
||||
| Frontend | Vue 3.4+, Vite 5+, TailwindCSS |
|
||||
| Database | PostgreSQL 15+ |
|
||||
| Cache/Queue | Redis 7+ |
|
||||
@@ -640,6 +640,32 @@ Or set `GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true` in the environment.
|
||||
Use `http_bridge` for client-WebSocket/upstream-HTTP operation when rolling out
|
||||
or mitigating upstream WebSocket issues.
|
||||
|
||||
#### Force OpenAI upstream HTTP/SSE
|
||||
|
||||
When an egress proxy or network repeatedly reconnects OpenAI Responses
|
||||
WebSockets, set the global fallback in the persisted deployment configuration:
|
||||
|
||||
```yaml
|
||||
gateway:
|
||||
openai_ws:
|
||||
force_http: true
|
||||
```
|
||||
|
||||
For Compose and Apple container deployments, the equivalent `.env` setting is:
|
||||
|
||||
```bash
|
||||
GATEWAY_OPENAI_WS_FORCE_HTTP=true
|
||||
```
|
||||
|
||||
This selects HTTP/SSE for OpenAI upstream Responses traffic that would
|
||||
otherwise use WebSocket. It does not change the client-facing protocol or force
|
||||
HTTP/1.1; configure `gateway.openai_http2.enabled` (or
|
||||
`GATEWAY_OPENAI_HTTP2_ENABLED=false`) separately when a proxy is incompatible
|
||||
with HTTP/2. Unlike the account-level `http_bridge` mode, this global fallback
|
||||
takes effect without enabling `mode_router_v2_enabled`. Keep the setting in the
|
||||
deployment's persisted `.env` or `config.yaml`, rather than inside a running
|
||||
container, so it is read again after an image update or container recreation.
|
||||
|
||||
#### ⚠️ Important: Creating the Admin Account
|
||||
|
||||
The initial admin account is **only created via the setup wizard** (served at `http://<host>:8080` on first run). The `default.admin_email` / `default.admin_password` fields in `config.yaml` are **not used** to create it — they exist in the template for historical reasons.
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
# Sub2API
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
@@ -196,7 +196,7 @@ Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的
|
||||
|
||||
| 组件 | 技术 |
|
||||
|------|------|
|
||||
| 后端 | Go 1.26.5, Gin, Ent |
|
||||
| 后端 | Go 1.27.0, Gin, Ent |
|
||||
| 前端 | Vue 3.4+, Vite 5+, TailwindCSS |
|
||||
| 数据库 | PostgreSQL 15+ |
|
||||
| 缓存/队列 | Redis 7+ |
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
# Sub2API
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
@@ -195,7 +195,7 @@ Sub2API を拡張・統合するコミュニティプロジェクト:
|
||||
|
||||
| コンポーネント | 技術 |
|
||||
|-----------|------------|
|
||||
| バックエンド | Go 1.26.5, Gin, Ent |
|
||||
| バックエンド | Go 1.27.0, Gin, Ent |
|
||||
| フロントエンド | Vue 3.4+, Vite 5+, TailwindCSS |
|
||||
| データベース | PostgreSQL 15+ |
|
||||
| キャッシュ/キュー | Redis 7+ |
|
||||
|
||||
@@ -121,6 +121,16 @@ linters:
|
||||
# Default: true — must be true, ent generates 130K+ lines of code
|
||||
generated-is-used: true
|
||||
|
||||
exclusions:
|
||||
rules:
|
||||
# G703/G704 污点分析在测试文件中只会命中 httptest mock 与测试者自设的
|
||||
# 环境变量路径,不构成攻击面;且该分析跨环境结果不稳定(本地/CI 报告的
|
||||
# 位置集合不同),逐点 nolint 无法收敛,故按路径豁免。生产代码不豁免,
|
||||
# 必须逐点 //nolint:gosec 并写明信任边界。
|
||||
- path: '_test\.go$'
|
||||
linters: [ gosec ]
|
||||
text: 'G70[34]'
|
||||
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.26.6-alpine
|
||||
FROM golang:1.27.0-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -125,6 +125,7 @@ func provideCleanup(
|
||||
upstreamBillingProbe *service.UpstreamBillingProbeService,
|
||||
ollamaCloudUsage *service.OllamaCloudUsageService,
|
||||
auditLog *service.AuditLogService,
|
||||
openAIAutoReset *service.OpenAIQuotaAutoResetService,
|
||||
promptAudit *securityaudit.PromptService,
|
||||
pluginManager *service.PluginManager,
|
||||
) func() {
|
||||
@@ -145,6 +146,12 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpenAIQuotaAutoResetService", func() error {
|
||||
if openAIAutoReset != nil {
|
||||
openAIAutoReset.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsIngressRejectAggregator", func() error {
|
||||
if opsIngressReject != nil {
|
||||
opsIngressReject.Stop()
|
||||
|
||||
@@ -194,7 +194,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
|
||||
groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService)
|
||||
claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream)
|
||||
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
|
||||
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository, configConfig)
|
||||
grokQuotaFetcher := service.NewGrokQuotaFetcher()
|
||||
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, configConfig, usageLogRepository, settingService)
|
||||
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService)
|
||||
@@ -304,7 +304,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService)
|
||||
paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry)
|
||||
availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService)
|
||||
modelPlazaHandler := handler.NewModelPlazaHandler(channelService, apiKeyService, settingService)
|
||||
modelPlazaService := service.NewModelPlazaService(channelRepository, groupRepository, pricingService, billingService, modelPricingResolver)
|
||||
modelPlazaHandler := handler.NewModelPlazaHandler(modelPlazaService, apiKeyService, settingService)
|
||||
imageTaskStore := repository.NewImageTaskStore(redisClient)
|
||||
imageTaskService := service.ProvideImageTaskService(imageTaskStore, imageStorageSettingService)
|
||||
asyncImageHandler := handler.NewAsyncImageHandler(imageTaskService, openAIGatewayHandler)
|
||||
@@ -318,7 +319,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
|
||||
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
|
||||
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
|
||||
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService)
|
||||
openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache)
|
||||
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService)
|
||||
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
@@ -345,7 +347,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
|
||||
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
|
||||
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService, pluginManager)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
|
||||
application := &Application{
|
||||
Server: httpServer,
|
||||
PromptAudit: promptService,
|
||||
@@ -426,6 +428,7 @@ func provideCleanup(
|
||||
upstreamBillingProbe *service.UpstreamBillingProbeService,
|
||||
ollamaCloudUsage *service.OllamaCloudUsageService,
|
||||
auditLog *service.AuditLogService,
|
||||
openAIAutoReset *service.OpenAIQuotaAutoResetService,
|
||||
promptAudit *securityaudit.PromptService,
|
||||
pluginManager *service.PluginManager,
|
||||
) func() {
|
||||
@@ -445,6 +448,12 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpenAIQuotaAutoResetService", func() error {
|
||||
if openAIAutoReset != nil {
|
||||
openAIAutoReset.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsIngressRejectAggregator", func() error {
|
||||
if opsIngressReject != nil {
|
||||
opsIngressReject.Stop()
|
||||
|
||||
@@ -94,6 +94,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
nil, // upstreamBillingProbe
|
||||
nil, // ollamaCloudUsage
|
||||
nil, // auditLog
|
||||
nil, // openAIAutoReset
|
||||
nil, // promptAudit
|
||||
nil, // pluginManager
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -100,7 +101,7 @@ type Group struct {
|
||||
// 是否按上下文长度应用模型阶梯价格;默认开启以保持官方/渠道长上下文价
|
||||
LongContextPricingEnabled bool `json:"long_context_pricing_enabled,omitempty"`
|
||||
// 分组逐模型定价;优先级高于渠道和内置定价
|
||||
ModelPricing json.RawMessage `json:"model_pricing,omitempty"`
|
||||
ModelPricing jsontext.Value `json:"model_pricing,omitempty"`
|
||||
// 是否仅允许 Claude Code 客户端
|
||||
ClaudeCodeOnly bool `json:"claude_code_only,omitempty"`
|
||||
// 非 Claude Code 请求降级使用的分组 ID
|
||||
|
||||
@@ -4,7 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -575,7 +575,7 @@ func (_c *GroupCreate) SetNillableLongContextPricingEnabled(v *bool) *GroupCreat
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (_c *GroupCreate) SetModelPricing(v json.RawMessage) *GroupCreate {
|
||||
func (_c *GroupCreate) SetModelPricing(v jsontext.Value) *GroupCreate {
|
||||
_c.mutation.SetModelPricing(v)
|
||||
return _c
|
||||
}
|
||||
@@ -2445,7 +2445,7 @@ func (u *GroupUpsert) UpdateLongContextPricingEnabled() *GroupUpsert {
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (u *GroupUpsert) SetModelPricing(v json.RawMessage) *GroupUpsert {
|
||||
func (u *GroupUpsert) SetModelPricing(v jsontext.Value) *GroupUpsert {
|
||||
u.Set(group.FieldModelPricing, v)
|
||||
return u
|
||||
}
|
||||
@@ -3615,7 +3615,7 @@ func (u *GroupUpsertOne) UpdateLongContextPricingEnabled() *GroupUpsertOne {
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (u *GroupUpsertOne) SetModelPricing(v json.RawMessage) *GroupUpsertOne {
|
||||
func (u *GroupUpsertOne) SetModelPricing(v jsontext.Value) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetModelPricing(v)
|
||||
})
|
||||
@@ -5005,7 +5005,7 @@ func (u *GroupUpsertBulk) UpdateLongContextPricingEnabled() *GroupUpsertBulk {
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (u *GroupUpsertBulk) SetModelPricing(v json.RawMessage) *GroupUpsertBulk {
|
||||
func (u *GroupUpsertBulk) SetModelPricing(v jsontext.Value) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetModelPricing(v)
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -803,13 +803,13 @@ func (_u *GroupUpdate) SetNillableLongContextPricingEnabled(v *bool) *GroupUpdat
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (_u *GroupUpdate) SetModelPricing(v json.RawMessage) *GroupUpdate {
|
||||
func (_u *GroupUpdate) SetModelPricing(v jsontext.Value) *GroupUpdate {
|
||||
_u.mutation.SetModelPricing(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendModelPricing appends value to the "model_pricing" field.
|
||||
func (_u *GroupUpdate) AppendModelPricing(v json.RawMessage) *GroupUpdate {
|
||||
func (_u *GroupUpdate) AppendModelPricing(v jsontext.Value) *GroupUpdate {
|
||||
_u.mutation.AppendModelPricing(v)
|
||||
return _u
|
||||
}
|
||||
@@ -2924,13 +2924,13 @@ func (_u *GroupUpdateOne) SetNillableLongContextPricingEnabled(v *bool) *GroupUp
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (_u *GroupUpdateOne) SetModelPricing(v json.RawMessage) *GroupUpdateOne {
|
||||
func (_u *GroupUpdateOne) SetModelPricing(v jsontext.Value) *GroupUpdateOne {
|
||||
_u.mutation.SetModelPricing(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendModelPricing appends value to the "model_pricing" field.
|
||||
func (_u *GroupUpdateOne) AppendModelPricing(v json.RawMessage) *GroupUpdateOne {
|
||||
func (_u *GroupUpdateOne) AppendModelPricing(v jsontext.Value) *GroupUpdateOne {
|
||||
_u.mutation.AppendModelPricing(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
+23
-23
@@ -4,7 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
@@ -22142,8 +22142,8 @@ type GroupMutation struct {
|
||||
audio_stt_price_per_hour *float64
|
||||
addaudio_stt_price_per_hour *float64
|
||||
long_context_pricing_enabled *bool
|
||||
model_pricing *json.RawMessage
|
||||
appendmodel_pricing json.RawMessage
|
||||
model_pricing *jsontext.Value
|
||||
appendmodel_pricing jsontext.Value
|
||||
claude_code_only *bool
|
||||
fallback_group_id *int64
|
||||
addfallback_group_id *int64
|
||||
@@ -24404,13 +24404,13 @@ func (m *GroupMutation) ResetLongContextPricingEnabled() {
|
||||
}
|
||||
|
||||
// SetModelPricing sets the "model_pricing" field.
|
||||
func (m *GroupMutation) SetModelPricing(jm json.RawMessage) {
|
||||
m.model_pricing = &jm
|
||||
func (m *GroupMutation) SetModelPricing(j jsontext.Value) {
|
||||
m.model_pricing = &j
|
||||
m.appendmodel_pricing = nil
|
||||
}
|
||||
|
||||
// ModelPricing returns the value of the "model_pricing" field in the mutation.
|
||||
func (m *GroupMutation) ModelPricing() (r json.RawMessage, exists bool) {
|
||||
func (m *GroupMutation) ModelPricing() (r jsontext.Value, exists bool) {
|
||||
v := m.model_pricing
|
||||
if v == nil {
|
||||
return
|
||||
@@ -24421,7 +24421,7 @@ func (m *GroupMutation) ModelPricing() (r json.RawMessage, exists bool) {
|
||||
// OldModelPricing returns the old "model_pricing" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldModelPricing(ctx context.Context) (v json.RawMessage, err error) {
|
||||
func (m *GroupMutation) OldModelPricing(ctx context.Context) (v jsontext.Value, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldModelPricing is only allowed on UpdateOne operations")
|
||||
}
|
||||
@@ -24435,13 +24435,13 @@ func (m *GroupMutation) OldModelPricing(ctx context.Context) (v json.RawMessage,
|
||||
return oldValue.ModelPricing, nil
|
||||
}
|
||||
|
||||
// AppendModelPricing adds jm to the "model_pricing" field.
|
||||
func (m *GroupMutation) AppendModelPricing(jm json.RawMessage) {
|
||||
m.appendmodel_pricing = append(m.appendmodel_pricing, jm...)
|
||||
// AppendModelPricing adds j to the "model_pricing" field.
|
||||
func (m *GroupMutation) AppendModelPricing(j jsontext.Value) {
|
||||
m.appendmodel_pricing = append(m.appendmodel_pricing, j...)
|
||||
}
|
||||
|
||||
// AppendedModelPricing returns the list of values that were appended to the "model_pricing" field in this mutation.
|
||||
func (m *GroupMutation) AppendedModelPricing() (json.RawMessage, bool) {
|
||||
func (m *GroupMutation) AppendedModelPricing() (jsontext.Value, bool) {
|
||||
if len(m.appendmodel_pricing) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
@@ -26515,7 +26515,7 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
|
||||
m.SetLongContextPricingEnabled(v)
|
||||
return nil
|
||||
case group.FieldModelPricing:
|
||||
v, ok := value.(json.RawMessage)
|
||||
v, ok := value.(jsontext.Value)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
@@ -43151,8 +43151,8 @@ type UsageCleanupTaskMutation struct {
|
||||
created_at *time.Time
|
||||
updated_at *time.Time
|
||||
status *string
|
||||
filters *json.RawMessage
|
||||
appendfilters json.RawMessage
|
||||
filters *jsontext.Value
|
||||
appendfilters jsontext.Value
|
||||
created_by *int64
|
||||
addcreated_by *int64
|
||||
deleted_rows *int64
|
||||
@@ -43376,13 +43376,13 @@ func (m *UsageCleanupTaskMutation) ResetStatus() {
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (m *UsageCleanupTaskMutation) SetFilters(jm json.RawMessage) {
|
||||
m.filters = &jm
|
||||
func (m *UsageCleanupTaskMutation) SetFilters(j jsontext.Value) {
|
||||
m.filters = &j
|
||||
m.appendfilters = nil
|
||||
}
|
||||
|
||||
// Filters returns the value of the "filters" field in the mutation.
|
||||
func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) {
|
||||
func (m *UsageCleanupTaskMutation) Filters() (r jsontext.Value, exists bool) {
|
||||
v := m.filters
|
||||
if v == nil {
|
||||
return
|
||||
@@ -43393,7 +43393,7 @@ func (m *UsageCleanupTaskMutation) Filters() (r json.RawMessage, exists bool) {
|
||||
// OldFilters returns the old "filters" field's value of the UsageCleanupTask entity.
|
||||
// If the UsageCleanupTask object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMessage, err error) {
|
||||
func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v jsontext.Value, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldFilters is only allowed on UpdateOne operations")
|
||||
}
|
||||
@@ -43407,13 +43407,13 @@ func (m *UsageCleanupTaskMutation) OldFilters(ctx context.Context) (v json.RawMe
|
||||
return oldValue.Filters, nil
|
||||
}
|
||||
|
||||
// AppendFilters adds jm to the "filters" field.
|
||||
func (m *UsageCleanupTaskMutation) AppendFilters(jm json.RawMessage) {
|
||||
m.appendfilters = append(m.appendfilters, jm...)
|
||||
// AppendFilters adds j to the "filters" field.
|
||||
func (m *UsageCleanupTaskMutation) AppendFilters(j jsontext.Value) {
|
||||
m.appendfilters = append(m.appendfilters, j...)
|
||||
}
|
||||
|
||||
// AppendedFilters returns the list of values that were appended to the "filters" field in this mutation.
|
||||
func (m *UsageCleanupTaskMutation) AppendedFilters() (json.RawMessage, bool) {
|
||||
func (m *UsageCleanupTaskMutation) AppendedFilters() (jsontext.Value, bool) {
|
||||
if len(m.appendfilters) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
@@ -43964,7 +43964,7 @@ func (m *UsageCleanupTaskMutation) SetField(name string, value ent.Value) error
|
||||
m.SetStatus(v)
|
||||
return nil
|
||||
case usagecleanuptask.FieldFilters:
|
||||
v, ok := value.(json.RawMessage)
|
||||
v, ok := value.(jsontext.Value)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -25,7 +26,7 @@ type UsageCleanupTask struct {
|
||||
// Status holds the value of the "status" field.
|
||||
Status string `json:"status,omitempty"`
|
||||
// Filters holds the value of the "filters" field.
|
||||
Filters json.RawMessage `json:"filters,omitempty"`
|
||||
Filters jsontext.Value `json:"filters,omitempty"`
|
||||
// CreatedBy holds the value of the "created_by" field.
|
||||
CreatedBy int64 `json:"created_by,omitempty"`
|
||||
// DeletedRows holds the value of the "deleted_rows" field.
|
||||
|
||||
@@ -4,7 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -58,7 +58,7 @@ func (_c *UsageCleanupTaskCreate) SetStatus(v string) *UsageCleanupTaskCreate {
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (_c *UsageCleanupTaskCreate) SetFilters(v json.RawMessage) *UsageCleanupTaskCreate {
|
||||
func (_c *UsageCleanupTaskCreate) SetFilters(v jsontext.Value) *UsageCleanupTaskCreate {
|
||||
_c.mutation.SetFilters(v)
|
||||
return _c
|
||||
}
|
||||
@@ -375,7 +375,7 @@ func (u *UsageCleanupTaskUpsert) UpdateStatus() *UsageCleanupTaskUpsert {
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (u *UsageCleanupTaskUpsert) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsert {
|
||||
func (u *UsageCleanupTaskUpsert) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsert {
|
||||
u.Set(usagecleanuptask.FieldFilters, v)
|
||||
return u
|
||||
}
|
||||
@@ -592,7 +592,7 @@ func (u *UsageCleanupTaskUpsertOne) UpdateStatus() *UsageCleanupTaskUpsertOne {
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (u *UsageCleanupTaskUpsertOne) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsertOne {
|
||||
func (u *UsageCleanupTaskUpsertOne) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsertOne {
|
||||
return u.Update(func(s *UsageCleanupTaskUpsert) {
|
||||
s.SetFilters(v)
|
||||
})
|
||||
@@ -999,7 +999,7 @@ func (u *UsageCleanupTaskUpsertBulk) UpdateStatus() *UsageCleanupTaskUpsertBulk
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (u *UsageCleanupTaskUpsertBulk) SetFilters(v json.RawMessage) *UsageCleanupTaskUpsertBulk {
|
||||
func (u *UsageCleanupTaskUpsertBulk) SetFilters(v jsontext.Value) *UsageCleanupTaskUpsertBulk {
|
||||
return u.Update(func(s *UsageCleanupTaskUpsert) {
|
||||
s.SetFilters(v)
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -51,13 +51,13 @@ func (_u *UsageCleanupTaskUpdate) SetNillableStatus(v *string) *UsageCleanupTask
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (_u *UsageCleanupTaskUpdate) SetFilters(v json.RawMessage) *UsageCleanupTaskUpdate {
|
||||
func (_u *UsageCleanupTaskUpdate) SetFilters(v jsontext.Value) *UsageCleanupTaskUpdate {
|
||||
_u.mutation.SetFilters(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendFilters appends value to the "filters" field.
|
||||
func (_u *UsageCleanupTaskUpdate) AppendFilters(v json.RawMessage) *UsageCleanupTaskUpdate {
|
||||
func (_u *UsageCleanupTaskUpdate) AppendFilters(v jsontext.Value) *UsageCleanupTaskUpdate {
|
||||
_u.mutation.AppendFilters(v)
|
||||
return _u
|
||||
}
|
||||
@@ -374,13 +374,13 @@ func (_u *UsageCleanupTaskUpdateOne) SetNillableStatus(v *string) *UsageCleanupT
|
||||
}
|
||||
|
||||
// SetFilters sets the "filters" field.
|
||||
func (_u *UsageCleanupTaskUpdateOne) SetFilters(v json.RawMessage) *UsageCleanupTaskUpdateOne {
|
||||
func (_u *UsageCleanupTaskUpdateOne) SetFilters(v jsontext.Value) *UsageCleanupTaskUpdateOne {
|
||||
_u.mutation.SetFilters(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AppendFilters appends value to the "filters" field.
|
||||
func (_u *UsageCleanupTaskUpdateOne) AppendFilters(v json.RawMessage) *UsageCleanupTaskUpdateOne {
|
||||
func (_u *UsageCleanupTaskUpdateOne) AppendFilters(v jsontext.Value) *UsageCleanupTaskUpdateOne {
|
||||
_u.mutation.AppendFilters(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
module github.com/Wei-Shaw/sub2api
|
||||
|
||||
go 1.26.6
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.14.5
|
||||
|
||||
@@ -61,6 +61,10 @@ const (
|
||||
// 可通过 gateway.upstream_response_read_max_bytes 配置项覆盖。
|
||||
const DefaultUpstreamResponseReadMaxBytes int64 = 128 * 1024 * 1024
|
||||
|
||||
// DefaultModelsListReadMaxBytes 上游模型列表响应体的默认读取上限。
|
||||
// 可通过 gateway.models_list_read_max_bytes 配置项覆盖。
|
||||
const DefaultModelsListReadMaxBytes int64 = 8 * 1024 * 1024
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig `mapstructure:"server"`
|
||||
Log LogConfig `mapstructure:"log"`
|
||||
@@ -960,6 +964,8 @@ type GatewayConfig struct {
|
||||
TextMaxBodySize int64 `mapstructure:"text_max_body_size"`
|
||||
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
|
||||
UpstreamResponseReadMaxBytes int64 `mapstructure:"upstream_response_read_max_bytes"`
|
||||
// 上游模型列表响应体读取上限(字节)
|
||||
ModelsListReadMaxBytes int64 `mapstructure:"models_list_read_max_bytes"`
|
||||
// 代理探测响应体读取上限(字节)
|
||||
ProxyProbeResponseReadMaxBytes int64 `mapstructure:"proxy_probe_response_read_max_bytes"`
|
||||
// Gemini 上游响应头调试日志开关(默认关闭,避免高频日志开销)
|
||||
@@ -2456,6 +2462,7 @@ func setDefaults() {
|
||||
viper.SetDefault("gateway.max_body_size", int64(256*1024*1024))
|
||||
viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024))
|
||||
viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes)
|
||||
viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes)
|
||||
viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024))
|
||||
viper.SetDefault("gateway.gemini_debug_response_headers", false)
|
||||
viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy)
|
||||
@@ -3265,6 +3272,9 @@ func (c *Config) Validate() error {
|
||||
if c.Gateway.UpstreamResponseReadMaxBytes <= 0 {
|
||||
return fmt.Errorf("gateway.upstream_response_read_max_bytes must be positive")
|
||||
}
|
||||
if c.Gateway.ModelsListReadMaxBytes <= 0 {
|
||||
return fmt.Errorf("gateway.models_list_read_max_bytes must be positive")
|
||||
}
|
||||
if c.Gateway.ProxyProbeResponseReadMaxBytes <= 0 {
|
||||
return fmt.Errorf("gateway.proxy_probe_response_read_max_bytes must be positive")
|
||||
}
|
||||
|
||||
@@ -23,6 +23,13 @@ func resetViperWithJWTSecret(t *testing.T) {
|
||||
t.Setenv("JWT_SECRET", strings.Repeat("x", 32))
|
||||
}
|
||||
|
||||
func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes)
|
||||
}
|
||||
|
||||
func TestLoadTimezonePrecedence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -553,6 +560,15 @@ func TestLoadOpenAIWSClientFirstMessageTimeoutFromEnv(t *testing.T) {
|
||||
require.Equal(t, 120, cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds)
|
||||
}
|
||||
|
||||
func TestLoadOpenAIWSForceHTTPFromEnv(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
t.Setenv("GATEWAY_OPENAI_WS_FORCE_HTTP", "true")
|
||||
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.True(t, cfg.Gateway.OpenAIWS.ForceHTTP)
|
||||
}
|
||||
|
||||
func TestLoadDefaultOpenAICompactModel(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
|
||||
@@ -1794,6 +1810,11 @@ func TestValidateConfigErrors(t *testing.T) {
|
||||
mutate: func(c *Config) { c.Gateway.TextMaxBodySize = c.Gateway.MaxBodySize + 1 },
|
||||
wantErr: "gateway.text_max_body_size",
|
||||
},
|
||||
{
|
||||
name: "gateway models list read limit",
|
||||
mutate: func(c *Config) { c.Gateway.ModelsListReadMaxBytes = 0 },
|
||||
wantErr: "gateway.models_list_read_max_bytes",
|
||||
},
|
||||
{
|
||||
name: "gateway response header timeout",
|
||||
mutate: func(c *Config) { c.Gateway.ResponseHeaderTimeout = -1 },
|
||||
|
||||
@@ -74,8 +74,9 @@ type channelModelPricingRequest struct {
|
||||
}
|
||||
|
||||
type channelTimePricingRequest struct {
|
||||
Timezone string `json:"timezone"`
|
||||
Periods []channelTimePricingPeriodRequest `json:"periods"`
|
||||
Timezone string `json:"timezone"`
|
||||
WeekdaysOnly bool `json:"weekdays_only"`
|
||||
Periods []channelTimePricingPeriodRequest `json:"periods"`
|
||||
}
|
||||
|
||||
type channelTimePricingPeriodRequest struct {
|
||||
@@ -144,8 +145,9 @@ type channelModelPricingResponse struct {
|
||||
}
|
||||
|
||||
type channelTimePricingResponse struct {
|
||||
Timezone string `json:"timezone"`
|
||||
Periods []channelTimePricingPeriodResponse `json:"periods"`
|
||||
Timezone string `json:"timezone"`
|
||||
WeekdaysOnly bool `json:"weekdays_only"`
|
||||
Periods []channelTimePricingPeriodResponse `json:"periods"`
|
||||
}
|
||||
|
||||
type channelTimePricingPeriodResponse struct {
|
||||
@@ -282,7 +284,11 @@ func timePricingToResponse(value *service.ChannelTimePricing) *channelTimePricin
|
||||
Multiplier: period.Multiplier,
|
||||
})
|
||||
}
|
||||
return &channelTimePricingResponse{Timezone: value.Timezone, Periods: periods}
|
||||
return &channelTimePricingResponse{
|
||||
Timezone: value.Timezone,
|
||||
WeekdaysOnly: value.WeekdaysOnly,
|
||||
Periods: periods,
|
||||
}
|
||||
}
|
||||
|
||||
func intervalToResponse(iv service.PricingInterval) pricingIntervalResponse {
|
||||
@@ -374,7 +380,11 @@ func timePricingRequestToService(value *channelTimePricingRequest) *service.Chan
|
||||
Multiplier: period.Multiplier,
|
||||
})
|
||||
}
|
||||
return &service.ChannelTimePricing{Timezone: value.Timezone, Periods: periods}
|
||||
return &service.ChannelTimePricing{
|
||||
Timezone: value.Timezone,
|
||||
WeekdaysOnly: value.WeekdaysOnly,
|
||||
Periods: periods,
|
||||
}
|
||||
}
|
||||
|
||||
func accountStatsPricingRuleRequestToService(r accountStatsPricingRuleRequest) service.AccountStatsPricingRule {
|
||||
|
||||
@@ -426,7 +426,8 @@ func TestPricingRequestToService_TimePricing(t *testing.T) {
|
||||
Models: []string{"gpt-5"},
|
||||
BillingMode: "token",
|
||||
TimePricing: &channelTimePricingRequest{
|
||||
Timezone: "Asia/Shanghai",
|
||||
Timezone: "Asia/Shanghai",
|
||||
WeekdaysOnly: true,
|
||||
Periods: []channelTimePricingPeriodRequest{{
|
||||
StartTime: "09:00", EndTime: "12:00", Multiplier: 2,
|
||||
}},
|
||||
@@ -435,6 +436,7 @@ func TestPricingRequestToService_TimePricing(t *testing.T) {
|
||||
|
||||
got := pricingRequestToService([]channelModelPricingRequest{req}, true)
|
||||
require.Equal(t, "Asia/Shanghai", got[0].TimePricing.Timezone)
|
||||
require.True(t, got[0].TimePricing.WeekdaysOnly)
|
||||
require.Equal(t, 2.0, got[0].TimePricing.Periods[0].Multiplier)
|
||||
}
|
||||
|
||||
@@ -483,7 +485,8 @@ func TestPricingToResponse_TimePricing(t *testing.T) {
|
||||
got := pricingToResponse(&service.ChannelModelPricing{
|
||||
BillingMode: service.BillingModeToken,
|
||||
TimePricing: &service.ChannelTimePricing{
|
||||
Timezone: "Asia/Shanghai",
|
||||
Timezone: "Asia/Shanghai",
|
||||
WeekdaysOnly: true,
|
||||
Periods: []service.ChannelTimePricingPeriod{{
|
||||
StartTime: "14:00", EndTime: "18:00", Multiplier: 1.25,
|
||||
}},
|
||||
@@ -492,6 +495,7 @@ func TestPricingToResponse_TimePricing(t *testing.T) {
|
||||
|
||||
require.NotNil(t, got.TimePricing)
|
||||
require.Equal(t, "Asia/Shanghai", got.TimePricing.Timezone)
|
||||
require.True(t, got.TimePricing.WeekdaysOnly)
|
||||
require.Equal(t, 1.25, got.TimePricing.Periods[0].Multiplier)
|
||||
}
|
||||
|
||||
|
||||
@@ -615,8 +615,10 @@ func (h *GrokOAuthHandler) ResetQuota(c *gin.Context) {
|
||||
response.BadRequest(c, "grok quota service is not enabled")
|
||||
return
|
||||
}
|
||||
// ResetQuota 恒返回 GROK_QUOTA_RESET_UNSUPPORTED(xAI 无 OAuth 配额重置接口),err != nil 恒真为预期。
|
||||
//nolint:staticcheck // SA4023
|
||||
result, err := h.quotaService.ResetQuota(c.Request.Context(), accountID)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:staticcheck // SA4023
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -34,12 +34,6 @@ type openAIAccountStateRecoverer interface {
|
||||
RecoverAccountState(ctx context.Context, accountID int64, options service.AccountRecoveryOptions) (*service.SuccessfulTestRecoveryResult, error)
|
||||
}
|
||||
|
||||
const (
|
||||
openAIQuotaResetWarningCacheRefreshFailed = "reset_credit_cache_refresh_failed"
|
||||
openAIQuotaResetWarningAccountRecoveryFailed = "account_state_recovery_failed"
|
||||
openAIQuotaResetWarningAccountRefreshFailed = "account_state_refresh_failed"
|
||||
)
|
||||
|
||||
// openAIQuotaResetPostProcessTimeout bounds the work performed AFTER the
|
||||
// (non-refundable) reset credit has already been consumed upstream. The whole
|
||||
// request must stay comfortably inside the panel HTTP client timeout, otherwise
|
||||
@@ -493,6 +487,7 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
service.NotifyOpenAIAutoResetCredit(accountID)
|
||||
response.Success(c, usage)
|
||||
}
|
||||
|
||||
@@ -523,6 +518,7 @@ func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) {
|
||||
response.Error(c, http.StatusInternalServerError, "openai quota query returned an empty result")
|
||||
return
|
||||
}
|
||||
service.NotifyOpenAIAutoResetCredit(accountID)
|
||||
|
||||
refreshResponse := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *usage}
|
||||
// A failed snapshot write leaves the previous cache intact — report it as a
|
||||
@@ -600,54 +596,19 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
|
||||
postCtx, cancelPost := openAIQuotaResetPostProcessContext(c.Request.Context())
|
||||
defer cancelPost()
|
||||
|
||||
// Step 1 — unblocking the account is the whole point of consuming a credit
|
||||
// (#3672 / #3740), so it runs FIRST and is never gated on the display cache.
|
||||
// Recovery is DB-only and leaves the manual `schedulable` switch untouched.
|
||||
if h.rateLimitService == nil {
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
postResult := service.RunOpenAIQuotaResetPostProcess(
|
||||
postCtx,
|
||||
accountID,
|
||||
h.quotaService,
|
||||
h.rateLimitService,
|
||||
h.adminService.GetAccount,
|
||||
)
|
||||
resetResponse.Quota = postResult.Quota
|
||||
resetResponse.CacheRefreshed = postResult.CacheRefreshed
|
||||
resetResponse.AccountStateRecovered = postResult.AccountStateRecovered
|
||||
resetResponse.WarningCode = postResult.WarningCode
|
||||
if postResult.Account != nil {
|
||||
resetResponse.Account = dto.AccountFromService(postResult.Account)
|
||||
}
|
||||
if _, err := h.rateLimitService.RecoverAccountState(postCtx, accountID, service.AccountRecoveryOptions{
|
||||
InvalidateToken: true,
|
||||
}); err != nil {
|
||||
// Recovery failures are almost always storage-level; the remaining steps
|
||||
// share that dependency, so stop here instead of compounding the failure.
|
||||
slog.Warn("openai_quota_reset_account_recovery_failed", "account_id", accountID, "error", err)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRecoveryFailed
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
}
|
||||
resetResponse.AccountStateRecovered = true
|
||||
|
||||
// Step 2 — refresh the reset-credit display cache. A failure here is reported
|
||||
// but must not hide the recovered account row produced by step 3.
|
||||
usage, usageErr := h.quotaService.QueryUsage(postCtx, accountID)
|
||||
switch {
|
||||
case usageErr != nil || usage == nil:
|
||||
slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", usageErr)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed
|
||||
default:
|
||||
if err := h.quotaService.CacheResetCreditsSnapshot(postCtx, accountID, usage.RateLimitResetCredits); err != nil {
|
||||
slog.Warn("openai_quota_reset_cache_refresh_failed", "account_id", accountID, "error", err)
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningCacheRefreshFailed
|
||||
} else {
|
||||
resetResponse.Quota = usage
|
||||
resetResponse.CacheRefreshed = true
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3 — hand back the post-recovery account row so the list drops the
|
||||
// stale rate-limit badge without waiting for the next poll.
|
||||
account, err := h.adminService.GetAccount(postCtx, accountID)
|
||||
if err != nil {
|
||||
slog.Warn("openai_quota_reset_account_refresh_failed", "account_id", accountID, "error", err)
|
||||
if resetResponse.WarningCode == "" {
|
||||
resetResponse.WarningCode = openAIQuotaResetWarningAccountRefreshFailed
|
||||
}
|
||||
response.Success(c, resetResponse)
|
||||
return
|
||||
}
|
||||
resetResponse.Account = dto.AccountFromService(account)
|
||||
response.Success(c, resetResponse)
|
||||
}
|
||||
@@ -215,7 +215,7 @@ func TestOpenAIResetQuota_RecoveryFailureStopsWorkflow(t *testing.T) {
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.False(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
@@ -237,7 +237,7 @@ func TestOpenAIResetQuota_MissingRecovererReportsRecoveryFailure(t *testing.T) {
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningAccountRecoveryFailed, envelope.Data.WarningCode)
|
||||
require.False(t, envelope.Data.AccountStateRecovered)
|
||||
require.Zero(t, quota.queryCalls)
|
||||
require.Zero(t, adminService.calls)
|
||||
@@ -260,7 +260,7 @@ func TestOpenAIResetQuota_QueryFailureStillRecoversAndReturnsAccount(t *testing.
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
@@ -285,7 +285,7 @@ func TestOpenAIResetQuota_CacheFailureStillRecoversAndReturnsAccount(t *testing.
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.False(t, envelope.Data.CacheRefreshed)
|
||||
require.Nil(t, envelope.Data.Quota)
|
||||
@@ -307,7 +307,7 @@ func TestOpenAIResetQuota_AccountRefreshFailureReportsRecoveredState(t *testing.
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningAccountRefreshFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningAccountRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.CacheRefreshed)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.NotNil(t, envelope.Data.Quota)
|
||||
@@ -331,7 +331,7 @@ func TestOpenAIResetQuota_CacheAndAccountFailureKeepsFirstWarning(t *testing.T)
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.Nil(t, envelope.Data.Account)
|
||||
}
|
||||
@@ -435,7 +435,7 @@ func TestOpenAIQuotaEmptyUsageIsHandledWithoutPanic(t *testing.T) {
|
||||
status, envelope := performOpenAIQuotaResetRequest(t, handler)
|
||||
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, openAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.Equal(t, service.OpenAIQuotaResetWarningCacheRefreshFailed, envelope.Data.WarningCode)
|
||||
require.True(t, envelope.Data.AccountStateRecovered)
|
||||
require.NotNil(t, envelope.Data.Account)
|
||||
require.Zero(t, quota.cacheCalls)
|
||||
|
||||
@@ -441,7 +441,7 @@ func buildSettingKeyByJSONName() map[string]string {
|
||||
out := make(map[string]string, t.NumField())
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
if field.Type.Kind() == reflect.Ptr {
|
||||
if field.Type.Kind() == reflect.Pointer {
|
||||
continue
|
||||
}
|
||||
name, _, _ := strings.Cut(field.Tag.Get("json"), ",")
|
||||
|
||||
@@ -1144,10 +1144,10 @@ func (k oidcJWK) publicKey() (any, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode ec y: %w", err)
|
||||
}
|
||||
if !curve.IsOnCurve(x, y) {
|
||||
if !curve.IsOnCurve(x, y) { //nolint:staticcheck // JWK 以裸坐标给出公钥;替换为 ecdsa.ParseUncompressedPublicKey 需改变点编码,待单独迁移
|
||||
return nil, errors.New("ec point is not on curve")
|
||||
}
|
||||
return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, nil
|
||||
return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, nil //nolint:staticcheck // 同上
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported jwk kty: %s", k.Kty)
|
||||
}
|
||||
|
||||
@@ -284,13 +284,13 @@ func toUserSupportedModels(
|
||||
return out
|
||||
}
|
||||
|
||||
// toUserPricing 将 service 层定价转换为用户 DTO;入参为 nil 时返回 nil。
|
||||
func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing {
|
||||
if p == nil {
|
||||
// toUserPricingIntervals 将定价区间转换为用户 DTO 白名单形态;nil 入参返回 nil(JSON omitempty 可省略)。
|
||||
func toUserPricingIntervals(src []service.PricingInterval) []userPricingIntervalDTO {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
intervals := make([]userPricingIntervalDTO, 0, len(p.Intervals))
|
||||
for _, iv := range p.Intervals {
|
||||
intervals := make([]userPricingIntervalDTO, 0, len(src))
|
||||
for _, iv := range src {
|
||||
intervals = append(intervals, userPricingIntervalDTO{
|
||||
MinTokens: iv.MinTokens,
|
||||
MaxTokens: iv.MaxTokens,
|
||||
@@ -302,6 +302,19 @@ func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing {
|
||||
PerRequestPrice: iv.PerRequestPrice,
|
||||
})
|
||||
}
|
||||
return intervals
|
||||
}
|
||||
|
||||
// toUserPricing 将 service 层定价转换为用户 DTO;入参为 nil 时返回 nil。
|
||||
func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
intervals := toUserPricingIntervals(p.Intervals)
|
||||
if intervals == nil {
|
||||
// 用户侧定价的 intervals 固定输出数组(空配置为 []),保持既有契约。
|
||||
intervals = []userPricingIntervalDTO{}
|
||||
}
|
||||
billingMode := string(p.BillingMode)
|
||||
if billingMode == "" {
|
||||
billingMode = string(service.BillingModeToken)
|
||||
|
||||
@@ -569,6 +569,13 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
forceCacheBilling := fs.ForceCacheBilling
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
// 长上下文规则由计费服务统一持有(模型广场展示同源),入口只负责声明自己适用该规则。
|
||||
var longContextThreshold int
|
||||
var longContextMultiplier float64
|
||||
if rule := h.gatewayService.LegacyLongContextRule(service.PlatformGemini); rule != nil {
|
||||
longContextThreshold = rule.Threshold
|
||||
longContextMultiplier = rule.Multiplier
|
||||
}
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsageWithLongContext(ctx, &service.RecordUsageLongContextInput{
|
||||
Result: result,
|
||||
@@ -583,8 +590,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
|
||||
UserAgent: userAgent,
|
||||
IPAddress: clientIP,
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
LongContextThreshold: 200000, // Gemini 200K 阈值
|
||||
LongContextMultiplier: 2.0, // 超出部分双倍计费
|
||||
LongContextThreshold: longContextThreshold,
|
||||
LongContextMultiplier: longContextMultiplier,
|
||||
ForceCacheBilling: forceCacheBilling,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
|
||||
@@ -17,39 +17,60 @@ import (
|
||||
// - 匿名:仅非专属分组(订阅型照常展示);
|
||||
// - 登录:非专属分组 + user_allowed_groups 授权的专属分组(不检查订阅有效性)。
|
||||
type ModelPlazaHandler struct {
|
||||
channelService *service.ChannelService
|
||||
plazaService *service.ModelPlazaService
|
||||
apiKeyService *service.APIKeyService
|
||||
settingService *service.SettingService
|
||||
}
|
||||
|
||||
// NewModelPlazaHandler 创建模型广场 handler。
|
||||
func NewModelPlazaHandler(
|
||||
channelService *service.ChannelService,
|
||||
plazaService *service.ModelPlazaService,
|
||||
apiKeyService *service.APIKeyService,
|
||||
settingService *service.SettingService,
|
||||
) *ModelPlazaHandler {
|
||||
return &ModelPlazaHandler{
|
||||
channelService: channelService,
|
||||
plazaService: plazaService,
|
||||
apiKeyService: apiKeyService,
|
||||
settingService: settingService,
|
||||
}
|
||||
}
|
||||
|
||||
// modelPlazaOfficialPricing LiteLLM 官方参考价(USD per token)。
|
||||
// modelPlazaOfficialPricing 官方参考价(USD per token,与计费目录同源)。
|
||||
type modelPlazaOfficialPricing struct {
|
||||
InputPrice *float64 `json:"input_price"`
|
||||
OutputPrice *float64 `json:"output_price"`
|
||||
CacheWritePrice *float64 `json:"cache_write_price"`
|
||||
CacheWrite1hPrice *float64 `json:"cache_write_1h_price,omitempty"`
|
||||
CacheReadPrice *float64 `json:"cache_read_price"`
|
||||
// Intervals 官方长上下文阶梯,仅多档模型给出。
|
||||
Intervals []userPricingIntervalDTO `json:"intervals,omitempty"`
|
||||
}
|
||||
|
||||
// modelPlazaModel 广场模型条目:渠道定价(白名单形态)+ 官方参考价。
|
||||
// modelPlazaTimePricingPeriod 分时倍率时段(配置时区当天 [start, end))。
|
||||
type modelPlazaTimePricingPeriod struct {
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
Multiplier float64 `json:"multiplier"`
|
||||
}
|
||||
|
||||
// modelPlazaTimePricing 计费会生效的分时倍率(仅倍率 ≠ 1 的时段)。
|
||||
// WeekdaysOnly 为 true 时时段仅周一至周五生效,周末整天按标准价计费。
|
||||
type modelPlazaTimePricing struct {
|
||||
Timezone string `json:"timezone"`
|
||||
WeekdaysOnly bool `json:"weekdays_only,omitempty"`
|
||||
Periods []modelPlazaTimePricingPeriod `json:"periods"`
|
||||
}
|
||||
|
||||
// modelPlazaModel 广场模型条目:实收口径展示定价(白名单形态)+ 官方参考价。
|
||||
type modelPlazaModel struct {
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
Pricing *userSupportedModelPricing `json:"pricing"`
|
||||
OfficialPricing *modelPlazaOfficialPricing `json:"official_pricing"`
|
||||
// LongContextBasis 多档时的计价基准:"whole_request"(整单按档)| "marginal"(仅超出部分)。
|
||||
LongContextBasis string `json:"long_context_basis,omitempty"`
|
||||
// TimePricing 分时倍率时段,落在时段内的请求整单乘倍率;无分时省略。
|
||||
TimePricing *modelPlazaTimePricing `json:"time_pricing,omitempty"`
|
||||
}
|
||||
|
||||
// modelPlazaGroup 广场分组条目(白名单字段)。
|
||||
@@ -68,9 +89,11 @@ type modelPlazaGroup struct {
|
||||
IsExclusive bool `json:"is_exclusive"`
|
||||
// 生图独立倍率:为 true 时图片计费模型的实付倍率取 ImageRateMultiplier,
|
||||
// 不取分组/用户专属倍率。
|
||||
ImageRateIndependent bool `json:"image_rate_independent"`
|
||||
ImageRateMultiplier float64 `json:"image_rate_multiplier"`
|
||||
Models []modelPlazaModel `json:"models"`
|
||||
ImageRateIndependent bool `json:"image_rate_independent"`
|
||||
ImageRateMultiplier float64 `json:"image_rate_multiplier"`
|
||||
// 分组是否启用长上下文阶梯计费;关闭时模型实付列只展示最低档/基础价。
|
||||
LongContextPricingEnabled bool `json:"long_context_pricing_enabled"`
|
||||
Models []modelPlazaModel `json:"models"`
|
||||
}
|
||||
|
||||
// modelPlazaResponse 广场页响应。
|
||||
@@ -98,7 +121,7 @@ func (h *ModelPlazaHandler) Get(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
groups, err := h.channelService.ListPlazaGroups(c.Request.Context())
|
||||
groups, err := h.plazaService.ListGroups(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
@@ -161,27 +184,30 @@ func toModelPlazaGroupDTO(g *service.PlazaGroup, userRates map[int64]float64) mo
|
||||
for i := range g.Models {
|
||||
m := &g.Models[i]
|
||||
models = append(models, modelPlazaModel{
|
||||
Name: m.Name,
|
||||
Platform: m.Platform,
|
||||
Pricing: toUserPricing(m.Pricing),
|
||||
OfficialPricing: toModelPlazaOfficialPricing(m.OfficialPricing),
|
||||
Name: m.Name,
|
||||
Platform: m.Platform,
|
||||
Pricing: toUserPricing(m.Pricing),
|
||||
OfficialPricing: toModelPlazaOfficialPricing(m.OfficialPricing),
|
||||
LongContextBasis: string(m.LongContextBasis),
|
||||
TimePricing: toModelPlazaTimePricing(m.TimePricing),
|
||||
})
|
||||
}
|
||||
dto := modelPlazaGroup{
|
||||
ID: g.ID,
|
||||
Name: g.Name,
|
||||
Description: g.Description,
|
||||
Platform: g.Platform,
|
||||
SubscriptionType: g.SubscriptionType,
|
||||
RateMultiplier: g.RateMultiplier,
|
||||
PeakRateEnabled: g.PeakRateEnabled,
|
||||
PeakStart: g.PeakStart,
|
||||
PeakEnd: g.PeakEnd,
|
||||
PeakRateMultiplier: g.PeakRateMultiplier,
|
||||
IsExclusive: g.IsExclusive,
|
||||
ImageRateIndependent: g.ImageRateIndependent,
|
||||
ImageRateMultiplier: g.ImageRateMultiplier,
|
||||
Models: models,
|
||||
ID: g.ID,
|
||||
Name: g.Name,
|
||||
Description: g.Description,
|
||||
Platform: g.Platform,
|
||||
SubscriptionType: g.SubscriptionType,
|
||||
RateMultiplier: g.RateMultiplier,
|
||||
PeakRateEnabled: g.PeakRateEnabled,
|
||||
PeakStart: g.PeakStart,
|
||||
PeakEnd: g.PeakEnd,
|
||||
PeakRateMultiplier: g.PeakRateMultiplier,
|
||||
IsExclusive: g.IsExclusive,
|
||||
ImageRateIndependent: g.ImageRateIndependent,
|
||||
ImageRateMultiplier: g.ImageRateMultiplier,
|
||||
LongContextPricingEnabled: g.LongContextPricingEnabled,
|
||||
Models: models,
|
||||
}
|
||||
if rate, ok := userRates[g.ID]; ok {
|
||||
dto.UserRateMultiplier = &rate
|
||||
@@ -189,6 +215,22 @@ func toModelPlazaGroupDTO(g *service.PlazaGroup, userRates map[int64]float64) mo
|
||||
return dto
|
||||
}
|
||||
|
||||
// toModelPlazaTimePricing 转换分时倍率;nil 透传(JSON 省略)。
|
||||
func toModelPlazaTimePricing(p *service.TimePricingSchedule) *modelPlazaTimePricing {
|
||||
if p == nil || len(p.Periods) == 0 {
|
||||
return nil
|
||||
}
|
||||
periods := make([]modelPlazaTimePricingPeriod, 0, len(p.Periods))
|
||||
for _, period := range p.Periods {
|
||||
periods = append(periods, modelPlazaTimePricingPeriod{
|
||||
StartTime: period.StartTime,
|
||||
EndTime: period.EndTime,
|
||||
Multiplier: period.Multiplier,
|
||||
})
|
||||
}
|
||||
return &modelPlazaTimePricing{Timezone: p.Timezone, WeekdaysOnly: p.WeekdaysOnly, Periods: periods}
|
||||
}
|
||||
|
||||
// toModelPlazaOfficialPricing 转换官方参考价;nil 透传(前端显示 "-")。
|
||||
func toModelPlazaOfficialPricing(p *service.PlazaOfficialPricing) *modelPlazaOfficialPricing {
|
||||
if p == nil {
|
||||
@@ -200,5 +242,6 @@ func toModelPlazaOfficialPricing(p *service.PlazaOfficialPricing) *modelPlazaOff
|
||||
CacheWritePrice: p.CacheWritePrice,
|
||||
CacheWrite1hPrice: p.CacheWrite1hPrice,
|
||||
CacheReadPrice: p.CacheReadPrice,
|
||||
Intervals: toUserPricingIntervals(p.Intervals),
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func TestToModelPlazaGroupDTO_UserRateAndFieldWhitelist(t *testing.T) {
|
||||
"id", "name", "description", "platform", "subscription_type",
|
||||
"rate_multiplier", "user_rate_multiplier", "is_exclusive", "models",
|
||||
"peak_rate_enabled", "peak_start", "peak_end", "peak_rate_multiplier",
|
||||
"image_rate_independent", "image_rate_multiplier",
|
||||
"image_rate_independent", "image_rate_multiplier", "long_context_pricing_enabled",
|
||||
} {
|
||||
_, exists := decoded[key]
|
||||
require.Truef(t, exists, "plaza group DTO must expose %q", key)
|
||||
@@ -109,6 +109,12 @@ func TestToModelPlazaGroupDTO_UserRateAndFieldWhitelist(t *testing.T) {
|
||||
require.Contains(t, official, "cache_read_price")
|
||||
_, has1h := official["cache_write_1h_price"]
|
||||
require.False(t, has1h, "1h 缓存写价为 nil 时应 omitempty")
|
||||
_, hasOfficialIntervals := official["intervals"]
|
||||
require.False(t, hasOfficialIntervals, "官方无阶梯时 intervals 应 omitempty")
|
||||
_, hasBasis := model["long_context_basis"]
|
||||
require.False(t, hasBasis, "单档模型不输出 long_context_basis")
|
||||
_, hasTimePricing := model["time_pricing"]
|
||||
require.False(t, hasTimePricing, "无分时时不输出 time_pricing")
|
||||
|
||||
// 无专属倍率:user_rate_multiplier 整个字段省略
|
||||
dtoNoRate := toModelPlazaGroupDTO(&g, nil)
|
||||
@@ -124,4 +130,94 @@ func TestToModelPlazaOfficialPricing_NilPassthrough(t *testing.T) {
|
||||
require.Nil(t, toModelPlazaOfficialPricing(nil))
|
||||
}
|
||||
|
||||
func TestToModelPlazaGroupDTO_LongContextTiersAndBasis(t *testing.T) {
|
||||
maxTokens := 272000
|
||||
g := service.PlazaGroup{
|
||||
ID: 3, Name: "ladder", Platform: "openai", SubscriptionType: "standard", RateMultiplier: 1,
|
||||
LongContextPricingEnabled: true,
|
||||
Models: []service.PlazaModel{{
|
||||
Name: "gpt-5.4",
|
||||
Platform: "openai",
|
||||
Pricing: &service.ChannelModelPricing{
|
||||
BillingMode: service.BillingModeToken,
|
||||
InputPrice: testPtr(2.5e-6),
|
||||
Intervals: []service.PricingInterval{
|
||||
{MinTokens: 0, MaxTokens: &maxTokens, TierLabel: "≤272K", InputPrice: testPtr(2.5e-6)},
|
||||
{MinTokens: 272000, TierLabel: ">272K", InputPrice: testPtr(5e-6)},
|
||||
},
|
||||
},
|
||||
OfficialPricing: &service.PlazaOfficialPricing{
|
||||
InputPrice: testPtr(2.5e-6),
|
||||
Intervals: []service.PricingInterval{
|
||||
{MinTokens: 0, MaxTokens: &maxTokens, TierLabel: "≤272K", InputPrice: testPtr(2.5e-6)},
|
||||
{MinTokens: 272000, TierLabel: ">272K", InputPrice: testPtr(5e-6)},
|
||||
},
|
||||
},
|
||||
LongContextBasis: service.ContextPricingBasisWholeRequest,
|
||||
}},
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(toModelPlazaGroupDTO(&g, nil))
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &decoded))
|
||||
require.Equal(t, true, decoded["long_context_pricing_enabled"])
|
||||
|
||||
model := decoded["models"].([]any)[0].(map[string]any)
|
||||
require.Equal(t, "whole_request", model["long_context_basis"])
|
||||
|
||||
pricing := model["pricing"].(map[string]any)
|
||||
paidTiers := pricing["intervals"].([]any)
|
||||
require.Len(t, paidTiers, 2)
|
||||
require.Equal(t, ">272K", paidTiers[1].(map[string]any)["tier_label"])
|
||||
|
||||
official := model["official_pricing"].(map[string]any)
|
||||
officialTiers := official["intervals"].([]any)
|
||||
require.Len(t, officialTiers, 2)
|
||||
first := officialTiers[0].(map[string]any)
|
||||
require.Equal(t, "≤272K", first["tier_label"])
|
||||
require.InDelta(t, 272000, first["max_tokens"].(float64), 0)
|
||||
require.Contains(t, first, "cache_write_price", "区间 DTO 字段齐全(nil 输出 null)")
|
||||
}
|
||||
|
||||
func testPtr(v float64) *float64 { return &v }
|
||||
|
||||
func TestToModelPlazaGroupDTO_TimePricing(t *testing.T) {
|
||||
g := service.PlazaGroup{
|
||||
ID: 4, Name: "cn", Platform: "deepseek", SubscriptionType: "standard", RateMultiplier: 1,
|
||||
Models: []service.PlazaModel{{
|
||||
Name: "deepseek-chat",
|
||||
Platform: "deepseek",
|
||||
Pricing: &service.ChannelModelPricing{BillingMode: service.BillingModeToken, InputPrice: testPtr(0.28e-6)},
|
||||
TimePricing: &service.TimePricingSchedule{Timezone: "Asia/Shanghai", Periods: []service.TimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
}},
|
||||
}, {
|
||||
Name: "deepseek-reasoner",
|
||||
Platform: "deepseek",
|
||||
Pricing: &service.ChannelModelPricing{BillingMode: service.BillingModeToken, InputPrice: testPtr(0.56e-6)},
|
||||
TimePricing: &service.TimePricingSchedule{Timezone: "Asia/Shanghai", WeekdaysOnly: true, Periods: []service.TimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
raw, err := json.Marshal(toModelPlazaGroupDTO(&g, nil))
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &decoded))
|
||||
model := decoded["models"].([]any)[0].(map[string]any)
|
||||
tp := model["time_pricing"].(map[string]any)
|
||||
require.Equal(t, "Asia/Shanghai", tp["timezone"])
|
||||
_, hasWeekdaysOnly := tp["weekdays_only"]
|
||||
require.False(t, hasWeekdaysOnly, "未开启仅工作日时字段省略")
|
||||
periods := tp["periods"].([]any)
|
||||
require.Len(t, periods, 1)
|
||||
first := periods[0].(map[string]any)
|
||||
require.Equal(t, "00:30", first["start_time"])
|
||||
require.Equal(t, "08:30", first["end_time"])
|
||||
require.InDelta(t, 0.5, first["multiplier"].(float64), 1e-12)
|
||||
|
||||
weekdaysModel := decoded["models"].([]any)[1].(map[string]any)
|
||||
weekdaysTP := weekdaysModel["time_pricing"].(map[string]any)
|
||||
require.Equal(t, true, weekdaysTP["weekdays_only"])
|
||||
}
|
||||
@@ -89,6 +89,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
return
|
||||
}
|
||||
if _, err := service.ValidateOpenAIServiceTierField(body); err != nil {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
if service.IsGPTImageGenerationModel(reqModel) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Chat Completions endpoint")
|
||||
return
|
||||
|
||||
@@ -392,6 +392,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
return
|
||||
}
|
||||
if _, err := service.ValidateOpenAIServiceTierField(body); err != nil {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
|
||||
previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String())
|
||||
if previousResponseID != "" {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 非法 service_tier 必须在两个 OpenAI 端点(/v1/responses、/v1/chat/completions)
|
||||
// 上以 OpenAI 兼容错误结构返回 HTTP 400。这些用例在 handler 的 service_tier
|
||||
// 校验处短路,不会进入账号选择/重试。
|
||||
//
|
||||
// 合法值(fast/priority/flex/auto/default/scale)与省略/null 的接受语义由
|
||||
// service 层纯校验函数 TestValidateOpenAIServiceTierField 覆盖,避免 handler
|
||||
// 测试走入真实账号选择/重试路径。
|
||||
|
||||
func newServiceTierHandlerTest(t *testing.T) *OpenAIGatewayHandler {
|
||||
t.Helper()
|
||||
return &OpenAIGatewayHandler{
|
||||
gatewayService: &service.OpenAIGatewayService{},
|
||||
billingCacheService: service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, &config.Config{RunMode: config.RunModeSimple}, nil),
|
||||
apiKeyService: &service.APIKeyService{},
|
||||
concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService(
|
||||
&helperConcurrencyCacheStub{userSeq: []bool{true}},
|
||||
)},
|
||||
cfg: &config.Config{},
|
||||
imageLimiter: &imageConcurrencyLimiter{},
|
||||
}
|
||||
}
|
||||
|
||||
func runOpenAIHandlerServiceTierTest(t *testing.T, path, body string, handler func(h *OpenAIGatewayHandler, c *gin.Context)) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
groupID := int64(6401)
|
||||
userID := int64(6402)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 6403,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{
|
||||
ID: groupID,
|
||||
Platform: service.PlatformOpenAI,
|
||||
},
|
||||
User: &service.User{ID: userID, Status: service.StatusActive},
|
||||
})
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: userID, Concurrency: 1})
|
||||
|
||||
handler(newServiceTierHandlerTest(t), c)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_InvalidServiceTierRejected400(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"model":"gpt-5.5","input":"hi","service_tier":"turbo"}`,
|
||||
`{"model":"gpt-5.5","input":"hi","service_tier":"SPEED"}`,
|
||||
`{"model":"gpt-5.5","input":"hi","service_tier":""}`,
|
||||
`{"model":"gpt-5.5","input":"hi","service_tier":123}`,
|
||||
`{"model":"gpt-5.5","input":"hi","service_tier":{}}`,
|
||||
} {
|
||||
rec := runOpenAIHandlerServiceTierTest(t, "/v1/responses", body, func(h *OpenAIGatewayHandler, c *gin.Context) {
|
||||
h.Responses(c)
|
||||
})
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, "body=%s", body)
|
||||
require.Contains(t, rec.Body.String(), "invalid_request_error", "body=%s", body)
|
||||
require.Contains(t, rec.Body.String(), "invalid service_tier", "body=%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerChatCompletions_InvalidServiceTierRejected400(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"turbo"}`,
|
||||
`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":"ultra"}`,
|
||||
`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":""}`,
|
||||
`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"service_tier":["priority"]}`,
|
||||
} {
|
||||
rec := runOpenAIHandlerServiceTierTest(t, "/v1/chat/completions", body, func(h *OpenAIGatewayHandler, c *gin.Context) {
|
||||
h.ChatCompletions(c)
|
||||
})
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, "body=%s", body)
|
||||
require.Contains(t, rec.Body.String(), "invalid_request_error", "body=%s", body)
|
||||
require.Contains(t, rec.Body.String(), "invalid service_tier", "body=%s", body)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,7 @@ func ProvideHandlers(
|
||||
batchImageHandler *BatchImageHandler,
|
||||
_ *service.IdempotencyCoordinator,
|
||||
_ *service.IdempotencyCleanupService,
|
||||
_ *service.OpenAIQuotaAutoResetService,
|
||||
) *Handlers {
|
||||
return &Handlers{
|
||||
Auth: authHandler,
|
||||
|
||||
@@ -255,8 +255,6 @@ const (
|
||||
proxyTLSHandshakeTimeout = 5 * time.Second
|
||||
// clientTimeout 整体请求超时(含连接、发送、等待响应、读取 body)
|
||||
clientTimeout = 10 * time.Second
|
||||
// fetchAvailableModelsBodyLimit limits model-list responses to avoid unbounded memory use.
|
||||
fetchAvailableModelsBodyLimit int64 = 8 << 20
|
||||
)
|
||||
|
||||
func NewClient(proxyURL string) (*Client, error) {
|
||||
@@ -656,10 +654,13 @@ type FetchAvailableModelsResponse struct {
|
||||
|
||||
// FetchAvailableModels 获取可用模型和配额信息,返回解析后的结构体和原始 JSON
|
||||
// 支持 URL fallback:sandbox → daily → prod
|
||||
func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string) (*FetchAvailableModelsResponse, map[string]any, error) {
|
||||
func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) {
|
||||
if c == nil || c.httpClient == nil {
|
||||
return nil, nil, errors.New("antigravity client is not configured")
|
||||
}
|
||||
if bodyLimit <= 0 {
|
||||
return nil, nil, errors.New("fetchAvailableModels body limit must be positive")
|
||||
}
|
||||
|
||||
reqBody := FetchAvailableModelsRequest{Project: projectID}
|
||||
bodyBytes, err := json.Marshal(reqBody)
|
||||
@@ -693,13 +694,13 @@ func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectI
|
||||
return nil, nil, lastErr
|
||||
}
|
||||
|
||||
respBodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, fetchAvailableModelsBodyLimit+1))
|
||||
respBodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1))
|
||||
_ = resp.Body.Close() // 立即关闭,避免循环内 defer 导致的资源泄漏
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
if int64(len(respBodyBytes)) > fetchAvailableModelsBodyLimit {
|
||||
return nil, nil, fmt.Errorf("响应超过 %d 字节", fetchAvailableModelsBodyLimit)
|
||||
if int64(len(respBodyBytes)) > bodyLimit {
|
||||
return nil, nil, fmt.Errorf("响应超过 %d 字节", bodyLimit)
|
||||
}
|
||||
|
||||
// 检查是否需要 URL 降级
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultFetchAvailableModelsBodyLimit int64 = 8 << 20
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NewAPIRequestWithURL
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1517,7 +1519,7 @@ func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
resp, rawResp, err := client.FetchAvailableModels(context.Background(), "test-token", "project-abc")
|
||||
resp, rawResp, err := client.FetchAvailableModels(context.Background(), "test-token", "project-abc", defaultFetchAvailableModelsBodyLimit)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAvailableModels 失败: %v", err)
|
||||
}
|
||||
@@ -1562,6 +1564,34 @@ func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModels_RejectsNonPositiveBodyLimit(t *testing.T) {
|
||||
client := mustNewClient(t, "")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", 0)
|
||||
if err == nil || !strings.Contains(err.Error(), "body limit must be positive") {
|
||||
t.Fatalf("非正读取上限应返回调用错误: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModels_UsesConfiguredBodyLimit(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"models":{"model-a":{}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", 8)
|
||||
if err == nil {
|
||||
t.Fatal("响应超过配置上限时应返回错误")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "响应超过 8 字节") {
|
||||
t.Fatalf("错误应包含配置上限: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_FetchAvailableModels_HTTPError_RealCall(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
@@ -1572,7 +1602,7 @@ func TestClient_FetchAvailableModels_HTTPError_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "bad-token", "proj")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "bad-token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil {
|
||||
t.Fatal("服务器返回 403 时应返回错误")
|
||||
}
|
||||
@@ -1592,7 +1622,7 @@ func TestClient_FetchAvailableModels_InvalidJSON_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil {
|
||||
t.Fatal("无效 JSON 响应应返回错误")
|
||||
}
|
||||
@@ -1622,7 +1652,7 @@ func TestClient_FetchAvailableModels_URLFallback_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server1.URL, server2.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj")
|
||||
resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAvailableModels 应在 fallback 后成功: %v", err)
|
||||
}
|
||||
@@ -1650,7 +1680,7 @@ func TestClient_FetchAvailableModels_AllURLsFail_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server1.URL, server2.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj")
|
||||
_, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil {
|
||||
t.Fatal("所有 URL 都失败时应返回错误")
|
||||
}
|
||||
@@ -1669,7 +1699,7 @@ func TestClient_FetchAvailableModels_ContextCanceled_RealCall(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
_, _, err := client.FetchAvailableModels(ctx, "token", "proj")
|
||||
_, _, err := client.FetchAvailableModels(ctx, "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err == nil {
|
||||
t.Fatal("context 取消时应返回错误")
|
||||
}
|
||||
@@ -1686,7 +1716,7 @@ func TestClient_FetchAvailableModels_EmptyModels_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
resp, rawResp, err := client.FetchAvailableModels(context.Background(), "token", "proj")
|
||||
resp, rawResp, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAvailableModels 失败: %v", err)
|
||||
}
|
||||
@@ -1748,7 +1778,7 @@ func TestClient_FetchAvailableModels_404Fallback_RealCall(t *testing.T) {
|
||||
withMockBaseURLs(t, []string{server1.URL, server2.URL})
|
||||
|
||||
client := mustNewClient(t, "")
|
||||
resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj")
|
||||
resp, _, err := client.FetchAvailableModels(context.Background(), "token", "proj", defaultFetchAvailableModelsBodyLimit)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAvailableModels 应在 404 fallback 后成功: %v", err)
|
||||
}
|
||||
|
||||
@@ -674,7 +674,7 @@ func TestDirectBridge_NonStreamingMatchesDoubleConversion(t *testing.T) {
|
||||
direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514")
|
||||
|
||||
// Double-conversion bridge
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil)
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, nil, false, nil)
|
||||
double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514")
|
||||
|
||||
// Compare key fields
|
||||
@@ -988,7 +988,7 @@ func TestDirectBridge_NonStreamingMatchesDoubleConversion_CacheWriteTokens(t *te
|
||||
|
||||
direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514")
|
||||
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil)
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, nil, false, nil)
|
||||
double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514")
|
||||
|
||||
require.Equal(t, double.Usage.InputTokens, direct.Usage.InputTokens)
|
||||
@@ -1058,7 +1058,7 @@ func TestDirectBridge_NonStreamingMatchesDoubleConversion_EmptyChoices(t *testin
|
||||
|
||||
direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514")
|
||||
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil)
|
||||
responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, nil, false, nil)
|
||||
double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514")
|
||||
|
||||
require.Equal(t, AnthropicStopReasonString(double.StopReason), AnthropicStopReasonString(direct.StopReason))
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestChatReasoningAlias_AnthropicStreaming(t *testing.T) {
|
||||
func TestChatReasoningAlias_ResponsesSharedPaths(t *testing.T) {
|
||||
var response ChatCompletionsResponse
|
||||
readIssue5302Fixture(t, "nonstream_reasoning.json", &response)
|
||||
nonStream := ChatCompletionsResponseToResponses(&response, "reasoning-model", nil, false, nil)
|
||||
nonStream := ChatCompletionsResponseToResponses(&response, "reasoning-model", nil, nil, false, nil)
|
||||
require.Len(t, nonStream.Output, 2)
|
||||
require.Equal(t, "reasoning", nonStream.Output[0].Type)
|
||||
require.Equal(t, "fallback reasoning", nonStream.Output[0].Summary[0].Text)
|
||||
|
||||
@@ -159,6 +159,20 @@ func CustomToolNames(tools []ResponsesTool) map[string]bool {
|
||||
return out
|
||||
}
|
||||
|
||||
// FunctionToolNames collects explicitly declared top-level function tools.
|
||||
func FunctionToolNames(tools []ResponsesTool) map[string]bool {
|
||||
var out map[string]bool
|
||||
for _, tool := range tools {
|
||||
if tool.Type == "function" && tool.Name != "" {
|
||||
if out == nil {
|
||||
out = make(map[string]bool)
|
||||
}
|
||||
out[tool.Name] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NamespacedToolName 记录 namespace 子工具的原始归属(命名空间 + 裸子工具名)。
|
||||
type NamespacedToolName struct {
|
||||
Namespace string
|
||||
@@ -197,6 +211,43 @@ func NamespaceToolNames(tools []ResponsesTool) map[string]NamespacedToolName {
|
||||
return out
|
||||
}
|
||||
|
||||
// customToolCallName restores both the exact downgraded custom-tool name and
|
||||
// namespace-prefixed aliases that chat models sometimes infer from neighboring
|
||||
// flattened namespace tools (for example functions__exec beside
|
||||
// functions__wait). A real declared namespace child always owns its flattened
|
||||
// name, and ambiguous aliases are left as ordinary function calls.
|
||||
func customToolCallName(name string, customTools, functionTools map[string]bool, namespaceTools map[string]NamespacedToolName) (string, bool) {
|
||||
if functionTools[name] {
|
||||
return "", false
|
||||
}
|
||||
if customTools[name] {
|
||||
return name, true
|
||||
}
|
||||
if _, ok := namespaceTools[name]; ok {
|
||||
return "", false
|
||||
}
|
||||
match := ""
|
||||
for customName := range customTools {
|
||||
for _, namespaceTool := range namespaceTools {
|
||||
if flattenNamespaceToolName(namespaceTool.Namespace, customName) != name {
|
||||
continue
|
||||
}
|
||||
if match != "" && match != customName {
|
||||
return "", false
|
||||
}
|
||||
match = customName
|
||||
}
|
||||
}
|
||||
return match, match != ""
|
||||
}
|
||||
|
||||
func customNameForStreamTool(state *ChatCompletionsToResponsesStreamState, name string) string {
|
||||
if customName, ok := customToolCallName(name, state.CustomTools, state.FunctionTools, state.NamespaceTools); ok {
|
||||
return customName
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// HasToolSearchTool 判断 Responses 请求是否声明了 tool_search 服务端工具。chat 桥
|
||||
// 回程时需据此把模型对代理工具的调用还原为 tool_search_call 项:codex 只在该项类型
|
||||
// 且 execution=client 时执行 tool search,同名 function_call 会因 payload 不匹配
|
||||
@@ -918,6 +969,9 @@ func responsesToolsToChatTools(tools []ResponsesTool) ([]ChatTool, error) {
|
||||
topLevel := make(map[string]bool)
|
||||
for _, tool := range tools {
|
||||
if (tool.Type == "function" || tool.Type == "custom") && tool.Name != "" {
|
||||
if topLevel[tool.Name] {
|
||||
return nil, fmt.Errorf("duplicate top-level executable tool name %q; this upstream cannot disambiguate duplicate names, rename one of the tools", tool.Name)
|
||||
}
|
||||
topLevel[tool.Name] = true
|
||||
}
|
||||
}
|
||||
@@ -1148,7 +1202,7 @@ func extractCustomToolCallInput(arguments string) string {
|
||||
// toolSearch 表示客户端声明了 tool_search 工具(见 HasToolSearchTool),代理工具
|
||||
// 的调用会还原为 tool_search_call 项;namespaceTools 是 namespace 子工具的摊平名
|
||||
// 映射(见 NamespaceToolNames),命中的调用还原为带 namespace 字段的 function_call 项。
|
||||
func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model string, customTools map[string]bool, toolSearch bool, namespaceTools map[string]NamespacedToolName) *ResponsesResponse {
|
||||
func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model string, customTools, functionTools map[string]bool, toolSearch bool, namespaceTools map[string]NamespacedToolName) *ResponsesResponse {
|
||||
id := ""
|
||||
if resp != nil {
|
||||
id = resp.ID
|
||||
@@ -1158,10 +1212,11 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str
|
||||
}
|
||||
|
||||
out := &ResponsesResponse{
|
||||
ID: id,
|
||||
Object: "response",
|
||||
Model: model,
|
||||
Status: "completed",
|
||||
ID: id,
|
||||
Object: "response",
|
||||
Model: model,
|
||||
Status: "completed",
|
||||
ServiceTier: chatServiceTier(resp),
|
||||
}
|
||||
if resp == nil {
|
||||
out.Output = []ResponsesOutput{emptyResponsesMessageOutput()}
|
||||
@@ -1173,7 +1228,7 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str
|
||||
|
||||
if len(resp.Choices) > 0 {
|
||||
choice := resp.Choices[0]
|
||||
out.Output = chatMessageToResponsesOutput(choice.Message, customTools, toolSearch, namespaceTools)
|
||||
out.Output = chatMessageToResponsesOutput(choice.Message, customTools, functionTools, toolSearch, namespaceTools)
|
||||
if choice.FinishReason == "length" {
|
||||
out.Status = "incomplete"
|
||||
out.IncompleteDetails = &ResponsesIncompleteDetails{Reason: "max_output_tokens"}
|
||||
@@ -1188,7 +1243,14 @@ func ChatCompletionsResponseToResponses(resp *ChatCompletionsResponse, model str
|
||||
return out
|
||||
}
|
||||
|
||||
func chatMessageToResponsesOutput(message ChatMessage, customTools map[string]bool, toolSearch bool, namespaceTools map[string]NamespacedToolName) []ResponsesOutput {
|
||||
func chatServiceTier(resp *ChatCompletionsResponse) string {
|
||||
if resp == nil {
|
||||
return ""
|
||||
}
|
||||
return resp.ServiceTier
|
||||
}
|
||||
|
||||
func chatMessageToResponsesOutput(message ChatMessage, customTools, functionTools map[string]bool, toolSearch bool, namespaceTools map[string]NamespacedToolName) []ResponsesOutput {
|
||||
var outputs []ResponsesOutput
|
||||
reasoning := message.reasoningText()
|
||||
if reasoning != "" {
|
||||
@@ -1224,12 +1286,12 @@ func chatMessageToResponsesOutput(message ChatMessage, customTools map[string]bo
|
||||
if strings.TrimSpace(arguments) == "" {
|
||||
arguments = "{}"
|
||||
}
|
||||
if customTools[toolCall.Function.Name] {
|
||||
if customName, ok := customToolCallName(toolCall.Function.Name, customTools, functionTools, namespaceTools); ok {
|
||||
outputs = append(outputs, ResponsesOutput{
|
||||
Type: "custom_tool_call",
|
||||
ID: generateItemID(),
|
||||
CallID: toolCall.ID,
|
||||
Name: toolCall.Function.Name,
|
||||
Name: customName,
|
||||
Input: extractCustomToolCallInput(arguments),
|
||||
Status: "completed",
|
||||
})
|
||||
@@ -1360,6 +1422,7 @@ type ChatCompletionsToResponsesStreamState struct {
|
||||
ResponseID string
|
||||
Model string
|
||||
Created int64
|
||||
ServiceTier string // upstream Chat chunk service_tier, echoed on response events
|
||||
SequenceNumber int
|
||||
CreatedSent bool
|
||||
CompletedSent bool
|
||||
@@ -1396,6 +1459,9 @@ type ChatCompletionsToResponsesStreamState struct {
|
||||
// 路由回它注册的 custom 工具。
|
||||
CustomTools map[string]bool
|
||||
|
||||
// FunctionTools is the set of explicitly declared top-level function tools.
|
||||
FunctionTools map[string]bool
|
||||
|
||||
// ToolSearchDeclared 表示客户端请求声明了 tool_search 工具(见
|
||||
// HasToolSearchTool)。命中的代理调用按 tool_search_call 项还原,codex 只按
|
||||
// 该项类型(且 execution=client)执行 tool search。
|
||||
@@ -1488,6 +1554,9 @@ func ChatCompletionsChunkToResponsesEvents(
|
||||
if state.Model == "" && chunk.Model != "" {
|
||||
state.Model = chunk.Model
|
||||
}
|
||||
if chunk.ServiceTier != "" {
|
||||
state.ServiceTier = chunk.ServiceTier
|
||||
}
|
||||
if chunk.Usage != nil {
|
||||
state.Usage = ChatUsageToResponsesUsage(chunk.Usage)
|
||||
}
|
||||
@@ -1644,6 +1713,7 @@ func FinalizeChatCompletionsResponsesStream(state *ChatCompletionsToResponsesStr
|
||||
Object: "response",
|
||||
Model: state.Model,
|
||||
Status: status,
|
||||
ServiceTier: state.ServiceTier,
|
||||
Output: state.chatOutput(),
|
||||
Usage: state.Usage,
|
||||
IncompleteDetails: incompleteDetails,
|
||||
@@ -1659,11 +1729,12 @@ func ensureChatToResponsesCreated(state *ChatCompletionsToResponsesStreamState)
|
||||
state.CreatedSent = true
|
||||
return []ResponsesStreamEvent{chatToResponsesEvent(state, "response.created", &ResponsesStreamEvent{
|
||||
Response: &ResponsesResponse{
|
||||
ID: state.ResponseID,
|
||||
Object: "response",
|
||||
Model: state.Model,
|
||||
Status: "in_progress",
|
||||
Output: []ResponsesOutput{},
|
||||
ID: state.ResponseID,
|
||||
Object: "response",
|
||||
Model: state.Model,
|
||||
Status: "in_progress",
|
||||
ServiceTier: state.ServiceTier,
|
||||
Output: []ResponsesOutput{},
|
||||
},
|
||||
})}
|
||||
}
|
||||
@@ -1796,11 +1867,11 @@ func announceChatToolItem(
|
||||
if state.toolAnnounced[idx] {
|
||||
return nil
|
||||
}
|
||||
if !force && stored.Function.Name == "" && (len(state.CustomTools) > 0 || state.ToolSearchDeclared || len(state.NamespaceTools) > 0) {
|
||||
if !force && stored.Function.Name == "" && (len(state.CustomTools) > 0 || len(state.FunctionTools) > 0 || state.ToolSearchDeclared || len(state.NamespaceTools) > 0) {
|
||||
return nil
|
||||
}
|
||||
state.toolAnnounced[idx] = true
|
||||
isCustom := state.CustomTools[stored.Function.Name]
|
||||
customName, isCustom := customToolCallName(stored.Function.Name, state.CustomTools, state.FunctionTools, state.NamespaceTools)
|
||||
isToolSearch := !isCustom && state.ToolSearchDeclared && stored.Function.Name == toolSearchProxyName
|
||||
state.toolIsCustom[idx] = isCustom
|
||||
state.toolIsToolSearch[idx] = isToolSearch
|
||||
@@ -1814,6 +1885,9 @@ func announceChatToolItem(
|
||||
// namespace 子工具的调用仍按 function_call 生命周期下发,但 added/done 项要
|
||||
// 还原为裸子工具名 + namespace 字段(codex 按 namespace+name 路由)。
|
||||
itemName, itemNamespace := stored.Function.Name, ""
|
||||
if isCustom {
|
||||
itemName = customName
|
||||
}
|
||||
if ns, ok := state.NamespaceTools[stored.Function.Name]; ok && !isCustom && !isToolSearch {
|
||||
state.toolNamespace[idx] = ns
|
||||
itemName, itemNamespace = ns.Name, ns.Namespace
|
||||
@@ -1883,7 +1957,7 @@ func closeChatToolItems(state *ChatCompletionsToResponsesStreamState) []Response
|
||||
OutputIndex: outputIndex,
|
||||
ItemID: itemID,
|
||||
CallID: toolCall.ID,
|
||||
Name: toolCall.Function.Name,
|
||||
Name: customNameForStreamTool(state, toolCall.Function.Name),
|
||||
Input: input,
|
||||
}),
|
||||
chatToResponsesEvent(state, "response.output_item.done", &ResponsesStreamEvent{
|
||||
@@ -1892,7 +1966,7 @@ func closeChatToolItems(state *ChatCompletionsToResponsesStreamState) []Response
|
||||
Type: "custom_tool_call",
|
||||
ID: itemID,
|
||||
CallID: toolCall.ID,
|
||||
Name: toolCall.Function.Name,
|
||||
Name: customNameForStreamTool(state, toolCall.Function.Name),
|
||||
Input: input,
|
||||
Status: "completed",
|
||||
},
|
||||
@@ -1983,7 +2057,7 @@ func (state *ChatCompletionsToResponsesStreamState) chatOutput() []ResponsesOutp
|
||||
Type: "custom_tool_call",
|
||||
ID: generateItemID(),
|
||||
CallID: toolCall.ID,
|
||||
Name: toolCall.Function.Name,
|
||||
Name: customNameForStreamTool(state, toolCall.Function.Name),
|
||||
Input: extractCustomToolCallInput(arguments),
|
||||
Status: "completed",
|
||||
})
|
||||
|
||||
+149
-4
@@ -34,6 +34,60 @@ func TestResponsesToChatCompletionsRequest_CustomToolBecomesFunctionTool(t *test
|
||||
assert.Equal(t, "wait", out.Tools[1].Function.Name)
|
||||
}
|
||||
|
||||
func TestResponsesChatBridge_MixedCustomAndNamespaceToolNames(t *testing.T) {
|
||||
req := &ResponsesRequest{
|
||||
Model: "deepseek-test",
|
||||
Input: json.RawMessage(`"run pwd"`),
|
||||
Tools: []ResponsesTool{
|
||||
{Type: "custom", Name: "exec", Description: "Runs a command"},
|
||||
{Type: "namespace", Name: "functions", Tools: []ResponsesTool{
|
||||
{Type: "function", Name: "wait", Parameters: json.RawMessage(`{"type":"object"}`)},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
chatReq, err := ResponsesToChatCompletionsRequest(req)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, chatReq.Tools, 2)
|
||||
assert.Equal(t, "exec", chatReq.Tools[0].Function.Name)
|
||||
assert.Equal(t, "functions__wait", chatReq.Tools[1].Function.Name)
|
||||
|
||||
customTools := CustomToolNames(req.Tools)
|
||||
namespaceTools := NamespaceToolNames(req.Tools)
|
||||
resp := &ChatCompletionsResponse{Choices: []ChatChoice{{Message: ChatMessage{ToolCalls: []ChatToolCall{
|
||||
{ID: "call_exact", Function: ChatFunctionCall{Name: "exec", Arguments: `{"input":"pwd"}`}},
|
||||
{ID: "call_wait", Function: ChatFunctionCall{Name: "functions__wait", Arguments: `{"cell_id":"1"}`}},
|
||||
{ID: "call_alias", Function: ChatFunctionCall{Name: "functions__exec", Arguments: `not-json`}},
|
||||
}}}}}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, req.Model, customTools, FunctionToolNames(req.Tools), false, namespaceTools)
|
||||
require.Len(t, out.Output, 3)
|
||||
assert.Equal(t, "custom_tool_call", out.Output[0].Type)
|
||||
assert.Equal(t, "exec", out.Output[0].Name)
|
||||
assert.Equal(t, "pwd", out.Output[0].Input)
|
||||
assert.Equal(t, "function_call", out.Output[1].Type)
|
||||
assert.Equal(t, "functions", out.Output[1].Namespace)
|
||||
assert.Equal(t, "wait", out.Output[1].Name)
|
||||
assert.Equal(t, "custom_tool_call", out.Output[2].Type)
|
||||
assert.Equal(t, "exec", out.Output[2].Name)
|
||||
assert.Equal(t, "not-json", out.Output[2].Input)
|
||||
}
|
||||
|
||||
func TestChatCompletionsResponseToResponses_ExplicitFunctionOwnsCustomAliasCollision(t *testing.T) {
|
||||
resp := &ChatCompletionsResponse{Choices: []ChatChoice{{Message: ChatMessage{ToolCalls: []ChatToolCall{{
|
||||
ID: "call_function", Function: ChatFunctionCall{Name: "functions__exec", Arguments: `{"path":"/tmp"}`},
|
||||
}}}}}}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-test",
|
||||
map[string]bool{"exec": true}, map[string]bool{"functions__exec": true}, false,
|
||||
map[string]NamespacedToolName{"functions__wait": {Namespace: "functions", Name: "wait"}})
|
||||
|
||||
require.Len(t, out.Output, 1)
|
||||
assert.Equal(t, "function_call", out.Output[0].Type)
|
||||
assert.Equal(t, "functions__exec", out.Output[0].Name)
|
||||
assert.Equal(t, `{"path":"/tmp"}`, out.Output[0].Arguments)
|
||||
}
|
||||
|
||||
func TestResponsesToChatCompletionsRequest_AdditionalToolsItem(t *testing.T) {
|
||||
req := &ResponsesRequest{
|
||||
Model: "gpt-test",
|
||||
@@ -173,7 +227,7 @@ func TestChatCompletionsResponseToResponses_CustomToolCallOutputItem(t *testing.
|
||||
}},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", map[string]bool{"exec": true}, false, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", map[string]bool{"exec": true}, nil, false, nil)
|
||||
require.Len(t, out.Output, 2)
|
||||
|
||||
assert.Equal(t, "custom_tool_call", out.Output[0].Type)
|
||||
@@ -264,6 +318,68 @@ func TestChatCompletionsChunkToResponsesEvents_CustomToolCallStream(t *testing.T
|
||||
assert.True(t, foundCustom, "response.completed 缺少 custom_tool_call 输出项")
|
||||
}
|
||||
|
||||
func TestChatCompletionsChunkToResponsesEvents_MixedCustomNamespaceAliasStream(t *testing.T) {
|
||||
state := NewChatCompletionsToResponsesStreamState("deepseek-test")
|
||||
state.CustomTools = map[string]bool{"exec": true}
|
||||
state.NamespaceTools = map[string]NamespacedToolName{
|
||||
"functions__wait": {Namespace: "functions", Name: "wait"},
|
||||
}
|
||||
|
||||
idx := 0
|
||||
chunk := &ChatCompletionsChunk{Choices: []ChatChunkChoice{{Delta: ChatDelta{ToolCalls: []ChatToolCall{{
|
||||
Index: &idx, ID: "call_alias", Function: ChatFunctionCall{Name: "functions__exec", Arguments: `not-json`},
|
||||
}}}}}}
|
||||
events := ChatCompletionsChunkToResponsesEvents(chunk, state)
|
||||
events = append(events, FinalizeChatCompletionsResponsesStream(state)...)
|
||||
|
||||
for _, evt := range events {
|
||||
if evt.Type == "response.output_item.added" && evt.Item != nil && evt.Item.Type == "custom_tool_call" {
|
||||
assert.Equal(t, "exec", evt.Item.Name)
|
||||
}
|
||||
if evt.Type == "response.custom_tool_call_input.done" {
|
||||
assert.Equal(t, "exec", evt.Name)
|
||||
assert.Equal(t, "not-json", evt.Input)
|
||||
}
|
||||
if evt.Type == "response.output_item.done" && evt.Item != nil && evt.Item.Type == "custom_tool_call" {
|
||||
assert.Equal(t, "exec", evt.Item.Name)
|
||||
assert.Equal(t, "not-json", evt.Item.Input)
|
||||
}
|
||||
}
|
||||
|
||||
final := events[len(events)-1]
|
||||
require.Equal(t, "response.completed", final.Type)
|
||||
require.Len(t, final.Response.Output, 1)
|
||||
assert.Equal(t, "custom_tool_call", final.Response.Output[0].Type)
|
||||
assert.Equal(t, "exec", final.Response.Output[0].Name)
|
||||
assert.Equal(t, "not-json", final.Response.Output[0].Input)
|
||||
}
|
||||
|
||||
func TestChatCompletionsChunkToResponsesEvents_ExplicitFunctionOwnsCustomAliasCollision(t *testing.T) {
|
||||
state := NewChatCompletionsToResponsesStreamState("deepseek-test")
|
||||
state.CustomTools = map[string]bool{"exec": true}
|
||||
state.FunctionTools = map[string]bool{"functions__exec": true}
|
||||
state.NamespaceTools = map[string]NamespacedToolName{
|
||||
"functions__wait": {Namespace: "functions", Name: "wait"},
|
||||
}
|
||||
|
||||
idx := 0
|
||||
chunk := &ChatCompletionsChunk{Choices: []ChatChunkChoice{{Delta: ChatDelta{ToolCalls: []ChatToolCall{{
|
||||
Index: &idx, ID: "call_function", Function: ChatFunctionCall{Name: "functions__exec", Arguments: `{"path":"/tmp"}`},
|
||||
}}}}}}
|
||||
events := ChatCompletionsChunkToResponsesEvents(chunk, state)
|
||||
events = append(events, FinalizeChatCompletionsResponsesStream(state)...)
|
||||
|
||||
for _, evt := range events {
|
||||
assert.NotEqual(t, "response.custom_tool_call_input.done", evt.Type)
|
||||
}
|
||||
final := events[len(events)-1]
|
||||
require.Equal(t, "response.completed", final.Type)
|
||||
require.Len(t, final.Response.Output, 1)
|
||||
assert.Equal(t, "function_call", final.Response.Output[0].Type)
|
||||
assert.Equal(t, "functions__exec", final.Response.Output[0].Name)
|
||||
assert.Equal(t, `{"path":"/tmp"}`, final.Response.Output[0].Arguments)
|
||||
}
|
||||
|
||||
func TestResponsesToChatCompletionsRequest_ToolSearchToolBecomesProxyFunction(t *testing.T) {
|
||||
req := &ResponsesRequest{
|
||||
Model: "glm-5.2",
|
||||
@@ -280,6 +396,18 @@ func TestResponsesToChatCompletionsRequest_ToolSearchToolBecomesProxyFunction(t
|
||||
assert.Contains(t, string(out.Tools[0].Function.Parameters), `"query"`)
|
||||
}
|
||||
|
||||
func TestResponsesToChatCompletionsRequest_DropsDeferredFlagWithToolSearch(t *testing.T) {
|
||||
var req ResponsesRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"model":"glm-5.2","input":"hi","tools":[{"type":"tool_search"},{"type":"function","name":"shell","defer_loading":true}]}`), &req))
|
||||
|
||||
out, err := ResponsesToChatCompletionsRequest(&req)
|
||||
require.NoError(t, err)
|
||||
encoded, err := json.Marshal(out)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(encoded), "defer_loading")
|
||||
require.Contains(t, string(encoded), `"name":"tool_search"`)
|
||||
}
|
||||
|
||||
// codex 只在 ResponseItem 为 tool_search_call 变体且 execution=client 时执行
|
||||
// tool search;同名 function_call 会命中 ToolSearchHandler 后因 payload 不匹配
|
||||
// 触发 FunctionCallError::Fatal,直接中止整个 turn,因此回程必须还原项类型。
|
||||
@@ -296,7 +424,7 @@ func TestChatCompletionsResponseToResponses_ToolSearchCallOutputItem(t *testing.
|
||||
}},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, true, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, nil, true, nil)
|
||||
require.Len(t, out.Output, 1)
|
||||
|
||||
item := out.Output[0]
|
||||
@@ -328,7 +456,7 @@ func TestChatCompletionsResponseToResponses_ToolSearchNotDeclaredKeepsFunctionCa
|
||||
}
|
||||
|
||||
// 客户端未声明 type=tool_search 时,同名普通 function 工具不受影响。
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, false, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, nil, false, nil)
|
||||
require.Len(t, out.Output, 1)
|
||||
assert.Equal(t, "function_call", out.Output[0].Type)
|
||||
}
|
||||
@@ -644,6 +772,23 @@ func TestResponsesToChatCompletionsRequest_RejectsToolSearchNameConflict(t *test
|
||||
assert.Equal(t, "tool_search", out.Tools[0].Function.Name)
|
||||
}
|
||||
|
||||
func TestResponsesToChatCompletionsRequest_RejectsDuplicateTopLevelExecutableNames(t *testing.T) {
|
||||
for _, tools := range [][]ResponsesTool{
|
||||
{{Type: "custom", Name: "exec"}, {Type: "function", Name: "exec"}},
|
||||
{{Type: "function", Name: "exec"}, {Type: "function", Name: "exec"}},
|
||||
{{Type: "custom", Name: "exec"}, {Type: "custom", Name: "exec"}},
|
||||
} {
|
||||
_, err := ResponsesToChatCompletionsRequest(&ResponsesRequest{
|
||||
Model: "glm-5.2",
|
||||
Input: json.RawMessage(`"hi"`),
|
||||
Tools: tools,
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "exec")
|
||||
assert.Contains(t, err.Error(), "cannot disambiguate")
|
||||
}
|
||||
}
|
||||
|
||||
// tool_choice 指向被转换丢弃的工具(如 web_search)或不存在的名字时不能原样转发,
|
||||
// chat 上游会因选择项指向未声明工具而 400;字符串形式与指向幸存工具的选择保持转发。
|
||||
func TestResponsesToChatCompletionsRequest_DropsToolChoiceForDroppedTool(t *testing.T) {
|
||||
@@ -795,7 +940,7 @@ func TestChatCompletionsResponseToResponses_NamespacedToolCallRestored(t *testin
|
||||
"mcp__svc__echo": {Namespace: "mcp__svc", Name: "echo"},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, false, nsTools)
|
||||
out := ChatCompletionsResponseToResponses(resp, "glm-5.2", nil, nil, false, nsTools)
|
||||
require.Len(t, out.Output, 2)
|
||||
|
||||
item := out.Output[0]
|
||||
|
||||
@@ -65,7 +65,7 @@ func TestChatCompletionsResponseToResponses_SkipsInvalidFunctionArguments(t *tes
|
||||
}},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-v4-flash", nil, false, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-v4-flash", nil, nil, false, nil)
|
||||
require.Equal(t, "incomplete", out.Status)
|
||||
require.Len(t, out.Output, 1)
|
||||
require.Equal(t, "function_call", out.Output[0].Type)
|
||||
|
||||
@@ -532,7 +532,7 @@ func TestChatCompletionsResponseToResponses_DeepSeekReasoningOnlyFallsBackToMess
|
||||
}},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-reasoner", nil, false, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-reasoner", nil, nil, false, nil)
|
||||
|
||||
require.Len(t, out.Output, 2)
|
||||
require.Equal(t, "reasoning", out.Output[0].Type)
|
||||
@@ -566,7 +566,7 @@ func TestChatCompletionsResponseToResponses_DeepSeekReasoningToolCallDoesNotFall
|
||||
}},
|
||||
}
|
||||
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-reasoner", nil, false, nil)
|
||||
out := ChatCompletionsResponseToResponses(resp, "deepseek-reasoner", nil, nil, false, nil)
|
||||
|
||||
require.Len(t, out.Output, 2)
|
||||
require.Equal(t, "reasoning", out.Output[0].Type)
|
||||
|
||||
@@ -119,6 +119,9 @@ func AdaptResponsesClientTools(req map[string]any) (ResponsesClientToolMapping,
|
||||
lowered = append(lowered, raw)
|
||||
}
|
||||
}
|
||||
if stripResponsesDeferredToolFlags(lowered) {
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
req["tools"] = lowered
|
||||
}
|
||||
@@ -141,6 +144,26 @@ func AdaptResponsesClientTools(req map[string]any) (ResponsesClientToolMapping,
|
||||
return adapter, changed, nil
|
||||
}
|
||||
|
||||
// stripResponsesDeferredToolFlags removes defer_loading only when the final
|
||||
// declaration list no longer contains the built-in tool_search it requires.
|
||||
func stripResponsesDeferredToolFlags(tools []any) bool {
|
||||
if hasResponsesToolSearchDeclaration(tools) {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
for _, raw := range tools {
|
||||
tool, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, exists := tool["defer_loading"]; exists {
|
||||
delete(tool, "defer_loading")
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// AdaptResponsesClientToolsWithInheritedMapping lowers client-tool history on
|
||||
// a follow-up request that omits the session-level tools declaration. An
|
||||
// explicitly present tools field, including an empty or malformed value,
|
||||
|
||||
@@ -66,6 +66,33 @@ func TestAdaptResponsesClientTools_LowersDeclarationsHistoryChoiceAndNamespaces(
|
||||
require.Equal(t, "team__send", namespaceCall["name"])
|
||||
}
|
||||
|
||||
func TestAdaptResponsesClientTools_RemovesDeferredFlagsWhenToolSearchIsLowered(t *testing.T) {
|
||||
req := map[string]any{
|
||||
"tools": []any{
|
||||
map[string]any{"type": "tool_search"},
|
||||
map[string]any{"type": "function", "name": "shell", "defer_loading": true},
|
||||
map[string]any{"type": "function", "name": "apply_patch"},
|
||||
},
|
||||
}
|
||||
|
||||
_, changed, err := AdaptResponsesClientTools(req)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
tools := requireResponsesClientToolValue[[]any](t, req["tools"])
|
||||
require.Equal(t, toolSearchProxyName, requireResponsesClientToolValue[map[string]any](t, tools[0])["name"])
|
||||
require.NotContains(t, requireResponsesClientToolValue[map[string]any](t, tools[1]), "defer_loading")
|
||||
}
|
||||
|
||||
func TestStripResponsesDeferredToolFlags_PreservesFlagsWithBuiltInToolSearch(t *testing.T) {
|
||||
tools := []any{
|
||||
map[string]any{"type": "tool_search"},
|
||||
map[string]any{"type": "function", "name": "shell", "defer_loading": true},
|
||||
}
|
||||
|
||||
require.False(t, stripResponsesDeferredToolFlags(tools))
|
||||
require.Equal(t, true, requireResponsesClientToolValue[map[string]any](t, tools[1])["defer_loading"])
|
||||
}
|
||||
|
||||
func TestAdaptResponsesClientTools_LowersDiscoveredToolSearchOutput(t *testing.T) {
|
||||
requestJSON := `{
|
||||
"tools":[{"type":"tool_search"}],
|
||||
|
||||
@@ -23,10 +23,11 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
|
||||
}
|
||||
|
||||
out := &ChatCompletionsResponse{
|
||||
ID: id,
|
||||
Object: "chat.completion",
|
||||
Created: time.Now().Unix(),
|
||||
Model: model,
|
||||
ID: id,
|
||||
Object: "chat.completion",
|
||||
Created: time.Now().Unix(),
|
||||
Model: model,
|
||||
ServiceTier: resp.ServiceTier,
|
||||
}
|
||||
|
||||
var contentText string
|
||||
@@ -118,6 +119,7 @@ type ResponsesEventToChatState struct {
|
||||
ID string
|
||||
Model string
|
||||
Created int64
|
||||
ServiceTier string // upstream tier observed on response events; echoed on chunks
|
||||
SentRole bool
|
||||
SawToolCall bool
|
||||
SawText bool
|
||||
@@ -187,12 +189,13 @@ func FinalizeResponsesChatStream(state *ResponsesEventToChatState) []ChatComplet
|
||||
|
||||
if state.IncludeUsage && state.Usage != nil {
|
||||
chunks = append(chunks, ChatCompletionsChunk{
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
Choices: []ChatChunkChoice{},
|
||||
Usage: state.Usage,
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ServiceTier: state.ServiceTier,
|
||||
Choices: []ChatChunkChoice{},
|
||||
Usage: state.Usage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -218,6 +221,9 @@ func resToChatHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToCh
|
||||
if state.Model == "" && evt.Response.Model != "" {
|
||||
state.Model = evt.Response.Model
|
||||
}
|
||||
if evt.Response.ServiceTier != "" {
|
||||
state.ServiceTier = evt.Response.ServiceTier
|
||||
}
|
||||
}
|
||||
// Emit the role chunk.
|
||||
if state.SentRole {
|
||||
@@ -301,6 +307,9 @@ func resToChatHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo
|
||||
if evt.Response.Usage != nil {
|
||||
state.Usage = chatUsageFromResponsesUsage(evt.Response.Usage)
|
||||
}
|
||||
if evt.Response.ServiceTier != "" {
|
||||
state.ServiceTier = evt.Response.ServiceTier
|
||||
}
|
||||
|
||||
switch evt.Response.Status {
|
||||
case "incomplete":
|
||||
@@ -326,12 +335,13 @@ func resToChatHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo
|
||||
|
||||
if state.IncludeUsage && state.Usage != nil {
|
||||
chunks = append(chunks, ChatCompletionsChunk{
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
Choices: []ChatChunkChoice{},
|
||||
Usage: state.Usage,
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ServiceTier: state.ServiceTier,
|
||||
Choices: []ChatChunkChoice{},
|
||||
Usage: state.Usage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -401,10 +411,11 @@ func completionDetailsFromResponses(src *ResponsesOutputTokensDetails) *ChatToke
|
||||
|
||||
func makeChatDeltaChunk(state *ResponsesEventToChatState, delta ChatDelta) ChatCompletionsChunk {
|
||||
return ChatCompletionsChunk{
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ServiceTier: state.ServiceTier,
|
||||
Choices: []ChatChunkChoice{{
|
||||
Index: 0,
|
||||
Delta: delta,
|
||||
@@ -416,10 +427,11 @@ func makeChatDeltaChunk(state *ResponsesEventToChatState, delta ChatDelta) ChatC
|
||||
func makeChatFinishChunk(state *ResponsesEventToChatState, finishReason string) ChatCompletionsChunk {
|
||||
empty := ""
|
||||
return ChatCompletionsChunk{
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ID: state.ID,
|
||||
Object: "chat.completion.chunk",
|
||||
Created: state.Created,
|
||||
Model: state.Model,
|
||||
ServiceTier: state.ServiceTier,
|
||||
Choices: []ChatChunkChoice{{
|
||||
Index: 0,
|
||||
Delta: ChatDelta{Content: &empty},
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 上游响应中的 service_tier 必须如实回传,不被重写/丢弃:
|
||||
// 非流式(ResponsesResponse → ChatCompletionsResponse)与流式 chunk 均覆盖。
|
||||
|
||||
func TestResponsesToChatCompletions_PreservesUpstreamServiceTier(t *testing.T) {
|
||||
resp := &ResponsesResponse{
|
||||
ID: "resp_1",
|
||||
Object: "response",
|
||||
Model: "gpt-5.5",
|
||||
Status: "completed",
|
||||
ServiceTier: "priority",
|
||||
Output: []ResponsesOutput{{
|
||||
Type: "message",
|
||||
Role: "assistant",
|
||||
Content: []ResponsesContentPart{{
|
||||
Type: "output_text",
|
||||
Text: "hi",
|
||||
}},
|
||||
}},
|
||||
Usage: &ResponsesUsage{InputTokens: 1, OutputTokens: 1},
|
||||
}
|
||||
|
||||
chat := ResponsesToChatCompletions(resp, "gpt-5.5")
|
||||
require.Equal(t, "priority", chat.ServiceTier)
|
||||
|
||||
// 序列化后字段仍在(omitempty 不丢非空值)。
|
||||
raw, err := json.Marshal(chat)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(raw), `"service_tier":"priority"`)
|
||||
}
|
||||
|
||||
func TestResponsesToChatCompletions_OmitsMissingServiceTier(t *testing.T) {
|
||||
resp := &ResponsesResponse{ID: "resp_1", Model: "gpt-5.5", Status: "completed"}
|
||||
chat := ResponsesToChatCompletions(resp, "gpt-5.5")
|
||||
require.Empty(t, chat.ServiceTier)
|
||||
raw, err := json.Marshal(chat)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "service_tier")
|
||||
}
|
||||
|
||||
func TestResponsesEventToChatChunks_PreservesUpstreamServiceTier(t *testing.T) {
|
||||
state := NewResponsesEventToChatState()
|
||||
state.IncludeUsage = true
|
||||
|
||||
created := &ResponsesStreamEvent{Type: "response.created"}
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"type":"response.created","response":{"id":"resp_s1","model":"gpt-5.5","service_tier":"priority","status":"in_progress"}}`), created))
|
||||
|
||||
chunks := ResponsesEventToChatChunks(created, state)
|
||||
require.NotEmpty(t, chunks)
|
||||
for _, chunk := range chunks {
|
||||
require.Equal(t, "priority", chunk.ServiceTier)
|
||||
}
|
||||
|
||||
// 后续 delta chunk 继续携带(OpenAI 流式 chunk 的 service_tier 语义)。
|
||||
delta := &ResponsesStreamEvent{Type: "response.output_text.delta", Delta: "hi"}
|
||||
chunks = ResponsesEventToChatChunks(delta, state)
|
||||
require.NotEmpty(t, chunks)
|
||||
require.Equal(t, "priority", chunks[0].ServiceTier)
|
||||
|
||||
// 终止事件同样携带。
|
||||
completed := &ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{
|
||||
ID: "resp", Model: "gpt-5.5", Status: "completed",
|
||||
Usage: &ResponsesUsage{InputTokens: 1, OutputTokens: 1},
|
||||
}}
|
||||
chunks = ResponsesEventToChatChunks(completed, state)
|
||||
require.NotEmpty(t, chunks)
|
||||
for _, chunk := range chunks {
|
||||
require.Equal(t, "priority", chunk.ServiceTier)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesEventToChatChunks_NoServiceTierStaysClean(t *testing.T) {
|
||||
state := NewResponsesEventToChatState()
|
||||
created := &ResponsesStreamEvent{Type: "response.created", Response: &ResponsesResponse{ID: "resp", Model: "gpt-5.5"}}
|
||||
chunks := ResponsesEventToChatChunks(created, state)
|
||||
require.NotEmpty(t, chunks)
|
||||
require.Empty(t, chunks[0].ServiceTier)
|
||||
raw, err := json.Marshal(chunks[0])
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "service_tier")
|
||||
}
|
||||
|
||||
// 上游 JSON 反序列化时 service_tier 进入 ResponsesResponse(缓冲桥读取链路)。
|
||||
func TestResponsesResponse_UnmarshalPreservesServiceTier(t *testing.T) {
|
||||
var resp ResponsesResponse
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","object":"response","model":"gpt-5.5","status":"completed","service_tier":"flex","output":[]}`), &resp))
|
||||
require.Equal(t, "flex", resp.ServiceTier)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 反向转换(Chat-only fallback):CC 响应/流 chunk 的 service_tier 保留到
|
||||
// Responses 形态,客户端与计费都能拿到上游回显。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestChatCompletionsResponseToResponses_PreservesServiceTier(t *testing.T) {
|
||||
cc := &ChatCompletionsResponse{
|
||||
ID: "chatcmpl-1",
|
||||
Model: "gpt-5.5",
|
||||
ServiceTier: "default",
|
||||
Choices: []ChatChoice{{
|
||||
Index: 0,
|
||||
Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)},
|
||||
FinishReason: "stop",
|
||||
}},
|
||||
Usage: &ChatUsage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2},
|
||||
}
|
||||
resp := ChatCompletionsResponseToResponses(cc, "gpt-5.5", nil, nil, false, nil)
|
||||
require.Equal(t, "default", resp.ServiceTier)
|
||||
|
||||
raw, err := json.Marshal(resp)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(raw), `"service_tier":"default"`)
|
||||
}
|
||||
|
||||
func TestChatCompletionsResponseToResponses_NilRespOmitsServiceTier(t *testing.T) {
|
||||
resp := ChatCompletionsResponseToResponses(nil, "gpt-5.5", nil, nil, false, nil)
|
||||
require.Empty(t, resp.ServiceTier)
|
||||
}
|
||||
|
||||
func TestChatCompletionsChunkToResponsesEvents_PreservesServiceTier(t *testing.T) {
|
||||
state := NewChatCompletionsToResponsesStreamState("gpt-5.5")
|
||||
chunk := &ChatCompletionsChunk{
|
||||
ID: "chatcmpl-2",
|
||||
Model: "gpt-5.5",
|
||||
ServiceTier: "flex",
|
||||
Choices: []ChatChunkChoice{{
|
||||
Index: 0,
|
||||
Delta: ChatDelta{Content: strPtr("hi")},
|
||||
}},
|
||||
}
|
||||
events := ChatCompletionsChunkToResponsesEvents(chunk, state)
|
||||
require.NotEmpty(t, events)
|
||||
|
||||
// response.created 携带 service_tier。
|
||||
created := findEvent(events, "response.created")
|
||||
require.NotNil(t, created)
|
||||
require.NotNil(t, created.Response)
|
||||
require.Equal(t, "flex", created.Response.ServiceTier)
|
||||
|
||||
// 终止事件同样携带。
|
||||
final := FinalizeChatCompletionsResponsesStream(state)
|
||||
completed := findEvent(final, "response.completed")
|
||||
require.NotNil(t, completed)
|
||||
require.NotNil(t, completed.Response)
|
||||
require.Equal(t, "flex", completed.Response.ServiceTier)
|
||||
}
|
||||
|
||||
func TestChatCompletionsChunkToResponsesEvents_NoTierStaysClean(t *testing.T) {
|
||||
state := NewChatCompletionsToResponsesStreamState("gpt-5.5")
|
||||
chunk := &ChatCompletionsChunk{ID: "chatcmpl-3", Model: "gpt-5.5"}
|
||||
events := ChatCompletionsChunkToResponsesEvents(chunk, state)
|
||||
created := findEvent(events, "response.created")
|
||||
require.NotNil(t, created)
|
||||
require.Empty(t, created.Response.ServiceTier)
|
||||
raw, err := json.Marshal(created)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "service_tier")
|
||||
}
|
||||
|
||||
func findEvent(events []ResponsesStreamEvent, eventType string) *ResponsesStreamEvent {
|
||||
for i := range events {
|
||||
if events[i].Type == eventType {
|
||||
return &events[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -155,12 +155,26 @@ func AnthropicStopReasonString(p *string) string {
|
||||
return *p
|
||||
}
|
||||
|
||||
// AnthropicPromptTokensDetails holds OpenAI-compatible prompt token details
|
||||
// occasionally included by Anthropic-compatible providers.
|
||||
type AnthropicPromptTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// AnthropicUsage holds token counts in Anthropic format.
|
||||
type AnthropicUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
// Anthropic-compatible providers can also expose their native OpenAI-style
|
||||
// total/cache fields. Preserve them so callers can normalize provider totals
|
||||
// into Anthropic's mutually-exclusive billing buckets.
|
||||
PromptTokens int `json:"prompt_tokens,omitempty"`
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
PromptTokensDetails *AnthropicPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
|
||||
PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens,omitempty"`
|
||||
PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -344,12 +358,13 @@ func (t *ResponsesTool) UnmarshalJSON(data []byte) error {
|
||||
|
||||
// ResponsesResponse is the non-streaming response from POST /v1/responses.
|
||||
type ResponsesResponse struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"` // "response"
|
||||
Model string `json:"model"`
|
||||
Status string `json:"status"` // "completed" | "incomplete" | "failed"
|
||||
Output []ResponsesOutput `json:"output"`
|
||||
Usage *ResponsesUsage `json:"usage,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"` // "response"
|
||||
Model string `json:"model"`
|
||||
Status string `json:"status"` // "completed" | "incomplete" | "failed"
|
||||
Output []ResponsesOutput `json:"output"`
|
||||
Usage *ResponsesUsage `json:"usage,omitempty"`
|
||||
ServiceTier string `json:"service_tier,omitempty"` // upstream tier, echoed back verbatim
|
||||
|
||||
// incomplete_details is present when status="incomplete"
|
||||
IncompleteDetails *ResponsesIncompleteDetails `json:"incomplete_details,omitempty"`
|
||||
|
||||
@@ -53,10 +53,10 @@ func Do(client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
if req == nil || !Active(req.Context()) {
|
||||
return client.Do(req)
|
||||
return client.Do(req) //nolint:gosec // G704: 通用埋点包装器,不构造 URL;请求由调用方构造,SSRF 信任边界在调用方
|
||||
}
|
||||
startedAt := time.Now()
|
||||
response, err := client.Do(req)
|
||||
response, err := client.Do(req) //nolint:gosec // G704: 同上
|
||||
RecordDependency(req.Context(), dependencyModule(req), startedAt, time.Now())
|
||||
return response, err
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -19,6 +22,16 @@ func http2KeepAliveTestPoolSettings() poolSettings {
|
||||
}
|
||||
}
|
||||
|
||||
// requireHTTP2Configured 断言 http2 已显式挂到 http.Transport 上。
|
||||
// x/net/http2 在 go1.27 && !http2legacy 下是标准库 HTTP/2 的包装:ConfigureTransports 通过
|
||||
// Transport.RegisterProtocol("http/2") 注册配置并打开 Protocols.HTTP2(TLSNextProto 不承载 h2 入口),
|
||||
// ReadIdleTimeout/PingTimeout 在建连时映射为 http.HTTP2Config.SendPingTimeout/PingTimeout。
|
||||
func requireHTTP2Configured(t *testing.T, tr *http.Transport, msg string) {
|
||||
t.Helper()
|
||||
require.NotNil(t, tr.Protocols, msg)
|
||||
require.True(t, tr.Protocols.HTTP2(), msg)
|
||||
}
|
||||
|
||||
// Codex/OpenAI 上游改走 HTTP/2 后,池化连接被代理/NAT 静默掐断会成为“死连接”:
|
||||
// 两端都以为连接存活,请求落上去会挂到 TCP 重传超时(分钟级)才失败。Go 的
|
||||
// http2.Transport 默认 ReadIdleTimeout=0(不发健康 PING),无法检测这种死连接。
|
||||
@@ -34,7 +47,7 @@ func TestEnableOpenAIHTTP2KeepAlive_EnablesPingHealthCheck(t *testing.T) {
|
||||
require.Positive(t, h2.ReadIdleTimeout, "必须启用空闲 PING 探测以剔除死连接")
|
||||
require.Equal(t, openAIHTTP2ReadIdleTimeout, h2.ReadIdleTimeout)
|
||||
require.Equal(t, openAIHTTP2PingTimeout, h2.PingTimeout, "PING 无响应必须有超时判定")
|
||||
require.NotNil(t, tr.TLSNextProto["h2"], "http2 必须已挂到底层 http.Transport 上")
|
||||
requireHTTP2Configured(t, tr, "http2 必须已挂到底层 http.Transport 上")
|
||||
}
|
||||
|
||||
// openai_h2 模式构建的 Transport 必须带上 H2 PING 健康探测,从源头剔除死连接。
|
||||
@@ -42,17 +55,45 @@ func TestBuildUpstreamTransport_OpenAIH2_EnablesPingHealthCheck(t *testing.T) {
|
||||
tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeOpenAIH2)
|
||||
require.NoError(t, err)
|
||||
require.True(t, tr.ForceAttemptHTTP2, "openai_h2 必须启用 HTTP/2")
|
||||
require.NotNil(t, tr.TLSNextProto["h2"], "openai_h2 必须显式配置 http2 以启用 ReadIdleTimeout")
|
||||
requireHTTP2Configured(t, tr, "openai_h2 必须显式配置 http2 以启用 ReadIdleTimeout")
|
||||
}
|
||||
|
||||
// 非 H2 模式(default/h1)不应因本次改动被误配置:default 走 Go 自动 H2(惰性配置,
|
||||
// 构建时 TLSNextProto 仍为空),h1 模式显式禁用 H2。避免波及 Claude/Gemini 热路径。
|
||||
// 构建时 Protocols/TLSNextProto 仍为空),h1 模式显式禁用 H2。避免波及 Claude/Gemini 热路径。
|
||||
func TestBuildUpstreamTransport_NonOpenAIH2_NotEagerlyConfigured(t *testing.T) {
|
||||
tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeDefault)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, tr.Protocols, "default 模式不应在构建期主动配置 http2 keepalive")
|
||||
require.Nil(t, tr.TLSNextProto["h2"], "default 模式不应在构建期主动配置 http2 keepalive")
|
||||
}
|
||||
|
||||
// openai_h2 模式构建的 Transport 必须真正以 HTTP/2 与上游通信,PING 健康探测才有载体:
|
||||
// 自定义 DialContext 下 Go 不会自动启用 H2,全靠 enableOpenAIHTTP2KeepAlive 的显式配置。
|
||||
func TestBuildUpstreamTransport_OpenAIH2_NegotiatesHTTP2(t *testing.T) {
|
||||
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
srv.EnableHTTP2 = true
|
||||
srv.StartTLS()
|
||||
defer srv.Close()
|
||||
|
||||
tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), nil, upstreamProtocolModeOpenAIH2)
|
||||
require.NoError(t, err)
|
||||
defer tr.CloseIdleConnections()
|
||||
require.NotNil(t, tr.TLSClientConfig)
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(srv.Certificate())
|
||||
tr.TLSClientConfig.RootCAs = roots
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL, nil)
|
||||
require.NoError(t, err)
|
||||
resp, err := tr.RoundTrip(req)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, resp.Body.Close())
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
require.Equal(t, 2, resp.ProtoMajor, "openai_h2 必须协商到 HTTP/2")
|
||||
}
|
||||
|
||||
// 死连接在经 HTTP 代理(CONNECT 隧道)时最高发,这是带 proxy 账号的真实生产路径:
|
||||
// 显式 http2 配置须与 Transport.Proxy 同时正确生效,不能相互干扰。
|
||||
func TestBuildUpstreamTransport_OpenAIH2_WithHTTPProxy_EnablesKeepAlive(t *testing.T) {
|
||||
@@ -62,6 +103,6 @@ func TestBuildUpstreamTransport_OpenAIH2_WithHTTPProxy_EnablesKeepAlive(t *testi
|
||||
tr, err := buildUpstreamTransport(http2KeepAliveTestPoolSettings(), proxyURL, upstreamProtocolModeOpenAIH2)
|
||||
require.NoError(t, err)
|
||||
require.True(t, tr.ForceAttemptHTTP2)
|
||||
require.NotNil(t, tr.TLSNextProto["h2"], "经代理的 openai_h2 也必须启用 http2 keepalive")
|
||||
requireHTTP2Configured(t, tr, "经代理的 openai_h2 也必须启用 http2 keepalive")
|
||||
require.NotNil(t, tr.Proxy, "HTTP 代理仍须通过 Transport.Proxy 生效")
|
||||
}
|
||||
@@ -780,7 +780,7 @@ func (s usageLogScannerStub) Scan(dest ...any) error {
|
||||
}
|
||||
for i := range dest {
|
||||
dv := reflect.ValueOf(dest[i])
|
||||
if dv.Kind() != reflect.Ptr {
|
||||
if dv.Kind() != reflect.Pointer {
|
||||
return fmt.Errorf("dest[%d] is not pointer", i)
|
||||
}
|
||||
dv.Elem().Set(reflect.ValueOf(s.values[i]))
|
||||
|
||||
@@ -729,6 +729,9 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou
|
||||
if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); len(updates) > 0 {
|
||||
mergeAccountExtra(account, updates)
|
||||
s.persistOpenAICodexProbeSnapshot(account.ID, updates)
|
||||
if account.ParentAccountID != nil {
|
||||
notifyOpenAIAutoReset(*account.ParentAccountID)
|
||||
}
|
||||
if usage.UpdatedAt == nil {
|
||||
usage.UpdatedAt = &now
|
||||
}
|
||||
@@ -921,7 +924,9 @@ func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, u
|
||||
go func() {
|
||||
updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer updateCancel()
|
||||
_ = s.accountRepo.UpdateExtra(updateCtx, accountID, updates)
|
||||
if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil {
|
||||
notifyOpenAIAutoReset(accountID)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
|
||||
@@ -470,6 +470,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accountExtra, err = normalizeOpenAIAutoResetCreditExtra(input.Platform, input.Type, false, accountExtra)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 绑定分组
|
||||
groupIDs := input.GroupIDs
|
||||
@@ -559,6 +563,14 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
effectiveType := account.Type
|
||||
if input.Type != "" {
|
||||
effectiveType = input.Type
|
||||
}
|
||||
normalizedExtra, err = normalizeOpenAIAutoResetCreditExtra(account.Platform, effectiveType, account.IsShadow(), normalizedExtra)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
previousProbeIdentity := upstreamBillingProbeIdentity(account)
|
||||
previousOllamaUsageIdentity := ollamaCloudUsageIdentity(account)
|
||||
@@ -649,6 +661,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
OllamaCloudUsageSnapshotExtraKey,
|
||||
OpenAIAutoResetCreditStateExtraKey,
|
||||
} {
|
||||
if v, ok := account.Extra[key]; ok {
|
||||
normalizedExtra[key] = v
|
||||
@@ -860,6 +873,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
// (如 model_rate_limits / passive_usage_* 等)。
|
||||
func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, updates map[string]any) error {
|
||||
updates = sanitizedCodexFingerprintExtraUpdates(updates)
|
||||
updates = stripOpenAIAutoResetCreditManagedExtra(updates, true)
|
||||
delete(updates, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingProbeExtraKey)
|
||||
@@ -886,6 +900,7 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd
|
||||
func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUpdateAccountsInput) (*BulkUpdateAccountsResult, error) {
|
||||
// Managed probe/session state may only enter through dedicated typed endpoints.
|
||||
input.Extra = sanitizedCodexFingerprintExtraUpdates(input.Extra)
|
||||
input.Extra = stripOpenAIAutoResetCreditManagedExtra(input.Extra, true)
|
||||
delete(input.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingProbeExtraKey)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
)
|
||||
|
||||
@@ -28,11 +29,12 @@ const (
|
||||
// AntigravityQuotaFetcher 从 Antigravity API 获取额度
|
||||
type AntigravityQuotaFetcher struct {
|
||||
proxyRepo ProxyRepository
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewAntigravityQuotaFetcher 创建 AntigravityQuotaFetcher
|
||||
func NewAntigravityQuotaFetcher(proxyRepo ProxyRepository) *AntigravityQuotaFetcher {
|
||||
return &AntigravityQuotaFetcher{proxyRepo: proxyRepo}
|
||||
func NewAntigravityQuotaFetcher(proxyRepo ProxyRepository, cfg *config.Config) *AntigravityQuotaFetcher {
|
||||
return &AntigravityQuotaFetcher{proxyRepo: proxyRepo, cfg: cfg}
|
||||
}
|
||||
|
||||
// CanFetch 检查是否可以获取此账户的额度
|
||||
@@ -55,7 +57,7 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou
|
||||
}
|
||||
|
||||
// 调用 API 获取配额
|
||||
modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID)
|
||||
modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID, resolveModelsListReadLimit(f.cfg))
|
||||
if err != nil {
|
||||
// 403 Forbidden: 不报错,返回 is_forbidden 标记
|
||||
var forbiddenErr *antigravity.ForbiddenError
|
||||
|
||||
@@ -3,11 +3,16 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
)
|
||||
|
||||
@@ -390,6 +395,36 @@ func TestBuildUsageInfo_AICredits(t *testing.T) {
|
||||
require.Equal(t, 5.0, info.AICredits[0].MinimumBalance)
|
||||
}
|
||||
|
||||
func TestFetchQuotaUsesConfiguredModelsListBodyLimit(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"models":{"model-a":{}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldBaseURLs := append([]string(nil), antigravity.BaseURLs...)
|
||||
oldAvailability := antigravity.DefaultURLAvailability
|
||||
t.Cleanup(func() {
|
||||
antigravity.BaseURLs = oldBaseURLs
|
||||
antigravity.DefaultURLAvailability = oldAvailability
|
||||
})
|
||||
antigravity.BaseURLs = []string{server.URL}
|
||||
antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute)
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.ModelsListReadMaxBytes = 8
|
||||
fetcher := NewAntigravityQuotaFetcher(nil, cfg)
|
||||
_, err := fetcher.FetchQuota(context.Background(), &Account{
|
||||
Platform: PlatformAntigravity,
|
||||
Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"access_token": "token",
|
||||
"project_id": "project",
|
||||
},
|
||||
}, "")
|
||||
require.ErrorContains(t, err, "响应超过 8 字节")
|
||||
}
|
||||
|
||||
func TestFetchQuota_ForbiddenReturnsIsForbidden(t *testing.T) {
|
||||
// 模拟 FetchQuota 遇到 403 时的行为:
|
||||
// FetchAvailableModels 返回 ForbiddenError → FetchQuota 应返回 is_forbidden=true
|
||||
|
||||
@@ -0,0 +1,470 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ContextPricingBasis 阶梯的计价基准。
|
||||
type ContextPricingBasis string
|
||||
|
||||
const (
|
||||
// ContextPricingBasisWholeRequest 整单按所在档单价计价(目录阶梯、渠道区间)。
|
||||
ContextPricingBasisWholeRequest ContextPricingBasis = "whole_request"
|
||||
// ContextPricingBasisMarginal 仅超出阈值的部分按该档单价计价(平台旧规则)。
|
||||
ContextPricingBasisMarginal ContextPricingBasis = "marginal"
|
||||
)
|
||||
|
||||
// ContextPricingTier (MinTokens, MaxTokens] 区间内的有效 per-token 单价(USD)。
|
||||
// nil 表示该项无价/不计费;MaxTokens 为 nil 表示无上限。
|
||||
type ContextPricingTier struct {
|
||||
MinTokens int
|
||||
MaxTokens *int
|
||||
Label string
|
||||
Input *float64
|
||||
Output *float64
|
||||
CacheWrite *float64
|
||||
CacheRead *float64
|
||||
}
|
||||
|
||||
// TimePricingPeriod 分时倍率时段:配置时区当天 [StartTime, EndTime) 内整单费用乘 Multiplier。
|
||||
type TimePricingPeriod struct {
|
||||
StartTime string
|
||||
EndTime string
|
||||
Multiplier float64
|
||||
}
|
||||
|
||||
// TimePricingSchedule 分组+模型生效的分时倍率(仅列出倍率 ≠ 1 的时段,按开始时间升序)。
|
||||
// WeekdaysOnly 为 true 时时段仅周一至周五生效,周末整天按标准价计费。
|
||||
type TimePricingSchedule struct {
|
||||
Timezone string
|
||||
WeekdaysOnly bool
|
||||
Periods []TimePricingPeriod
|
||||
}
|
||||
|
||||
// ContextPricingSchedule 分组+模型按上下文长度分档的有效单价表。
|
||||
// 单价由真实计费函数探针得出,与扣费同源;单档表示无阶梯。
|
||||
// Tiers 为标准时段单价;TimePricing 非 nil 时,落在时段内的请求整单再乘对应倍率。
|
||||
type ContextPricingSchedule struct {
|
||||
Basis ContextPricingBasis
|
||||
Tiers []ContextPricingTier
|
||||
TimePricing *TimePricingSchedule
|
||||
}
|
||||
|
||||
// ContextPricingScheduleInput 阶梯表查询输入。
|
||||
type ContextPricingScheduleInput struct {
|
||||
Model string
|
||||
// Group 为 nil 表示查官方参考价:无分组、无渠道定价,也不套用平台旧规则。
|
||||
Group *Group
|
||||
// Platform 为请求的具体平台(composite 分组传模型所属平台),
|
||||
// 决定渠道定价查找与平台旧规则的适用。
|
||||
Platform string
|
||||
}
|
||||
|
||||
var errContextPricingResolverRequired = errors.New("context pricing schedule: resolver is required")
|
||||
|
||||
// 探针步长:相邻两个探针点相差 contextProbeDelta 个 token,单价 = Δcost / Δtoken。
|
||||
const contextProbeDelta = 1000
|
||||
|
||||
// ResolveContextPricingSchedule 解析分组+模型的上下文阶梯单价表。
|
||||
//
|
||||
// 解析链与扣费完全一致:Resolver.Resolve(分组卡 → 渠道 → 目录 → 策略)给出定价,
|
||||
// CalculateTokenCostForRequest 给出路径(分组/渠道定价 → 平台旧规则 → 内置目录)。
|
||||
// 断点只取自计费自身的规则输入(渠道区间边界、目录阶梯阈值、旧规则阈值),
|
||||
// 每一段的单价由真实计费函数在该段内两点探针的差商得到,因此倍率、策略等
|
||||
// 规则变更无需同步到这里;相邻同价段会合并。
|
||||
//
|
||||
// 非 token 计费模式返回 (nil, nil);模型无任何定价来源时返回 ErrModelPricingUnavailable。
|
||||
func (s *BillingService) ResolveContextPricingSchedule(ctx context.Context, resolver *ModelPricingResolver, in ContextPricingScheduleInput) (*ContextPricingSchedule, error) {
|
||||
if s == nil || resolver == nil {
|
||||
return nil, errContextPricingResolverRequired
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if in.Platform != "" {
|
||||
ctx = WithResolvedTargetPlatform(ctx, in.Platform)
|
||||
}
|
||||
|
||||
pricingInput := PricingInput{Model: in.Model, Group: in.Group}
|
||||
if in.Group != nil {
|
||||
gid := in.Group.ID
|
||||
pricingInput.GroupID = &gid
|
||||
}
|
||||
resolved := resolver.Resolve(ctx, pricingInput)
|
||||
if resolved == nil {
|
||||
return nil, ErrModelPricingUnavailable
|
||||
}
|
||||
if resolved.Mode != "" && resolved.Mode != BillingModeToken {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var legacy *LegacyLongContextRule
|
||||
if in.Group != nil {
|
||||
legacy = s.LegacyLongContextRule(in.Platform)
|
||||
}
|
||||
if !legacyLongContextApplies(resolved, in.Group, legacy) {
|
||||
legacy = nil
|
||||
}
|
||||
|
||||
req := TokenCostRequest{
|
||||
Ctx: ctx,
|
||||
Model: in.Model,
|
||||
Group: in.Group,
|
||||
RateMultiplier: 1,
|
||||
Resolver: resolver,
|
||||
Resolved: resolved,
|
||||
LegacyLongContext: legacy,
|
||||
}
|
||||
probe := func(tokens UsageTokens) (*CostBreakdown, error) {
|
||||
r := req
|
||||
r.Tokens = tokens
|
||||
return s.CalculateTokenCostForRequest(r)
|
||||
}
|
||||
|
||||
plan := s.contextPricingBreakpoints(resolver, resolved, in.Model, legacy)
|
||||
segments := buildContextSegments(plan.bounds)
|
||||
|
||||
tiers := make([]ContextPricingTier, 0, len(segments))
|
||||
for _, seg := range segments {
|
||||
tier, err := probeContextTier(seg, resolved, probe)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tiers = append(tiers, tier)
|
||||
}
|
||||
tiers = mergeEqualContextTiers(tiers)
|
||||
applyContextTierLabels(tiers, plan)
|
||||
|
||||
basis := ContextPricingBasisWholeRequest
|
||||
if legacy != nil {
|
||||
basis = ContextPricingBasisMarginal
|
||||
}
|
||||
return &ContextPricingSchedule{Basis: basis, Tiers: tiers, TimePricing: resolvedTimePricingSchedule(resolved)}, nil
|
||||
}
|
||||
|
||||
// resolvedTimePricingSchedule 列出计费会生效的分时倍率时段。
|
||||
// 时段来自解析到的渠道定价配置,每个时段的倍率用计费自己的 resolvedChannelTimeMultiplier
|
||||
// 在时段内取值:定价来源不是渠道(分组价卡覆盖)、配置非法等情况下计费按 1 计,
|
||||
// 这里也就自然得到"无分时"。倍率为 1 的时段不列出。
|
||||
func resolvedTimePricingSchedule(resolved *ResolvedPricing) *TimePricingSchedule {
|
||||
if resolved == nil || resolved.channelPricing == nil || resolved.channelPricing.TimePricing == nil {
|
||||
return nil
|
||||
}
|
||||
cfg := resolved.channelPricing.TimePricing
|
||||
location, err := loadChannelTimePricingLocation(cfg.Timezone)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
type probedPeriod struct {
|
||||
start int
|
||||
period TimePricingPeriod
|
||||
}
|
||||
probed := make([]probedPeriod, 0, len(cfg.Periods))
|
||||
for _, period := range cfg.Periods {
|
||||
start, err := parseChannelTime(period.StartTime, false)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// 时段按每日循环,取该时段开始后 1 秒作为探针时刻。
|
||||
// 锚点日必须是工作日(2026-01-05 为周一):weekdays_only 配置在周末恒为 1,
|
||||
// 锚点落在周末会把时段整组剔除。
|
||||
at := time.Date(2026, time.January, 5, 0, 0, start+1, 0, location)
|
||||
multiplier := resolvedChannelTimeMultiplier(resolved, at)
|
||||
if multiplier == 1 {
|
||||
continue
|
||||
}
|
||||
probed = append(probed, probedPeriod{start: start, period: TimePricingPeriod{
|
||||
StartTime: period.StartTime,
|
||||
EndTime: period.EndTime,
|
||||
Multiplier: multiplier,
|
||||
}})
|
||||
}
|
||||
if len(probed) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.SliceStable(probed, func(i, j int) bool { return probed[i].start < probed[j].start })
|
||||
out := &TimePricingSchedule{
|
||||
Timezone: cfg.Timezone,
|
||||
WeekdaysOnly: cfg.WeekdaysOnly,
|
||||
Periods: make([]TimePricingPeriod, 0, len(probed)),
|
||||
}
|
||||
for _, p := range probed {
|
||||
out.Periods = append(out.Periods, p.period)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// contextBreakpointPlan 描述断点来源。
|
||||
type contextBreakpointPlan struct {
|
||||
bounds []int
|
||||
// thresholdBound 为目录阶梯/旧规则的断点值((0,b] / (b,∞)),0 表示无。
|
||||
thresholdBound int
|
||||
// thresholdInclusive 为真表示达到阈值即进入高档(断点 = 阈值-1)。
|
||||
thresholdInclusive bool
|
||||
threshold int
|
||||
}
|
||||
|
||||
// contextPricingBreakpoints 从计费自身的规则输入收集价格断点(不读取任何倍率)。
|
||||
func (s *BillingService) contextPricingBreakpoints(resolver *ModelPricingResolver, resolved *ResolvedPricing, model string, legacy *LegacyLongContextRule) contextBreakpointPlan {
|
||||
plan := contextBreakpointPlan{}
|
||||
if legacy != nil {
|
||||
plan.bounds = []int{legacy.Threshold}
|
||||
plan.thresholdBound = legacy.Threshold
|
||||
plan.threshold = legacy.Threshold
|
||||
return plan
|
||||
}
|
||||
if !resolved.longContextPricingEnabled {
|
||||
return plan
|
||||
}
|
||||
if len(resolved.Intervals) > 0 {
|
||||
// 区间边界即断点;空洞段(含末档上限之外)由计费回落 base,探针会自然得到基础价。
|
||||
set := make(map[int]struct{}, len(resolved.Intervals)*2)
|
||||
for i := range resolved.Intervals {
|
||||
iv := &resolved.Intervals[i]
|
||||
if iv.MinTokens > 0 {
|
||||
set[iv.MinTokens] = struct{}{}
|
||||
}
|
||||
if iv.MaxTokens != nil {
|
||||
set[*iv.MaxTokens] = struct{}{}
|
||||
}
|
||||
}
|
||||
for b := range set {
|
||||
plan.bounds = append(plan.bounds, b)
|
||||
}
|
||||
sort.Ints(plan.bounds)
|
||||
return plan
|
||||
}
|
||||
pricing := resolver.GetIntervalPricing(resolved, 1)
|
||||
if pricing == nil {
|
||||
return plan
|
||||
}
|
||||
pricing = s.applyModelSpecificPricingPolicy(model, pricing)
|
||||
if pricing.LongContextInputThreshold <= 0 {
|
||||
return plan
|
||||
}
|
||||
bound := pricing.LongContextInputThreshold
|
||||
if pricing.LongContextThresholdInclusive {
|
||||
bound--
|
||||
}
|
||||
if bound <= 0 {
|
||||
return plan
|
||||
}
|
||||
plan.bounds = []int{bound}
|
||||
plan.thresholdBound = bound
|
||||
plan.threshold = pricing.LongContextInputThreshold
|
||||
plan.thresholdInclusive = pricing.LongContextThresholdInclusive
|
||||
return plan
|
||||
}
|
||||
|
||||
// contextSegment 探针用的 (min, max] 段;max 为 nil 表示无上限。
|
||||
type contextSegment struct {
|
||||
min int
|
||||
max *int
|
||||
}
|
||||
|
||||
// buildContextSegments 把升序断点切成 (0,b1], (b1,b2], …, (bn,∞);无断点时为单个开区间。
|
||||
func buildContextSegments(bounds []int) []contextSegment {
|
||||
segments := make([]contextSegment, 0, len(bounds)+1)
|
||||
prev := 0
|
||||
for _, b := range bounds {
|
||||
if b <= prev {
|
||||
continue
|
||||
}
|
||||
upper := b
|
||||
segments = append(segments, contextSegment{min: prev, max: &upper})
|
||||
prev = b
|
||||
}
|
||||
segments = append(segments, contextSegment{min: prev})
|
||||
return segments
|
||||
}
|
||||
|
||||
// probeContextTier 在段内两点探针,单价 = ΔActualCost / Δtoken(倍率固定为 1)。
|
||||
// 每次只喂一种 token,ActualCost 即该项费用;旧边际规则的加倍只体现在 ActualCost
|
||||
// 而不在分项费用里,因此统一读 ActualCost。整单阶梯与边际规则在同一段内都是
|
||||
// 线性函数,差商同时适用,无需区分规则类型。
|
||||
func probeContextTier(seg contextSegment, resolved *ResolvedPricing, probe func(UsageTokens) (*CostBreakdown, error)) (ContextPricingTier, error) {
|
||||
tier := ContextPricingTier{MinTokens: seg.min, MaxTokens: seg.max}
|
||||
c := seg.min + 1
|
||||
delta := contextProbeDelta
|
||||
if seg.max != nil {
|
||||
if width := *seg.max - seg.min; width-1 < delta {
|
||||
delta = width - 1
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
tier.Input, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{InputTokens: n} }, c, delta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
}
|
||||
tier.CacheRead, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{CacheReadTokens: n} }, c, delta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
}
|
||||
tier.CacheWrite, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{CacheCreationTokens: n} }, c, delta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
}
|
||||
// 输出价只随上下文所在档变化:固定上下文 c,对输出 token 数做差商(固定部分相减抵消)。
|
||||
tier.Output, err = probeComponentPrice(func(n int) UsageTokens { return UsageTokens{InputTokens: c, OutputTokens: n} }, 0, contextProbeDelta, probe)
|
||||
if err != nil {
|
||||
return tier, err
|
||||
}
|
||||
|
||||
explicit := explicitContextPricingFields(resolved, c)
|
||||
tier.Input = contextPricePtr(tier.Input, explicit.input)
|
||||
tier.Output = contextPricePtr(tier.Output, explicit.output)
|
||||
tier.CacheWrite = contextPricePtr(tier.CacheWrite, explicit.cacheWrite)
|
||||
tier.CacheRead = contextPricePtr(tier.CacheRead, explicit.cacheRead)
|
||||
return tier, nil
|
||||
}
|
||||
|
||||
// probeComponentPrice 返回 [from, from+delta] 上 ActualCost 的差商;delta 为 0(退化段)时退回平均单价。
|
||||
func probeComponentPrice(tokensAt func(int) UsageTokens, from, delta int, probe func(UsageTokens) (*CostBreakdown, error)) (*float64, error) {
|
||||
if delta <= 0 {
|
||||
n := from
|
||||
if n <= 0 {
|
||||
n = 1
|
||||
}
|
||||
cost, err := probe(tokensAt(n))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := roundContextPrice(cost.ActualCost / float64(n))
|
||||
return &v, nil
|
||||
}
|
||||
lo, err := probe(tokensAt(from))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hi, err := probe(tokensAt(from + delta))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := roundContextPrice((hi.ActualCost - lo.ActualCost) / float64(delta))
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// roundContextPrice 去掉差商带来的浮点噪声(保留 12 位有效数字)。
|
||||
func roundContextPrice(v float64) float64 {
|
||||
if v == 0 || math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
return 0
|
||||
}
|
||||
r, err := strconv.ParseFloat(strconv.FormatFloat(v, 'g', 12, 64), 64)
|
||||
if err != nil {
|
||||
return v
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type explicitContextFields struct {
|
||||
input, output, cacheWrite, cacheRead bool
|
||||
}
|
||||
|
||||
// explicitContextPricingFields 判断各项是否被分组卡/渠道定价(含命中区间)显式配置。
|
||||
// 显式配置为 0 时计费按 $0 收,展示应为 $0 而非“无价”。
|
||||
func explicitContextPricingFields(resolved *ResolvedPricing, contextTokens int) explicitContextFields {
|
||||
var out explicitContextFields
|
||||
if resolved == nil || resolved.channelPricing == nil {
|
||||
return out
|
||||
}
|
||||
cp := resolved.channelPricing
|
||||
out.input = cp.InputPrice != nil
|
||||
out.output = cp.OutputPrice != nil
|
||||
out.cacheWrite = cp.CacheWritePrice != nil
|
||||
out.cacheRead = cp.CacheReadPrice != nil
|
||||
if iv := FindMatchingInterval(resolved.Intervals, contextTokens); iv != nil {
|
||||
out.input = out.input || iv.InputPrice != nil
|
||||
out.output = out.output || iv.OutputPrice != nil
|
||||
out.cacheWrite = out.cacheWrite || iv.CacheWritePrice != nil
|
||||
out.cacheRead = out.cacheRead || iv.CacheReadPrice != nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func contextPricePtr(v *float64, explicit bool) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
if *v == 0 && !explicit {
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// mergeEqualContextTiers 合并相邻且四项单价相同的段(倍率 ≤1 的目录、关闭阶梯等场景塌成单档)。
|
||||
func mergeEqualContextTiers(tiers []ContextPricingTier) []ContextPricingTier {
|
||||
if len(tiers) < 2 {
|
||||
return tiers
|
||||
}
|
||||
merged := make([]ContextPricingTier, 0, len(tiers))
|
||||
for _, t := range tiers {
|
||||
if n := len(merged); n > 0 && sameContextPrices(merged[n-1], t) {
|
||||
merged[n-1].MaxTokens = t.MaxTokens
|
||||
continue
|
||||
}
|
||||
merged = append(merged, t)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
func sameContextPrices(a, b ContextPricingTier) bool {
|
||||
return samePricePtr(a.Input, b.Input) && samePricePtr(a.Output, b.Output) &&
|
||||
samePricePtr(a.CacheWrite, b.CacheWrite) && samePricePtr(a.CacheRead, b.CacheRead)
|
||||
}
|
||||
|
||||
func samePricePtr(a, b *float64) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == nil && b == nil
|
||||
}
|
||||
if *a == *b {
|
||||
return true
|
||||
}
|
||||
scale := math.Max(math.Abs(*a), math.Abs(*b))
|
||||
return math.Abs(*a-*b) <= scale*1e-9
|
||||
}
|
||||
|
||||
// applyContextTierLabels 给多档阶梯打统一形态的标签:有上限的档为「≤上限」,
|
||||
// 末档为「>下限」;档位按上下文升序,因此相邻的 ≤100K / ≤200K 即表示 (100K,200K]。
|
||||
// 目录阶梯/旧规则在"达到阈值即进高档"时改用 < / ≥ 表达阈值本身。
|
||||
// 渠道区间上的 tier_label 不用于 token 档位(token 模式的管理表单不暴露该字段)。
|
||||
func applyContextTierLabels(tiers []ContextPricingTier, plan contextBreakpointPlan) {
|
||||
if len(tiers) < 2 {
|
||||
return
|
||||
}
|
||||
for i := range tiers {
|
||||
t := &tiers[i]
|
||||
switch {
|
||||
case plan.thresholdInclusive && t.MaxTokens != nil && *t.MaxTokens == plan.thresholdBound:
|
||||
t.Label = "<" + formatContextTokenCount(plan.threshold)
|
||||
case plan.thresholdInclusive && t.MinTokens == plan.thresholdBound:
|
||||
t.Label = "≥" + formatContextTokenCount(plan.threshold)
|
||||
case t.MaxTokens != nil:
|
||||
t.Label = "≤" + formatContextTokenCount(*t.MaxTokens)
|
||||
default:
|
||||
t.Label = ">" + formatContextTokenCount(t.MinTokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// formatContextTokenCount 把 token 数格式化为 272K / 1M 等短标签。
|
||||
func formatContextTokenCount(n int) string {
|
||||
switch {
|
||||
case n >= 1_000_000 && n%1_000_000 == 0:
|
||||
return strconv.Itoa(n/1_000_000) + "M"
|
||||
case n >= 1_000_000:
|
||||
return trimFloatLabel(float64(n)/1_000_000) + "M"
|
||||
case n >= 1_000:
|
||||
return trimFloatLabel(float64(n)/1_000) + "K"
|
||||
}
|
||||
return strconv.Itoa(n)
|
||||
}
|
||||
|
||||
func trimFloatLabel(v float64) string {
|
||||
return strconv.FormatFloat(math.Round(v*100)/100, 'f', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"math/rand"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// scheduleScenario 阶梯表测试场景:同一份场景既做断言也做与计费函数的对账。
|
||||
type scheduleScenario struct {
|
||||
name string
|
||||
model string
|
||||
platform string
|
||||
groupPlatform string
|
||||
group *Group
|
||||
channel []ChannelModelPricing
|
||||
catalog *PricingService
|
||||
wantErr bool
|
||||
wantNil bool
|
||||
wantBasis ContextPricingBasis
|
||||
check func(t *testing.T, s *ContextPricingSchedule)
|
||||
}
|
||||
|
||||
func enabledGroup(platform string) *Group {
|
||||
return &Group{ID: 100, Platform: platform, LongContextPricingEnabled: true}
|
||||
}
|
||||
|
||||
func disabledGroup(platform string) *Group {
|
||||
return &Group{ID: 100, Platform: platform, LongContextPricingEnabled: false}
|
||||
}
|
||||
|
||||
func sonnetChannel(iv ...PricingInterval) []ChannelModelPricing {
|
||||
return []ChannelModelPricing{{
|
||||
Platform: PlatformAnthropic, Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
|
||||
InputPrice: testPtrFloat64(2e-6), Intervals: iv,
|
||||
}}
|
||||
}
|
||||
|
||||
func requireTier(t *testing.T, tier ContextPricingTier, min int, max *int, label string, input, output, cacheWrite, cacheRead *float64) {
|
||||
t.Helper()
|
||||
require.Equal(t, min, tier.MinTokens, "min")
|
||||
if max == nil {
|
||||
require.Nil(t, tier.MaxTokens, "max should be unbounded")
|
||||
} else {
|
||||
require.NotNil(t, tier.MaxTokens, "max")
|
||||
require.Equal(t, *max, *tier.MaxTokens, "max")
|
||||
}
|
||||
require.Equal(t, label, tier.Label, "label")
|
||||
requirePrice(t, input, tier.Input, "input")
|
||||
requirePrice(t, output, tier.Output, "output")
|
||||
requirePrice(t, cacheWrite, tier.CacheWrite, "cache_write")
|
||||
requirePrice(t, cacheRead, tier.CacheRead, "cache_read")
|
||||
}
|
||||
|
||||
func requirePrice(t *testing.T, want, got *float64, field string) {
|
||||
t.Helper()
|
||||
if want == nil {
|
||||
require.Nil(t, got, field)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, got, field)
|
||||
require.InDelta(t, *want, *got, 1e-15, field)
|
||||
}
|
||||
|
||||
func scheduleScenarios() []scheduleScenario {
|
||||
p := testPtrFloat64
|
||||
return []scheduleScenario{
|
||||
{
|
||||
name: "官方阶梯 gpt-5.4 整单两档", model: "gpt-5.4", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: enabledGroup(PlatformOpenAI), wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(272000), "≤272K", p(2.5e-6), p(15e-6), p(2.5e-6), p(0.25e-6))
|
||||
requireTier(t, s.Tiers[1], 272000, nil, ">272K", p(5e-6), p(22.5e-6), p(5e-6), p(0.5e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Grok 达到阈值即进高档", model: "grok-4.5", platform: PlatformGrok, groupPlatform: PlatformGrok,
|
||||
group: enabledGroup(PlatformGrok), wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(199999), "<200K", p(2e-6), p(6e-6), nil, p(0.3e-6))
|
||||
requireTier(t, s.Tiers[1], 199999, nil, "≥200K", p(4e-6), p(12e-6), nil, p(0.6e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "分组关闭阶梯只剩基础档", model: "gpt-5.4", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: disabledGroup(PlatformOpenAI), wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
requireTier(t, s.Tiers[0], 0, nil, "", p(2.5e-6), p(15e-6), p(2.5e-6), p(0.25e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "官方参考价(无分组)带目录阶梯", model: "gpt-5.4", platform: "", groupPlatform: PlatformOpenAI,
|
||||
group: nil, wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[1], 272000, nil, ">272K", p(5e-6), p(22.5e-6), p(5e-6), p(0.5e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "渠道倍率区间按渠道平价覆盖后的 base 折算(区间自定义标签不用于档位)", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(200000), InputMultiplier: p(1)},
|
||||
PricingInterval{MinTokens: 200000, TierLabel: "long", InputMultiplier: p(2), OutputMultiplier: p(1.5), CacheWriteMultiplier: p(2), CacheReadMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(200000), "≤200K", p(2e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
requireTier(t, s.Tiers[1], 200000, nil, ">200K", p(4e-6), p(22.5e-6), p(7.5e-6), p(0.6e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "区间显式价优先于倍率", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(200000), InputMultiplier: p(1)},
|
||||
PricingInterval{MinTokens: 200000, InputPrice: p(9e-6), InputMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requirePrice(t, p(9e-6), s.Tiers[1].Input, "input")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "区间空洞按 base 补档且同价段合并", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(100000), InputMultiplier: p(0.5)},
|
||||
PricingInterval{MinTokens: 200000, InputMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 3)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(100000), "≤100K", p(1e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
requireTier(t, s.Tiers[1], 100000, intPtr(200000), "≤200K", p(2e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
requireTier(t, s.Tiers[2], 200000, nil, ">200K", p(4e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "首档同价空洞被合并", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(100000), InputMultiplier: p(1)},
|
||||
PricingInterval{MinTokens: 200000, InputMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(200000), "≤200K", p(2e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
requireTier(t, s.Tiers[1], 200000, nil, ">200K", p(4e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "末档有上限时尾段回落 base", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(200000), InputMultiplier: p(1)},
|
||||
PricingInterval{MinTokens: 200000, MaxTokens: intPtr(1000000), InputMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 3)
|
||||
requireTier(t, s.Tiers[1], 200000, intPtr(1000000), "≤1M", p(4e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
requireTier(t, s.Tiers[2], 1000000, nil, ">1M", p(2e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "分组关闭时渠道区间折叠到 1-token 档", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: disabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(
|
||||
PricingInterval{MinTokens: 0, MaxTokens: intPtr(200000), InputMultiplier: p(0.5)},
|
||||
PricingInterval{MinTokens: 200000, InputMultiplier: p(2)},
|
||||
),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
requireTier(t, s.Tiers[0], 0, nil, "", p(1e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "分组关闭且首档不从 0 起时平价为 base", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: disabledGroup(PlatformAnthropic), wantBasis: ContextPricingBasisWholeRequest,
|
||||
channel: sonnetChannel(PricingInterval{MinTokens: 200000, InputMultiplier: p(2)}),
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
requirePrice(t, p(2e-6), s.Tiers[0].Input, "input")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "分组 token 价卡整张替换渠道定价并剥区间", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: &Group{ID: 100, Platform: PlatformAnthropic, LongContextPricingEnabled: true, ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{"claude-sonnet-*"}, BillingMode: BillingModeToken, InputPrice: p(1e-6),
|
||||
Intervals: []PricingInterval{{MinTokens: 200000, InputMultiplier: p(5)}},
|
||||
}}},
|
||||
channel: sonnetChannel(PricingInterval{MinTokens: 200000, InputMultiplier: p(3)}),
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
requireTier(t, s.Tiers[0], 0, nil, "", p(1e-6), p(15e-6), p(3.75e-6), p(0.3e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "分组价卡之上叠加官方阶梯", model: "gpt-5.4", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: &Group{ID: 100, Platform: PlatformOpenAI, LongContextPricingEnabled: true, ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{"gpt-5.4"}, BillingMode: BillingModeToken, InputPrice: p(1e-6),
|
||||
}}},
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requirePrice(t, p(1e-6), s.Tiers[0].Input, "input")
|
||||
requirePrice(t, p(2e-6), s.Tiers[1].Input, "input")
|
||||
requirePrice(t, p(22.5e-6), s.Tiers[1].Output, "output")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Gemini 旧规则按超出部分计价", model: "gemini-2.5-pro", platform: PlatformGemini, groupPlatform: PlatformGemini,
|
||||
group: enabledGroup(PlatformGemini), catalog: geminiCatalogStub(), wantBasis: ContextPricingBasisMarginal,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(200000), "≤200K", p(1.25e-6), p(10e-6), nil, p(0.3125e-6))
|
||||
requireTier(t, s.Tiers[1], 200000, nil, ">200K", p(2.5e-6), p(10e-6), nil, p(0.625e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Gemini 分组关闭时不用旧规则", model: "gemini-2.5-pro", platform: PlatformGemini, groupPlatform: PlatformGemini,
|
||||
group: disabledGroup(PlatformGemini), catalog: geminiCatalogStub(), wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Gemini 有渠道定价时旧规则让位", model: "gemini-2.5-pro", platform: PlatformGemini, groupPlatform: PlatformGemini,
|
||||
group: enabledGroup(PlatformGemini), catalog: geminiCatalogStub(),
|
||||
channel: []ChannelModelPricing{{
|
||||
Platform: PlatformGemini, Models: []string{"gemini-2.5-pro"}, BillingMode: BillingModeToken, InputPrice: p(3e-6),
|
||||
}},
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
requirePrice(t, p(3e-6), s.Tiers[0].Input, "input")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Gemini 官方参考不套用站内旧规则", model: "gemini-2.5-pro", platform: "", groupPlatform: PlatformGemini,
|
||||
group: nil, catalog: geminiCatalogStub(), wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "composite 分组按模型平台取渠道定价并叠加官方阶梯", model: "gpt-5.4", platform: PlatformOpenAI, groupPlatform: PlatformComposite,
|
||||
group: enabledGroup(PlatformComposite),
|
||||
channel: []ChannelModelPricing{{
|
||||
Platform: PlatformOpenAI, Models: []string{"gpt-5.4"}, BillingMode: BillingModeToken, InputPrice: p(1e-6),
|
||||
}},
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requirePrice(t, p(1e-6), s.Tiers[0].Input, "input")
|
||||
requirePrice(t, p(2e-6), s.Tiers[1].Input, "input")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "渠道显式 cache_write=0 保留为 0", model: "claude-sonnet-4", platform: PlatformAnthropic, groupPlatform: PlatformAnthropic,
|
||||
group: enabledGroup(PlatformAnthropic),
|
||||
channel: []ChannelModelPricing{{
|
||||
Platform: PlatformAnthropic, Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
|
||||
InputPrice: p(2e-6), CacheWritePrice: p(0),
|
||||
}},
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 1)
|
||||
require.NotNil(t, s.Tiers[0].CacheWrite)
|
||||
require.Zero(t, *s.Tiers[0].CacheWrite)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "gpt-5.6 缺 cache_write 时按策略补 1.25 倍并带阶梯", model: "gpt-5.6-sol", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: enabledGroup(PlatformOpenAI),
|
||||
catalog: newStubPricingServiceFromMap(map[string]*LiteLLMModelPricing{
|
||||
"gpt-5.6-sol": {Mode: "chat", InputCostPerToken: 5e-6, OutputCostPerToken: 30e-6, CacheReadInputTokenCost: 0.5e-6},
|
||||
}),
|
||||
wantBasis: ContextPricingBasisWholeRequest,
|
||||
check: func(t *testing.T, s *ContextPricingSchedule) {
|
||||
require.Len(t, s.Tiers, 2)
|
||||
requireTier(t, s.Tiers[0], 0, intPtr(272000), "≤272K", p(5e-6), p(30e-6), p(6.25e-6), p(0.5e-6))
|
||||
requireTier(t, s.Tiers[1], 272000, nil, ">272K", p(10e-6), p(45e-6), p(12.5e-6), p(1e-6))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "图片模式返回 nil", model: "gpt-image-2", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: enabledGroup(PlatformOpenAI),
|
||||
channel: []ChannelModelPricing{{
|
||||
Platform: PlatformOpenAI, Models: []string{"gpt-image-2"}, BillingMode: BillingModeImage, PerRequestPrice: p(0.04),
|
||||
}},
|
||||
wantNil: true,
|
||||
},
|
||||
{
|
||||
name: "无任何定价来源报错", model: "unknown-model-xyz", platform: PlatformOpenAI, groupPlatform: PlatformOpenAI,
|
||||
group: enabledGroup(PlatformOpenAI), wantErr: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newScheduleTestEnv(t *testing.T, sc scheduleScenario) (*BillingService, *ModelPricingResolver) {
|
||||
t.Helper()
|
||||
return newTokenCostTestEnv(t, sc.groupPlatform, sc.channel, sc.catalog)
|
||||
}
|
||||
|
||||
func TestResolveContextPricingSchedule_Scenarios(t *testing.T) {
|
||||
for _, sc := range scheduleScenarios() {
|
||||
t.Run(sc.name, func(t *testing.T) {
|
||||
bs, resolver := newScheduleTestEnv(t, sc)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: sc.model, Group: sc.group, Platform: sc.platform,
|
||||
})
|
||||
if sc.wantErr {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, sched)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
if sc.wantNil {
|
||||
require.Nil(t, sched)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, sched)
|
||||
require.Equal(t, sc.wantBasis, sched.Basis)
|
||||
require.NotEmpty(t, sched.Tiers)
|
||||
require.Zero(t, sched.Tiers[0].MinTokens, "首档从 0 起")
|
||||
for i := 1; i < len(sched.Tiers); i++ {
|
||||
require.NotNil(t, sched.Tiers[i-1].MaxTokens)
|
||||
require.Equal(t, *sched.Tiers[i-1].MaxTokens, sched.Tiers[i].MinTokens, "档位连续")
|
||||
require.Less(t, sched.Tiers[i-1].MinTokens, sched.Tiers[i].MinTokens, "档位按上下文升序")
|
||||
}
|
||||
if len(sched.Tiers) > 1 {
|
||||
for i, tier := range sched.Tiers {
|
||||
require.NotEmpty(t, tier.Label, "多档时每档都有标签 #%d", i)
|
||||
}
|
||||
require.Nil(t, sched.Tiers[len(sched.Tiers)-1].MaxTokens, "末档无上限")
|
||||
}
|
||||
if sc.check != nil {
|
||||
sc.check(t, sched)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveContextPricingSchedule_NilResolver(t *testing.T) {
|
||||
bs := NewBillingService(&config.Config{}, nil)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), nil, ContextPricingScheduleInput{Model: "gpt-5.4"})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, sched)
|
||||
}
|
||||
|
||||
// --- 对账:阶梯表推算的费用必须等于真实计费函数 ---
|
||||
|
||||
type tokenKind int
|
||||
|
||||
const (
|
||||
kindInput tokenKind = iota
|
||||
kindOutput
|
||||
kindCacheRead
|
||||
kindCacheWrite
|
||||
)
|
||||
|
||||
func tierPrice(tier ContextPricingTier, kind tokenKind) float64 {
|
||||
var p *float64
|
||||
switch kind {
|
||||
case kindInput:
|
||||
p = tier.Input
|
||||
case kindOutput:
|
||||
p = tier.Output
|
||||
case kindCacheRead:
|
||||
p = tier.CacheRead
|
||||
case kindCacheWrite:
|
||||
p = tier.CacheWrite
|
||||
}
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
func tierAt(tiers []ContextPricingTier, contextTokens int) ContextPricingTier {
|
||||
for _, tier := range tiers {
|
||||
if contextTokens > tier.MinTokens && (tier.MaxTokens == nil || contextTokens <= *tier.MaxTokens) {
|
||||
return tier
|
||||
}
|
||||
}
|
||||
return tiers[len(tiers)-1]
|
||||
}
|
||||
|
||||
// expectedCostFromSchedule 按阶梯表推算 contextTokens 个某类 token 的费用:
|
||||
// 整单基准取所在档单价 × 全量;边际基准逐段累加。
|
||||
func expectedCostFromSchedule(s *ContextPricingSchedule, kind tokenKind, contextTokens int) float64 {
|
||||
if s.Basis == ContextPricingBasisMarginal {
|
||||
total := 0.0
|
||||
for _, tier := range s.Tiers {
|
||||
if contextTokens <= tier.MinTokens {
|
||||
break
|
||||
}
|
||||
upper := contextTokens
|
||||
if tier.MaxTokens != nil && *tier.MaxTokens < upper {
|
||||
upper = *tier.MaxTokens
|
||||
}
|
||||
total += float64(upper-tier.MinTokens) * tierPrice(tier, kind)
|
||||
}
|
||||
return total
|
||||
}
|
||||
return float64(contextTokens) * tierPrice(tierAt(s.Tiers, contextTokens), kind)
|
||||
}
|
||||
|
||||
func TestResolveContextPricingSchedule_ParityWithBilling(t *testing.T) {
|
||||
const outputProbe = 1000
|
||||
rng := rand.New(rand.NewSource(20260823))
|
||||
for _, sc := range scheduleScenarios() {
|
||||
if sc.wantErr || sc.wantNil {
|
||||
continue
|
||||
}
|
||||
t.Run(sc.name, func(t *testing.T) {
|
||||
bs, resolver := newScheduleTestEnv(t, sc)
|
||||
ctx := context.Background()
|
||||
if sc.platform != "" {
|
||||
ctx = WithResolvedTargetPlatform(ctx, sc.platform)
|
||||
}
|
||||
sched, err := bs.ResolveContextPricingSchedule(ctx, resolver, ContextPricingScheduleInput{
|
||||
Model: sc.model, Group: sc.group, Platform: sc.platform,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, sched)
|
||||
|
||||
// 消费方视角重建同一份计费请求(与网关一致)。
|
||||
pricingInput := PricingInput{Model: sc.model, Group: sc.group}
|
||||
if sc.group != nil {
|
||||
gid := sc.group.ID
|
||||
pricingInput.GroupID = &gid
|
||||
}
|
||||
resolved := resolver.Resolve(ctx, pricingInput)
|
||||
var legacy *LegacyLongContextRule
|
||||
if sc.group != nil {
|
||||
legacy = bs.LegacyLongContextRule(sc.platform)
|
||||
}
|
||||
if !legacyLongContextApplies(resolved, sc.group, legacy) {
|
||||
legacy = nil
|
||||
}
|
||||
cost := func(tokens UsageTokens) float64 {
|
||||
bd, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: ctx, Model: sc.model, Group: sc.group, Tokens: tokens, RateMultiplier: 1,
|
||||
Resolver: resolver, Resolved: resolved, LegacyLongContext: legacy,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return bd.ActualCost
|
||||
}
|
||||
|
||||
probes := []int{1, 2, 999, 1000, 1001, 10_000_000}
|
||||
for _, tier := range sched.Tiers {
|
||||
for _, b := range []*int{tier.MaxTokens} {
|
||||
if b == nil {
|
||||
continue
|
||||
}
|
||||
probes = append(probes, *b-1, *b, *b+1)
|
||||
}
|
||||
}
|
||||
for i := 0; i < 8; i++ {
|
||||
probes = append(probes, 1+rng.Intn(3_000_000))
|
||||
}
|
||||
|
||||
for _, c := range probes {
|
||||
if c <= 0 {
|
||||
continue
|
||||
}
|
||||
assertCostClose(t, expectedCostFromSchedule(sched, kindInput, c), cost(UsageTokens{InputTokens: c}), "input@%d", c)
|
||||
assertCostClose(t, expectedCostFromSchedule(sched, kindCacheRead, c), cost(UsageTokens{CacheReadTokens: c}), "cache_read@%d", c)
|
||||
assertCostClose(t, expectedCostFromSchedule(sched, kindCacheWrite, c), cost(UsageTokens{CacheCreationTokens: c}), "cache_write@%d", c)
|
||||
wantOutput := float64(outputProbe) * tierPrice(tierAt(sched.Tiers, c), kindOutput)
|
||||
gotOutput := cost(UsageTokens{InputTokens: c, OutputTokens: outputProbe}) - cost(UsageTokens{InputTokens: c})
|
||||
assertCostClose(t, wantOutput, gotOutput, "output@%d", c)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertCostClose(t *testing.T, want, got float64, format string, args ...any) {
|
||||
t.Helper()
|
||||
tolerance := 1e-12 + 1e-9*math.Abs(want)
|
||||
require.InDeltaf(t, want, got, tolerance, format, args...)
|
||||
}
|
||||
|
||||
func sonnetChannelWithTimePricing(tp *ChannelTimePricing) []ChannelModelPricing {
|
||||
return []ChannelModelPricing{{
|
||||
Platform: PlatformAnthropic, Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
|
||||
InputPrice: testPtrFloat64(2e-6), TimePricing: tp,
|
||||
}}
|
||||
}
|
||||
|
||||
func TestResolveContextPricingSchedule_TimePricing(t *testing.T) {
|
||||
valid := &ChannelTimePricing{Timezone: "Asia/Shanghai", Periods: []ChannelTimePricingPeriod{
|
||||
{StartTime: "18:00", EndTime: "22:00:00", Multiplier: 1.2},
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
{StartTime: "12:00", EndTime: "13:00", Multiplier: 1},
|
||||
}}
|
||||
|
||||
t.Run("渠道分时按开始时间升序列出且跳过倍率 1 的时段", func(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, sonnetChannelWithTimePricing(valid), nil)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: "claude-sonnet-4", Group: enabledGroup(PlatformAnthropic), Platform: PlatformAnthropic,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, sched.TimePricing)
|
||||
require.Equal(t, "Asia/Shanghai", sched.TimePricing.Timezone)
|
||||
require.False(t, sched.TimePricing.WeekdaysOnly)
|
||||
require.Equal(t, []TimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
{StartTime: "18:00", EndTime: "22:00:00", Multiplier: 1.2},
|
||||
}, sched.TimePricing.Periods)
|
||||
// 阶梯表单价是标准时段价,不含分时倍率
|
||||
requirePrice(t, testPtrFloat64(2e-6), sched.Tiers[0].Input, "input")
|
||||
|
||||
// 对账:时段内的真实计费 = 标准单价 × token × 倍率
|
||||
group := enabledGroup(PlatformAnthropic)
|
||||
gid := group.ID
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "claude-sonnet-4", GroupID: &gid, Group: group})
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
for _, tc := range []struct {
|
||||
at time.Time
|
||||
want float64
|
||||
}{
|
||||
{time.Date(2026, 8, 23, 3, 0, 0, 0, loc), 0.5},
|
||||
{time.Date(2026, 8, 23, 12, 30, 0, 0, loc), 1},
|
||||
{time.Date(2026, 8, 23, 21, 59, 59, 0, loc), 1.2},
|
||||
{time.Date(2026, 8, 23, 22, 0, 0, 0, loc), 1},
|
||||
} {
|
||||
cost, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "claude-sonnet-4", Group: group, Tokens: UsageTokens{InputTokens: 1000},
|
||||
RateMultiplier: 1, PricingAt: tc.at, Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assertCostClose(t, 1000*2e-6*tc.want, cost.ActualCost, "at %s", tc.at)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("仅工作日配置透传标注且时段仍列出", func(t *testing.T) {
|
||||
weekdays := &ChannelTimePricing{Timezone: "Asia/Shanghai", WeekdaysOnly: true, Periods: []ChannelTimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
}}
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, sonnetChannelWithTimePricing(weekdays), nil)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: "claude-sonnet-4", Group: enabledGroup(PlatformAnthropic), Platform: PlatformAnthropic,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, sched.TimePricing, "探针锚点必须落在工作日,否则仅工作日配置的时段会被整组剔除")
|
||||
require.True(t, sched.TimePricing.WeekdaysOnly)
|
||||
require.Equal(t, []TimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
}, sched.TimePricing.Periods)
|
||||
|
||||
// 对账:工作日时段内乘倍率,周末同一时段按标准价
|
||||
group := enabledGroup(PlatformAnthropic)
|
||||
gid := group.ID
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "claude-sonnet-4", GroupID: &gid, Group: group})
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
for _, tc := range []struct {
|
||||
at time.Time
|
||||
want float64
|
||||
}{
|
||||
{time.Date(2026, 8, 24, 3, 0, 0, 0, loc), 0.5}, // 周一
|
||||
{time.Date(2026, 8, 23, 3, 0, 0, 0, loc), 1}, // 周日
|
||||
} {
|
||||
cost, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "claude-sonnet-4", Group: group, Tokens: UsageTokens{InputTokens: 1000},
|
||||
RateMultiplier: 1, PricingAt: tc.at, Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assertCostClose(t, 1000*2e-6*tc.want, cost.ActualCost, "at %s", tc.at)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("配置非法时计费按 1 计,阶梯表不列分时", func(t *testing.T) {
|
||||
invalid := &ChannelTimePricing{Timezone: "Asia/Shanghai", Periods: []ChannelTimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
{StartTime: "08:00", EndTime: "09:00", Multiplier: 0.8}, // 与上一段重叠
|
||||
}}
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, sonnetChannelWithTimePricing(invalid), nil)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: "claude-sonnet-4", Group: enabledGroup(PlatformAnthropic), Platform: PlatformAnthropic,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, sched.TimePricing)
|
||||
})
|
||||
|
||||
t.Run("分组价卡覆盖后渠道分时不再生效", func(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, sonnetChannelWithTimePricing(valid), nil)
|
||||
group := &Group{ID: 100, Platform: PlatformAnthropic, LongContextPricingEnabled: true, ModelPricing: []ChannelModelPricing{{
|
||||
Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken, InputPrice: testPtrFloat64(1e-6),
|
||||
}}}
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: "claude-sonnet-4", Group: group, Platform: PlatformAnthropic,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, sched.TimePricing)
|
||||
})
|
||||
|
||||
t.Run("无分时配置为 nil", func(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, sonnetChannelWithTimePricing(nil), nil)
|
||||
sched, err := bs.ResolveContextPricingSchedule(context.Background(), resolver, ContextPricingScheduleInput{
|
||||
Model: "claude-sonnet-4", Group: enabledGroup(PlatformAnthropic), Platform: PlatformAnthropic,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, sched.TimePricing)
|
||||
})
|
||||
}
|
||||
@@ -1475,7 +1475,8 @@ func (s *BillingService) applyModelSpecificPricingPolicy(model string, pricing *
|
||||
(pricing.LongContextInputThreshold <= 0 || pricing.LongContextInputMultiplier <= 0 || pricing.LongContextOutputMultiplier <= 0)
|
||||
needsCacheCreationPolicy := isGPT56 && !pricing.CacheCreationPriceExplicit && (pricing.CacheCreationPricePerToken <= 0 ||
|
||||
(pricing.InputPricePerTokenPriority > 0 && pricing.CacheCreationPricePerTokenPriority <= 0))
|
||||
if !needsLongContextPolicy && !needsCacheCreationPolicy {
|
||||
fastRatio := openAIModelFastPricingRatio(normalized)
|
||||
if !needsLongContextPolicy && !needsCacheCreationPolicy && fastRatio <= 0 {
|
||||
return pricing
|
||||
}
|
||||
cloned := *pricing
|
||||
@@ -1498,9 +1499,45 @@ func (s *BillingService) applyModelSpecificPricingPolicy(model string, pricing *
|
||||
cloned.LongContextOutputMultiplier = openAIGPT54LongContextOutputMultiplier
|
||||
}
|
||||
}
|
||||
if fastRatio > 0 {
|
||||
enforceOpenAIFastPricingRatio(&cloned, fastRatio)
|
||||
}
|
||||
return &cloned
|
||||
}
|
||||
|
||||
// openAIModelFastPricingRatio 返回业务口径下 OpenAI GPT-5.x 模型 Fast/priority
|
||||
// 的标准价倍率:gpt-5.6 系列与 gpt-5.4 为 2x,gpt-5.5 为 2.5x。未定义 Fast
|
||||
// 档的模型(如 gpt-5.5-pro、gpt-5.4-mini/nano)返回 0。
|
||||
func openAIModelFastPricingRatio(normalized string) float64 {
|
||||
switch normalized {
|
||||
case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna":
|
||||
return 2.0
|
||||
case "gpt-5.5":
|
||||
return 2.5
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// enforceOpenAIFastPricingRatio 把 priority 档价格改写为「标准价 × ratio」。
|
||||
// 本地/远程 LiteLLM 目录可能只带官方旧口径(如 gpt-5.5 priority 仍标 2x),
|
||||
// 直接采用会导致 Fast 模式少计费;这里按业务倍率兜底修正,且对已正确的
|
||||
// fallback 条目(2x/2.5x)是幂等的。computeTokenBreakdown 在 priority 价格
|
||||
// 存在时走显式档位价、不再叠加通用 tier 倍率,因此不会重复乘价。
|
||||
func enforceOpenAIFastPricingRatio(pricing *ModelPricing, ratio float64) {
|
||||
if pricing == nil || ratio <= 0 {
|
||||
return
|
||||
}
|
||||
pricing.InputPricePerTokenPriority = pricing.InputPricePerToken * ratio
|
||||
pricing.OutputPricePerTokenPriority = pricing.OutputPricePerToken * ratio
|
||||
if pricing.CacheReadPricePerToken > 0 {
|
||||
pricing.CacheReadPricePerTokenPriority = pricing.CacheReadPricePerToken * ratio
|
||||
}
|
||||
if pricing.CacheCreationPricePerToken > 0 {
|
||||
pricing.CacheCreationPricePerTokenPriority = pricing.CacheCreationPricePerToken * ratio
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BillingService) shouldApplySessionLongContextPricing(tokens UsageTokens, pricing *ModelPricing) bool {
|
||||
if pricing == nil || pricing.LongContextInputThreshold <= 0 {
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LegacyLongContextRule 平台级"超出阈值部分按倍率计费"的旧规则。
|
||||
//
|
||||
// 语义为边际计费:仅 input/cache_read 中超过 Threshold 的部分乘 Multiplier,
|
||||
// output 与 cache_write 不受影响(见 CalculateCostWithLongContext)。
|
||||
// 只有 Gemini 原生 /v1beta 入口在该分组对该模型没有分组/渠道定价时才使用;
|
||||
// 规则常量由 BillingService 统一持有,网关与模型广场都从这里读取。
|
||||
type LegacyLongContextRule struct {
|
||||
Threshold int
|
||||
Multiplier float64
|
||||
}
|
||||
|
||||
const (
|
||||
geminiLegacyLongContextThreshold = 200000
|
||||
geminiLegacyLongContextMultiplier = 2.0
|
||||
)
|
||||
|
||||
// LegacyLongContextRule 返回平台的旧长上下文规则;无规则的平台返回 nil。
|
||||
func (s *BillingService) LegacyLongContextRule(platform string) *LegacyLongContextRule {
|
||||
if platform == PlatformGemini {
|
||||
return &LegacyLongContextRule{
|
||||
Threshold: geminiLegacyLongContextThreshold,
|
||||
Multiplier: geminiLegacyLongContextMultiplier,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TokenCostRequest 通用网关 token 计费请求。
|
||||
type TokenCostRequest struct {
|
||||
Ctx context.Context
|
||||
Model string
|
||||
Group *Group
|
||||
Tokens UsageTokens
|
||||
RateMultiplier float64
|
||||
PricingAt time.Time
|
||||
ServiceTier string
|
||||
Resolver *ModelPricingResolver
|
||||
// Resolved 为调用方预先解析的定价(Resolver.Resolve 的结果),nil 表示未解析。
|
||||
Resolved *ResolvedPricing
|
||||
// LegacyLongContext 入口携带的旧长上下文规则,nil 表示该入口不使用。
|
||||
LegacyLongContext *LegacyLongContextRule
|
||||
}
|
||||
|
||||
// legacyLongContextApplies 判定请求是否走旧长上下文规则:
|
||||
// 分组/渠道显式定价优先;否则在规则存在且分组长上下文开关开启时生效。
|
||||
func legacyLongContextApplies(resolved *ResolvedPricing, group *Group, rule *LegacyLongContextRule) bool {
|
||||
if rule == nil || rule.Threshold <= 0 {
|
||||
return false
|
||||
}
|
||||
if resolved != nil && (resolved.Source == PricingSourceGroup || resolved.Source == PricingSourceChannel) {
|
||||
return false
|
||||
}
|
||||
return group == nil || group.LongContextPricingEnabled
|
||||
}
|
||||
|
||||
// CalculateTokenCostForRequest 按通用网关的路径选择计算 token 费用:
|
||||
// 1. 分组/渠道显式定价 → 统一计费(区间、分组卡、目录阶梯均在其中);
|
||||
// 2. 否则入口带旧长上下文规则且分组开关开启 → 旧边际计费;
|
||||
// 3. 否则有解析器与分组 → 统一计费(内置目录定价);
|
||||
// 4. 否则按模型目录直接计费。
|
||||
//
|
||||
// 模型广场的阶梯表查询与网关使用同一入口,保证展示与扣费同源。
|
||||
func (s *BillingService) CalculateTokenCostForRequest(req TokenCostRequest) (*CostBreakdown, error) {
|
||||
resolved := req.Resolved
|
||||
if resolved != nil && (resolved.Source == PricingSourceGroup || resolved.Source == PricingSourceChannel) {
|
||||
return s.CalculateCostUnified(s.tokenCostInput(req, resolved))
|
||||
}
|
||||
if legacyLongContextApplies(resolved, req.Group, req.LegacyLongContext) {
|
||||
return s.CalculateCostWithLongContext(req.Model, req.Tokens, req.RateMultiplier,
|
||||
req.LegacyLongContext.Threshold, req.LegacyLongContext.Multiplier)
|
||||
}
|
||||
if req.Resolver != nil && req.Group != nil {
|
||||
return s.CalculateCostUnified(s.tokenCostInput(req, resolved))
|
||||
}
|
||||
return s.CalculateCost(req.Model, req.Tokens, req.RateMultiplier)
|
||||
}
|
||||
|
||||
func (s *BillingService) tokenCostInput(req TokenCostRequest, resolved *ResolvedPricing) CostInput {
|
||||
input := CostInput{
|
||||
Ctx: req.Ctx,
|
||||
Model: req.Model,
|
||||
Group: req.Group,
|
||||
Tokens: req.Tokens,
|
||||
RequestCount: 1,
|
||||
RateMultiplier: req.RateMultiplier,
|
||||
PricingAt: req.PricingAt,
|
||||
ServiceTier: req.ServiceTier,
|
||||
Resolver: req.Resolver,
|
||||
Resolved: resolved,
|
||||
}
|
||||
if req.Group != nil {
|
||||
gid := req.Group.ID
|
||||
input.GroupID = &gid
|
||||
}
|
||||
return input
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newTokenCostTestEnv 构造带渠道定价的计费环境:group 100 挂一个渠道,定价由 pricing 指定。
|
||||
func newTokenCostTestEnv(t *testing.T, groupPlatform string, pricing []ChannelModelPricing, catalog *PricingService) (*BillingService, *ModelPricingResolver) {
|
||||
t.Helper()
|
||||
repo := &mockChannelRepository{
|
||||
listAllFn: func(_ context.Context) ([]Channel, error) {
|
||||
return []Channel{{
|
||||
ID: 1, Name: "ch", Status: StatusActive, GroupIDs: []int64{100}, ModelPricing: pricing,
|
||||
}}, nil
|
||||
},
|
||||
getGroupPlatformsFn: func(_ context.Context, _ []int64) (map[int64]string, error) {
|
||||
return map[int64]string{100: groupPlatform}, nil
|
||||
},
|
||||
}
|
||||
cs := NewChannelService(repo, nil, nil, nil)
|
||||
bs := NewBillingService(&config.Config{}, catalog)
|
||||
return bs, NewModelPricingResolver(cs, bs)
|
||||
}
|
||||
|
||||
func geminiCatalogStub() *PricingService {
|
||||
return newStubPricingServiceFromMap(map[string]*LiteLLMModelPricing{
|
||||
"gemini-2.5-pro": {
|
||||
Mode: "chat",
|
||||
InputCostPerToken: 1.25e-6,
|
||||
OutputCostPerToken: 10e-6,
|
||||
CacheReadInputTokenCost: 0.3125e-6,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestLegacyLongContextRule_OnlyGemini(t *testing.T) {
|
||||
bs := NewBillingService(&config.Config{}, nil)
|
||||
rule := bs.LegacyLongContextRule(PlatformGemini)
|
||||
require.NotNil(t, rule)
|
||||
require.Equal(t, 200000, rule.Threshold)
|
||||
require.InDelta(t, 2.0, rule.Multiplier, 1e-12)
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformAnthropic, PlatformAntigravity, PlatformComposite, ""} {
|
||||
require.Nil(t, bs.LegacyLongContextRule(platform), platform)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_ChannelPricingWinsOverLegacyRule(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformGemini, []ChannelModelPricing{{
|
||||
Platform: PlatformGemini, Models: []string{"gemini-2.5-pro"}, BillingMode: BillingModeToken,
|
||||
InputPrice: testPtrFloat64(10e-6), OutputPrice: testPtrFloat64(40e-6),
|
||||
}}, geminiCatalogStub())
|
||||
group := &Group{ID: 100, Platform: PlatformGemini, LongContextPricingEnabled: true}
|
||||
gid := group.ID
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "gemini-2.5-pro", GroupID: &gid, Group: group})
|
||||
require.Equal(t, PricingSourceChannel, resolved.Source)
|
||||
|
||||
tokens := UsageTokens{InputTokens: 300000, OutputTokens: 1000}
|
||||
got, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "gemini-2.5-pro", Group: group, Tokens: tokens, RateMultiplier: 1,
|
||||
Resolver: resolver, Resolved: resolved, LegacyLongContext: bs.LegacyLongContextRule(PlatformGemini),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
want, err := bs.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(), Model: "gemini-2.5-pro", GroupID: &gid, Group: group, Tokens: tokens,
|
||||
RequestCount: 1, RateMultiplier: 1, Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
// 渠道平价 10e-6 × 300K,旧规则未叠加
|
||||
require.InDelta(t, 3.0, got.InputCost, 1e-9)
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_LegacyRuleFollowsGroupToggle(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformGemini, nil, geminiCatalogStub())
|
||||
tokens := UsageTokens{InputTokens: 300000, OutputTokens: 1000}
|
||||
rule := bs.LegacyLongContextRule(PlatformGemini)
|
||||
|
||||
for _, enabled := range []bool{true, false} {
|
||||
group := &Group{ID: 100, Platform: PlatformGemini, LongContextPricingEnabled: enabled}
|
||||
gid := group.ID
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "gemini-2.5-pro", GroupID: &gid, Group: group})
|
||||
require.Equal(t, PricingSourceLiteLLM, resolved.Source)
|
||||
|
||||
got, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "gemini-2.5-pro", Group: group, Tokens: tokens, RateMultiplier: 1,
|
||||
Resolver: resolver, Resolved: resolved, LegacyLongContext: rule,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
if enabled {
|
||||
want, err := bs.CalculateCostWithLongContext("gemini-2.5-pro", tokens, 1, rule.Threshold, rule.Multiplier)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
// 输入 200K × 1.25e-6 + 超出 100K × 1.25e-6 × 2 = 0.5;输出 1000 × 10e-6 = 0.01。
|
||||
// 旧路径的加倍只体现在 ActualCost(分项 InputCost 不含倍率),探针也据此取值。
|
||||
require.InDelta(t, 0.51, got.ActualCost, 1e-9)
|
||||
require.True(t, got.LongContextBillingApplied)
|
||||
} else {
|
||||
want, err := bs.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(), Model: "gemini-2.5-pro", GroupID: &gid, Group: group, Tokens: tokens,
|
||||
RequestCount: 1, RateMultiplier: 1, Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
require.InDelta(t, 0.385, got.ActualCost, 1e-9)
|
||||
require.False(t, got.LongContextBillingApplied)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_BuiltInPricingUsesUnifiedPath(t *testing.T) {
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformOpenAI, nil, nil)
|
||||
group := &Group{ID: 100, Platform: PlatformOpenAI, LongContextPricingEnabled: true}
|
||||
gid := group.ID
|
||||
tokens := UsageTokens{InputTokens: 300000, OutputTokens: 1000}
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "gpt-5.4", GroupID: &gid, Group: group})
|
||||
|
||||
got, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "gpt-5.4", Group: group, Tokens: tokens, RateMultiplier: 1,
|
||||
Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
want, err := bs.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(), Model: "gpt-5.4", GroupID: &gid, Group: group, Tokens: tokens,
|
||||
RequestCount: 1, RateMultiplier: 1, Resolver: resolver,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
// 目录阶梯:超 272K 整单输入 ×2
|
||||
require.InDelta(t, 300000*2.5e-6*2, got.InputCost, 1e-9)
|
||||
require.True(t, got.LongContextBillingApplied)
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_NoResolverFallsBackToCatalog(t *testing.T) {
|
||||
bs := NewBillingService(&config.Config{}, nil)
|
||||
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 10}
|
||||
got, err := bs.CalculateTokenCostForRequest(TokenCostRequest{Model: "gpt-5.4", Tokens: tokens, RateMultiplier: 1})
|
||||
require.NoError(t, err)
|
||||
want, err := bs.CalculateCost("gpt-5.4", tokens, 1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
}
|
||||
@@ -109,8 +109,9 @@ type ChannelModelPricing struct {
|
||||
|
||||
// ChannelTimePricing 渠道模型定价的分时倍率配置。
|
||||
type ChannelTimePricing struct {
|
||||
Timezone string `json:"timezone"`
|
||||
Periods []ChannelTimePricingPeriod `json:"periods"`
|
||||
Timezone string `json:"timezone"`
|
||||
WeekdaysOnly bool `json:"weekdays_only,omitempty"`
|
||||
Periods []ChannelTimePricingPeriod `json:"periods"`
|
||||
}
|
||||
|
||||
// ChannelTimePricingPeriod 是秒级的左闭右开分时倍率区间,并兼容历史 HH:mm 数据。
|
||||
@@ -216,7 +217,10 @@ func (p ChannelModelPricing) Clone() ChannelModelPricing {
|
||||
copy(cp.Intervals, p.Intervals)
|
||||
}
|
||||
if p.TimePricing != nil {
|
||||
cp.TimePricing = &ChannelTimePricing{Timezone: p.TimePricing.Timezone}
|
||||
cp.TimePricing = &ChannelTimePricing{
|
||||
Timezone: p.TimePricing.Timezone,
|
||||
WeekdaysOnly: p.TimePricing.WeekdaysOnly,
|
||||
}
|
||||
if p.TimePricing.Periods != nil {
|
||||
cp.TimePricing.Periods = append([]ChannelTimePricingPeriod(nil), p.TimePricing.Periods...)
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func (s *ChannelService) ListAvailable(ctx context.Context) ([]AvailableChannel,
|
||||
ch.normalizeBillingModelSource()
|
||||
|
||||
supported := ch.SupportedModels()
|
||||
s.fillGlobalPricingFallback(supported)
|
||||
fillGlobalPricingFallback(s.pricingService, supported)
|
||||
|
||||
out = append(out, AvailableChannel{
|
||||
ID: ch.ID,
|
||||
@@ -117,16 +117,16 @@ func (s *ChannelService) ListAvailable(ctx context.Context) ([]AvailableChannel,
|
||||
// 1. Pricing == nil(渠道完全没声明该模型的定价条目)
|
||||
// 2. Pricing 非 nil 但所有价格字段为空(admin UI 建了条目但没填价格)
|
||||
//
|
||||
// 当 s.pricingService 为 nil(测试场景),跳过回落。
|
||||
func (s *ChannelService) fillGlobalPricingFallback(models []SupportedModel) {
|
||||
if s.pricingService == nil {
|
||||
// 当 pricingService 为 nil(测试场景),跳过回落。可用渠道与模型广场共用。
|
||||
func fillGlobalPricingFallback(pricingService *PricingService, models []SupportedModel) {
|
||||
if pricingService == nil {
|
||||
return
|
||||
}
|
||||
for i := range models {
|
||||
if !pricingNeedsFallback(models[i].Pricing) {
|
||||
continue
|
||||
}
|
||||
lp := s.pricingService.GetModelPricing(models[i].Name)
|
||||
lp := pricingService.GetModelPricing(models[i].Name)
|
||||
if lp == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ func TestFillGlobalPricingFallback_NilPricing(t *testing.T) {
|
||||
models := []SupportedModel{
|
||||
{Name: "claude-opus-4-5", Platform: "anthropic"},
|
||||
}
|
||||
svc.fillGlobalPricingFallback(models)
|
||||
fillGlobalPricingFallback(svc.pricingService, models)
|
||||
require.NotNil(t, models[0].Pricing)
|
||||
require.NotNil(t, models[0].Pricing.InputPrice)
|
||||
require.InDelta(t, 5e-6, *models[0].Pricing.InputPrice, 1e-12)
|
||||
@@ -281,7 +281,7 @@ func TestFillGlobalPricingFallback_EmptyPricingFillsFromLiteLLM(t *testing.T) {
|
||||
},
|
||||
},
|
||||
}
|
||||
svc.fillGlobalPricingFallback(models)
|
||||
fillGlobalPricingFallback(svc.pricingService, models)
|
||||
require.NotNil(t, models[0].Pricing)
|
||||
require.Equal(t, BillingModeImage, models[0].Pricing.BillingMode)
|
||||
require.NotNil(t, models[0].Pricing.ImageOutputPrice)
|
||||
@@ -302,7 +302,7 @@ func TestFillGlobalPricingFallback_KeepsExistingPrice(t *testing.T) {
|
||||
models := []SupportedModel{
|
||||
{Name: "served-model", Platform: "anthropic", Pricing: existing},
|
||||
}
|
||||
svc.fillGlobalPricingFallback(models)
|
||||
fillGlobalPricingFallback(svc.pricingService, models)
|
||||
require.Same(t, existing, models[0].Pricing)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PlazaOfficialPricing 模型广场展示用的 LiteLLM 官方参考价(USD per token)。
|
||||
// 字段为 nil 表示官方数据中该项缺失(0 视为未配置)。
|
||||
type PlazaOfficialPricing struct {
|
||||
InputPrice *float64
|
||||
OutputPrice *float64
|
||||
CacheWritePrice *float64 // 5m 缓存写入(= LiteLLM cache_creation)
|
||||
CacheWrite1hPrice *float64 // 1h 缓存写入(LiteLLM cache_creation_above_1hr)
|
||||
CacheReadPrice *float64
|
||||
}
|
||||
|
||||
// PlazaModel 模型广场中单个模型条目:渠道定价 + 官方参考价。
|
||||
type PlazaModel struct {
|
||||
Name string
|
||||
Platform string
|
||||
Pricing *ChannelModelPricing
|
||||
OfficialPricing *PlazaOfficialPricing
|
||||
}
|
||||
|
||||
// PlazaGroup 模型广场中以分组为顶层的条目。
|
||||
//
|
||||
// 与 AvailableGroupRef 相比多了 Description 与 Models;Models 来自该分组关联渠道的
|
||||
// 支持模型(普通分组按分组平台隔离,Composite 分组展开关联渠道已配置的
|
||||
// 具体平台),与「可用渠道」页口径一致。
|
||||
type PlazaGroup struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
Platform string
|
||||
SubscriptionType string
|
||||
RateMultiplier float64
|
||||
PeakRateEnabled bool
|
||||
PeakStart string
|
||||
PeakEnd string
|
||||
PeakRateMultiplier float64
|
||||
IsExclusive bool
|
||||
// 图片按次实付倍率:ImageRateIndependent 为 true 时,图片计费模型的实付
|
||||
// = 档位价 × ImageRateMultiplier,不乘分组/用户专属倍率(与计费口径一致)。
|
||||
ImageRateIndependent bool
|
||||
ImageRateMultiplier float64
|
||||
Models []PlazaModel
|
||||
}
|
||||
|
||||
// ListPlazaGroups 返回模型广场数据:每个活跃分组附带其可用模型与定价。
|
||||
//
|
||||
// 聚合口径与 ListAvailable 一致(Active 渠道、SupportedModels ∪ 全局定价回落、
|
||||
// 平台隔离),仅把顶层从渠道换成分组:
|
||||
// - 渠道按 lower(name) 排序后遍历,保证同名模型去重结果确定;
|
||||
// - 同分组同名模型「先见者胜」,仅当已存条目无定价而新条目有定价时升级替换;
|
||||
// - 图片计费模型的档位价按实收口径合成(分组图片价 > 渠道档位价 > 渠道默认按次价,
|
||||
// 见 plazaImageDisplayPricing);
|
||||
// - 每个模型附带 LiteLLM 官方参考价(查不到为 nil);
|
||||
// - 只返回 Models 非空的分组;分组按 RateMultiplier 升序(同倍率按名称),
|
||||
// 组内模型按名称排序。
|
||||
//
|
||||
// 可见性过滤(专属分组)不在此层做,由 handler 按登录态裁剪。
|
||||
func (s *ChannelService) ListPlazaGroups(ctx context.Context) ([]PlazaGroup, error) {
|
||||
channels, err := s.repo.ListAll(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list channels: %w", err)
|
||||
}
|
||||
groups, err := s.groupRepo.ListActive(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list active groups: %w", err)
|
||||
}
|
||||
|
||||
sort.SliceStable(channels, func(i, j int) bool {
|
||||
return strings.ToLower(channels[i].Name) < strings.ToLower(channels[j].Name)
|
||||
})
|
||||
|
||||
byGroup := make(map[int64]*PlazaGroup, len(groups))
|
||||
groupEnt := make(map[int64]*Group, len(groups))
|
||||
order := make([]int64, 0, len(groups))
|
||||
for i := range groups {
|
||||
g := &groups[i]
|
||||
byGroup[g.ID] = &PlazaGroup{
|
||||
ID: g.ID,
|
||||
Name: g.Name,
|
||||
Description: g.Description,
|
||||
Platform: g.Platform,
|
||||
SubscriptionType: g.SubscriptionType,
|
||||
RateMultiplier: g.RateMultiplier,
|
||||
PeakRateEnabled: g.PeakRateEnabled,
|
||||
PeakStart: g.PeakStart,
|
||||
PeakEnd: g.PeakEnd,
|
||||
PeakRateMultiplier: g.PeakRateMultiplier,
|
||||
IsExclusive: g.IsExclusive,
|
||||
ImageRateIndependent: g.ImageRateIndependent,
|
||||
ImageRateMultiplier: g.ImageRateMultiplier,
|
||||
}
|
||||
groupEnt[g.ID] = g
|
||||
order = append(order, g.ID)
|
||||
}
|
||||
|
||||
type modelKey struct {
|
||||
platform string
|
||||
name string
|
||||
}
|
||||
// modelIdx[groupID][platform+modelName] = index into byGroup[groupID].Models
|
||||
modelIdx := make(map[int64]map[modelKey]int, len(groups))
|
||||
for i := range channels {
|
||||
ch := &channels[i]
|
||||
if ch.Status != StatusActive {
|
||||
continue
|
||||
}
|
||||
ch.normalizeBillingModelSource()
|
||||
supported := ch.SupportedModels()
|
||||
s.fillGlobalPricingFallback(supported)
|
||||
|
||||
for _, gid := range ch.GroupIDs {
|
||||
pg, ok := byGroup[gid]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
idx := modelIdx[gid]
|
||||
if idx == nil {
|
||||
idx = make(map[modelKey]int, len(supported))
|
||||
modelIdx[gid] = idx
|
||||
}
|
||||
for j := range supported {
|
||||
m := supported[j]
|
||||
if pg.Platform == PlatformComposite {
|
||||
if !isConcreteRequestPlatform(m.Platform) {
|
||||
continue
|
||||
}
|
||||
} else if m.Platform != pg.Platform {
|
||||
continue
|
||||
}
|
||||
pricing := plazaImageDisplayPricing(m.Pricing, groupEnt[gid])
|
||||
key := modelKey{platform: m.Platform, name: m.Name}
|
||||
if at, seen := idx[key]; seen {
|
||||
// 先见者胜;仅当已存条目无定价而新条目有定价时升级。
|
||||
if pg.Models[at].Pricing == nil && pricing != nil {
|
||||
pg.Models[at].Pricing = pricing
|
||||
}
|
||||
continue
|
||||
}
|
||||
idx[key] = len(pg.Models)
|
||||
pg.Models = append(pg.Models, PlazaModel{
|
||||
Name: m.Name,
|
||||
Platform: m.Platform,
|
||||
Pricing: pricing,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
officialMemo := make(map[string]*PlazaOfficialPricing)
|
||||
out := make([]PlazaGroup, 0, len(order))
|
||||
for _, gid := range order {
|
||||
pg := byGroup[gid]
|
||||
if len(pg.Models) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.SliceStable(pg.Models, func(i, j int) bool {
|
||||
if pg.Models[i].Name != pg.Models[j].Name {
|
||||
return pg.Models[i].Name < pg.Models[j].Name
|
||||
}
|
||||
return pg.Models[i].Platform < pg.Models[j].Platform
|
||||
})
|
||||
for j := range pg.Models {
|
||||
pg.Models[j].OfficialPricing = s.lookupOfficialPricing(pg.Models[j].Name, officialMemo)
|
||||
}
|
||||
out = append(out, *pg)
|
||||
}
|
||||
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].RateMultiplier != out[j].RateMultiplier {
|
||||
return out[i].RateMultiplier < out[j].RateMultiplier
|
||||
}
|
||||
return out[i].Name < out[j].Name
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// plazaImageDisplayPricing 为图片计费模型合成展示定价,使档位价与实收口径一致:
|
||||
// 每档(1K/2K/4K)单价 = 分组图片价 > 渠道同档位价 > 渠道默认按次价,无价的档不展示。
|
||||
// 分组未配任何图片价、或定价非图片模式时原样返回。返回克隆,不修改入参
|
||||
// (渠道定价指针指向缓存共享数据)。
|
||||
func plazaImageDisplayPricing(p *ChannelModelPricing, g *Group) *ChannelModelPricing {
|
||||
if p == nil || g == nil || p.BillingMode != BillingModeImage {
|
||||
return p
|
||||
}
|
||||
if g.ImagePrice1K == nil && g.ImagePrice2K == nil && g.ImagePrice4K == nil {
|
||||
return p
|
||||
}
|
||||
channelTierPrice := func(label string) *float64 {
|
||||
for i := range p.Intervals {
|
||||
if p.Intervals[i].TierLabel == label && p.Intervals[i].PerRequestPrice != nil {
|
||||
return p.Intervals[i].PerRequestPrice
|
||||
}
|
||||
}
|
||||
return p.PerRequestPrice
|
||||
}
|
||||
tiers := []struct {
|
||||
label string
|
||||
groupPrice *float64
|
||||
}{
|
||||
{"1K", g.ImagePrice1K},
|
||||
{"2K", g.ImagePrice2K},
|
||||
{"4K", g.ImagePrice4K},
|
||||
}
|
||||
clone := *p
|
||||
clone.Intervals = make([]PricingInterval, 0, len(tiers))
|
||||
for i, t := range tiers {
|
||||
price := t.groupPrice
|
||||
if price == nil {
|
||||
price = channelTierPrice(t.label)
|
||||
}
|
||||
if price == nil {
|
||||
continue
|
||||
}
|
||||
v := *price
|
||||
clone.Intervals = append(clone.Intervals, PricingInterval{
|
||||
TierLabel: t.label,
|
||||
PerRequestPrice: &v,
|
||||
SortOrder: i,
|
||||
})
|
||||
}
|
||||
return &clone
|
||||
}
|
||||
|
||||
// lookupOfficialPricing 查询模型的 LiteLLM 官方参考价,带 memo 避免同名模型重复转换。
|
||||
// pricingService 为 nil(测试场景)或查不到时返回 nil。
|
||||
func (s *ChannelService) lookupOfficialPricing(modelName string, memo map[string]*PlazaOfficialPricing) *PlazaOfficialPricing {
|
||||
if s.pricingService == nil {
|
||||
return nil
|
||||
}
|
||||
if cached, ok := memo[modelName]; ok {
|
||||
return cached
|
||||
}
|
||||
var result *PlazaOfficialPricing
|
||||
if lp := s.pricingService.GetModelPricing(modelName); lp != nil && !lp.TokenPricingAbsent {
|
||||
result = &PlazaOfficialPricing{
|
||||
InputPrice: nonZeroPtr(lp.InputCostPerToken),
|
||||
OutputPrice: nonZeroPtr(lp.OutputCostPerToken),
|
||||
CacheWritePrice: nonZeroPtr(lp.CacheCreationInputTokenCost),
|
||||
CacheWrite1hPrice: nonZeroPtr(lp.CacheCreationInputTokenCostAbove1hr),
|
||||
CacheReadPrice: nonZeroPtr(lp.CacheReadInputTokenCost),
|
||||
}
|
||||
if result.InputPrice == nil && result.OutputPrice == nil &&
|
||||
result.CacheWritePrice == nil && result.CacheWrite1hPrice == nil && result.CacheReadPrice == nil {
|
||||
result = nil
|
||||
}
|
||||
}
|
||||
memo[modelName] = result
|
||||
return result
|
||||
}
|
||||
@@ -198,7 +198,8 @@ func TestChannelModelPricingClone(t *testing.T) {
|
||||
{MinTokens: 0, TierLabel: "tier1"},
|
||||
},
|
||||
TimePricing: &ChannelTimePricing{
|
||||
Timezone: "Asia/Shanghai",
|
||||
Timezone: "Asia/Shanghai",
|
||||
WeekdaysOnly: true,
|
||||
Periods: []ChannelTimePricingPeriod{{
|
||||
StartTime: "09:00",
|
||||
EndTime: "12:00",
|
||||
@@ -217,9 +218,11 @@ func TestChannelModelPricingClone(t *testing.T) {
|
||||
require.Equal(t, "tier1", original.Intervals[0].TierLabel)
|
||||
|
||||
cloned.TimePricing.Timezone = "America/New_York"
|
||||
cloned.TimePricing.WeekdaysOnly = false
|
||||
cloned.TimePricing.Periods[0].StartTime = "10:00"
|
||||
cloned.TimePricing.Periods[0].Multiplier = 3
|
||||
require.Equal(t, "Asia/Shanghai", original.TimePricing.Timezone)
|
||||
require.True(t, original.TimePricing.WeekdaysOnly)
|
||||
require.Equal(t, "09:00", original.TimePricing.Periods[0].StartTime)
|
||||
require.Equal(t, 2.0, original.TimePricing.Periods[0].Multiplier)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ func (config *ChannelTimePricing) MultiplierAt(at time.Time) float64 {
|
||||
}
|
||||
|
||||
local := at.In(location)
|
||||
if config.WeekdaysOnly && (local.Weekday() == time.Saturday || local.Weekday() == time.Sunday) {
|
||||
return 1.0
|
||||
}
|
||||
second := local.Hour()*60*60 + local.Minute()*60 + local.Second()
|
||||
for _, period := range periods {
|
||||
if second >= period.start && second < period.end {
|
||||
|
||||
@@ -95,6 +95,30 @@ func TestChannelTimePricingMultiplierAt(t *testing.T) {
|
||||
require.Equal(t, 2.0, newYork.MultiplierAt(at))
|
||||
}
|
||||
|
||||
func TestChannelTimePricingMultiplierAtWeekdaysOnly(t *testing.T) {
|
||||
config := &ChannelTimePricing{
|
||||
Timezone: "Asia/Shanghai",
|
||||
WeekdaysOnly: true,
|
||||
Periods: onePeriod(),
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
at time.Time
|
||||
want float64
|
||||
}{
|
||||
{name: "Monday in configured timezone", at: time.Date(2026, 6, 29, 1, 0, 0, 0, time.UTC), want: 2},
|
||||
{name: "Saturday in configured timezone", at: time.Date(2026, 7, 4, 1, 0, 0, 0, time.UTC), want: 1},
|
||||
{name: "Sunday in configured timezone", at: time.Date(2026, 7, 5, 1, 0, 0, 0, time.UTC), want: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, config.MultiplierAt(tt.at))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelTimePricingMultiplierAtSecondPrecision(t *testing.T) {
|
||||
config := timeConfig(ChannelTimePricingPeriod{StartTime: "09:00:30", EndTime: "09:00:45", Multiplier: 2})
|
||||
shanghai, err := time.LoadLocation("Asia/Shanghai")
|
||||
|
||||
@@ -296,6 +296,7 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput(
|
||||
UpstreamModel: input.RequestModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
Stream: input.RequestStream,
|
||||
Duration: time.Since(input.StartTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
@@ -697,6 +698,72 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
usage.CacheCreationInputTokens = int(total)
|
||||
}
|
||||
}
|
||||
|
||||
// Kimi's Anthropic-compatible stream uses input_tokens with two meanings:
|
||||
// message_start reports total prompt input, while message_delta reports only
|
||||
// uncached input. prompt_tokens remains the total in both events. Normalize
|
||||
// to ClaudeUsage's mutually-exclusive buckets so downstream billing does not
|
||||
// subtract cache tokens from an already-uncached value.
|
||||
usageNode := parsed.Get("usage")
|
||||
if parsed.Get("type").String() == "message_start" {
|
||||
usageNode = parsed.Get("message.usage")
|
||||
}
|
||||
normalizeAnthropicCompatiblePromptUsage(usageNode, usage)
|
||||
}
|
||||
|
||||
// normalizeAnthropicCompatiblePromptUsage converts provider-native OpenAI-style
|
||||
// prompt/cache fields into Claude's mutually-exclusive usage buckets. Native
|
||||
// Anthropic responses do not expose these aliases and are left alone.
|
||||
func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *ClaudeUsage) bool {
|
||||
if usage == nil || !usageNode.Exists() {
|
||||
return false
|
||||
}
|
||||
promptTokens := usageNode.Get("prompt_tokens")
|
||||
promptCacheHitTokens := usageNode.Get("prompt_cache_hit_tokens")
|
||||
promptCacheMissTokens := usageNode.Get("prompt_cache_miss_tokens")
|
||||
if (!promptTokens.Exists() || promptTokens.Int() <= 0) &&
|
||||
!promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() {
|
||||
return false
|
||||
}
|
||||
|
||||
cacheReadTokens := usage.CacheReadInputTokens
|
||||
if v := usageNode.Get("cache_read_input_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
}
|
||||
if cacheReadTokens == 0 {
|
||||
if v := usageNode.Get("cached_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
}
|
||||
}
|
||||
if cacheReadTokens == 0 {
|
||||
if v := usageNode.Get("prompt_tokens_details.cached_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
}
|
||||
}
|
||||
if cacheReadTokens == 0 && promptCacheHitTokens.Exists() {
|
||||
cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0)
|
||||
}
|
||||
|
||||
cacheCreationTokens := usage.CacheCreationInputTokens
|
||||
if v := usageNode.Get("cache_creation_input_tokens"); v.Exists() {
|
||||
cacheCreationTokens = int(v.Int())
|
||||
}
|
||||
if cacheCreationTokens == 0 {
|
||||
cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int()
|
||||
cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int()
|
||||
if cc5m > 0 || cc1h > 0 {
|
||||
cacheCreationTokens = int(cc5m + cc1h)
|
||||
}
|
||||
}
|
||||
|
||||
if promptCacheMissTokens.Exists() {
|
||||
usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0)
|
||||
} else {
|
||||
usage.InputTokens = max(int(promptTokens.Int())-cacheReadTokens-cacheCreationTokens, 0)
|
||||
}
|
||||
usage.CacheReadInputTokens = cacheReadTokens
|
||||
usage.CacheCreationInputTokens = cacheCreationTokens
|
||||
return true
|
||||
}
|
||||
|
||||
func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage {
|
||||
@@ -730,6 +797,7 @@ func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage {
|
||||
usage.CacheReadInputTokens = int(cached)
|
||||
}
|
||||
}
|
||||
normalizeAnthropicCompatiblePromptUsage(usageNode, usage)
|
||||
return usage
|
||||
}
|
||||
|
||||
|
||||
@@ -888,6 +888,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
UpstreamModel: mappedModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
Stream: reqStream,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
@@ -913,8 +914,9 @@ func anthropicSpeedModel(parsed *ParsedRequest, result *ForwardResult) string {
|
||||
// 承载(Opus 4.7 的 fast mode 已被移除,传 speed=fast 会直接报错)。这里按模型和
|
||||
// 平台收紧,避免上游根本没跑 fast 时仍然按 2x 计费——宁可漏收也不能多收。
|
||||
//
|
||||
// 注:判据是请求参数而非响应里的 usage.speed。等 usage 解析链路统一暴露该字段后,
|
||||
// 应改为以响应为准。
|
||||
// 这里只决定请求侧的档位;上游响应里的 usage.speed 由 UpstreamResponseServiceTier
|
||||
// 带回,用量记录时经 ResolveBillingServiceTier 只降不升(usage.speed=standard 则按
|
||||
// 标准价计费)。
|
||||
func anthropicSpeedServiceTier(account *Account, speed, model string) *string {
|
||||
if account == nil || account.Platform != PlatformAnthropic || speed != "fast" {
|
||||
return nil
|
||||
|
||||
@@ -285,18 +285,46 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if dst == nil {
|
||||
return
|
||||
}
|
||||
if src.InputTokens > 0 {
|
||||
dst.InputTokens = src.InputTokens
|
||||
|
||||
// Some Anthropic-compatible providers retain OpenAI-style prompt/cache
|
||||
// fields. Prefer those authoritative totals or hit/miss buckets over the
|
||||
// overloaded input_tokens field. This covers Kimi's changing stream
|
||||
// semantics as well as GLM/DeepSeek cache aliases.
|
||||
if src.PromptTokens > 0 || src.PromptCacheHitTokens != nil || src.PromptCacheMissTokens != nil {
|
||||
cacheReadTokens := src.CacheReadInputTokens
|
||||
if cacheReadTokens == 0 && src.CachedTokens > 0 {
|
||||
cacheReadTokens = src.CachedTokens
|
||||
}
|
||||
if cacheReadTokens == 0 && src.PromptTokensDetails != nil && src.PromptTokensDetails.CachedTokens > 0 {
|
||||
cacheReadTokens = src.PromptTokensDetails.CachedTokens
|
||||
}
|
||||
if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil {
|
||||
cacheReadTokens = max(*src.PromptCacheHitTokens, 0)
|
||||
}
|
||||
|
||||
if src.PromptCacheMissTokens != nil {
|
||||
dst.InputTokens = max(*src.PromptCacheMissTokens, 0)
|
||||
} else {
|
||||
dst.InputTokens = max(src.PromptTokens-cacheReadTokens-src.CacheCreationInputTokens, 0)
|
||||
}
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
|
||||
} else {
|
||||
if src.InputTokens > 0 {
|
||||
dst.InputTokens = src.InputTokens
|
||||
}
|
||||
if src.CacheReadInputTokens > 0 {
|
||||
dst.CacheReadInputTokens = src.CacheReadInputTokens
|
||||
} else if src.CachedTokens > 0 {
|
||||
dst.CacheReadInputTokens = src.CachedTokens
|
||||
}
|
||||
if src.CacheCreationInputTokens > 0 {
|
||||
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
|
||||
}
|
||||
}
|
||||
if src.OutputTokens > 0 {
|
||||
dst.OutputTokens = src.OutputTokens
|
||||
}
|
||||
if src.CacheReadInputTokens > 0 {
|
||||
dst.CacheReadInputTokens = src.CacheReadInputTokens
|
||||
}
|
||||
if src.CacheCreationInputTokens > 0 {
|
||||
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
|
||||
}
|
||||
}
|
||||
|
||||
// parseAnthropicSSEField parses an SSE field line in the form "field:value" or "field: value".
|
||||
|
||||
@@ -694,3 +694,74 @@ func TestGatewayServiceRecordUsage_ReasoningEffortNil(t *testing.T) {
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Nil(t, usageRepo.lastLog.ReasoningEffort)
|
||||
}
|
||||
|
||||
// newGatewayRecordUsageServiceWithResolverForTest mirrors production wiring for
|
||||
// token billing: a pricing resolver plus a grouped API key select the unified
|
||||
// billing path, which is the only one that honours the service tier.
|
||||
func newGatewayRecordUsageServiceWithResolverForTest(usageRepo UsageLogRepository) (*GatewayService, *APIKey) {
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
|
||||
svc.resolver = NewModelPricingResolver(nil, svc.billingService)
|
||||
groupID := int64(7)
|
||||
return svc, &APIKey{ID: 1, GroupID: &groupID, Group: &Group{ID: groupID, RateMultiplier: 1.0}}
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_FastSpeedDowngradedByUpstreamResponse(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageBestEffortLogRepoStub{}
|
||||
svc, apiKey := newGatewayRecordUsageServiceWithResolverForTest(usageRepo)
|
||||
|
||||
tier := "fast"
|
||||
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: &ForwardResult{
|
||||
RequestID: "fast_downgraded_test",
|
||||
Usage: ClaudeUsage{InputTokens: 100, OutputTokens: 50},
|
||||
Model: "claude-opus-5",
|
||||
Duration: time.Second,
|
||||
ServiceTier: &tier,
|
||||
UpstreamResponseServiceTier: "standard",
|
||||
},
|
||||
APIKey: apiKey,
|
||||
User: &User{ID: 1},
|
||||
Account: &Account{ID: 1, Platform: PlatformAnthropic},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.NotNil(t, usageRepo.lastLog.ServiceTier)
|
||||
require.Equal(t, "standard", *usageRepo.lastLog.ServiceTier)
|
||||
|
||||
tokens := UsageTokens{InputTokens: 100, OutputTokens: 50}
|
||||
standardCost, err := svc.billingService.CalculateCost("claude-opus-5", tokens, 1.0)
|
||||
require.NoError(t, err)
|
||||
fastCost, err := svc.billingService.CalculateCostWithServiceTier("claude-opus-5", tokens, 1.0, "fast")
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, fastCost.TotalCost, standardCost.TotalCost, "fast mode must carry a premium for the test to be meaningful")
|
||||
require.InDelta(t, standardCost.TotalCost, usageRepo.lastLog.TotalCost, 1e-10)
|
||||
}
|
||||
|
||||
func TestGatewayServiceRecordUsage_FastSpeedHonouredKeepsPremium(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageBestEffortLogRepoStub{}
|
||||
svc, apiKey := newGatewayRecordUsageServiceWithResolverForTest(usageRepo)
|
||||
|
||||
tier := "fast"
|
||||
err := svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: &ForwardResult{
|
||||
RequestID: "fast_honoured_test",
|
||||
Usage: ClaudeUsage{InputTokens: 100, OutputTokens: 50},
|
||||
Model: "claude-opus-5",
|
||||
Duration: time.Second,
|
||||
ServiceTier: &tier,
|
||||
UpstreamResponseServiceTier: "fast",
|
||||
},
|
||||
APIKey: apiKey,
|
||||
User: &User{ID: 1},
|
||||
Account: &Account{ID: 1, Platform: PlatformAnthropic},
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, "fast", *usageRepo.lastLog.ServiceTier)
|
||||
|
||||
fastCost, err := svc.billingService.CalculateCostWithServiceTier("claude-opus-5", UsageTokens{InputTokens: 100, OutputTokens: 50}, 1.0, "fast")
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, fastCost.TotalCost, usageRepo.lastLog.TotalCost, 1e-10)
|
||||
}
|
||||
@@ -614,13 +614,18 @@ type ForwardResult struct {
|
||||
// response before any client-facing rewrite or protocol conversion.
|
||||
UpstreamResponseModel string
|
||||
UpstreamResponseModelConflict bool
|
||||
Stream bool
|
||||
Duration time.Duration
|
||||
FirstTokenMs *int // 首字时间(流式请求)
|
||||
ClientDisconnect bool // 客户端是否在流式传输过程中断开
|
||||
ReasoningEffort *string
|
||||
// ServiceTier records the billable request tier. OpenAI uses service_tier;
|
||||
// Anthropic speed=fast is normalized to "fast".
|
||||
// UpstreamResponseServiceTier is the tier the upstream reports having used
|
||||
// (Anthropic usage.speed: "fast" / "standard"); "" when not declared.
|
||||
UpstreamResponseServiceTier string
|
||||
Stream bool
|
||||
Duration time.Duration
|
||||
FirstTokenMs *int // 首字时间(流式请求)
|
||||
ClientDisconnect bool // 客户端是否在流式传输过程中断开
|
||||
ReasoningEffort *string
|
||||
// ServiceTier records the tier requested by the client. OpenAI uses
|
||||
// service_tier; Anthropic speed=fast is normalized to "fast". Usage recording
|
||||
// lowers it to UpstreamResponseServiceTier when the upstream reports a
|
||||
// cheaper tier (see ResolveBillingServiceTier).
|
||||
ServiceTier *string
|
||||
|
||||
// 图片生成计费字段(图片生成模型使用)
|
||||
@@ -1515,19 +1520,19 @@ func (s *GatewayService) initDebugGatewayBodyFile(path string) {
|
||||
}
|
||||
|
||||
// 如果 path 指向一个已存在的目录,自动追加默认文件名
|
||||
if info, err := os.Stat(path); err == nil && info.IsDir() {
|
||||
if info, err := os.Stat(path); err == nil && info.IsDir() { //nolint:gosec // G703: path 仅来自启动环境变量 SUB2API_DEBUG_GATEWAY_BODY(运维配置),非请求输入
|
||||
path = filepath.Join(path, debugGatewayBodyDefaultFilename)
|
||||
}
|
||||
|
||||
// 确保父目录存在
|
||||
if dir := filepath.Dir(path); dir != "." {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil { //nolint:gosec // G703: 同上
|
||||
slog.Error("failed to create gateway debug log directory", "dir", dir, "error", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) //nolint:gosec // G703: 同上
|
||||
if err != nil {
|
||||
slog.Error("failed to open gateway debug log file", "path", path, "error", err)
|
||||
return
|
||||
|
||||
@@ -680,6 +680,7 @@ func partialStreamUsageResult(c *gin.Context, resp *http.Response, streamResult
|
||||
UpstreamModel: upstreamModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: streamResult.firstTokenMs,
|
||||
|
||||
@@ -776,6 +776,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
|
||||
account := input.Account
|
||||
subscription := input.Subscription
|
||||
ApplyForwardImageBillingResolution(result)
|
||||
logServiceTierBillingDowngrade("service.gateway", account, result.RequestID, ApplyForwardServiceTierBillingResolution(result))
|
||||
|
||||
// 强制缓存计费:将 input_tokens 转为 cache_read_input_tokens
|
||||
// 用于粘性会话切换时的特殊计费处理
|
||||
@@ -1121,7 +1122,8 @@ func (s *GatewayService) calculateImageCost(
|
||||
return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier)
|
||||
}
|
||||
|
||||
// calculateTokenCost 计算 Token 计费:根据 opts 决定走普通/长上下文/渠道统一计费。
|
||||
// calculateTokenCost 计算 Token 计费:路径选择(分组/渠道定价 → 旧长上下文规则 → 内置定价)
|
||||
// 统一交给 BillingService.CalculateTokenCostForRequest,与模型广场的阶梯表查询同源。
|
||||
func (s *GatewayService) calculateTokenCost(
|
||||
ctx context.Context,
|
||||
result *ForwardResult,
|
||||
@@ -1141,39 +1143,28 @@ func (s *GatewayService) calculateTokenCost(
|
||||
ImageOutputTokens: result.Usage.ImageOutputTokens,
|
||||
}
|
||||
|
||||
var cost *CostBreakdown
|
||||
var err error
|
||||
|
||||
// Explicit group/channel pricing wins. Built-in pricing also uses the unified
|
||||
// resolver so the group long-context toggle can veto model-native tiers.
|
||||
if resolved := s.resolveChannelPricing(ctx, billingModel, apiKey); resolved != nil {
|
||||
var resolved *ResolvedPricing
|
||||
if s.resolver != nil && apiKey.Group != nil {
|
||||
gid := apiKey.Group.ID
|
||||
cost, err = s.billingService.CalculateCostUnified(CostInput{
|
||||
Ctx: ctx,
|
||||
Model: billingModel,
|
||||
GroupID: &gid,
|
||||
Group: apiKey.Group,
|
||||
Tokens: tokens,
|
||||
RequestCount: 1,
|
||||
RateMultiplier: multiplier,
|
||||
PricingAt: pricingAt,
|
||||
ServiceTier: optionalStringValue(result.ServiceTier),
|
||||
Resolver: s.resolver,
|
||||
Resolved: resolved,
|
||||
})
|
||||
} else if opts.LongContextThreshold > 0 && (apiKey.Group == nil || apiKey.Group.LongContextPricingEnabled) {
|
||||
// 长上下文双倍计费(如 Gemini 200K 阈值)
|
||||
cost, err = s.billingService.CalculateCostWithLongContext(billingModel, tokens, multiplier, opts.LongContextThreshold, opts.LongContextMultiplier)
|
||||
} else if s.resolver != nil && apiKey.Group != nil {
|
||||
gid := apiKey.Group.ID
|
||||
cost, err = s.billingService.CalculateCostUnified(CostInput{
|
||||
Ctx: ctx, Model: billingModel, GroupID: &gid, Group: apiKey.Group,
|
||||
Tokens: tokens, RequestCount: 1, RateMultiplier: multiplier, PricingAt: pricingAt,
|
||||
ServiceTier: optionalStringValue(result.ServiceTier), Resolver: s.resolver,
|
||||
})
|
||||
} else {
|
||||
cost, err = s.billingService.CalculateCost(billingModel, tokens, multiplier)
|
||||
resolved = s.resolver.Resolve(ctx, PricingInput{Model: billingModel, GroupID: &gid, Group: apiKey.Group})
|
||||
}
|
||||
var legacy *LegacyLongContextRule
|
||||
if opts.LongContextThreshold > 0 {
|
||||
legacy = &LegacyLongContextRule{Threshold: opts.LongContextThreshold, Multiplier: opts.LongContextMultiplier}
|
||||
}
|
||||
|
||||
cost, err := s.billingService.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: ctx,
|
||||
Model: billingModel,
|
||||
Group: apiKey.Group,
|
||||
Tokens: tokens,
|
||||
RateMultiplier: multiplier,
|
||||
PricingAt: pricingAt,
|
||||
ServiceTier: optionalStringValue(result.ServiceTier),
|
||||
Resolver: s.resolver,
|
||||
Resolved: resolved,
|
||||
LegacyLongContext: legacy,
|
||||
})
|
||||
if err != nil {
|
||||
logger.LegacyPrintf("service.gateway", "Calculate cost failed: %v", err)
|
||||
return &CostBreakdown{ActualCost: 0}
|
||||
@@ -1181,6 +1172,14 @@ func (s *GatewayService) calculateTokenCost(
|
||||
return cost
|
||||
}
|
||||
|
||||
// LegacyLongContextRule 透传 BillingService 的平台旧长上下文规则,供入口 handler 取用。
|
||||
func (s *GatewayService) LegacyLongContextRule(platform string) *LegacyLongContextRule {
|
||||
if s == nil || s.billingService == nil {
|
||||
return nil
|
||||
}
|
||||
return s.billingService.LegacyLongContextRule(platform)
|
||||
}
|
||||
|
||||
// buildRecordUsageLog 构建使用日志并设置计费模式。
|
||||
func (s *GatewayService) buildRecordUsageLog(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -301,6 +301,22 @@ func (u *grokHybridUpstream) snapshot() ([]*http.Request, [][]byte) {
|
||||
return requests, bodies
|
||||
}
|
||||
|
||||
// quotaSnapshot 返回配额探测链路的请求及请求体,不含 scheduleGrokObservedModelsSync
|
||||
// 在 QueryQuota 返回后异步发出的 GET /v1/models:该请求是否已落到上游取决于调度时序。
|
||||
func (u *grokHybridUpstream) quotaSnapshot() ([]*http.Request, [][]byte) {
|
||||
requests, bodies := u.snapshot()
|
||||
quotaRequests := make([]*http.Request, 0, len(requests))
|
||||
quotaBodies := make([][]byte, 0, len(bodies))
|
||||
for i, req := range requests {
|
||||
if req.URL.Path == "/v1/models" {
|
||||
continue
|
||||
}
|
||||
quotaRequests = append(quotaRequests, req)
|
||||
quotaBodies = append(quotaBodies, bodies[i])
|
||||
}
|
||||
return quotaRequests, quotaBodies
|
||||
}
|
||||
|
||||
func (r *grokQuotaProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error) {
|
||||
r.calls++
|
||||
return r.proxies[id], nil
|
||||
@@ -741,7 +757,7 @@ func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) {
|
||||
require.EqualValues(t, 2_000_000, *result.Snapshot.Tokens.Limit)
|
||||
require.True(t, result.HeadersObserved)
|
||||
|
||||
requests, bodies := upstream.snapshot()
|
||||
requests, bodies := upstream.quotaSnapshot()
|
||||
require.Len(t, requests, 3)
|
||||
responseCalls := 0
|
||||
for i, req := range requests {
|
||||
@@ -781,7 +797,7 @@ func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) {
|
||||
require.Empty(t, result.Model)
|
||||
require.Nil(t, result.LocalUsage24h)
|
||||
|
||||
requests, _ := upstream.snapshot()
|
||||
requests, _ := upstream.quotaSnapshot()
|
||||
require.Len(t, requests, 2)
|
||||
for _, req := range requests {
|
||||
require.Equal(t, "/v1/billing", req.URL.Path)
|
||||
@@ -806,7 +822,7 @@ func TestGrokQuotaServiceQueryQuotaCustomPaidMonthlyLimitSkipsActiveProbe(t *tes
|
||||
require.InDelta(t, monthlyLimit, *result.Billing.MonthlyLimitCents, 1e-9)
|
||||
require.Nil(t, result.Snapshot)
|
||||
|
||||
requests, _ := upstream.snapshot()
|
||||
requests, _ := upstream.quotaSnapshot()
|
||||
require.Len(t, requests, 2)
|
||||
for _, req := range requests {
|
||||
require.Equal(t, "/v1/billing", req.URL.Path)
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseSSEUsagePassthroughNormalizesKimiPromptUsage(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
|
||||
parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":0,"prompt_tokens":173306,"cached_tokens":0}}}`, usage)
|
||||
require.Equal(t, 173306, usage.InputTokens)
|
||||
require.Zero(t, usage.CacheReadInputTokens)
|
||||
|
||||
parseSSEUsagePassthrough(`{"type":"message_delta","usage":{"input_tokens":250,"cache_creation_input_tokens":0,"cache_read_input_tokens":173056,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`, usage)
|
||||
require.Equal(t, 250, usage.InputTokens, "Kimi message_delta input_tokens is already the uncached bucket")
|
||||
require.Equal(t, 173056, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 166, usage.OutputTokens)
|
||||
}
|
||||
|
||||
func TestParseSSEUsagePassthroughKimiFullyCachedInputReplacesStartTotal(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
|
||||
parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"prompt_tokens":173306}}}`, usage)
|
||||
parseSSEUsagePassthrough(`{"type":"message_delta","usage":{"input_tokens":0,"cache_read_input_tokens":173306,"output_tokens":8,"prompt_tokens":173306,"cached_tokens":173306}}`, usage)
|
||||
|
||||
require.Zero(t, usage.InputTokens, "an explicit zero uncached bucket must not retain message_start's total")
|
||||
require.Equal(t, 173306, usage.CacheReadInputTokens)
|
||||
}
|
||||
|
||||
func TestParseClaudeUsageFromResponseBodyNormalizesCNProviderAliases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantInput int
|
||||
wantCacheRead int
|
||||
wantOutput int
|
||||
}{
|
||||
{
|
||||
name: "Kimi top-level cached_tokens",
|
||||
body: `{"usage":{"input_tokens":173306,"output_tokens":166,"cache_read_input_tokens":173056,"prompt_tokens":173306,"cached_tokens":173056}}`,
|
||||
wantInput: 250,
|
||||
wantCacheRead: 173056,
|
||||
wantOutput: 166,
|
||||
},
|
||||
{
|
||||
name: "GLM nested prompt cache details",
|
||||
body: `{"usage":{"input_tokens":1200,"output_tokens":300,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`,
|
||||
wantInput: 400,
|
||||
wantCacheRead: 800,
|
||||
wantOutput: 300,
|
||||
},
|
||||
{
|
||||
name: "DeepSeek prompt cache hit and miss buckets",
|
||||
body: `{"usage":{"input_tokens":1200,"output_tokens":300,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`,
|
||||
wantInput: 400,
|
||||
wantCacheRead: 800,
|
||||
wantOutput: 300,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
usage := parseClaudeUsageFromResponseBody([]byte(tt.body))
|
||||
require.Equal(t, tt.wantInput, usage.InputTokens)
|
||||
require.Equal(t, tt.wantCacheRead, usage.CacheReadInputTokens)
|
||||
require.Equal(t, tt.wantOutput, usage.OutputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSSEUsagePassthroughNormalizesGLMAndDeepSeekAliases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data string
|
||||
wantInput int
|
||||
wantCacheRead int
|
||||
}{
|
||||
{
|
||||
name: "GLM",
|
||||
data: `{"type":"message_delta","usage":{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`,
|
||||
wantInput: 400,
|
||||
wantCacheRead: 800,
|
||||
},
|
||||
{
|
||||
name: "DeepSeek",
|
||||
data: `{"type":"message_delta","usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`,
|
||||
wantInput: 400,
|
||||
wantCacheRead: 800,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
parseSSEUsagePassthrough(tt.data, usage)
|
||||
require.Equal(t, tt.wantInput, usage.InputTokens)
|
||||
require.Equal(t, tt.wantCacheRead, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 30, usage.OutputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeAnthropicUsageNormalizesKimiStreamForOpenAIBilling(t *testing.T) {
|
||||
var start apicompat.AnthropicStreamEvent
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"type":"message_start","message":{"usage":{"input_tokens":173306,"prompt_tokens":173306,"cached_tokens":0}}}`), &start))
|
||||
var delta apicompat.AnthropicStreamEvent
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"type":"message_delta","usage":{"input_tokens":250,"cache_read_input_tokens":173056,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`), &delta))
|
||||
|
||||
usage := &ClaudeUsage{}
|
||||
mergeAnthropicUsage(usage, start.Message.Usage)
|
||||
mergeAnthropicUsage(usage, *delta.Usage)
|
||||
require.Equal(t, 250, usage.InputTokens)
|
||||
require.Equal(t, 173056, usage.CacheReadInputTokens)
|
||||
|
||||
openAIUsage := claudeUsageToOpenAIUsage(usage)
|
||||
require.Equal(t, 173306, openAIUsage.InputTokens, "OpenAI gateway expects an inclusive input total")
|
||||
require.Equal(t, 250, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens)
|
||||
require.Equal(t, 166, openAIUsage.OutputTokens)
|
||||
}
|
||||
|
||||
func TestMergeAnthropicUsageNormalizesGLMAndDeepSeekAliases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
}{
|
||||
{
|
||||
name: "GLM",
|
||||
raw: `{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}`,
|
||||
},
|
||||
{
|
||||
name: "DeepSeek",
|
||||
raw: `{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var src apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.raw), &src))
|
||||
|
||||
usage := &ClaudeUsage{}
|
||||
mergeAnthropicUsage(usage, src)
|
||||
require.Equal(t, 400, usage.InputTokens)
|
||||
require.Equal(t, 800, usage.CacheReadInputTokens)
|
||||
|
||||
openAIUsage := claudeUsageToOpenAIUsage(usage)
|
||||
require.Equal(t, 1200, openAIUsage.InputTokens)
|
||||
require.Equal(t, 400, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeUsageToOpenAIUsagePreservesCNProviderNativeAnthropicBuckets(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
usage ClaudeUsage
|
||||
wantTotal int
|
||||
wantUncached int
|
||||
}{
|
||||
{
|
||||
name: "GLM",
|
||||
usage: ClaudeUsage{
|
||||
InputTokens: 2,
|
||||
OutputTokens: 302,
|
||||
CacheCreationInputTokens: 733,
|
||||
CacheReadInputTokens: 376156,
|
||||
},
|
||||
wantTotal: 376891,
|
||||
wantUncached: 2,
|
||||
},
|
||||
{
|
||||
name: "DeepSeek",
|
||||
usage: ClaudeUsage{
|
||||
InputTokens: 400,
|
||||
OutputTokens: 30,
|
||||
CacheReadInputTokens: 800,
|
||||
},
|
||||
wantTotal: 1200,
|
||||
wantUncached: 400,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
openAIUsage := claudeUsageToOpenAIUsage(&tt.usage)
|
||||
require.Equal(t, tt.wantTotal, openAIUsage.InputTokens)
|
||||
require.Equal(t, tt.wantUncached, openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens)
|
||||
require.Equal(t, tt.usage.CacheReadInputTokens, openAIUsage.CacheReadInputTokens)
|
||||
require.Equal(t, tt.usage.CacheCreationInputTokens, openAIUsage.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNProviderAnthropicUsageBillsUncachedInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
model string
|
||||
body string
|
||||
wantInput int
|
||||
}{
|
||||
{
|
||||
name: "Kimi",
|
||||
model: "k3",
|
||||
body: `{"usage":{"input_tokens":173306,"output_tokens":166,"prompt_tokens":173306,"cached_tokens":173056}}`,
|
||||
wantInput: 250,
|
||||
},
|
||||
{
|
||||
name: "GLM",
|
||||
model: "glm-5.2",
|
||||
body: `{"usage":{"input_tokens":1200,"output_tokens":30,"prompt_tokens":1200,"prompt_tokens_details":{"cached_tokens":800}}}`,
|
||||
wantInput: 400,
|
||||
},
|
||||
{
|
||||
name: "DeepSeek",
|
||||
model: "deepseek-v4-flash",
|
||||
body: `{"usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}}`,
|
||||
wantInput: 400,
|
||||
},
|
||||
}
|
||||
|
||||
billing := NewBillingService(&config.Config{}, nil)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
claudeUsage := parseClaudeUsageFromResponseBody([]byte(tt.body))
|
||||
openAIUsage := claudeUsageToOpenAIUsage(claudeUsage)
|
||||
uncachedInput := max(openAIUsage.InputTokens-openAIUsage.CacheReadInputTokens-openAIUsage.CacheCreationInputTokens, 0)
|
||||
require.Equal(t, tt.wantInput, uncachedInput)
|
||||
|
||||
cost, err := billing.CalculateCost(tt.model, UsageTokens{
|
||||
InputTokens: uncachedInput,
|
||||
OutputTokens: openAIUsage.OutputTokens,
|
||||
CacheCreationTokens: openAIUsage.CacheCreationInputTokens,
|
||||
CacheReadTokens: openAIUsage.CacheReadInputTokens,
|
||||
}, 1)
|
||||
require.NoError(t, err)
|
||||
require.Positive(t, cost.InputCost, "uncached input must contribute to the final charge")
|
||||
|
||||
pricing, err := billing.GetModelPricing(tt.model)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, float64(tt.wantInput)*pricing.InputPricePerToken, cost.InputCost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PlazaOfficialPricing 模型广场展示用的官方参考价(USD per token),与计费同源:
|
||||
// LiteLLM → 内置兜底价卡 → 模型策略。字段为 nil 表示该项缺失(0 视为未配置)。
|
||||
type PlazaOfficialPricing struct {
|
||||
InputPrice *float64
|
||||
OutputPrice *float64
|
||||
CacheWritePrice *float64 // 5m 缓存写入(= LiteLLM cache_creation)
|
||||
CacheWrite1hPrice *float64 // 1h 缓存写入,仅计费会区分 5m/1h 时给出
|
||||
CacheReadPrice *float64
|
||||
// Intervals 官方长上下文阶梯(多档时给出),不受分组开关影响。
|
||||
Intervals []PricingInterval
|
||||
}
|
||||
|
||||
// PlazaModel 模型广场中单个模型条目:按实收口径合成的展示定价 + 官方参考价。
|
||||
type PlazaModel struct {
|
||||
Name string
|
||||
Platform string
|
||||
Pricing *ChannelModelPricing
|
||||
OfficialPricing *PlazaOfficialPricing
|
||||
// LongContextBasis 多档时的计价基准(整单 / 仅超出部分),单档为空。
|
||||
LongContextBasis ContextPricingBasis
|
||||
// TimePricing 计费会生效的分时倍率时段;无分时为 nil。
|
||||
TimePricing *TimePricingSchedule
|
||||
}
|
||||
|
||||
// PlazaGroup 模型广场中以分组为顶层的条目。
|
||||
//
|
||||
// 与 AvailableGroupRef 相比多了 Description 与 Models;Models 来自该分组关联渠道的
|
||||
// 支持模型(普通分组按分组平台隔离,Composite 分组展开关联渠道已配置的
|
||||
// 具体平台),与「可用渠道」页口径一致。
|
||||
type PlazaGroup struct {
|
||||
ID int64
|
||||
Name string
|
||||
Description string
|
||||
Platform string
|
||||
SubscriptionType string
|
||||
RateMultiplier float64
|
||||
PeakRateEnabled bool
|
||||
PeakStart string
|
||||
PeakEnd string
|
||||
PeakRateMultiplier float64
|
||||
IsExclusive bool
|
||||
// 图片按次实付倍率:ImageRateIndependent 为 true 时,图片计费模型的实付
|
||||
// = 档位价 × ImageRateMultiplier,不乘分组/用户专属倍率(与计费口径一致)。
|
||||
ImageRateIndependent bool
|
||||
ImageRateMultiplier float64
|
||||
// LongContextPricingEnabled 分组是否按上下文长度应用阶梯价;关闭时模型展示的是最低档。
|
||||
LongContextPricingEnabled bool
|
||||
Models []PlazaModel
|
||||
}
|
||||
|
||||
// ModelPlazaService 聚合模型广场数据。
|
||||
//
|
||||
// 模型枚举来自渠道配置;token 模型的展示单价与阶梯由 BillingService 的阶梯表
|
||||
// 查询给出(与扣费走同一条解析链与计费函数),图片/按次模型沿用渠道/分组档位价。
|
||||
type ModelPlazaService struct {
|
||||
channelRepo ChannelRepository
|
||||
groupRepo GroupRepository
|
||||
pricingService *PricingService
|
||||
billingService *BillingService
|
||||
resolver *ModelPricingResolver
|
||||
}
|
||||
|
||||
// NewModelPlazaService 创建模型广场服务。
|
||||
func NewModelPlazaService(
|
||||
channelRepo ChannelRepository,
|
||||
groupRepo GroupRepository,
|
||||
pricingService *PricingService,
|
||||
billingService *BillingService,
|
||||
resolver *ModelPricingResolver,
|
||||
) *ModelPlazaService {
|
||||
return &ModelPlazaService{
|
||||
channelRepo: channelRepo,
|
||||
groupRepo: groupRepo,
|
||||
pricingService: pricingService,
|
||||
billingService: billingService,
|
||||
resolver: resolver,
|
||||
}
|
||||
}
|
||||
|
||||
// ListGroups 返回模型广场数据:每个活跃分组附带其可用模型与定价。
|
||||
//
|
||||
// 模型枚举口径与 ListAvailable 一致(Active 渠道、SupportedModels ∪ 全局定价回落、
|
||||
// 平台隔离),仅把顶层从渠道换成分组:
|
||||
// - 渠道按 lower(name) 排序后遍历,保证同名模型去重结果确定;
|
||||
// - 同分组同名模型「先见者胜」,仅当已存条目无定价而新条目有定价时升级替换;
|
||||
// - token 模型的单价与阶梯按实收口径合成(见 ResolveContextPricingSchedule),
|
||||
// 图片计费模型的档位价按实收口径合成(见 plazaImageDisplayPricing);
|
||||
// - 每个模型附带官方参考价(查不到为 nil);
|
||||
// - 只返回 Models 非空的分组;分组按 RateMultiplier 升序(同倍率按名称),
|
||||
// 组内模型按名称排序。
|
||||
//
|
||||
// 可见性过滤(专属分组)不在此层做,由 handler 按登录态裁剪。
|
||||
func (s *ModelPlazaService) ListGroups(ctx context.Context) ([]PlazaGroup, error) {
|
||||
channels, err := s.channelRepo.ListAll(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list channels: %w", err)
|
||||
}
|
||||
groups, err := s.groupRepo.ListActive(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list active groups: %w", err)
|
||||
}
|
||||
|
||||
sort.SliceStable(channels, func(i, j int) bool {
|
||||
return strings.ToLower(channels[i].Name) < strings.ToLower(channels[j].Name)
|
||||
})
|
||||
|
||||
byGroup := make(map[int64]*PlazaGroup, len(groups))
|
||||
groupEnt := make(map[int64]*Group, len(groups))
|
||||
order := make([]int64, 0, len(groups))
|
||||
for i := range groups {
|
||||
g := &groups[i]
|
||||
byGroup[g.ID] = &PlazaGroup{
|
||||
ID: g.ID,
|
||||
Name: g.Name,
|
||||
Description: g.Description,
|
||||
Platform: g.Platform,
|
||||
SubscriptionType: g.SubscriptionType,
|
||||
RateMultiplier: g.RateMultiplier,
|
||||
PeakRateEnabled: g.PeakRateEnabled,
|
||||
PeakStart: g.PeakStart,
|
||||
PeakEnd: g.PeakEnd,
|
||||
PeakRateMultiplier: g.PeakRateMultiplier,
|
||||
IsExclusive: g.IsExclusive,
|
||||
ImageRateIndependent: g.ImageRateIndependent,
|
||||
ImageRateMultiplier: g.ImageRateMultiplier,
|
||||
LongContextPricingEnabled: g.LongContextPricingEnabled,
|
||||
}
|
||||
groupEnt[g.ID] = g
|
||||
order = append(order, g.ID)
|
||||
}
|
||||
|
||||
type modelKey struct {
|
||||
platform string
|
||||
name string
|
||||
}
|
||||
// modelIdx[groupID][platform+modelName] = index into byGroup[groupID].Models
|
||||
modelIdx := make(map[int64]map[modelKey]int, len(groups))
|
||||
for i := range channels {
|
||||
ch := &channels[i]
|
||||
if ch.Status != StatusActive {
|
||||
continue
|
||||
}
|
||||
ch.normalizeBillingModelSource()
|
||||
supported := ch.SupportedModels()
|
||||
fillGlobalPricingFallback(s.pricingService, supported)
|
||||
|
||||
for _, gid := range ch.GroupIDs {
|
||||
pg, ok := byGroup[gid]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
idx := modelIdx[gid]
|
||||
if idx == nil {
|
||||
idx = make(map[modelKey]int, len(supported))
|
||||
modelIdx[gid] = idx
|
||||
}
|
||||
for j := range supported {
|
||||
m := supported[j]
|
||||
if pg.Platform == PlatformComposite {
|
||||
if !isConcreteRequestPlatform(m.Platform) {
|
||||
continue
|
||||
}
|
||||
} else if m.Platform != pg.Platform {
|
||||
continue
|
||||
}
|
||||
key := modelKey{platform: m.Platform, name: m.Name}
|
||||
if at, seen := idx[key]; seen {
|
||||
// 先见者胜;仅当已存条目无定价而新条目有定价时升级。
|
||||
if pg.Models[at].Pricing == nil && m.Pricing != nil {
|
||||
pg.Models[at].Pricing = m.Pricing
|
||||
}
|
||||
continue
|
||||
}
|
||||
idx[key] = len(pg.Models)
|
||||
pg.Models = append(pg.Models, PlazaModel{
|
||||
Name: m.Name,
|
||||
Platform: m.Platform,
|
||||
Pricing: m.Pricing,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
officialMemo := make(map[string]*PlazaOfficialPricing)
|
||||
out := make([]PlazaGroup, 0, len(order))
|
||||
for _, gid := range order {
|
||||
pg := byGroup[gid]
|
||||
if len(pg.Models) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.SliceStable(pg.Models, func(i, j int) bool {
|
||||
if pg.Models[i].Name != pg.Models[j].Name {
|
||||
return pg.Models[i].Name < pg.Models[j].Name
|
||||
}
|
||||
return pg.Models[i].Platform < pg.Models[j].Platform
|
||||
})
|
||||
g := groupEnt[gid]
|
||||
for j := range pg.Models {
|
||||
s.fillDisplayPricing(ctx, &pg.Models[j], g)
|
||||
pg.Models[j].OfficialPricing = s.lookupOfficialPricing(ctx, pg.Models[j].Name, officialMemo)
|
||||
}
|
||||
out = append(out, *pg)
|
||||
}
|
||||
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].RateMultiplier != out[j].RateMultiplier {
|
||||
return out[i].RateMultiplier < out[j].RateMultiplier
|
||||
}
|
||||
return out[i].Name < out[j].Name
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fillDisplayPricing 把模型的展示定价换成实收口径:
|
||||
// token 模型取计费阶梯表(单价与档位均由真实计费函数得出),
|
||||
// 图片/按次模型(或阶梯表不可用时)沿用渠道定价与分组图片档位价。
|
||||
func (s *ModelPlazaService) fillDisplayPricing(ctx context.Context, m *PlazaModel, g *Group) {
|
||||
if s.billingService != nil && s.resolver != nil {
|
||||
sched, err := s.billingService.ResolveContextPricingSchedule(ctx, s.resolver, ContextPricingScheduleInput{
|
||||
Model: m.Name,
|
||||
Group: g,
|
||||
Platform: m.Platform,
|
||||
})
|
||||
if err == nil && sched != nil && len(sched.Tiers) > 0 {
|
||||
m.Pricing = plazaPricingFromSchedule(m.Pricing, sched)
|
||||
if len(sched.Tiers) > 1 {
|
||||
m.LongContextBasis = sched.Basis
|
||||
}
|
||||
m.TimePricing = sched.TimePricing
|
||||
return
|
||||
}
|
||||
}
|
||||
m.Pricing = plazaImageDisplayPricing(m.Pricing, g)
|
||||
}
|
||||
|
||||
// plazaPricingFromSchedule 把阶梯表压成展示用的 ChannelModelPricing:
|
||||
// 平价取首档单价,多档时 Intervals 逐档给出绝对单价;图片/按次字段沿用原始定价。
|
||||
func plazaPricingFromSchedule(raw *ChannelModelPricing, sched *ContextPricingSchedule) *ChannelModelPricing {
|
||||
out := &ChannelModelPricing{BillingMode: BillingModeToken}
|
||||
if raw != nil {
|
||||
out.ImageInputPrice = raw.ImageInputPrice
|
||||
out.ImageOutputPrice = raw.ImageOutputPrice
|
||||
out.PerRequestPrice = raw.PerRequestPrice
|
||||
}
|
||||
first := sched.Tiers[0]
|
||||
out.InputPrice = first.Input
|
||||
out.OutputPrice = first.Output
|
||||
out.CacheWritePrice = first.CacheWrite
|
||||
out.CacheReadPrice = first.CacheRead
|
||||
if len(sched.Tiers) > 1 {
|
||||
out.Intervals = plazaIntervalsFromTiers(sched.Tiers)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func plazaIntervalsFromTiers(tiers []ContextPricingTier) []PricingInterval {
|
||||
intervals := make([]PricingInterval, 0, len(tiers))
|
||||
for i, t := range tiers {
|
||||
intervals = append(intervals, PricingInterval{
|
||||
MinTokens: t.MinTokens,
|
||||
MaxTokens: t.MaxTokens,
|
||||
TierLabel: t.Label,
|
||||
InputPrice: t.Input,
|
||||
OutputPrice: t.Output,
|
||||
CacheWritePrice: t.CacheWrite,
|
||||
CacheReadPrice: t.CacheRead,
|
||||
SortOrder: i,
|
||||
})
|
||||
}
|
||||
return intervals
|
||||
}
|
||||
|
||||
// plazaImageDisplayPricing 为图片计费模型合成展示定价,使档位价与实收口径一致:
|
||||
// 每档(1K/2K/4K)单价 = 分组图片价 > 渠道同档位价 > 渠道默认按次价,无价的档不展示。
|
||||
// 分组未配任何图片价、或定价非图片模式时原样返回。返回克隆,不修改入参
|
||||
// (渠道定价指针指向缓存共享数据)。
|
||||
func plazaImageDisplayPricing(p *ChannelModelPricing, g *Group) *ChannelModelPricing {
|
||||
if p == nil || g == nil || p.BillingMode != BillingModeImage {
|
||||
return p
|
||||
}
|
||||
if g.ImagePrice1K == nil && g.ImagePrice2K == nil && g.ImagePrice4K == nil {
|
||||
return p
|
||||
}
|
||||
channelTierPrice := func(label string) *float64 {
|
||||
for i := range p.Intervals {
|
||||
if p.Intervals[i].TierLabel == label && p.Intervals[i].PerRequestPrice != nil {
|
||||
return p.Intervals[i].PerRequestPrice
|
||||
}
|
||||
}
|
||||
return p.PerRequestPrice
|
||||
}
|
||||
tiers := []struct {
|
||||
label string
|
||||
groupPrice *float64
|
||||
}{
|
||||
{"1K", g.ImagePrice1K},
|
||||
{"2K", g.ImagePrice2K},
|
||||
{"4K", g.ImagePrice4K},
|
||||
}
|
||||
clone := *p
|
||||
clone.Intervals = make([]PricingInterval, 0, len(tiers))
|
||||
for i, t := range tiers {
|
||||
price := t.groupPrice
|
||||
if price == nil {
|
||||
price = channelTierPrice(t.label)
|
||||
}
|
||||
if price == nil {
|
||||
continue
|
||||
}
|
||||
v := *price
|
||||
clone.Intervals = append(clone.Intervals, PricingInterval{
|
||||
TierLabel: t.label,
|
||||
PerRequestPrice: &v,
|
||||
SortOrder: i,
|
||||
})
|
||||
}
|
||||
return &clone
|
||||
}
|
||||
|
||||
// lookupOfficialPricing 查询模型的官方参考价(与计费同源:LiteLLM → 内置兜底 → 模型策略),
|
||||
// 带 memo 避免同名模型重复解析。官方阶梯按无分组、无渠道的口径查阶梯表。
|
||||
// billingService 为 nil(测试场景)或查不到时返回 nil。
|
||||
func (s *ModelPlazaService) lookupOfficialPricing(ctx context.Context, modelName string, memo map[string]*PlazaOfficialPricing) *PlazaOfficialPricing {
|
||||
if s.billingService == nil {
|
||||
return nil
|
||||
}
|
||||
if cached, ok := memo[modelName]; ok {
|
||||
return cached
|
||||
}
|
||||
var result *PlazaOfficialPricing
|
||||
if mp, err := s.billingService.GetModelPricing(modelName); err == nil && mp != nil {
|
||||
result = &PlazaOfficialPricing{
|
||||
InputPrice: nonZeroPtr(mp.InputPricePerToken),
|
||||
OutputPrice: nonZeroPtr(mp.OutputPricePerToken),
|
||||
CacheWritePrice: nonZeroPtr(mp.CacheCreationPricePerToken),
|
||||
CacheReadPrice: nonZeroPtr(mp.CacheReadPricePerToken),
|
||||
}
|
||||
// 计费只在支持 5m/1h 分档时使用 1h 价,其余情况 1h 价对用户无意义。
|
||||
if mp.SupportsCacheBreakdown {
|
||||
result.CacheWrite1hPrice = nonZeroPtr(mp.CacheCreation1hPrice)
|
||||
}
|
||||
if s.resolver != nil {
|
||||
sched, schedErr := s.billingService.ResolveContextPricingSchedule(ctx, s.resolver, ContextPricingScheduleInput{Model: modelName})
|
||||
if schedErr == nil && sched != nil && len(sched.Tiers) > 1 {
|
||||
result.Intervals = plazaIntervalsFromTiers(sched.Tiers)
|
||||
}
|
||||
}
|
||||
if result.InputPrice == nil && result.OutputPrice == nil && result.CacheWritePrice == nil &&
|
||||
result.CacheWrite1hPrice == nil && result.CacheReadPrice == nil && len(result.Intervals) == 0 {
|
||||
result = nil
|
||||
}
|
||||
}
|
||||
memo[modelName] = result
|
||||
return result
|
||||
}
|
||||
+193
-28
@@ -7,17 +7,16 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newPlazaChannelService 构造 ListPlazaGroups 测试用的 ChannelService。
|
||||
func newPlazaChannelService(channels []Channel, groups []Group, pricing *PricingService) *ChannelService {
|
||||
// newPlazaService 构造 ListGroups 测试用的 ModelPlazaService(不接计费服务:展示定价原样透传)。
|
||||
func newPlazaService(channels []Channel, groups []Group, pricing *PricingService) *ModelPlazaService {
|
||||
repo := &mockChannelRepository{
|
||||
listAllFn: func(ctx context.Context) ([]Channel, error) { return channels, nil },
|
||||
}
|
||||
svc := NewChannelService(repo, &stubGroupRepoForAvailable{activeGroups: groups}, nil, nil)
|
||||
svc.pricingService = pricing
|
||||
return svc
|
||||
return NewModelPlazaService(repo, &stubGroupRepoForAvailable{activeGroups: groups}, pricing, nil, nil)
|
||||
}
|
||||
|
||||
func plazaPricedChannel(id int64, name string, groupIDs []int64, platform string, models ...string) Channel {
|
||||
@@ -46,8 +45,8 @@ func TestListPlazaGroups_GroupCentricAggregation(t *testing.T) {
|
||||
{ID: 10, Name: "g-main", Description: "desc", Platform: "anthropic", RateMultiplier: 1},
|
||||
{ID: 20, Name: "g-empty", Platform: "anthropic", RateMultiplier: 0.5},
|
||||
}
|
||||
svc := newPlazaChannelService(channels, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService(channels, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1, "无模型的分组不应返回")
|
||||
require.Equal(t, int64(10), out[0].ID)
|
||||
@@ -71,8 +70,8 @@ func TestListPlazaGroups_DedupFirstWinsWithPricingUpgrade(t *testing.T) {
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: "anthropic", RateMultiplier: 1}}
|
||||
|
||||
// alpha(无价)按名称序先于 beta(有价):先见者无价,应被有价条目升级。
|
||||
svc := newPlazaChannelService([]Channel{priced, unpriced}, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService([]Channel{priced, unpriced}, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1)
|
||||
require.Len(t, out[0].Models, 1)
|
||||
@@ -93,8 +92,8 @@ func TestListPlazaGroups_PlatformIsolation(t *testing.T) {
|
||||
{ID: 10, Name: "g-claude", Platform: "anthropic", RateMultiplier: 1},
|
||||
{ID: 20, Name: "g-gpt", Platform: "openai", RateMultiplier: 1},
|
||||
}
|
||||
svc := newPlazaChannelService([]Channel{ch}, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService([]Channel{ch}, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 2)
|
||||
byName := map[string][]PlazaModel{}
|
||||
@@ -122,7 +121,7 @@ func TestListPlazaGroups_CompositeIncludesConfiguredConcretePlatforms(t *testing
|
||||
}
|
||||
groups := []Group{{ID: 10, Name: "composite", Platform: PlatformComposite, RateMultiplier: 1}}
|
||||
|
||||
out, err := newPlazaChannelService([]Channel{ch}, groups, nil).ListPlazaGroups(context.Background())
|
||||
out, err := newPlazaService([]Channel{ch}, groups, nil).ListGroups(context.Background())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1)
|
||||
@@ -146,7 +145,7 @@ func TestListPlazaGroups_CompositeAndOrdinaryGroupsDoNotLeakPlatforms(t *testing
|
||||
{ID: 20, Name: "composite", Platform: PlatformComposite, RateMultiplier: 1},
|
||||
}
|
||||
|
||||
out, err := newPlazaChannelService([]Channel{ch}, groups, nil).ListPlazaGroups(context.Background())
|
||||
out, err := newPlazaService([]Channel{ch}, groups, nil).ListGroups(context.Background())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 2)
|
||||
@@ -173,8 +172,8 @@ func TestListPlazaGroups_InactiveChannelSkipped(t *testing.T) {
|
||||
inactive := plazaPricedChannel(1, "off", []int64{10}, "anthropic", "claude-sonnet")
|
||||
inactive.Status = "inactive"
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: "anthropic", RateMultiplier: 1}}
|
||||
svc := newPlazaChannelService([]Channel{inactive}, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService([]Channel{inactive}, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, out)
|
||||
}
|
||||
@@ -188,8 +187,8 @@ func TestListPlazaGroups_SortedByRateMultiplierAsc(t *testing.T) {
|
||||
{ID: 20, Name: "a-standard", Platform: "anthropic", RateMultiplier: 1},
|
||||
{ID: 30, Name: "cheap", Platform: "anthropic", RateMultiplier: 0.5},
|
||||
}
|
||||
svc := newPlazaChannelService(channels, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService(channels, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 3)
|
||||
require.Equal(t, "cheap", out[0].Name, "倍率低者在前")
|
||||
@@ -213,8 +212,11 @@ func TestListPlazaGroups_OfficialPricingFill(t *testing.T) {
|
||||
plazaPricedChannel(1, "ch", []int64{10}, "anthropic", "claude-sonnet", "unknown-model", "token-absent"),
|
||||
}
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: "anthropic", RateMultiplier: 1}}
|
||||
svc := newPlazaChannelService(channels, groups, pricingSvc)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService(channels, groups, pricingSvc)
|
||||
// 官方价与计费同源:需要计费服务与解析器(官方参考不查渠道,解析器无需渠道服务)。
|
||||
svc.billingService = NewBillingService(&config.Config{}, pricingSvc)
|
||||
svc.resolver = NewModelPricingResolver(nil, svc.billingService)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1)
|
||||
require.Len(t, out[0].Models, 3)
|
||||
@@ -256,8 +258,8 @@ func TestListPlazaGroups_GroupImagePriceOverridesChannelPricing(t *testing.T) {
|
||||
ImagePrice1K: &imgPrice, ImageRateIndependent: true, ImageRateMultiplier: 1},
|
||||
{ID: 20, Name: "g-plain", Platform: "openai", RateMultiplier: 0.1},
|
||||
}
|
||||
svc := newPlazaChannelService(channels, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService(channels, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 2)
|
||||
byName := map[string]PlazaGroup{}
|
||||
@@ -298,8 +300,8 @@ func TestListPlazaGroups_GroupImagePriceIgnoredForNonImageModes(t *testing.T) {
|
||||
imgPrice := 0.02
|
||||
channels := []Channel{plazaPricedChannel(1, "ch", []int64{10}, "openai", "gpt-5")}
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: "openai", RateMultiplier: 1, ImagePrice1K: &imgPrice}}
|
||||
svc := newPlazaChannelService(channels, groups, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := newPlazaService(channels, groups, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1)
|
||||
p := out[0].Models[0].Pricing
|
||||
@@ -314,17 +316,180 @@ func TestListPlazaGroups_RepoErrorsPropagate(t *testing.T) {
|
||||
repo := &mockChannelRepository{
|
||||
listAllFn: func(ctx context.Context) ([]Channel, error) { return nil, sentinel },
|
||||
}
|
||||
svc := NewChannelService(repo, &stubGroupRepoForAvailable{}, nil, nil)
|
||||
out, err := svc.ListPlazaGroups(context.Background())
|
||||
svc := NewModelPlazaService(repo, &stubGroupRepoForAvailable{}, nil, nil, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.Nil(t, out)
|
||||
require.ErrorIs(t, err, sentinel)
|
||||
|
||||
svc2 := NewChannelService(
|
||||
svc2 := NewModelPlazaService(
|
||||
&mockChannelRepository{listAllFn: func(ctx context.Context) ([]Channel, error) { return nil, nil }},
|
||||
&stubGroupRepoForAvailable{listActiveErr: sentinel},
|
||||
nil, nil,
|
||||
nil, nil, nil,
|
||||
)
|
||||
out2, err2 := svc2.ListPlazaGroups(context.Background())
|
||||
out2, err2 := svc2.ListGroups(context.Background())
|
||||
require.Nil(t, out2)
|
||||
require.ErrorIs(t, err2, sentinel)
|
||||
}
|
||||
|
||||
// newPlazaServiceWithBilling 构造接入计费服务与解析器的广场服务:解析器的渠道服务与广场共用同一份渠道数据。
|
||||
func newPlazaServiceWithBilling(channels []Channel, groups []Group, groupPlatforms map[int64]string, catalog *PricingService) *ModelPlazaService {
|
||||
repo := &mockChannelRepository{
|
||||
listAllFn: func(ctx context.Context) ([]Channel, error) { return channels, nil },
|
||||
getGroupPlatformsFn: func(ctx context.Context, _ []int64) (map[int64]string, error) {
|
||||
return groupPlatforms, nil
|
||||
},
|
||||
}
|
||||
cs := NewChannelService(repo, nil, nil, nil)
|
||||
bs := NewBillingService(&config.Config{}, catalog)
|
||||
return NewModelPlazaService(repo, &stubGroupRepoForAvailable{activeGroups: groups}, catalog, bs, NewModelPricingResolver(cs, bs))
|
||||
}
|
||||
|
||||
func plazaModelsByName(models []PlazaModel) map[string]PlazaModel {
|
||||
out := make(map[string]PlazaModel, len(models))
|
||||
for _, m := range models {
|
||||
out[m.Name] = m
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestListGroups_TokenLadderFollowsGroupToggle(t *testing.T) {
|
||||
// 同一渠道挂开启/关闭阶梯的两个分组:实付档位随分组开关,官方阶梯不受影响。
|
||||
channels := []Channel{{
|
||||
ID: 1, Name: "ch", Status: StatusActive, GroupIDs: []int64{10, 20},
|
||||
ModelPricing: []ChannelModelPricing{{Platform: PlatformOpenAI, Models: []string{"gpt-5.4"}, BillingMode: BillingModeToken}},
|
||||
}}
|
||||
groups := []Group{
|
||||
{ID: 10, Name: "on", Platform: PlatformOpenAI, RateMultiplier: 1, LongContextPricingEnabled: true},
|
||||
{ID: 20, Name: "off", Platform: PlatformOpenAI, RateMultiplier: 2, LongContextPricingEnabled: false},
|
||||
}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformOpenAI, 20: PlatformOpenAI}, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 2)
|
||||
|
||||
on, off := out[0], out[1]
|
||||
require.True(t, on.LongContextPricingEnabled)
|
||||
require.False(t, off.LongContextPricingEnabled)
|
||||
|
||||
onModel := on.Models[0]
|
||||
require.Equal(t, ContextPricingBasisWholeRequest, onModel.LongContextBasis)
|
||||
require.Len(t, onModel.Pricing.Intervals, 2)
|
||||
require.Equal(t, "≤272K", onModel.Pricing.Intervals[0].TierLabel)
|
||||
require.Equal(t, ">272K", onModel.Pricing.Intervals[1].TierLabel)
|
||||
require.InDelta(t, 2.5e-6, *onModel.Pricing.InputPrice, 1e-15)
|
||||
require.InDelta(t, 5e-6, *onModel.Pricing.Intervals[1].InputPrice, 1e-15)
|
||||
require.InDelta(t, 22.5e-6, *onModel.Pricing.Intervals[1].OutputPrice, 1e-15)
|
||||
require.InDelta(t, 5e-6, *onModel.Pricing.Intervals[1].CacheWritePrice, 1e-15)
|
||||
require.InDelta(t, 0.5e-6, *onModel.Pricing.Intervals[1].CacheReadPrice, 1e-15)
|
||||
|
||||
offModel := off.Models[0]
|
||||
require.Empty(t, offModel.LongContextBasis)
|
||||
require.Empty(t, offModel.Pricing.Intervals)
|
||||
require.InDelta(t, 2.5e-6, *offModel.Pricing.InputPrice, 1e-15)
|
||||
|
||||
for _, m := range []PlazaModel{onModel, offModel} {
|
||||
require.NotNil(t, m.OfficialPricing)
|
||||
require.Len(t, m.OfficialPricing.Intervals, 2, "官方阶梯不受分组开关影响")
|
||||
require.InDelta(t, 5e-6, *m.OfficialPricing.Intervals[1].InputPrice, 1e-15)
|
||||
require.InDelta(t, 2.5e-6, *m.OfficialPricing.InputPrice, 1e-15)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListGroups_GeminiLegacyRuleShownAsMarginal(t *testing.T) {
|
||||
channels := []Channel{{
|
||||
ID: 1, Name: "ch", Status: StatusActive, GroupIDs: []int64{10},
|
||||
ModelMapping: map[string]map[string]string{PlatformGemini: {"gemini-2.5-pro": "gemini-2.5-pro"}},
|
||||
}}
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: PlatformGemini, RateMultiplier: 1, LongContextPricingEnabled: true}}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformGemini}, geminiCatalogStub())
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, out, 1)
|
||||
m := out[0].Models[0]
|
||||
require.Equal(t, ContextPricingBasisMarginal, m.LongContextBasis)
|
||||
require.Len(t, m.Pricing.Intervals, 2)
|
||||
require.Equal(t, "≤200K", m.Pricing.Intervals[0].TierLabel)
|
||||
require.Equal(t, ">200K", m.Pricing.Intervals[1].TierLabel)
|
||||
require.InDelta(t, 2.5e-6, *m.Pricing.Intervals[1].InputPrice, 1e-15)
|
||||
require.InDelta(t, 10e-6, *m.Pricing.Intervals[1].OutputPrice, 1e-15)
|
||||
// 官方参考不套用站内旧规则
|
||||
require.NotNil(t, m.OfficialPricing)
|
||||
require.Empty(t, m.OfficialPricing.Intervals)
|
||||
}
|
||||
|
||||
func TestListGroups_GroupTokenCardOverridesChannelPricing(t *testing.T) {
|
||||
channels := []Channel{plazaPricedChannel(1, "ch", []int64{10}, PlatformAnthropic, "claude-sonnet-4")}
|
||||
groups := []Group{{
|
||||
ID: 10, Name: "g", Platform: PlatformAnthropic, RateMultiplier: 1, LongContextPricingEnabled: true,
|
||||
ModelPricing: []ChannelModelPricing{{Models: []string{"claude-sonnet-*"}, BillingMode: BillingModeToken, InputPrice: testPtrFloat64(1e-6)}},
|
||||
}}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformAnthropic}, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
m := out[0].Models[0]
|
||||
require.InDelta(t, 1e-6, *m.Pricing.InputPrice, 1e-15, "分组价卡优先于渠道平价")
|
||||
require.InDelta(t, 15e-6, *m.Pricing.OutputPrice, 1e-15, "卡未配置的项回落目录价")
|
||||
require.Empty(t, m.Pricing.Intervals)
|
||||
}
|
||||
|
||||
func TestListGroups_ImageModelKeepsTierSynthesisWithBilling(t *testing.T) {
|
||||
channels := []Channel{{
|
||||
ID: 1, Name: "ch", Status: StatusActive, GroupIDs: []int64{10},
|
||||
ModelPricing: []ChannelModelPricing{{
|
||||
Platform: PlatformOpenAI, Models: []string{"gpt-image-2"}, BillingMode: BillingModeImage,
|
||||
PerRequestPrice: testPtrFloat64(0.04),
|
||||
}},
|
||||
}}
|
||||
groups := []Group{{
|
||||
ID: 10, Name: "g", Platform: PlatformOpenAI, RateMultiplier: 1, LongContextPricingEnabled: true,
|
||||
ImagePrice1K: testPtrFloat64(0.02),
|
||||
}}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformOpenAI}, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
m := out[0].Models[0]
|
||||
require.Equal(t, BillingModeImage, m.Pricing.BillingMode)
|
||||
require.Empty(t, m.LongContextBasis)
|
||||
require.Len(t, m.Pricing.Intervals, 3)
|
||||
require.InDelta(t, 0.02, *m.Pricing.Intervals[0].PerRequestPrice, 1e-12)
|
||||
require.InDelta(t, 0.04, *m.Pricing.Intervals[1].PerRequestPrice, 1e-12)
|
||||
}
|
||||
|
||||
func TestListGroups_CatalogMissingStillShowsChannelFlatPricing(t *testing.T) {
|
||||
// 目录查不到的模型:计费按渠道平价(未配置项 $0),广场单档展示渠道平价,官方价为空。
|
||||
channels := []Channel{plazaPricedChannel(1, "ch", []int64{10}, PlatformAnthropic, "unknown-model-xyz")}
|
||||
groups := []Group{{ID: 10, Name: "g", Platform: PlatformAnthropic, RateMultiplier: 1, LongContextPricingEnabled: true}}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformAnthropic}, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
m := out[0].Models[0]
|
||||
require.NotNil(t, m.Pricing)
|
||||
require.InDelta(t, 3e-6, *m.Pricing.InputPrice, 1e-15)
|
||||
require.Empty(t, m.Pricing.Intervals)
|
||||
require.Nil(t, m.Pricing.CacheWritePrice, "目录无价且渠道未配置 → 无价")
|
||||
require.Nil(t, m.OfficialPricing)
|
||||
}
|
||||
|
||||
func TestListGroups_TimePricingPassthrough(t *testing.T) {
|
||||
channels := []Channel{{
|
||||
ID: 1, Name: "ch", Status: StatusActive, GroupIDs: []int64{10},
|
||||
ModelPricing: []ChannelModelPricing{{
|
||||
Platform: PlatformDeepseek, Models: []string{"deepseek-chat"}, BillingMode: BillingModeToken,
|
||||
InputPrice: testPtrFloat64(0.28e-6), OutputPrice: testPtrFloat64(0.42e-6),
|
||||
TimePricing: &ChannelTimePricing{Timezone: "Asia/Shanghai", Periods: []ChannelTimePricingPeriod{
|
||||
{StartTime: "00:30", EndTime: "08:30", Multiplier: 0.5},
|
||||
}},
|
||||
}},
|
||||
}}
|
||||
groups := []Group{{ID: 10, Name: "cn", Platform: PlatformDeepseek, RateMultiplier: 1, LongContextPricingEnabled: true}}
|
||||
svc := newPlazaServiceWithBilling(channels, groups, map[int64]string{10: PlatformDeepseek}, nil)
|
||||
out, err := svc.ListGroups(context.Background())
|
||||
require.NoError(t, err)
|
||||
m := out[0].Models[0]
|
||||
require.NotNil(t, m.TimePricing)
|
||||
require.Equal(t, "Asia/Shanghai", m.TimePricing.Timezone)
|
||||
require.Len(t, m.TimePricing.Periods, 1)
|
||||
require.InDelta(t, 0.5, m.TimePricing.Periods[0].Multiplier, 1e-12)
|
||||
// 展示单价为标准时段价
|
||||
require.InDelta(t, 0.28e-6, *m.Pricing.InputPrice, 1e-15)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package service
|
||||
|
||||
import "github.com/Wei-Shaw/sub2api/internal/config"
|
||||
|
||||
func resolveModelsListReadLimit(cfg *config.Config) int64 {
|
||||
if cfg != nil && cfg.Gateway.ModelsListReadMaxBytes > 0 {
|
||||
return cfg.Gateway.ModelsListReadMaxBytes
|
||||
}
|
||||
return config.DefaultModelsListReadMaxBytes
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResolveModelsListReadLimit(t *testing.T) {
|
||||
t.Run("nil config uses default", func(t *testing.T) {
|
||||
require.Equal(t, config.DefaultModelsListReadMaxBytes, resolveModelsListReadLimit(nil))
|
||||
})
|
||||
|
||||
t.Run("configured limit wins", func(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.ModelsListReadMaxBytes = 16 << 20
|
||||
require.Equal(t, int64(16<<20), resolveModelsListReadLimit(cfg))
|
||||
})
|
||||
|
||||
t.Run("non-positive limit uses default", func(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
require.Equal(t, config.DefaultModelsListReadMaxBytes, resolveModelsListReadLimit(cfg))
|
||||
})
|
||||
}
|
||||
@@ -1780,6 +1780,9 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con
|
||||
// rechecks won't reach healthy accounts that fell outside TopK — manifesting as
|
||||
// "no available accounts" even though healthy ones exist.
|
||||
if paused, decision := shouldAutoPauseOpenAIAccountByQuota(ctx, account); paused {
|
||||
if decision.reason != "" {
|
||||
return false, decision.reason
|
||||
}
|
||||
reason := "quota_auto_pause"
|
||||
if decision.window != "" {
|
||||
reason += "_" + decision.window
|
||||
|
||||
@@ -466,6 +466,75 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_DefaultDisabledUsesLega
|
||||
require.False(t, decision.StickyPreviousHit)
|
||||
}
|
||||
|
||||
// Regression: the legacy load-batch path had two bare ErrNoAvailableAccounts
|
||||
// exits that bypassed the diagnostics added for both the advanced scheduler and
|
||||
// the non-batched legacy selector. This is the default path when load batching
|
||||
// is enabled, so quota auto-pause could still surface as an opaque 503.
|
||||
func TestOpenAIGatewayService_SelectAccountWithScheduler_DefaultDisabled_LoadBatchReportsFilterReasons(t *testing.T) {
|
||||
resetOpenAIAdvancedSchedulerSettingCacheForTest()
|
||||
|
||||
ctx := withOpenAIQuotaAutoPauseSettings(context.Background(), OpsOpenAIAccountQuotaAutoPauseSettings{DefaultThreshold7d: 0.9})
|
||||
groupID := int64(10107)
|
||||
quotaPaused := Account{
|
||||
ID: 36003,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Extra: map[string]any{
|
||||
"codex_7d_used_percent": 95.0,
|
||||
"codex_7d_reset_at": time.Now().Add(24 * time.Hour).Format(time.RFC3339),
|
||||
"codex_usage_updated_at": time.Now().Add(-time.Minute).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
mappingMiss := Account{
|
||||
ID: 36004,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"gpt-4o": "gpt-4o"},
|
||||
},
|
||||
}
|
||||
excluded := Account{
|
||||
ID: 36005,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
}
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.Scheduling.LoadBatchEnabled = true
|
||||
svc := &OpenAIGatewayService{
|
||||
accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{quotaPaused, mappingMiss, excluded}},
|
||||
cache: &schedulerTestGatewayCache{},
|
||||
cfg: cfg,
|
||||
concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}),
|
||||
}
|
||||
|
||||
require.False(t, svc.isOpenAIAdvancedSchedulerEnabled(ctx))
|
||||
selection, decision, err := svc.SelectAccountWithScheduler(
|
||||
ctx,
|
||||
&groupID,
|
||||
"",
|
||||
"",
|
||||
"gpt-5.4-mini",
|
||||
map[int64]struct{}{excluded.ID: {}},
|
||||
OpenAIUpstreamTransportAny,
|
||||
false,
|
||||
)
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, ErrNoAvailableAccounts)
|
||||
require.Nil(t, selection)
|
||||
require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer)
|
||||
require.EqualError(t, err, "no available OpenAI accounts supporting model: gpt-5.4-mini (pool=3, filtered: excluded=1 model_not_supported=1 quota_auto_pause_7d=1)")
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_SelectAccountWithScheduler_DefaultDisabled_RequiredWSV2_SkipsHTTPOnlyAccount(t *testing.T) {
|
||||
resetOpenAIAdvancedSchedulerSettingCacheForTest()
|
||||
|
||||
|
||||
@@ -133,8 +133,8 @@ func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *test
|
||||
require.Equal(t, "account-agent-passthrough", req.Header.Get("chatgpt-account-id"))
|
||||
require.NotEqual(t, "client-session", req.Header.Get("session_id"))
|
||||
require.NotEqual(t, "client-conversation", req.Header.Get("conversation_id"))
|
||||
require.Equal(t, isolateOpenAISessionID(0, "client-session"), req.Header.Get("session_id"))
|
||||
require.Equal(t, isolateOpenAISessionID(0, "client-conversation"), req.Header.Get("conversation_id"))
|
||||
require.Equal(t, isolateOpenAIUpstreamSessionID(0, account, "client-session"), req.Header.Get("session_id"))
|
||||
require.Equal(t, isolateOpenAIUpstreamSessionID(0, account, "client-conversation"), req.Header.Get("conversation_id"))
|
||||
requestBody, err := io.ReadAll(req.Body)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(requestBody), `"prompt_cache_key":"cache-agent"`)
|
||||
@@ -147,7 +147,7 @@ func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *test
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"chatgpt_account_id": "account-oauth-passthrough",
|
||||
"chatgpt_account_id": "account-agent-passthrough",
|
||||
},
|
||||
}
|
||||
oauthRecorder := httptest.NewRecorder()
|
||||
|
||||
@@ -30,6 +30,9 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
|
||||
if s == nil || c == nil || account == nil {
|
||||
return nil, fmt.Errorf("service, context, and account are required")
|
||||
}
|
||||
if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modelResult := gjson.GetBytes(body, "model")
|
||||
requestedModel := strings.TrimSpace(modelResult.String())
|
||||
if modelResult.Type != gjson.String || requestedModel == "" {
|
||||
@@ -272,10 +275,11 @@ func (s *OpenAIGatewayService) buildOpenAIAlphaSearchResponsesWebSearchRequest(c
|
||||
}
|
||||
apiKeyID := getAPIKeyIDFromContext(c)
|
||||
if sessionID := strings.TrimSpace(gjson.GetBytes(alphaBody, "id").String()); sessionID != "" {
|
||||
isolated := isolateOpenAISessionID(apiKeyID, sessionID)
|
||||
isolated := isolateOpenAIUpstreamSessionID(apiKeyID, codexAccountIdentitySource(c, account), sessionID)
|
||||
req.Header.Set("Session_ID", isolated)
|
||||
req.Header.Set("Conversation_ID", isolated)
|
||||
}
|
||||
applyCodexAccountIdentityHeaders(req.Header, codexAccountIdentitySource(c, account), apiKeyID)
|
||||
enforceCodexIdentityHeadersWithUA(req.Header, s.codexIdentityOverrideUA(account))
|
||||
account.ApplyHeaderOverrides(req.Header)
|
||||
return req, nil
|
||||
@@ -393,6 +397,7 @@ func (s *OpenAIGatewayService) buildOpenAIAlphaSearchRequest(ctx context.Context
|
||||
if turnMetadata := openAIAlphaSearchInboundHeader(c, "X-Codex-Turn-Metadata"); turnMetadata != "" {
|
||||
req.Header.Set("X-Codex-Turn-Metadata", turnMetadata)
|
||||
}
|
||||
applyCodexAccountIdentityHeaders(req.Header, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c))
|
||||
canonical := resolveCodexOutboundIdentity("")
|
||||
if version := openAIAlphaSearchInboundHeader(c, "Version"); version != "" {
|
||||
req.Header.Set("Version", version)
|
||||
|
||||
@@ -59,6 +59,7 @@ func TestForwardAlphaSearchOAuthPreservesWire(t *testing.T) {
|
||||
c.Request.Header.Set("User-Agent", codexCLIUserAgent)
|
||||
c.Request.Header.Set("Originator", "codex_cli_rs")
|
||||
c.Request.Header.Set("Version", "0.144.1")
|
||||
c.Request.Header.Set("X-Codex-Turn-Metadata", `{"session_id":"search-session","turn_id":"search-turn"}`)
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
@@ -92,6 +93,14 @@ func TestForwardAlphaSearchOAuthPreservesWire(t *testing.T) {
|
||||
require.Equal(t, "application/json", upstream.lastReq.Header.Get("Accept"))
|
||||
require.Equal(t, codexCLIVersion, upstream.lastReq.Header.Get("Version"))
|
||||
require.Empty(t, upstream.lastReq.Header.Get("OpenAI-Beta"))
|
||||
require.Equal(t,
|
||||
scopeCodexAccountIdentityValue(account, 0, "session", "search-session"),
|
||||
gjson.Get(upstream.lastReq.Header.Get("X-Codex-Turn-Metadata"), "session_id").String(),
|
||||
)
|
||||
require.Equal(t,
|
||||
scopeCodexAccountIdentityValue(account, 0, "turn", "search-turn"),
|
||||
gjson.Get(upstream.lastReq.Header.Get("X-Codex-Turn-Metadata"), "turn_id").String(),
|
||||
)
|
||||
require.JSONEq(t, string(body), string(upstream.lastBody))
|
||||
}
|
||||
|
||||
@@ -156,7 +165,10 @@ func TestForwardAlphaSearchPATUsesResponsesWebSearchFallback(t *testing.T) {
|
||||
require.Equal(t, "text/event-stream", upstream.lastReq.Header.Get("Accept"))
|
||||
require.Equal(t, "responses=experimental", upstream.lastReq.Header.Get("OpenAI-Beta"))
|
||||
require.Equal(t, codexCLIVersion, upstream.lastReq.Header.Get("Version"))
|
||||
require.Equal(t, `{"turn_id":"turn-1"}`, upstream.lastReq.Header.Get("X-Codex-Turn-Metadata"))
|
||||
require.Equal(t,
|
||||
scopeCodexAccountIdentityValue(account, 0, "turn", "turn-1"),
|
||||
gjson.Get(upstream.lastReq.Header.Get("X-Codex-Turn-Metadata"), "turn_id").String(),
|
||||
)
|
||||
require.Equal(t, openai.CodexDefaultOriginator, upstream.lastReq.Header.Get("Originator"))
|
||||
require.Empty(t, upstream.lastReq.Header.Get("X-Codex-Beta-Features"))
|
||||
require.Empty(t, upstream.lastReq.Header.Get("X-Codex-Turn-State"))
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
const codexAccountIdentityNamespaceVersion = "v1"
|
||||
|
||||
const codexAccountIdentitySourceContextKey = "openai_codex_account_identity_source"
|
||||
|
||||
// prepareCodexAccountIdentitySource resolves credential shadows once per selected
|
||||
// attempt. The handler reuses gin.Context across failover attempts, so every entry
|
||||
// point overwrites the staged source before projecting outbound identity.
|
||||
func (s *OpenAIGatewayService) prepareCodexAccountIdentitySource(ctx context.Context, c *gin.Context, account *Account) (*Account, error) {
|
||||
source := account
|
||||
if account != nil && account.IsShadow() {
|
||||
resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source = resolved
|
||||
}
|
||||
if c != nil {
|
||||
c.Set(codexAccountIdentitySourceContextKey, source)
|
||||
}
|
||||
return source, nil
|
||||
}
|
||||
|
||||
func codexAccountIdentitySource(c *gin.Context, fallback *Account) *Account {
|
||||
if c != nil {
|
||||
if staged, ok := c.Get(codexAccountIdentitySourceContextKey); ok {
|
||||
if source, ok := staged.(*Account); ok && source != nil {
|
||||
return source
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// codexAccountIdentityNamespace returns a stable, credential-scoped namespace.
|
||||
// Multiple local rows that use the same ChatGPT account intentionally share the
|
||||
// same namespace. Setup tokens use an irreversible bearer fingerprint because
|
||||
// they have no refresh lifecycle or imported account metadata. Refreshable OAuth
|
||||
// otherwise falls back only to a persistent fingerprint seed: local row IDs are
|
||||
// deployment-relative and must never become upstream identity.
|
||||
func codexAccountIdentityNamespace(account *Account) string {
|
||||
if account == nil || !account.IsOpenAIOAuthLike() {
|
||||
return ""
|
||||
}
|
||||
if upstreamAccountID := strings.TrimSpace(account.GetChatGPTAccountID()); upstreamAccountID != "" {
|
||||
if upstreamUserID := strings.TrimSpace(account.GetCredential("chatgpt_user_id")); upstreamUserID != "" {
|
||||
return "chatgpt:" + upstreamAccountID + ":user:" + upstreamUserID
|
||||
}
|
||||
return "chatgpt:" + upstreamAccountID
|
||||
}
|
||||
if seed, ok := codexFingerprintSeed(account.Extra); ok {
|
||||
return "seed:" + seed
|
||||
}
|
||||
if account.Type == AccountTypeSetupToken {
|
||||
if token := strings.TrimSpace(account.GetOpenAIAccessToken()); token != "" {
|
||||
sum := sha256.Sum256([]byte("openai-setup-token:" + token))
|
||||
return fmt.Sprintf("setup-token:%x", sum[:16])
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// isolateOpenAIUpstreamSessionID preserves the existing API-key isolation while
|
||||
// adding the selected OAuth credential namespace. A scheduler failover therefore
|
||||
// cannot send the same session/conversation identity through two upstream accounts.
|
||||
func isolateOpenAIUpstreamSessionID(apiKeyID int64, account *Account, raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
namespace := codexAccountIdentityNamespace(account)
|
||||
if namespace == "" {
|
||||
return isolateOpenAISessionID(apiKeyID, raw)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("u%d:a%s:%s", apiKeyID, namespace, raw)))
|
||||
return fmt.Sprintf("%x", sum[:8])
|
||||
}
|
||||
|
||||
func scopeCodexAccountIdentityValue(account *Account, apiKeyID int64, kind, raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
namespace := codexAccountIdentityNamespace(account)
|
||||
if raw == "" || namespace == "" {
|
||||
return raw
|
||||
}
|
||||
return deriveStableUUIDv4(fmt.Sprintf(
|
||||
"sub2api:codex-account-identity:%s:user:%d:account:%s:kind:%s:value:%s",
|
||||
codexAccountIdentityNamespaceVersion,
|
||||
apiKeyID,
|
||||
namespace,
|
||||
kind,
|
||||
raw,
|
||||
))
|
||||
}
|
||||
|
||||
var codexAccountIdentityFields = []struct {
|
||||
name string
|
||||
kind string
|
||||
}{
|
||||
{name: "installation_id", kind: "installation"},
|
||||
{name: "x-codex-installation-id", kind: "installation"},
|
||||
{name: "session_id", kind: "session"},
|
||||
{name: "session-id", kind: "session"},
|
||||
{name: "thread_id", kind: "thread"},
|
||||
{name: "thread-id", kind: "thread"},
|
||||
{name: "turn_id", kind: "turn"},
|
||||
{name: "turn-id", kind: "turn"},
|
||||
{name: "window_id", kind: "window"},
|
||||
{name: "x-codex-window-id", kind: "window"},
|
||||
{name: "x-client-request-id", kind: "request"},
|
||||
}
|
||||
|
||||
func applyCodexAccountIdentityFields(values map[string]any, account *Account, apiKeyID int64) bool {
|
||||
if values == nil || codexAccountIdentityNamespace(account) == "" {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
for _, field := range codexAccountIdentityFields {
|
||||
raw, ok := values[field.name].(string)
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
continue
|
||||
}
|
||||
next := scopeCodexAccountIdentityValue(account, apiKeyID, field.kind, raw)
|
||||
if next != raw {
|
||||
values[field.name] = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func applyCodexAccountIdentityEmbeddedMetadata(values map[string]any, account *Account, apiKeyID int64) bool {
|
||||
raw, ok := values[openAIWSTurnMetadataHeader].(string)
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
return false
|
||||
}
|
||||
metadata := map[string]any{}
|
||||
if err := json.Unmarshal([]byte(raw), &metadata); err != nil || metadata == nil {
|
||||
return false
|
||||
}
|
||||
if !applyCodexAccountIdentityFields(metadata, account, apiKeyID) {
|
||||
return false
|
||||
}
|
||||
rebuilt, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
values[openAIWSTurnMetadataHeader] = string(rebuilt)
|
||||
return true
|
||||
}
|
||||
|
||||
func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, account *Account, apiKeyID int64) bool {
|
||||
if requestBody == nil || codexAccountIdentityNamespace(account) == "" {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
clientMetadata, _ := requestBody["client_metadata"].(map[string]any)
|
||||
originalBodySessionID := ""
|
||||
if clientMetadata != nil {
|
||||
originalBodySessionID, _ = clientMetadata["session_id"].(string)
|
||||
if applyCodexAccountIdentityFields(clientMetadata, account, apiKeyID) {
|
||||
changed = true
|
||||
}
|
||||
if applyCodexAccountIdentityEmbeddedMetadata(clientMetadata, account, apiKeyID) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if raw, ok := requestBody["prompt_cache_key"].(string); ok && strings.TrimSpace(raw) != "" {
|
||||
kind := "prompt-cache"
|
||||
if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID {
|
||||
kind = "session"
|
||||
}
|
||||
next := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw)
|
||||
if next != raw {
|
||||
requestBody["prompt_cache_key"] = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// applyCodexAccountIdentityClientMetadataRaw scopes only the small identity
|
||||
// subobjects with gjson/sjson. The passthrough hot path never unmarshals the
|
||||
// potentially multi-megabyte request body.
|
||||
func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, apiKeyID int64) ([]byte, bool, error) {
|
||||
if len(body) == 0 || codexAccountIdentityNamespace(account) == "" {
|
||||
return body, false, nil
|
||||
}
|
||||
root := gjson.ParseBytes(body)
|
||||
if !root.IsObject() {
|
||||
return body, false, nil
|
||||
}
|
||||
|
||||
next := body
|
||||
changed := false
|
||||
originalBodySessionID := ""
|
||||
if cm := gjson.GetBytes(body, "client_metadata"); cm.IsObject() {
|
||||
clientMetadata := map[string]any{}
|
||||
if err := json.Unmarshal([]byte(cm.Raw), &clientMetadata); err != nil {
|
||||
return body, false, fmt.Errorf("decode client_metadata for account identity: %w", err)
|
||||
}
|
||||
originalBodySessionID, _ = clientMetadata["session_id"].(string)
|
||||
metadataChanged := applyCodexAccountIdentityFields(clientMetadata, account, apiKeyID)
|
||||
if applyCodexAccountIdentityEmbeddedMetadata(clientMetadata, account, apiKeyID) {
|
||||
metadataChanged = true
|
||||
}
|
||||
if metadataChanged {
|
||||
raw, err := json.Marshal(clientMetadata)
|
||||
if err != nil {
|
||||
return body, false, fmt.Errorf("encode account-scoped client_metadata: %w", err)
|
||||
}
|
||||
var setErr error
|
||||
next, setErr = sjson.SetRawBytes(next, "client_metadata", raw)
|
||||
if setErr != nil {
|
||||
return body, false, fmt.Errorf("splice account-scoped client_metadata: %w", setErr)
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if promptCacheKey := gjson.GetBytes(body, "prompt_cache_key"); promptCacheKey.Type == gjson.String && strings.TrimSpace(promptCacheKey.String()) != "" {
|
||||
raw := promptCacheKey.String()
|
||||
kind := "prompt-cache"
|
||||
if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID {
|
||||
kind = "session"
|
||||
}
|
||||
scoped := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw)
|
||||
if scoped != raw {
|
||||
rewritten, err := sjson.SetBytes(next, "prompt_cache_key", scoped)
|
||||
if err != nil {
|
||||
return body, false, fmt.Errorf("splice account-scoped prompt_cache_key: %w", err)
|
||||
}
|
||||
next = rewritten
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return next, changed, nil
|
||||
}
|
||||
|
||||
func applyCodexAccountIdentityHeaders(headers http.Header, account *Account, apiKeyID int64) {
|
||||
if headers == nil || codexAccountIdentityNamespace(account) == "" {
|
||||
return
|
||||
}
|
||||
for _, field := range codexAccountIdentityFields {
|
||||
// Underscore session/conversation headers are rebuilt separately from the
|
||||
// prompt cache key by each request builder.
|
||||
if field.name == "session_id" {
|
||||
continue
|
||||
}
|
||||
raw := strings.TrimSpace(headers.Get(field.name))
|
||||
if raw != "" {
|
||||
headers.Set(field.name, scopeCodexAccountIdentityValue(account, apiKeyID, field.kind, raw))
|
||||
}
|
||||
}
|
||||
if raw := strings.TrimSpace(headers.Get(openAIWSTurnMetadataHeader)); raw != "" {
|
||||
metadata := map[string]any{}
|
||||
if err := json.Unmarshal([]byte(raw), &metadata); err == nil && metadata != nil && applyCodexAccountIdentityFields(metadata, account, apiKeyID) {
|
||||
if rebuilt, err := json.Marshal(metadata); err == nil {
|
||||
headers.Set(openAIWSTurnMetadataHeader, string(rebuilt))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type codexAccountIdentityRepoStub struct {
|
||||
AccountRepository
|
||||
account *Account
|
||||
}
|
||||
|
||||
func (s *codexAccountIdentityRepoStub) GetByID(_ context.Context, _ int64) (*Account, error) {
|
||||
return s.account, nil
|
||||
}
|
||||
|
||||
func TestCodexRequestBodyIdentityNamespaceIsStablePerOAuthAccount(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5.6-codex","prompt_cache_key":"client-session","client_metadata":{"x-codex-installation-id":"client-installation","session_id":"client-session","thread_id":"client-thread","x-codex-window-id":"client-window","x-codex-turn-metadata":"{\"installation_id\":\"client-installation\",\"session_id\":\"client-session\",\"thread_id\":\"client-thread\",\"turn_id\":\"client-turn\",\"window_id\":\"client-window\"}"}}`)
|
||||
account11 := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-11"}}
|
||||
account19 := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-19"}}
|
||||
|
||||
first, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
firstAgain, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
second, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account19, 77)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.JSONEq(t, string(first), string(firstAgain))
|
||||
|
||||
paths := []string{
|
||||
"prompt_cache_key",
|
||||
"client_metadata.x-codex-installation-id",
|
||||
"client_metadata.session_id",
|
||||
"client_metadata.thread_id",
|
||||
"client_metadata.x-codex-window-id",
|
||||
}
|
||||
for _, path := range paths {
|
||||
require.NotEqual(t, gjson.GetBytes(body, path).String(), gjson.GetBytes(first, path).String(), path)
|
||||
require.NotEqual(t, gjson.GetBytes(first, path).String(), gjson.GetBytes(second, path).String(), path)
|
||||
}
|
||||
require.Equal(t, gjson.GetBytes(first, "prompt_cache_key").String(), gjson.GetBytes(first, "client_metadata.session_id").String())
|
||||
|
||||
var embeddedFirst map[string]any
|
||||
var embeddedSecond map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(gjson.GetBytes(first, "client_metadata.x-codex-turn-metadata").String()), &embeddedFirst))
|
||||
require.NoError(t, json.Unmarshal([]byte(gjson.GetBytes(second, "client_metadata.x-codex-turn-metadata").String()), &embeddedSecond))
|
||||
for _, field := range []string{"installation_id", "session_id", "thread_id", "turn_id", "window_id"} {
|
||||
require.NotEqual(t, embeddedFirst[field], embeddedSecond[field], field)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexAccountIdentityNamespaceUsesStableCredentialSource(t *testing.T) {
|
||||
firstRow := &Account{ID: 8, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "shared-upstream-account"}}
|
||||
secondRow := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "shared-upstream-account"}}
|
||||
require.Equal(t, codexAccountIdentityNamespace(firstRow), codexAccountIdentityNamespace(secondRow))
|
||||
|
||||
firstUser := &Account{ID: 20, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "team-account", "chatgpt_user_id": "user-1"}}
|
||||
sameUser := &Account{ID: 21, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "team-account", "chatgpt_user_id": "user-1"}}
|
||||
secondUser := &Account{ID: 22, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "team-account", "chatgpt_user_id": "user-2"}}
|
||||
require.Equal(t, codexAccountIdentityNamespace(firstUser), codexAccountIdentityNamespace(sameUser))
|
||||
require.NotEqual(t, codexAccountIdentityNamespace(firstUser), codexAccountIdentityNamespace(secondUser))
|
||||
|
||||
seed := "11111111-1111-4111-8111-111111111111"
|
||||
seeded := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Extra: map[string]any{codexFingerprintSeedExtraKey: seed}}
|
||||
require.Equal(t, "seed:"+seed, codexAccountIdentityNamespace(seeded))
|
||||
|
||||
// Local row IDs repeat across independent deployments, so they are not a
|
||||
// safe fallback for upstream identity.
|
||||
require.Empty(t, codexAccountIdentityNamespace(&Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth}))
|
||||
|
||||
setupTokenA := &Account{ID: 30, Platform: PlatformOpenAI, Type: AccountTypeSetupToken, Credentials: map[string]any{"access_token": "setup-token-a"}}
|
||||
setupTokenADuplicate := &Account{ID: 31, Platform: PlatformOpenAI, Type: AccountTypeSetupToken, Credentials: map[string]any{"access_token": "setup-token-a"}}
|
||||
setupTokenB := &Account{ID: 32, Platform: PlatformOpenAI, Type: AccountTypeSetupToken, Credentials: map[string]any{"access_token": "setup-token-b"}}
|
||||
setupNamespace := codexAccountIdentityNamespace(setupTokenA)
|
||||
require.NotEmpty(t, setupNamespace)
|
||||
require.NotContains(t, setupNamespace, "setup-token-a")
|
||||
require.Equal(t, setupNamespace, codexAccountIdentityNamespace(setupTokenADuplicate))
|
||||
require.NotEqual(t, setupNamespace, codexAccountIdentityNamespace(setupTokenB))
|
||||
}
|
||||
|
||||
func TestCodexAccountIdentitySourceResolvesShadowAndOverwritesFailoverContext(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
|
||||
parentID := int64(11)
|
||||
parent := &Account{ID: parentID, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{
|
||||
"chatgpt_account_id": "team-account",
|
||||
"chatgpt_user_id": "user-1",
|
||||
}}
|
||||
shadow := &Account{ID: 111, ParentAccountID: &parentID, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
service := &OpenAIGatewayService{accountRepo: &codexAccountIdentityRepoStub{account: parent}}
|
||||
|
||||
resolved, err := service.prepareCodexAccountIdentitySource(context.Background(), c, shadow)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, parent, resolved)
|
||||
require.Same(t, parent, codexAccountIdentitySource(c, shadow))
|
||||
|
||||
req, err := service.buildUpstreamRequest(
|
||||
context.Background(), c, shadow,
|
||||
[]byte(`{"model":"gpt-5.6-codex","stream":true,"prompt_cache_key":"client-session"}`),
|
||||
"token", true, "client-session", true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, isolateOpenAIUpstreamSessionID(0, parent, "client-session"), req.Header.Get("session_id"))
|
||||
|
||||
next := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{
|
||||
"chatgpt_account_id": "other-account",
|
||||
"chatgpt_user_id": "user-2",
|
||||
}}
|
||||
resolved, err = service.prepareCodexAccountIdentitySource(context.Background(), c, next)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, next, resolved)
|
||||
require.Same(t, next, codexAccountIdentitySource(c, shadow))
|
||||
}
|
||||
|
||||
func TestBuildOpenAIWSHeadersNamespacesCodexIdentityByOAuthAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
|
||||
c.Set("api_key_id", int64(77))
|
||||
c.Request.Header.Set("x-codex-installation-id", "client-installation")
|
||||
c.Request.Header.Set("thread-id", "client-thread")
|
||||
c.Request.Header.Set("x-codex-window-id", "client-window")
|
||||
c.Request.Header.Set("x-client-request-id", "client-request")
|
||||
|
||||
account11 := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-11"}}
|
||||
account19 := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-19"}}
|
||||
service := &OpenAIGatewayService{}
|
||||
build := func(account *Account) http.Header {
|
||||
headers, _, err := service.buildOpenAIWSHeaders(
|
||||
context.Background(), c, account, "token",
|
||||
OpenAIWSProtocolDecision{Transport: OpenAIUpstreamTransportResponsesWebsocketV2},
|
||||
true, "", "", "client-session", "", "",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return headers
|
||||
}
|
||||
|
||||
first := build(account11)
|
||||
firstAgain := build(account11)
|
||||
second := build(account19)
|
||||
for _, header := range []string{"session_id", "x-codex-installation-id", "thread-id", "x-codex-window-id", "x-client-request-id"} {
|
||||
require.NotEmpty(t, first.Get(header), header)
|
||||
require.Equal(t, first.Get(header), firstAgain.Get(header), header)
|
||||
require.NotEqual(t, first.Get(header), second.Get(header), header)
|
||||
}
|
||||
|
||||
httpRequest, err := service.buildUpstreamRequest(
|
||||
context.Background(), c, account11,
|
||||
[]byte(`{"model":"gpt-5.6-codex","stream":true,"prompt_cache_key":"client-session"}`),
|
||||
"token", true, "client-session", true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, httpRequest.Header.Get("session_id"), first.Get("session_id"), "HTTP and WS must derive the same identity from the raw client key")
|
||||
}
|
||||
|
||||
func TestBuildUpstreamRequestNamespacesCodexIdentityByOAuthAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := &OpenAIGatewayService{}
|
||||
body := []byte(`{"model":"gpt-5.6-codex","stream":true,"prompt_cache_key":"client-session"}`)
|
||||
|
||||
build := func(accountID int64, chatgptAccountID string) http.Header {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Set("api_key", &APIKey{ID: 77})
|
||||
c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.0")
|
||||
c.Request.Header.Set("x-codex-installation-id", "client-installation")
|
||||
c.Request.Header.Set("x-codex-window-id", "client-window")
|
||||
c.Request.Header.Set("session-id", "client-session")
|
||||
c.Request.Header.Set("thread-id", "client-thread")
|
||||
c.Request.Header.Set("x-client-request-id", "client-request")
|
||||
c.Request.Header.Set("x-codex-turn-metadata", `{"installation_id":"client-installation","session_id":"client-session","thread_id":"client-thread","turn_id":"client-turn","window_id":"client-window"}`)
|
||||
|
||||
account := &Account{
|
||||
ID: accountID,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"chatgpt_account_id": chatgptAccountID,
|
||||
},
|
||||
}
|
||||
req, err := svc.buildUpstreamRequest(
|
||||
context.Background(), c, account, body, "oauth-token", true, "client-session", true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return req.Header
|
||||
}
|
||||
|
||||
first := build(11, "chatgpt-account-11")
|
||||
firstAgain := build(11, "chatgpt-account-11")
|
||||
second := build(19, "chatgpt-account-19")
|
||||
|
||||
identityHeaders := []string{
|
||||
"x-codex-installation-id",
|
||||
"x-codex-window-id",
|
||||
"session-id",
|
||||
"session_id",
|
||||
"conversation_id",
|
||||
"thread-id",
|
||||
"x-client-request-id",
|
||||
"x-codex-turn-metadata",
|
||||
}
|
||||
checked := 0
|
||||
for _, header := range identityHeaders {
|
||||
if first.Get(header) == "" && second.Get(header) == "" {
|
||||
continue
|
||||
}
|
||||
checked++
|
||||
require.NotEmpty(t, first.Get(header), header)
|
||||
require.Equal(t, first.Get(header), firstAgain.Get(header), "same account must retain stable identity: %s", header)
|
||||
require.NotEqual(t, first.Get(header), second.Get(header), "account failover must rotate upstream identity: %s", header)
|
||||
}
|
||||
require.GreaterOrEqual(t, checked, 5, "test must exercise the real outbound identity surface")
|
||||
}
|
||||
@@ -27,12 +27,11 @@ import (
|
||||
var chatgptCodexModelsURL = "https://chatgpt.com/backend-api/codex/models"
|
||||
|
||||
const (
|
||||
codexModelsManifestBodyLimit int64 = 8 << 20
|
||||
codexModelsManifestCacheBodyLimit = 1 << 20
|
||||
codexModelsManifestCacheMaxEntries = 64
|
||||
codexModelsManifestCacheTTL = 30 * time.Second
|
||||
codexModelsManifestCacheStaleTTL = 5 * time.Minute
|
||||
codexModelsManifestRequestTimeout = 15 * time.Second
|
||||
codexModelsManifestCacheBodyLimit = 1 << 20
|
||||
codexModelsManifestCacheMaxEntries = 64
|
||||
codexModelsManifestCacheTTL = 30 * time.Second
|
||||
codexModelsManifestCacheStaleTTL = 5 * time.Minute
|
||||
codexModelsManifestRequestTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// CodexModelsManifest carries the client representation plus caching metadata.
|
||||
@@ -515,13 +514,20 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont
|
||||
}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, codexModelsManifestBodyLimit))
|
||||
bodyLimit := resolveModelsListReadLimit(s.cfg)
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1))
|
||||
if err != nil {
|
||||
return nil, &codexModelsManifestUpstreamError{
|
||||
err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "read codex models manifest response: %v", err),
|
||||
retryable: isRetryableCodexModelsManifestTransportError(err),
|
||||
}
|
||||
}
|
||||
if int64(len(body)) > bodyLimit {
|
||||
return nil, &codexModelsManifestUpstreamError{
|
||||
err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "codex models manifest response exceeds %d bytes", bodyLimit),
|
||||
retryable: true,
|
||||
}
|
||||
}
|
||||
upstreamBody := body
|
||||
if request.useAPIKeyUpstream {
|
||||
body = convertOpenAIModelListToCodexManifest(body)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -623,6 +624,51 @@ func TestConvertOpenAIModelListToCodexManifest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCodexModelsManifestUsesConfiguredBodyLimit(t *testing.T) {
|
||||
upstream := &codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"models":[{"slug":"gpt-5.6"}]}`)),
|
||||
}, nil
|
||||
}}
|
||||
|
||||
s := newCodexModelsAPIKeyTestService(upstream)
|
||||
s.cfg.Gateway.ModelsListReadMaxBytes = 8
|
||||
_, err := s.FetchCodexModelsManifest(
|
||||
context.Background(),
|
||||
newCodexModelsAPIKeyTestAccount("https://upstream.example"),
|
||||
"0.144.0",
|
||||
"",
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", infraerrors.Reason(err))
|
||||
require.Contains(t, err.Error(), "response exceeds 8 bytes")
|
||||
require.True(t, IsRetryableCodexModelsManifestError(err))
|
||||
}
|
||||
|
||||
func TestFetchCodexModelsManifestAcceptsConfiguredLimitAboveLegacyBoundary(t *testing.T) {
|
||||
manifestBody := `{"models":[{"slug":"gpt-5.6","display_name":"` + strings.Repeat("x", (8<<20)+1024) + `"}]}`
|
||||
require.Greater(t, len(manifestBody), 8<<20)
|
||||
require.Less(t, len(manifestBody), 16<<20)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, manifestBody)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
original := chatgptCodexModelsURL
|
||||
chatgptCodexModelsURL = server.URL
|
||||
defer func() { chatgptCodexModelsURL = original }()
|
||||
|
||||
s := &OpenAIGatewayService{cfg: &config.Config{}}
|
||||
s.cfg.Gateway.ModelsListReadMaxBytes = 16 << 20
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), newCodexModelsTestAccount(), "0.144.0", "")
|
||||
require.NoError(t, err)
|
||||
require.True(t, bytes.Equal([]byte(manifestBody), manifest.Body), "manifest body must be returned intact")
|
||||
}
|
||||
|
||||
func TestFetchCodexModelsManifestRejectsInvalidEnvelope(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -1010,7 +1010,7 @@ func TestForwardAsAnthropic_ReusesOAuthCodexTurnState(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, secondResult)
|
||||
require.Equal(t, "turn_state_first", upstream.requests[1].Header.Get("x-codex-turn-state"))
|
||||
require.Equal(t, generateSessionUUID(isolateOpenAISessionID(0, "stable-cache-key")), upstream.requests[1].Header.Get("session_id"))
|
||||
require.Equal(t, generateSessionUUID(isolateOpenAIUpstreamSessionID(0, account, "stable-cache-key")), upstream.requests[1].Header.Get("session_id"))
|
||||
require.Empty(t, upstream.requests[1].Header.Get("conversation_id"))
|
||||
requireOpenAIMessagesCodexIdentity(t, upstream.requests[1], codexCLIUserAgent, openai.CodexDefaultOriginator)
|
||||
require.False(t, gjson.GetBytes(upstream.bodies[1], "prompt_cache_key").Exists())
|
||||
|
||||
@@ -0,0 +1,841 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 请求侧:service_tier 校验(fast/priority 等价、非法值拒绝、省略保持现状)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestValidateOpenAIServiceTierField(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("fast normalizes to priority", func(t *testing.T) {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"fast"}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", norm)
|
||||
})
|
||||
|
||||
t.Run("priority passes through", func(t *testing.T) {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"priority"}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", norm)
|
||||
})
|
||||
|
||||
t.Run("case and whitespace insensitive", func(t *testing.T) {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":" FAST "}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", norm)
|
||||
})
|
||||
|
||||
t.Run("official tiers pass through", func(t *testing.T) {
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale"} {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"` + tier + `"}`))
|
||||
require.NoError(t, err, "tier %q must be accepted", tier)
|
||||
require.Equal(t, tier, norm)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid tier rejected", func(t *testing.T) {
|
||||
_, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"turbo"}`))
|
||||
require.Error(t, err)
|
||||
var invalid *ErrInvalidOpenAIServiceTier
|
||||
require.True(t, errors.As(err, &invalid))
|
||||
require.Equal(t, "turbo", invalid.Value)
|
||||
require.Contains(t, err.Error(), "invalid service_tier")
|
||||
require.Contains(t, err.Error(), "fast", "allowed-value hint must mention fast")
|
||||
})
|
||||
|
||||
t.Run("omitted field stays valid", func(t *testing.T) {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","input":"hi"}`))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, norm)
|
||||
})
|
||||
|
||||
t.Run("null value keeps omission semantics", func(t *testing.T) {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":null}`))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, norm)
|
||||
})
|
||||
|
||||
t.Run("explicit empty string rejected as invalid enum value", func(t *testing.T) {
|
||||
_, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":""}`))
|
||||
require.Error(t, err)
|
||||
var invalid *ErrInvalidOpenAIServiceTier
|
||||
require.True(t, errors.As(err, &invalid))
|
||||
})
|
||||
|
||||
t.Run("non-string service_tier rejected", func(t *testing.T) {
|
||||
// service_tier 必须为字符串;数字/布尔/对象/数组等类型同样按非法值拒绝。
|
||||
for _, raw := range []string{
|
||||
`{"model":"gpt-5.5","service_tier":123}`,
|
||||
`{"model":"gpt-5.5","service_tier":true}`,
|
||||
`{"model":"gpt-5.5","service_tier":{}}`,
|
||||
`{"model":"gpt-5.5","service_tier":["priority"]}`,
|
||||
} {
|
||||
_, err := ValidateOpenAIServiceTierField([]byte(raw))
|
||||
require.Error(t, err, "raw=%s must be rejected", raw)
|
||||
var invalid *ErrInvalidOpenAIServiceTier
|
||||
require.True(t, errors.As(err, &invalid), "raw=%s", raw)
|
||||
require.Equal(t, "<non-string>", invalid.Value, "raw=%s", raw)
|
||||
require.Contains(t, err.Error(), "invalid service_tier")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversized unknown string is truncated", func(t *testing.T) {
|
||||
blob := strings.Repeat("z", 4096)
|
||||
_, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"` + blob + `"}`))
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "invalid service_tier")
|
||||
require.NotContains(t, err.Error(), blob)
|
||||
require.Less(t, len(err.Error()), 200)
|
||||
var invalid *ErrInvalidOpenAIServiceTier
|
||||
require.True(t, errors.As(err, &invalid))
|
||||
require.Equal(t, strings.Repeat("z", 64)+"...", invalid.Value)
|
||||
})
|
||||
|
||||
t.Run("non-string large object/array is not echoed", func(t *testing.T) {
|
||||
blob := strings.Repeat("x", 4096)
|
||||
payloads := []string{
|
||||
`{"model":"gpt-5.5","service_tier":{"blob":"` + blob + `"}}`,
|
||||
`{"model":"gpt-5.5","service_tier":["` + blob + `"]}`,
|
||||
}
|
||||
for _, raw := range payloads {
|
||||
_, err := ValidateOpenAIServiceTierField([]byte(raw))
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "invalid service_tier")
|
||||
require.NotContains(t, err.Error(), blob)
|
||||
require.Less(t, len(err.Error()), 200)
|
||||
var invalid *ErrInvalidOpenAIServiceTier
|
||||
require.True(t, errors.As(err, &invalid))
|
||||
require.Equal(t, "<non-string>", invalid.Value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 计费:gpt-5.6 系列 / gpt-5.4 按标准价 2x,gpt-5.5 按标准价 2.5x
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplyModelSpecificPricingPolicy_EnforcesOpenAIFastRatios(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &BillingService{}
|
||||
|
||||
t.Run("gpt-5.5 catalog 2x priority is corrected to 2.5x", func(t *testing.T) {
|
||||
// 模拟本地 LiteLLM 目录仍携带官方旧口径(gpt-5.5 priority = 2x)。
|
||||
catalog := &ModelPricing{
|
||||
InputPricePerToken: 5e-6,
|
||||
InputPricePerTokenPriority: 10e-6,
|
||||
OutputPricePerToken: 30e-6,
|
||||
OutputPricePerTokenPriority: 60e-6,
|
||||
CacheReadPricePerToken: 0.5e-6,
|
||||
CacheReadPricePerTokenPriority: 1e-6,
|
||||
}
|
||||
got := svc.applyModelSpecificPricingPolicy("gpt-5.5", catalog)
|
||||
require.InDelta(t, 12.5e-6, got.InputPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 75e-6, got.OutputPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 1.25e-6, got.CacheReadPricePerTokenPriority, 1e-12)
|
||||
// 标准价不被改动。
|
||||
require.InDelta(t, 5e-6, got.InputPricePerToken, 1e-12)
|
||||
// 原始指针不被污染。
|
||||
require.InDelta(t, 10e-6, catalog.InputPricePerTokenPriority, 1e-12)
|
||||
})
|
||||
|
||||
t.Run("gpt-5.4 keeps 2x", func(t *testing.T) {
|
||||
got := svc.applyModelSpecificPricingPolicy("gpt-5.4", &ModelPricing{
|
||||
InputPricePerToken: 2.5e-6,
|
||||
InputPricePerTokenPriority: 5e-6,
|
||||
OutputPricePerToken: 15e-6,
|
||||
OutputPricePerTokenPriority: 30e-6,
|
||||
})
|
||||
require.InDelta(t, 5e-6, got.InputPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 30e-6, got.OutputPricePerTokenPriority, 1e-12)
|
||||
})
|
||||
|
||||
t.Run("gpt-5.6 family keeps 2x", func(t *testing.T) {
|
||||
for _, model := range []string{"gpt-5.6", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.6-max", "gpt-5.6-sol-preview"} {
|
||||
got := svc.applyModelSpecificPricingPolicy(model, &ModelPricing{
|
||||
InputPricePerToken: 5e-6,
|
||||
InputPricePerTokenPriority: 10e-6,
|
||||
OutputPricePerToken: 30e-6,
|
||||
OutputPricePerTokenPriority: 60e-6,
|
||||
CacheReadPricePerToken: 0.5e-6,
|
||||
CacheReadPricePerTokenPriority: 1e-6,
|
||||
})
|
||||
require.InDelta(t, 10e-6, got.InputPricePerTokenPriority, 1e-12, "model %s", model)
|
||||
require.InDelta(t, 60e-6, got.OutputPricePerTokenPriority, 1e-12, "model %s", model)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing priority prices are backfilled from standard", func(t *testing.T) {
|
||||
got := svc.applyModelSpecificPricingPolicy("gpt-5.5", &ModelPricing{
|
||||
InputPricePerToken: 5e-6,
|
||||
OutputPricePerToken: 30e-6,
|
||||
CacheReadPricePerToken: 0.5e-6,
|
||||
CacheCreationPricePerToken: 5e-6,
|
||||
})
|
||||
require.InDelta(t, 12.5e-6, got.InputPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 75e-6, got.OutputPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 1.25e-6, got.CacheReadPricePerTokenPriority, 1e-12)
|
||||
require.InDelta(t, 12.5e-6, got.CacheCreationPricePerTokenPriority, 1e-12)
|
||||
})
|
||||
|
||||
t.Run("gpt-5.5-pro has no mandated fast tier", func(t *testing.T) {
|
||||
got := svc.applyModelSpecificPricingPolicy("gpt-5.5-pro", &ModelPricing{
|
||||
InputPricePerToken: 30e-6,
|
||||
InputPricePerTokenPriority: 60e-6,
|
||||
OutputPricePerToken: 180e-6,
|
||||
})
|
||||
require.InDelta(t, 60e-6, got.InputPricePerTokenPriority, 1e-12)
|
||||
})
|
||||
|
||||
t.Run("unrelated models untouched", func(t *testing.T) {
|
||||
got := svc.applyModelSpecificPricingPolicy("claude-opus-5", &ModelPricing{InputPricePerToken: 1, OutputPricePerToken: 2})
|
||||
require.InDelta(t, 1, got.InputPricePerToken, 1e-12)
|
||||
require.Zero(t, got.InputPricePerTokenPriority)
|
||||
})
|
||||
}
|
||||
|
||||
func TestOpenAIFastBillingMultiplier_2xAnd25x(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// 目录数据携带官方旧口径(gpt-5.5 priority=2x);修正后 fast 必须按 2.5x 计费。
|
||||
catalog := map[string]*LiteLLMModelPricing{
|
||||
"gpt-5.4": {
|
||||
InputCostPerToken: 2.5e-6,
|
||||
InputCostPerTokenPriority: 5e-6,
|
||||
OutputCostPerToken: 15e-6,
|
||||
OutputCostPerTokenPriority: 30e-6,
|
||||
CacheReadInputTokenCost: 0.25e-6,
|
||||
CacheReadInputTokenCostPriority: 0.5e-6,
|
||||
},
|
||||
"gpt-5.5": {
|
||||
InputCostPerToken: 5e-6,
|
||||
InputCostPerTokenPriority: 10e-6,
|
||||
OutputCostPerToken: 30e-6,
|
||||
OutputCostPerTokenPriority: 60e-6,
|
||||
CacheReadInputTokenCost: 0.5e-6,
|
||||
CacheReadInputTokenCostPriority: 1e-6,
|
||||
},
|
||||
"gpt-5.6-sol": {
|
||||
InputCostPerToken: 5e-6,
|
||||
InputCostPerTokenPriority: 10e-6,
|
||||
OutputCostPerToken: 30e-6,
|
||||
OutputCostPerTokenPriority: 60e-6,
|
||||
CacheReadInputTokenCost: 0.5e-6,
|
||||
CacheReadInputTokenCostPriority: 1e-6,
|
||||
},
|
||||
}
|
||||
billing := NewBillingService(&config.Config{}, &PricingService{pricingData: catalog})
|
||||
tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000}
|
||||
|
||||
standard := func(model string) *CostBreakdown {
|
||||
cost, err := billing.CalculateCost(model, tokens, 1)
|
||||
require.NoError(t, err)
|
||||
return cost
|
||||
}
|
||||
fast := func(model, tier string) *CostBreakdown {
|
||||
cost, err := billing.CalculateCostWithServiceTier(model, tokens, 1, tier)
|
||||
require.NoError(t, err)
|
||||
return cost
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
model string
|
||||
ratio float64
|
||||
}{
|
||||
{model: "gpt-5.4", ratio: 2.0},
|
||||
{model: "gpt-5.5", ratio: 2.5},
|
||||
{model: "gpt-5.6-sol", ratio: 2.0},
|
||||
{model: "gpt-5.6-terra", ratio: 2.0},
|
||||
{model: "gpt-5.6-luna", ratio: 2.0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.model+"/fast", func(t *testing.T) {
|
||||
base := standard(tt.model)
|
||||
fastCost := fast(tt.model, "fast")
|
||||
require.InDelta(t, base.TotalCost*tt.ratio, fastCost.TotalCost, 1e-9,
|
||||
"fast total must be %.1fx standard", tt.ratio)
|
||||
})
|
||||
t.Run(tt.model+"/priority_alias", func(t *testing.T) {
|
||||
fastCost := fast(tt.model, "fast")
|
||||
priorityCost := fast(tt.model, "priority")
|
||||
require.InDelta(t, fastCost.TotalCost, priorityCost.TotalCost, 1e-12,
|
||||
"client alias fast must bill identically to priority")
|
||||
require.InDelta(t, standard(tt.model).TotalCost*tt.ratio, priorityCost.TotalCost, 1e-9)
|
||||
})
|
||||
t.Run(tt.model+"/no_tier_unchanged", func(t *testing.T) {
|
||||
base := standard(tt.model)
|
||||
noTier, err := billing.CalculateCostWithServiceTier(tt.model, tokens, 1, "")
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, base.TotalCost, noTier.TotalCost, 1e-12)
|
||||
})
|
||||
t.Run(tt.model+"/default_equals_standard", func(t *testing.T) {
|
||||
base := standard(tt.model)
|
||||
defaultCost, err := billing.CalculateCostWithServiceTier(tt.model, tokens, 1, "default")
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, base.TotalCost, defaultCost.TotalCost, 1e-12)
|
||||
require.InDelta(t, base.InputCost, defaultCost.InputCost, 1e-12)
|
||||
require.InDelta(t, base.OutputCost, defaultCost.OutputCost, 1e-12)
|
||||
require.InDelta(t, base.CacheReadCost, defaultCost.CacheReadCost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIFastBilling_FastMultiplierOverridesEnforcedRatio(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &BillingService{}
|
||||
catalog := &ModelPricing{
|
||||
InputPricePerToken: 5e-6,
|
||||
InputPricePerTokenPriority: 10e-6,
|
||||
OutputPricePerToken: 30e-6,
|
||||
OutputPricePerTokenPriority: 60e-6,
|
||||
CacheReadPricePerToken: 0.5e-6,
|
||||
CacheReadPricePerTokenPriority: 1e-6,
|
||||
}
|
||||
pricing := svc.applyModelSpecificPricingPolicy("gpt-5.5", catalog)
|
||||
require.InDelta(t, 12.5e-6, pricing.InputPricePerTokenPriority, 1e-12, "enforce must still write 2.5x priority prices")
|
||||
require.InDelta(t, 75e-6, pricing.OutputPricePerTokenPriority, 1e-12)
|
||||
|
||||
multiplier := 1.7
|
||||
pricing.FastMultiplier = &multiplier
|
||||
|
||||
tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}
|
||||
standard := svc.computeTokenBreakdown(pricing, tokens, 1, "", false)
|
||||
fast := svc.computeTokenBreakdown(pricing, tokens, 1, "fast", false)
|
||||
priority := svc.computeTokenBreakdown(pricing, tokens, 1, "priority", false)
|
||||
|
||||
require.InDelta(t, standard.TotalCost*1.7, fast.TotalCost, 1e-9)
|
||||
require.InDelta(t, fast.TotalCost, priority.TotalCost, 1e-12)
|
||||
|
||||
withoutOverride := *pricing
|
||||
withoutOverride.FastMultiplier = nil
|
||||
enforced := svc.computeTokenBreakdown(&withoutOverride, tokens, 1, "fast", false)
|
||||
require.InDelta(t, standard.TotalCost*2.5, enforced.TotalCost, 1e-9,
|
||||
"without FastMultiplier the same enforced prices still bill 2.5x")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 上游 payload:fast 归一化为 priority 并确实到达上游
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestForwardAsChatCompletions_ServiceTierFastNormalizedToPriorityUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"fast","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-chat-st"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"stop"}}`)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 21,
|
||||
Name: "openai-compatible",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-compatible"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
}
|
||||
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5")
|
||||
require.Error(t, err) // upstream 400 → 错误返回,但请求体已被 recorder 捕获
|
||||
require.NotNil(t, upstream.lastBody)
|
||||
require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String(),
|
||||
"client alias fast must reach upstream as priority")
|
||||
}
|
||||
|
||||
func TestForwardAsChatCompletions_ServiceTierPriorityPreservedUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"priority","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-chat-st2"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"stop"}}`)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 2,
|
||||
Name: "openai-compatible",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-compatible"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
}
|
||||
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5")
|
||||
require.Error(t, err)
|
||||
require.NotNil(t, upstream.lastBody)
|
||||
require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String())
|
||||
}
|
||||
|
||||
func TestForward_ResponsesServiceTierFastNormalizedToPriorityUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-st"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`,
|
||||
)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, upstream.lastBody)
|
||||
require.Equal(t, "priority", gjson.GetBytes(upstream.lastBody, "service_tier").String(),
|
||||
"client alias fast must reach the upstream as priority")
|
||||
// 计费上下文:result 携带归一化后的 tier。
|
||||
require.NotNil(t, result.ServiceTier)
|
||||
require.Equal(t, "priority", *result.ServiceTier)
|
||||
}
|
||||
|
||||
func TestForward_ResponsesServiceTierOmittedStaysOmitted(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","input":"hello","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-st2"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"id":"resp_2","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`,
|
||||
)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, upstream.lastBody)
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "service_tier").Exists(),
|
||||
"omitted service_tier must stay omitted")
|
||||
require.Nil(t, result.ServiceTier)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 流式计费上下文:service_tier 需要从请求体传到 usage 计费
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestForwardStreaming_ServiceTierPropagatedToResult(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":true}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"data: {\"type\":\"response.output_text.delta\",\"item_id\":\"it_1\",\"output_index\":0,\"delta\":\"hi\"}\n\n" +
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" +
|
||||
"data: [DONE]\n\n"
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-resp-stream-st"}},
|
||||
Body: io.NopCloser(strings.NewReader(streamPayload)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, result.ServiceTier)
|
||||
require.Equal(t, "priority", *result.ServiceTier, "streaming billing context must carry the normalized tier")
|
||||
// /v1/responses 流是上游 SSE 原样透传:上游没回 service_tier 就不该出现;
|
||||
// 网关只在计费结果里携带请求侧 tier,不往下游流里注入。
|
||||
require.Contains(t, rec.Body.String(), `"delta":"hi"`, "streamed content must reach the client")
|
||||
require.NotContains(t, rec.Body.String(), `"service_tier"`, "upstream did not return service_tier, client stream must stay untouched")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 上游回显优先:请求 fast 但上游真实返回 default → 计费按标准价
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestForward_ResponsesUpstreamEchoesDefault_OverridesRequestFast(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// 上游回显 service_tier=default(例如请求实际被降级)。
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-echo"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","service_tier":"default","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`,
|
||||
)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, result.ServiceTier)
|
||||
require.Equal(t, "default", *result.ServiceTier,
|
||||
"upstream-echoed default must override the client-requested fast tier for billing")
|
||||
// 非流式响应原样透传:客户端同样看到 default。
|
||||
require.Contains(t, rec.Body.String(), `"service_tier":"default"`)
|
||||
require.NotContains(t, rec.Body.String(), `"service_tier":"priority"`)
|
||||
}
|
||||
|
||||
func TestForwardStreaming_UpstreamEchoesDefault_OverridesRequestFast(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"fast","input":"hello","stream":true}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_s1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"service_tier\":\"default\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" +
|
||||
"data: [DONE]\n\n"
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-resp-echo-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(streamPayload)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, result.ServiceTier)
|
||||
require.Equal(t, "default", *result.ServiceTier,
|
||||
"terminal SSE event's upstream-echoed default must win for billing")
|
||||
// 流式原样透传:客户端在终止事件里看到 default。
|
||||
require.Contains(t, rec.Body.String(), `"service_tier":"default"`)
|
||||
}
|
||||
|
||||
func TestForwardAsChatCompletions_UpstreamEchoesDefault_BillsStandard(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hello"}],"service_tier":"fast","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
streamPayload := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_c1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"data: {\"type\":\"response.output_text.delta\",\"item_id\":\"it_1\",\"output_index\":0,\"delta\":\"hi\"}\n\n" +
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_c1\",\"object\":\"response\",\"model\":\"gpt-5.5\",\"status\":\"completed\",\"service_tier\":\"default\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" +
|
||||
"data: [DONE]\n\n"
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid-chat-echo"}},
|
||||
Body: io.NopCloser(strings.NewReader(streamPayload)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(&openAIFastPolicyRepoStub{values: map[string]string{}}, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 21,
|
||||
Name: "openai-compatible",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-compatible"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, result.ServiceTier)
|
||||
require.Equal(t, "default", *result.ServiceTier,
|
||||
"CC bridge must bill on the upstream-echoed default, not the requested fast")
|
||||
// 缓冲转回 Chat Completions:客户端响应里如实回显 default。
|
||||
require.Contains(t, rec.Body.String(), `"service_tier":"default"`)
|
||||
require.NotContains(t, rec.Body.String(), `"service_tier":"priority"`)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// policy filter:删除 service_tier 后不得再按原请求 Fast 计费
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestForward_ServiceTierFilteredByPolicyBillsStandard(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"priority","input":"hello","stream":false}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// 管理员配置 priority → filter:字段在出站前被删除。
|
||||
settings := &OpenAIFastPolicySettings{Rules: []OpenAIFastPolicyRule{{
|
||||
ServiceTier: OpenAIFastTierPriority,
|
||||
Action: BetaPolicyActionFilter,
|
||||
Scope: BetaPolicyScopeAll,
|
||||
}}}
|
||||
raw, err := json.Marshal(settings)
|
||||
require.NoError(t, err)
|
||||
repo := &openAIFastPolicyRepoStub{values: map[string]string{SettingKeyOpenAIFastPolicySettings: string(raw)}}
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid-resp-filter"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`,
|
||||
)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
|
||||
httpUpstream: upstream,
|
||||
settingService: NewSettingService(repo, &config.Config{}),
|
||||
}
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_responses_supported": true},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
// 出站 body 已剥离 service_tier、上游也未回显 → 无 tier → 按标准价计费。
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "service_tier").Exists(),
|
||||
"policy filter must strip service_tier from the outbound body")
|
||||
require.Nil(t, result.ServiceTier, "filtered request must not bill as fast")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 上游回显观察与解析器单测
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestUpstreamResponseModelObserver_ObservesServiceTier(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
observer := &upstreamResponseModelObserver{}
|
||||
// 上游约束:非终止且有类型的事件(response.created)回显的是请求档位而非
|
||||
// 实际处理档位,忽略。
|
||||
observer.ObserveOpenAI([]byte(`{"type":"response.created","response":{"model":"gpt-5.5","service_tier":"flex"}}`), "response.created")
|
||||
require.Empty(t, observer.ServiceTier())
|
||||
|
||||
// terminal 声明(带 model 帧)优先。
|
||||
observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed")
|
||||
require.Equal(t, "default", observer.ServiceTier())
|
||||
|
||||
// Chat Completions 顶层 service_tier 按 untyped payload 观察(无 type 字段)。
|
||||
ccObserver := &upstreamResponseModelObserver{}
|
||||
ccObserver.ObserveOpenAI([]byte(`{"id":"chatcmpl-1","model":"gpt-5.5","service_tier":"priority","choices":[]}`), "")
|
||||
require.Equal(t, "priority", ccObserver.ServiceTier())
|
||||
|
||||
// 无 model 的帧不触发 tier 观察(上游约束:tier 声明必带 model)。
|
||||
modelFree := &upstreamResponseModelObserver{}
|
||||
modelFree.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"service_tier":"default"}}`), "response.completed")
|
||||
require.Empty(t, modelFree.ServiceTier())
|
||||
}
|
||||
|
||||
func TestResolvedOpenAIUpstreamServiceTier(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
priority := func() *string { v := "priority"; return &v }()
|
||||
|
||||
t.Run("upstream echo wins over outbound tier", func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(nil)
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed")
|
||||
|
||||
got := resolvedOpenAIUpstreamServiceTier(c, priority)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "default", *got)
|
||||
})
|
||||
|
||||
t.Run("no upstream echo falls back to outbound tier", func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(nil)
|
||||
beginUpstreamResponseModelObservation(c)
|
||||
|
||||
got := resolvedOpenAIUpstreamServiceTier(c, priority)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "priority", *got)
|
||||
})
|
||||
|
||||
t.Run("upstream alias fast normalizes to priority", func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(nil)
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"fast"}}`), "response.completed")
|
||||
|
||||
got := resolvedOpenAIUpstreamServiceTier(c, nil)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "priority", *got)
|
||||
})
|
||||
|
||||
t.Run("no observer keeps outbound tier", func(t *testing.T) {
|
||||
got := resolvedOpenAIUpstreamServiceTier(nil, priority)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "priority", *got)
|
||||
})
|
||||
|
||||
t.Run("no observer and no outbound tier stays nil", func(t *testing.T) {
|
||||
require.Nil(t, resolvedOpenAIUpstreamServiceTier(nil, nil))
|
||||
})
|
||||
|
||||
t.Run("local observer wins without gin context", func(t *testing.T) {
|
||||
observer := &upstreamResponseModelObserver{}
|
||||
observer.ObserveOpenAI([]byte(`{"type":"response.completed","response":{"model":"gpt-5.5","service_tier":"default"}}`), "response.completed")
|
||||
|
||||
got := resolvedOpenAIUpstreamServiceTierFromObserver(observer, priority)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "default", *got)
|
||||
})
|
||||
|
||||
t.Run("nil local observer falls back to outbound tier", func(t *testing.T) {
|
||||
got := resolvedOpenAIUpstreamServiceTierFromObserver(nil, priority)
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "priority", *got)
|
||||
})
|
||||
}
|
||||
@@ -249,6 +249,7 @@ type ccStreamScanState struct {
|
||||
// emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后
|
||||
// 记入 Warn 日志。
|
||||
func (s *OpenAIGatewayService) scanCCStream(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
logPrefix string,
|
||||
requestID string,
|
||||
@@ -272,6 +273,12 @@ func (s *OpenAIGatewayService) scanCCStream(
|
||||
st.SawDone = true
|
||||
break
|
||||
}
|
||||
// 观察上游 CC chunk 回显的 model / service_tier(计费以回显为准)。
|
||||
// CC chunk 无 type 字段,按 untyped payload 观察(上游约束:只有终止
|
||||
// 事件与无类型 body 报告实际处理档位)。
|
||||
if observer := upstreamResponseModelObserverFromContext(c); observer != nil {
|
||||
observer.ObserveOpenAI([]byte(payload), "")
|
||||
}
|
||||
|
||||
if u := extractCCStreamUsage(payload); u != nil {
|
||||
st.Usage = *u
|
||||
@@ -331,6 +338,11 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
|
||||
writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response")
|
||||
return nil, OpenAIUsage{}, fmt.Errorf("parse chat completions response: %w", err)
|
||||
}
|
||||
// 观察上游 CC JSON 回显的 model / service_tier(计费以回显为准)。
|
||||
// CC JSON 无 type 字段,按 untyped payload 观察(上游约束)。
|
||||
if observer := upstreamResponseModelObserverFromContext(c); observer != nil {
|
||||
observer.ObserveOpenAI(respBody, "")
|
||||
}
|
||||
|
||||
usage := OpenAIUsage{}
|
||||
if parsed, ok := extractOpenAIUsageFromJSONBytes(respBody); ok {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// stripEmptyChatToolCallIdentityFromSSELine 从 CC 流式 SSE 行中剔除
|
||||
// choices[*].delta.tool_calls[*] 上的空 id / 空 function.name 字段。
|
||||
//
|
||||
// DashScope/DeepSeek 等 OpenAI 兼容上游会把同一个 tool_calls[index]
|
||||
// 拆成多个 delta:首个 delta 带合法 id + function.name(arguments 可能
|
||||
// 为空),后续参数 delta 带 id:"" 与 function.name:"" 只追加 arguments
|
||||
// 碎片。dsh 等客户端按 `!== undefined` 合并字段,空串会被当成有效值
|
||||
// 覆盖首包合法 id/name,最终得到 {"id":"","name":"",...} 导致
|
||||
// ToolNotFoundError: unknown tool ""。这里无状态剔除空串字段(缺失
|
||||
// 即不覆盖),不补写、不记忆首包 id/name,适用于所有走 raw CC 直转
|
||||
// 路径的账号(不限定 DeepSeek)。
|
||||
//
|
||||
// 只处理流式 chunk 的 delta.tool_calls;非流式 message.tool_calls 不属于
|
||||
// 本 helper 范围。
|
||||
func stripEmptyChatToolCallIdentityFromSSELine(line string) string {
|
||||
payload, ok := extractOpenAISSEDataLine(line)
|
||||
if !ok {
|
||||
return line
|
||||
}
|
||||
trimmed := strings.TrimSpace(payload)
|
||||
if trimmed == "" || trimmed == "[DONE]" {
|
||||
return line
|
||||
}
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity([]byte(payload))
|
||||
if !changed {
|
||||
return line
|
||||
}
|
||||
prefixLen := len(line) - len(payload)
|
||||
if prefixLen < 0 {
|
||||
return line
|
||||
}
|
||||
return line[:prefixLen] + string(rewritten)
|
||||
}
|
||||
|
||||
// stripEmptyChatToolCallIdentity 从单个 CC 流式 chunk payload 中删除
|
||||
// choices[*].delta.tool_calls[*] 上存在但为空字符串的 id 与
|
||||
// function.name 字段;arguments(即使是空串)、index、type 与其它字段
|
||||
// 一律保留,非空 id/name 不动。多 choice、多 index 都会处理。
|
||||
//
|
||||
// 返回 (原始 payload, false) 当:payload 为空、不含 "tool_calls"、
|
||||
// 非法 JSON、无 choices / delta / tool_calls 数组、或没有需要删除的
|
||||
// 字段。sjson 删除失败时 fail-closed 返回原始 payload。
|
||||
func stripEmptyChatToolCallIdentity(payload []byte) ([]byte, bool) {
|
||||
if len(payload) == 0 {
|
||||
return payload, false
|
||||
}
|
||||
// 热路径快速失败:绝大多数 chunk 没有 tool_calls。
|
||||
if !bytes.Contains(payload, []byte("tool_calls")) {
|
||||
return payload, false
|
||||
}
|
||||
if !gjson.ValidBytes(payload) {
|
||||
return payload, false
|
||||
}
|
||||
choices := gjson.GetBytes(payload, "choices")
|
||||
if !choices.Exists() || !choices.IsArray() {
|
||||
return payload, false
|
||||
}
|
||||
updated := payload
|
||||
changed := false
|
||||
for ci, choice := range choices.Array() {
|
||||
delta := choice.Get("delta")
|
||||
if !delta.Exists() || !delta.IsObject() {
|
||||
continue
|
||||
}
|
||||
toolCalls := delta.Get("tool_calls")
|
||||
if !toolCalls.Exists() || !toolCalls.IsArray() {
|
||||
continue
|
||||
}
|
||||
for ti, tc := range toolCalls.Array() {
|
||||
if id := tc.Get("id"); id.Exists() && id.Type == gjson.String && id.Str == "" {
|
||||
next, err := sjson.DeleteBytes(updated, "choices."+strconv.Itoa(ci)+".delta.tool_calls."+strconv.Itoa(ti)+".id")
|
||||
if err != nil {
|
||||
return payload, false
|
||||
}
|
||||
updated = next
|
||||
changed = true
|
||||
}
|
||||
if name := tc.Get("function.name"); name.Exists() && name.Type == gjson.String && name.Str == "" {
|
||||
next, err := sjson.DeleteBytes(updated, "choices."+strconv.Itoa(ci)+".delta.tool_calls."+strconv.Itoa(ti)+".function.name")
|
||||
if err != nil {
|
||||
return payload, false
|
||||
}
|
||||
updated = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return payload, false
|
||||
}
|
||||
return updated, true
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_FirstChunkIdentityUntouched 首包带合法
|
||||
// id/name 的 delta 必须原样保留(changed=false)。
|
||||
func TestStripEmptyChatToolCallIdentity_FirstChunkIdentityUntouched(t *testing.T) {
|
||||
payload := []byte(`{"id":"chatcmpl_tool","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_example","type":"function","function":{"name":"web_search","arguments":""}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, string(payload), string(rewritten))
|
||||
require.Equal(t, "call_example", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").String())
|
||||
require.Equal(t, "web_search", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").String())
|
||||
// 首包 arguments 为空串也不应被删除。
|
||||
require.True(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").Exists())
|
||||
require.Equal(t, "", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_FollowUpDelta 后续参数 delta 的
|
||||
// `"id":""` 与 `"function":{"name":""}` 应被删除;arguments 碎片、
|
||||
// index、type 保留。
|
||||
func TestStripEmptyChatToolCallIdentity_FollowingDelta(t *testing.T) {
|
||||
payload := []byte(`{"id":"chatcmpl_tool","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"{\"query\":"}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.True(t, changed)
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").Exists())
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").Exists())
|
||||
require.Equal(t, `{"query":`, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
require.Equal(t, int64(0), gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.index").Int())
|
||||
require.Equal(t, "function", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.type").String())
|
||||
// 空串字段不得再出现在 payload 里。
|
||||
require.NotContains(t, string(rewritten), `"id":""`)
|
||||
require.NotContains(t, string(rewritten), `"name":""`)
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_OnlyEmptyName / _OnlyEmptyID 只删
|
||||
// 空的那一个,非空字段必须保留。
|
||||
func TestStripEmptyChatToolCallIdentity_OnlyEmptyName(t *testing.T) {
|
||||
payload := []byte(`{"id":"chatcmpl_tool","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"","arguments":"{}"}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "call_1", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").String())
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").Exists())
|
||||
require.Equal(t, "{}", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_OnlyEmptyID 覆盖 `"id": ""` 带空格的
|
||||
// JSON 形式,确认 gjson/sjson 均能识别。
|
||||
func TestStripEmptyChatToolCallIdentity_OnlyEmptyID(t *testing.T) {
|
||||
payload := []byte(`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id" : "" , "type" : "function","function":{"name":"get_weather","arguments":"{}"}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.True(t, changed)
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").Exists())
|
||||
require.Equal(t, "get_weather", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").String())
|
||||
require.Equal(t, "{}", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_EmptyArgumentsKept 空 arguments 不删,
|
||||
// 只有 id/name 空串被剔除。
|
||||
func TestStripEmptyChatToolCallIdentity_EmptyArgumentsKept(t *testing.T) {
|
||||
payload := []byte(`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":""}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.True(t, changed)
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").Exists())
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").Exists())
|
||||
require.True(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").Exists())
|
||||
require.Equal(t, "", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_TwoParallelToolCalls 两个并行 index 都要
|
||||
// 处理:合法的 index 0 保留,后续参数 delta 的 index 1 剔除空 id/name。
|
||||
func TestStripEmptyChatToolCallIdentity_TwoParallelToolCalls(t *testing.T) {
|
||||
payload := []byte(`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_a","type":"function","function":{"name":"tool_a","arguments":"{\"x\":"}},{"index":1,"id":"","type":"function","function":{"name":"","arguments":"{\"y\":"}}]}}]}`)
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity(payload)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "call_a", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.id").String())
|
||||
require.Equal(t, "tool_a", gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.name").String())
|
||||
require.Equal(t, `{"x":`, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.1.id").Exists())
|
||||
require.False(t, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.1.function.name").Exists())
|
||||
require.Equal(t, `{"y":`, gjson.GetBytes(rewritten, "choices.0.delta.tool_calls.1.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_Passthrough 无 tool_calls、无 choices、
|
||||
// 非数组 tool_calls、非法 JSON 一律原样返回。
|
||||
func TestStripEmptyChatToolCallIdentity_Passthrough(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload string
|
||||
}{
|
||||
{"no tool_calls", `{"choices":[{"index":0,"delta":{"content":"hi"}}]}`},
|
||||
{"no choices", `{"id":"chatcmpl_x"}`},
|
||||
{"empty choices", `{"choices":[]}`},
|
||||
{"tool_calls not array", `{"choices":[{"index":0,"delta":{"tool_calls":{"foo":1}}}]}`},
|
||||
{"invalid JSON", `{"choices":[{`},
|
||||
{"empty string", ``},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rewritten, changed := stripEmptyChatToolCallIdentity([]byte(tt.payload))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, tt.payload, string(rewritten))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentityFromSSELine_Passthrough SSE 行级:非
|
||||
// data 行、[DONE]、空行原样;data 行保留 `data: ` 前缀。
|
||||
func TestStripEmptyChatToolCallIdentityFromSSELine_Passthrough(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
line string
|
||||
}{
|
||||
{"done", "data: [DONE]"},
|
||||
{"non-data line", ": keep-alive"},
|
||||
{"empty line", ""},
|
||||
{"comment line", ":"},
|
||||
{"content chunk", `data: {"choices":[{"index":0,"delta":{"content":"hi"}}]}`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.line, stripEmptyChatToolCallIdentityFromSSELine(tt.line))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentityFromSSELine_KeepsDataPrefix 改写后的
|
||||
// SSE 行必须保留 `data: ` 前缀。
|
||||
func TestStripEmptyChatToolCallIdentityFromSSELine_KeepsDataPrefix(t *testing.T) {
|
||||
line := `data: {"id":"chatcmpl_tool","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"{}"}}]}}]}`
|
||||
got := stripEmptyChatToolCallIdentityFromSSELine(line)
|
||||
require.True(t, strings.HasPrefix(got, "data: "))
|
||||
payload, ok := extractOpenAISSEDataLine(got)
|
||||
require.True(t, ok)
|
||||
require.False(t, gjson.Get(payload, "choices.0.delta.tool_calls.0.id").Exists())
|
||||
require.False(t, gjson.Get(payload, "choices.0.delta.tool_calls.0.function.name").Exists())
|
||||
require.Equal(t, "{}", gjson.Get(payload, "choices.0.delta.tool_calls.0.function.arguments").String())
|
||||
}
|
||||
|
||||
// TestStripEmptyChatToolCallIdentity_DshClientMerge 模拟 dsh rc.2 adapter 的
|
||||
// 合并逻辑(字段存在——含空串——才覆盖):sanitize 后合并,最终 id/name 必须
|
||||
// 仍是首包合法值,arguments 为各碎片拼接。
|
||||
func TestStripEmptyChatToolCallIdentity_DshClientMerge(t *testing.T) {
|
||||
lines := []string{
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_example","type":"function","function":{"name":"web_search","arguments":""}}]}}]}`,
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"{\"query\":"}}]}}]}`,
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"\"example\"}"}}]}}]}`,
|
||||
}
|
||||
|
||||
var mergedID, mergedName, mergedArgs string
|
||||
for _, line := range lines {
|
||||
sanitized := stripEmptyChatToolCallIdentityFromSSELine(line)
|
||||
payload, ok := extractOpenAISSEDataLine(sanitized)
|
||||
require.True(t, ok)
|
||||
for _, tc := range gjson.Get(payload, "choices.0.delta.tool_calls").Array() {
|
||||
if v := tc.Get("id"); v.Exists() {
|
||||
mergedID = v.String()
|
||||
}
|
||||
if v := tc.Get("function.name"); v.Exists() {
|
||||
mergedName = v.String()
|
||||
}
|
||||
if v := tc.Get("function.arguments"); v.Exists() {
|
||||
mergedArgs += v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
require.Equal(t, "call_example", mergedID)
|
||||
require.Equal(t, "web_search", mergedName)
|
||||
require.Equal(t, `{"query":"example"}`, mergedArgs)
|
||||
}
|
||||
@@ -61,6 +61,9 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
) (*OpenAIForwardResult, error) {
|
||||
beginUpstreamResponseModelObservation(c)
|
||||
setCodexToolNameReverse(c, nil)
|
||||
if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
restrictionResult := s.detectCodexClientRestriction(c, account, body)
|
||||
logCodexCLIOnlyDetection(ctx, c, account, getAPIKeyIDFromContext(c), restrictionResult, body)
|
||||
@@ -190,7 +193,8 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
responsesBody = stripped
|
||||
}
|
||||
}
|
||||
responsesBody, normalizedServiceTier, err := normalizeResponsesBodyServiceTier(responsesBody)
|
||||
var normalizedServiceTier string
|
||||
responsesBody, normalizedServiceTier, err = normalizeResponsesBodyServiceTier(responsesBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("normalize service_tier in responses-shape body: %w", err)
|
||||
}
|
||||
@@ -260,6 +264,7 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
} else if promptCacheKey != "" {
|
||||
reqBody["prompt_cache_key"] = promptCacheKey
|
||||
}
|
||||
applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c))
|
||||
responsesBody, err = json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("remarshal after codex transform: %w", err)
|
||||
@@ -313,7 +318,7 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
|
||||
if promptCacheKey != "" {
|
||||
apiKeyID := getAPIKeyIDFromContext(c)
|
||||
upstreamReq.Header.Set("session_id", generateSessionUUID(isolateOpenAISessionID(apiKeyID, promptCacheKey)))
|
||||
upstreamReq.Header.Set("session_id", generateSessionUUID(isolateOpenAIUpstreamSessionID(apiKeyID, codexAccountIdentitySource(c, account), promptCacheKey)))
|
||||
}
|
||||
|
||||
// 7. Send request
|
||||
@@ -371,11 +376,13 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
return nil, handleErr
|
||||
}
|
||||
|
||||
// Propagate ServiceTier and ReasoningEffort to result for billing
|
||||
// Propagate ServiceTier and ReasoningEffort to result for billing.
|
||||
// 计费 tier 优先采用上游回显值;上游未回显时回退到最终出站 body(经过
|
||||
// fast policy filter/force 之后)里的 tier,policy filter 删掉字段后不再
|
||||
// 按原请求 Fast 计费。
|
||||
if handleErr == nil && result != nil {
|
||||
if responsesReq.ServiceTier != "" {
|
||||
st := responsesReq.ServiceTier
|
||||
result.ServiceTier = &st
|
||||
if tier := resolvedOpenAIUpstreamServiceTier(c, extractOpenAIServiceTierFromBody(responsesBody)); tier != nil {
|
||||
result.ServiceTier = tier
|
||||
}
|
||||
if responsesReq.Reasoning != nil && responsesReq.Reasoning.Effort != "" {
|
||||
re := responsesReq.Reasoning.Effort
|
||||
@@ -389,6 +396,8 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
|
||||
if snapshot := ParseCodexRateLimitHeaders(resp.Header); snapshot != nil {
|
||||
s.updateCodexUsageSnapshot(ctx, account.ID, snapshot)
|
||||
}
|
||||
} else if handleErr == nil && account.IsShadow() && account.ParentAccountID != nil {
|
||||
notifyOpenAIAutoReset(*account.ParentAccountID)
|
||||
}
|
||||
|
||||
return result, handleErr
|
||||
@@ -475,6 +484,7 @@ func (s *OpenAIGatewayService) handleChatBufferedStreamingResponse(
|
||||
observer = beginUpstreamResponseModelObservation(c)
|
||||
}
|
||||
observer.Observe(finalResponse.Model, true)
|
||||
observer.ObserveServiceTier(finalResponse.ServiceTier, true)
|
||||
if strings.TrimSpace(finalResponse.Status) == "failed" {
|
||||
payload, _ := json.Marshal(gin.H{"type": "response.failed", "response": finalResponse})
|
||||
// cyber_policy 致命不可重试:不 failover,以 Chat Completions 错误格式回写(F4),
|
||||
@@ -548,6 +558,7 @@ func (s *OpenAIGatewayService) handleChatBufferedStreamingResponse(
|
||||
UpstreamModel: upstreamModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
}
|
||||
@@ -668,6 +679,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse(
|
||||
UpstreamModel: upstreamModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
|
||||
@@ -69,9 +69,6 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions(
|
||||
}
|
||||
clientStream := gjson.GetBytes(body, "stream").Bool()
|
||||
|
||||
// 1b. Extract service tier from the raw body before any transformation.
|
||||
serviceTier := extractOpenAIServiceTierFromBody(body)
|
||||
|
||||
// 2. Resolve model mapping (same as ForwardAsChatCompletions)
|
||||
billingModel := resolveOpenAIForwardModel(account, originalModel, defaultMappedModel)
|
||||
upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel)
|
||||
@@ -106,6 +103,9 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions(
|
||||
return nil, policyErr
|
||||
}
|
||||
upstreamBody = updatedBody
|
||||
// 计费兜底 tier = 最终出站 body(policy filter/force 后)里的 tier;
|
||||
// 最终值由 resolvedOpenAIUpstreamServiceTier 决定(上游回显优先)。
|
||||
serviceTier := extractOpenAIServiceTierFromBody(upstreamBody)
|
||||
if account.Platform == PlatformGrok {
|
||||
strippedBody, stripErr := stripRedundantGrokChatViewImageTool(upstreamBody)
|
||||
if stripErr != nil {
|
||||
@@ -336,6 +336,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions(
|
||||
}
|
||||
}
|
||||
line = applyOllamaCloudRawChatCompletionsSSELine(account, line)
|
||||
line = stripEmptyChatToolCallIdentityFromSSELine(line)
|
||||
|
||||
writeLine(line)
|
||||
if line == "" {
|
||||
@@ -387,8 +388,9 @@ func (s *OpenAIGatewayService) streamRawChatCompletions(
|
||||
UpstreamModel: upstreamModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
ReasoningEffort: reasoningEffort,
|
||||
ServiceTier: serviceTier,
|
||||
ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier),
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
@@ -488,8 +490,9 @@ func (s *OpenAIGatewayService) bufferRawChatCompletions(
|
||||
UpstreamModel: upstreamModel,
|
||||
UpstreamResponseModel: observedUpstreamResponseModel(c),
|
||||
UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c),
|
||||
UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c),
|
||||
ReasoningEffort: reasoningEffort,
|
||||
ServiceTier: serviceTier,
|
||||
ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier),
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
}, nil
|
||||
|
||||
@@ -607,6 +607,86 @@ func TestForwardAsRawChatCompletions_SilentRefusalNormalContentExempt(t *testing
|
||||
require.Contains(t, rec.Body.String(), "data: [DONE]")
|
||||
}
|
||||
|
||||
// TestForwardAsRawChatCompletions_StripsEmptyToolCallIdentity 端到端验证 raw
|
||||
// CC 流式直转路径剔除 DashScope/DeepSeek 后续参数 delta 的空 id/name:
|
||||
// 下游仍保留首包合法 id/name 与 arguments 碎片,但后续 delta 不再带
|
||||
// `"id":""` / `"name":""`,避免 dsh 等客户端用 `!== undefined` 合并时把
|
||||
// 首包合法值覆盖掉(ToolNotFoundError: unknown tool "")。
|
||||
func TestForwardAsRawChatCompletions_StripsEmptyToolCallIdentity(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
body := []byte(`{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"weather"}],"stream":true}`)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstreamBody := strings.Join([]string{
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_example","type":"function","function":{"name":"web_search","arguments":""}}]}}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"{\"query\":"}}]}}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"","type":"function","function":{"name":"","arguments":"\"example\"}"}}]}}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_tool","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
}, "\n")
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_tool_identity"}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
}}
|
||||
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: rawChatCompletionsTestConfig(),
|
||||
httpUpstream: upstream,
|
||||
}
|
||||
account := rawChatCompletionsTestAccount()
|
||||
|
||||
result, err := svc.forwardAsRawChatCompletions(context.Background(), c, account, body, "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
|
||||
downstream := rec.Body.String()
|
||||
require.Contains(t, downstream, `"id":"call_example"`)
|
||||
require.Contains(t, downstream, `"name":"web_search"`)
|
||||
require.Contains(t, downstream, `{\"query\":`)
|
||||
require.Contains(t, downstream, `\"example\"}`)
|
||||
require.Contains(t, downstream, "data: [DONE]")
|
||||
require.NotContains(t, downstream, `"id":""`)
|
||||
require.NotContains(t, downstream, `"name":""`)
|
||||
|
||||
// 逐条扫下游 data payload:后续参数 delta 的 tool_calls.0.id /
|
||||
// function.name 必须已剔除(Exists() == false),首包合法值保留。
|
||||
followUpSeen := false
|
||||
for _, line := range strings.Split(downstream, "\n") {
|
||||
payload, ok := extractOpenAISSEDataLine(line)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
trimmed := strings.TrimSpace(payload)
|
||||
if trimmed == "" || trimmed == "[DONE]" {
|
||||
continue
|
||||
}
|
||||
delta := gjson.Get(payload, "choices.0.delta")
|
||||
if !delta.Exists() || !delta.Get("tool_calls").Exists() {
|
||||
continue
|
||||
}
|
||||
id := delta.Get("tool_calls.0.id")
|
||||
if id.String() == "call_example" {
|
||||
require.Equal(t, "web_search", delta.Get("tool_calls.0.function.name").String())
|
||||
continue
|
||||
}
|
||||
require.False(t, id.Exists(), "empty id must be stripped: %s", payload)
|
||||
require.False(t, delta.Get("tool_calls.0.function.name").Exists(), "empty name must be stripped: %s", payload)
|
||||
require.NotEmpty(t, delta.Get("tool_calls.0.function.arguments").String())
|
||||
followUpSeen = true
|
||||
}
|
||||
require.True(t, followUpSeen)
|
||||
}
|
||||
|
||||
func TestForwardAsRawChatCompletions_ClientDisconnectDrainsUsage(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user