mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-24 05:02:20 +08:00
fix(billing): 自动对账未知模型用量 (#1315)
This commit is contained in:
17 files changed
+816
-30
No files matched your search
+1
-1
@@ -193,7 +193,7 @@ Agent 按资源类型读取 `/api/v1/settings`、`/api/v1/models`、`/api/v1/rul
|
||||
- 模型调用沿用 `/v1/chat/completions`、`/v1/responses`、`/v1/messages`;MCP 使用 `POST /mcp/connectors/{id}/credentials/{credential_id}`,免认证使用 `POST /mcp/connectors/{id}`;全局调用密钥认证用户,地址确定授权资源,密钥作用域为 `mcp:invoke`。集中认证工具成功收费;独立认证、免认证和明确失败不收费。入口采用无状态 Streamable HTTP,支持握手、通知、工具列表和调用,返回 JSON;上游 JSON/SSE 均可解析。OAuth 调用前自动刷新,每次上游会话结束后清理。详见 [MCP 接入说明](backend/api/README.md#mcp-代理)。
|
||||
- 返回的 `X-Billing-Transaction-ID` 关联真实交易;可选 `Idempotency-Key` 重复请求返回原交易 ID 和 409,禁止再次执行;`X-Session-ID` 可选,提供时验证所属用户。
|
||||
- 周期采用上海时区;每分钟准备最多 100 个账户,读取或调用时兜底开户。额度变更不重发当期余额;周期切换在当前周期结束时生效。未消费余额不结转,跨周期调用仍结算到原账户。
|
||||
- 待结算交易按原交易 ID 自动重试,最多退避一小时;执行中断 30 分钟后转核查,不自动重放上游。管理端可填写证据和用量处理未知结果,已结算本地扣款通过关联冲正全额退款。流水禁止更新或删除。
|
||||
- 待结算交易按原交易 ID 自动重试,最多退避一小时;执行中断 30 分钟后转核查,不自动重放上游。`openai_responses` 调用会从早期流事件保存上游响应 ID;用量未知时,后台使用原模型凭据只读查询同一响应,只有取得完整真实 usage 才自动结算,处理中按退避重试 8 次,不支持查询或证据不足时继续保留人工核查。管理端可填写证据和用量处理未知结果,已结算本地扣款通过关联冲正全额退款。流水禁止更新或删除。
|
||||
|
||||
### 百智云钱包
|
||||
|
||||
|
||||
@@ -140,7 +140,12 @@ export type Transaction = {
|
||||
cached_input_tokens: number
|
||||
output_tokens: number
|
||||
known: boolean
|
||||
stream?: boolean
|
||||
result: string
|
||||
error_code?: string
|
||||
terminal_event?: string
|
||||
initial_error_code?: string
|
||||
reconciled?: boolean
|
||||
}
|
||||
entries?: Entry[]
|
||||
wallet_records?: {
|
||||
|
||||
@@ -365,7 +365,8 @@ export function BillingDetailsPage() {
|
||||
{view === "pending" && (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
这里只重试扣费确认;结果未知的业务调用不会自动重新执行。百智云历史余额以钱包侧记录为准。
|
||||
系统会自动重试扣费确认,并对带上游响应 ID 的 Responses
|
||||
异常查询真实用量;不会重新执行模型调用,证据不足时仍需人工核查。百智云历史余额以钱包侧记录为准。
|
||||
</p>
|
||||
{!!pending?.differences.length && (
|
||||
<div
|
||||
@@ -613,6 +614,34 @@ function TransactionDialog({
|
||||
<dd className="break-all">{data.session_id || "未关联会话"}</dd>
|
||||
<dt className="text-muted-foreground">原始计价</dt>
|
||||
<dd>{credits(data.raw_amount)} 积分</dd>
|
||||
{data.request_id && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">上游响应 ID</dt>
|
||||
<dd className="font-mono text-xs break-all">
|
||||
{data.request_id}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
{data.usage?.stream !== undefined && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">响应方式</dt>
|
||||
<dd>{data.usage.stream ? "流式" : "非流式"}</dd>
|
||||
</>
|
||||
)}
|
||||
{data.usage?.terminal_event && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">终止事件</dt>
|
||||
<dd className="font-mono text-xs break-all">
|
||||
{data.usage.terminal_event}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
{data.usage?.reconciled && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">用量来源</dt>
|
||||
<dd>上游自动对账</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{data.usage && data.category === "model" && (
|
||||
<Table>
|
||||
@@ -658,6 +687,11 @@ function TransactionDialog({
|
||||
处理原因:{data.error_code}
|
||||
</p>
|
||||
)}
|
||||
{data.usage?.initial_error_code && (
|
||||
<p className="rounded-md border p-3 text-sm">
|
||||
自动对账前原因:{data.usage.initial_error_code}
|
||||
</p>
|
||||
)}
|
||||
{data.wallet_records?.map((w) => (
|
||||
<div key={w.biz_id} className="rounded-md border p-3 text-xs">
|
||||
<p>百智云业务单:{w.biz_id}</p>
|
||||
|
||||
@@ -5079,6 +5079,9 @@ components:
|
||||
properties:
|
||||
known:
|
||||
type: boolean
|
||||
stream:
|
||||
type: boolean
|
||||
description: 是否为流式调用;历史记录可能缺失。
|
||||
result:
|
||||
enum:
|
||||
- succeeded
|
||||
@@ -5088,6 +5091,15 @@ components:
|
||||
type: string
|
||||
error_code:
|
||||
type: string
|
||||
terminal_event:
|
||||
type: string
|
||||
description: 代理观察到的流终止事件或非流式响应状态。
|
||||
initial_error_code:
|
||||
type: string
|
||||
description: 自动对账前的原始异常原因。
|
||||
reconciled:
|
||||
type: boolean
|
||||
description: 是否已通过上游查询自动补全用量。
|
||||
input_tokens:
|
||||
type: integer
|
||||
minimum: 0
|
||||
|
||||
@@ -104,6 +104,7 @@ func newApplicationHandler(ctx context.Context, logger *slog.Logger, pool *pgxpo
|
||||
identities.WithAccountPreserver(charges)
|
||||
keys := apikey.NewService(apikey.NewPostgres(pool))
|
||||
modelRepo := model.NewPostgres(pool)
|
||||
charges.WithUsageReconciler(modelUsageReconciler{models: modelRepo, responses: proxy.NewResponseReconciler()})
|
||||
models := model.NewService(modelRepo).WithKeyAuthenticator(keys).WithGatewayURL(strings.TrimRight(cfg.PublicURL, "/") + "/v1")
|
||||
storage, err := resource.NewS3(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,12 +3,14 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/billing"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/endpoint"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/mcp"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/proxy"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
@@ -21,6 +23,54 @@ type applicationHandler struct {
|
||||
}
|
||||
type modelBilling struct{ service *billing.Service }
|
||||
|
||||
type reconciliationModels interface {
|
||||
Get(context.Context, string) (model.Model, error)
|
||||
}
|
||||
|
||||
type modelUsageReconciler struct {
|
||||
models reconciliationModels
|
||||
responses *proxy.ResponseReconciler
|
||||
}
|
||||
|
||||
func (r modelUsageReconciler) Reconcile(ctx context.Context, request billing.ReconciliationRequest) (billing.ReconciliationResult, error) {
|
||||
item, err := r.models.Get(ctx, request.ResourceID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return billing.ReconciliationResult{State: billing.ReconciliationUnsupported}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return billing.ReconciliationResult{}, err
|
||||
}
|
||||
result, err := r.responses.Reconcile(ctx, proxy.Target{
|
||||
ModelID: item.ID,
|
||||
UpstreamModel: item.ModelID,
|
||||
Protocol: string(item.Protocol),
|
||||
BaseURL: item.BaseURL,
|
||||
APIKey: item.APIKey,
|
||||
}, request.RequestID)
|
||||
if err != nil {
|
||||
return billing.ReconciliationResult{}, err
|
||||
}
|
||||
switch result.State {
|
||||
case proxy.ResponseReconciliationPending:
|
||||
return billing.ReconciliationResult{State: billing.ReconciliationPending}, nil
|
||||
case proxy.ResponseReconciliationUnsupported:
|
||||
return billing.ReconciliationResult{State: billing.ReconciliationUnsupported}, nil
|
||||
case proxy.ResponseReconciliationResolved:
|
||||
if result.Call.InputTokens > math.MaxInt64 || result.Call.CachedInputTokens > math.MaxInt64 || result.Call.OutputTokens > math.MaxInt64 || result.Call.CachedInputTokens > result.Call.InputTokens {
|
||||
return billing.ReconciliationResult{State: billing.ReconciliationUnsupported}, nil
|
||||
}
|
||||
return billing.ReconciliationResult{
|
||||
State: billing.ReconciliationResolved,
|
||||
Usage: billing.Usage{
|
||||
Input: int64(result.Call.InputTokens), Cached: int64(result.Call.CachedInputTokens), Output: int64(result.Call.OutputTokens),
|
||||
Known: true, Result: result.Call.Result, RequestID: result.Call.RequestID,
|
||||
},
|
||||
}, nil
|
||||
default:
|
||||
return billing.ReconciliationResult{State: billing.ReconciliationUnsupported}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (b modelBilling) Begin(ctx context.Context, t proxy.Target, r proxy.BillingRequest) (proxy.Reservation, error) {
|
||||
var data map[string]json.RawMessage
|
||||
if err := json.Unmarshal(r.Body, &data); err != nil {
|
||||
@@ -60,7 +110,12 @@ func (b modelBilling) Finish(ctx context.Context, id string, c proxy.Call) error
|
||||
if c.InputTokens > math.MaxInt64 || c.CachedInputTokens > math.MaxInt64 || c.OutputTokens > math.MaxInt64 {
|
||||
return b.service.Finish(ctx, id, billing.Usage{Result: "failed", ErrorCode: "invalid_usage"})
|
||||
}
|
||||
return b.service.Finish(ctx, id, billing.Usage{Input: int64(c.InputTokens), Cached: int64(c.CachedInputTokens), Output: int64(c.OutputTokens), Known: c.Known, Result: c.Result, ErrorCode: c.ErrorCode, RequestID: c.RequestID})
|
||||
stream := c.Stream
|
||||
return b.service.Finish(ctx, id, billing.Usage{
|
||||
Input: int64(c.InputTokens), Cached: int64(c.CachedInputTokens), Output: int64(c.OutputTokens),
|
||||
Known: c.Known, Stream: &stream, Result: c.Result, ErrorCode: c.ErrorCode,
|
||||
RequestID: c.RequestID, TerminalEvent: c.TerminalEvent,
|
||||
})
|
||||
}
|
||||
|
||||
type toolBilling struct{ service *billing.Service }
|
||||
|
||||
@@ -879,6 +879,14 @@ SELECT
|
||||
SELECT
|
||||
pg_advisory_unlock(hashtextextended($1, 41));
|
||||
|
||||
-- name: TryReconciliationLock :one
|
||||
SELECT
|
||||
pg_try_advisory_lock(hashtextextended($1, 42));
|
||||
|
||||
-- name: ReleaseReconciliationLock :execresult
|
||||
SELECT
|
||||
pg_advisory_unlock(hashtextextended($1, 42));
|
||||
|
||||
-- name: SettlementStatus :one
|
||||
SELECT
|
||||
MODE,
|
||||
@@ -959,7 +967,46 @@ SET
|
||||
attempts = attempts + 1,
|
||||
next_retry_at = now() + make_interval(secs => LEAST (3600, 30 * power(2, LEAST (attempts, 7)))::int)
|
||||
WHERE
|
||||
id = $1;
|
||||
id = $1
|
||||
AND status IN ('settling', 'unknown');
|
||||
|
||||
-- name: TransactionsToReconcile :many
|
||||
SELECT
|
||||
id,
|
||||
resource_id,
|
||||
request_id,
|
||||
USAGE,
|
||||
error_code,
|
||||
attempts
|
||||
FROM
|
||||
billing_transactions
|
||||
WHERE
|
||||
status = 'unknown'
|
||||
AND category = 'model'
|
||||
AND request_id <> ''
|
||||
AND next_retry_at IS NOT NULL
|
||||
AND next_retry_at <= now()
|
||||
AND (error_code = 'usage_unknown'
|
||||
OR error_code = 'usage_missing'
|
||||
OR error_code = 'usage_incomplete'
|
||||
OR error_code = 'usage_parse_failed'
|
||||
OR error_code = 'usage_read_failed'
|
||||
OR error_code = 'usage_terminal_event_missing'
|
||||
OR error_code = 'stream_interrupted'
|
||||
OR error_code = 'upstream_error_event')
|
||||
ORDER BY
|
||||
started_at
|
||||
LIMIT 100;
|
||||
|
||||
-- name: StopReconciliation :execresult
|
||||
UPDATE
|
||||
billing_transactions
|
||||
SET
|
||||
next_retry_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE
|
||||
id = $1
|
||||
AND status = 'unknown';
|
||||
|
||||
-- name: ActiveUsersWithoutAccount :many
|
||||
SELECT
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package billing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/billing/sqlc"
|
||||
)
|
||||
|
||||
type ReconciliationState string
|
||||
|
||||
const (
|
||||
ReconciliationResolved ReconciliationState = "resolved"
|
||||
ReconciliationPending ReconciliationState = "pending"
|
||||
ReconciliationUnsupported ReconciliationState = "unsupported"
|
||||
)
|
||||
|
||||
type ReconciliationRequest struct {
|
||||
TransactionID string
|
||||
ResourceID string
|
||||
RequestID string
|
||||
}
|
||||
|
||||
type ReconciliationResult struct {
|
||||
State ReconciliationState
|
||||
Usage Usage
|
||||
}
|
||||
|
||||
type UsageReconciler interface {
|
||||
Reconcile(context.Context, ReconciliationRequest) (ReconciliationResult, error)
|
||||
}
|
||||
|
||||
const maxReconciliationAttempts = 8
|
||||
|
||||
func (s *Service) reconcileUnknown(ctx context.Context) error {
|
||||
if s.reconciler == nil {
|
||||
return nil
|
||||
}
|
||||
rows, err := sqlc.New(s.pool).TransactionsToReconcile(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Attempts >= maxReconciliationAttempts {
|
||||
if _, err := sqlc.New(s.pool).StopReconciliation(ctx, row.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
slog.WarnContext(ctx, "模型用量自动对账已停止", "transaction_id", row.ID, "attempts", row.Attempts)
|
||||
continue
|
||||
}
|
||||
attemptCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
err := s.reconcileUsage(attemptCtx, row)
|
||||
cancel()
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
slog.WarnContext(ctx, "模型用量自动对账失败", "transaction_id", row.ID, "error", err)
|
||||
if _, scheduleErr := sqlc.New(s.pool).ScheduleRetry(ctx, row.ID); scheduleErr != nil {
|
||||
return scheduleErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) reconcileUsage(ctx context.Context, row sqlc.TransactionsToReconcileRow) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Release()
|
||||
locked, err := sqlc.New(conn).TryReconciliationLock(ctx, row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !locked {
|
||||
return nil
|
||||
}
|
||||
defer func() {
|
||||
releaseCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, releaseErr := sqlc.New(conn).ReleaseReconciliationLock(releaseCtx, row.ID); releaseErr != nil {
|
||||
conn.Conn().Close(releaseCtx)
|
||||
}
|
||||
}()
|
||||
|
||||
status, err := sqlc.New(conn).TransactionStatus(ctx, row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status != "unknown" {
|
||||
return nil
|
||||
}
|
||||
result, err := s.reconciler.Reconcile(ctx, ReconciliationRequest{
|
||||
TransactionID: row.ID,
|
||||
ResourceID: row.ResourceID,
|
||||
RequestID: row.RequestID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch result.State {
|
||||
case ReconciliationPending:
|
||||
_, err = sqlc.New(conn).ScheduleRetry(ctx, row.ID)
|
||||
return err
|
||||
case ReconciliationUnsupported:
|
||||
_, err = sqlc.New(conn).StopReconciliation(ctx, row.ID)
|
||||
return err
|
||||
case ReconciliationResolved:
|
||||
if !result.Usage.Known {
|
||||
_, err = sqlc.New(conn).StopReconciliation(ctx, row.ID)
|
||||
if err == nil {
|
||||
slog.ErrorContext(ctx, "对账器返回了不可信用量", "transaction_id", row.ID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
default:
|
||||
_, err = sqlc.New(conn).StopReconciliation(ctx, row.ID)
|
||||
if err == nil {
|
||||
slog.ErrorContext(ctx, "对账器返回了未知结果", "transaction_id", row.ID, "state", result.State)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var original Usage
|
||||
if err := json.Unmarshal(row.Usage, &original); err != nil {
|
||||
return fmt.Errorf("读取原始用量证据: %w", err)
|
||||
}
|
||||
result.Usage.Stream = original.Stream
|
||||
result.Usage.TerminalEvent = original.TerminalEvent
|
||||
result.Usage.InitialErrorCode = row.ErrorCode
|
||||
result.Usage.Reconciled = true
|
||||
if result.Usage.RequestID == "" {
|
||||
result.Usage.RequestID = row.RequestID
|
||||
}
|
||||
if err := s.Finish(ctx, row.ID, result.Usage); err != nil {
|
||||
return err
|
||||
}
|
||||
slog.InfoContext(ctx, "模型用量自动对账已补全", "transaction_id", row.ID, "request_id", row.RequestID)
|
||||
return nil
|
||||
}
|
||||
@@ -106,12 +106,20 @@ type Service struct {
|
||||
pool *pgxpool.Pool
|
||||
now func() time.Time
|
||||
fallback *Wallet
|
||||
reconciler UsageReconciler
|
||||
walletMu sync.Mutex
|
||||
cachedWallet *Wallet
|
||||
}
|
||||
|
||||
func NewService(pool *pgxpool.Pool) *Service { return &Service{pool: pool, now: time.Now} }
|
||||
func (s *Service) WithWallet(w *Wallet) *Service { s.fallback = w; return s }
|
||||
func NewService(pool *pgxpool.Pool) *Service { return &Service{pool: pool, now: time.Now} }
|
||||
func (s *Service) WithWallet(w *Wallet) *Service {
|
||||
s.fallback = w
|
||||
return s
|
||||
}
|
||||
func (s *Service) WithUsageReconciler(r UsageReconciler) *Service {
|
||||
s.reconciler = r
|
||||
return s
|
||||
}
|
||||
func (s *Service) Initialize(ctx context.Context) error {
|
||||
p := defaultPolicy()
|
||||
b, _ := json.Marshal(p)
|
||||
|
||||
@@ -478,6 +478,64 @@ func TestMissingUsageKeepsReservation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type usageReconcilerStub struct {
|
||||
requests []ReconciliationRequest
|
||||
result ReconciliationResult
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *usageReconcilerStub) Reconcile(_ context.Context, request ReconciliationRequest) (ReconciliationResult, error) {
|
||||
s.requests = append(s.requests, request)
|
||||
return s.result, s.err
|
||||
}
|
||||
|
||||
func TestUnknownUsageIsAutomaticallyReconciled(t *testing.T) {
|
||||
s, user, model := fixture(t)
|
||||
ctx := t.Context()
|
||||
reconciler := &usageReconcilerStub{result: ReconciliationResult{
|
||||
State: ReconciliationResolved,
|
||||
Usage: Usage{Known: true, Result: "succeeded", RequestID: "resp_test", Input: 10000, Cached: 4000, Output: 2000},
|
||||
}}
|
||||
s.WithUsageReconciler(reconciler)
|
||||
r, err := s.Begin(ctx, Request{UserID: user, ResourceID: model, Category: "model"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Start(ctx, r.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream := true
|
||||
if err = s.Finish(ctx, r.ID, Usage{
|
||||
Known: false, Stream: &stream, Result: "failed", RequestID: "resp_test",
|
||||
ErrorCode: "usage_missing", TerminalEvent: "response.failed",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.recover(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reconciler.requests) != 1 || reconciler.requests[0].TransactionID != r.ID || reconciler.requests[0].RequestID != "resp_test" {
|
||||
t.Fatalf("对账请求不正确: %+v", reconciler.requests)
|
||||
}
|
||||
|
||||
var state string
|
||||
var raw []byte
|
||||
if err = s.pool.QueryRow(ctx, `SELECT status, usage FROM billing_transactions WHERE id=$1`, r.ID).Scan(&state, &raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var usage Usage
|
||||
if err = json.Unmarshal(raw, &usage); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state != "settled" || !usage.Reconciled || usage.InitialErrorCode != "usage_missing" || usage.Stream == nil || !*usage.Stream || usage.TerminalEvent != "response.failed" {
|
||||
t.Fatalf("自动对账证据不完整: state=%s usage=%+v", state, usage)
|
||||
}
|
||||
a, err := s.Account(ctx, user)
|
||||
if err != nil || a.Balance != amountText("14998.52") || a.Frozen != 0 {
|
||||
t.Fatal(a, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaChangePreservesUnopenedAccount(t *testing.T) {
|
||||
s, user, _ := fixture(t)
|
||||
ctx := t.Context()
|
||||
|
||||
@@ -1651,6 +1651,15 @@ func (q *Queries) ReleaseFrozenBalance(ctx context.Context, id string) (pgconn.C
|
||||
return q.db.Exec(ctx, releaseFrozenBalance, id)
|
||||
}
|
||||
|
||||
const releaseReconciliationLock = `-- name: ReleaseReconciliationLock :execresult
|
||||
SELECT
|
||||
pg_advisory_unlock(hashtextextended($1, 42))
|
||||
`
|
||||
|
||||
func (q *Queries) ReleaseReconciliationLock(ctx context.Context, hashtextextended string) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, releaseReconciliationLock, hashtextextended)
|
||||
}
|
||||
|
||||
const releaseSettlementLock = `-- name: ReleaseSettlementLock :execresult
|
||||
SELECT
|
||||
pg_advisory_unlock(hashtextextended($1, 41))
|
||||
@@ -1748,6 +1757,7 @@ SET
|
||||
next_retry_at = now() + make_interval(secs => LEAST (3600, 30 * power(2, LEAST (attempts, 7)))::int)
|
||||
WHERE
|
||||
id = $1
|
||||
AND status IN ('settling', 'unknown')
|
||||
`
|
||||
|
||||
func (q *Queries) ScheduleRetry(ctx context.Context, id string) (pgconn.CommandTag, error) {
|
||||
@@ -1951,6 +1961,21 @@ func (q *Queries) StartTransaction(ctx context.Context, id string) (pgconn.Comma
|
||||
return q.db.Exec(ctx, startTransaction, id)
|
||||
}
|
||||
|
||||
const stopReconciliation = `-- name: StopReconciliation :execresult
|
||||
UPDATE
|
||||
billing_transactions
|
||||
SET
|
||||
next_retry_at = NULL,
|
||||
updated_at = now()
|
||||
WHERE
|
||||
id = $1
|
||||
AND status = 'unknown'
|
||||
`
|
||||
|
||||
func (q *Queries) StopReconciliation(ctx context.Context, id string) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, stopReconciliation, id)
|
||||
}
|
||||
|
||||
const subjectExists = `-- name: SubjectExists :one
|
||||
SELECT
|
||||
CASE WHEN $1::text = 'group' THEN
|
||||
@@ -2177,6 +2202,71 @@ func (q *Queries) TransactionWalletRecords(ctx context.Context, transactionID st
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const transactionsToReconcile = `-- name: TransactionsToReconcile :many
|
||||
SELECT
|
||||
id,
|
||||
resource_id,
|
||||
request_id,
|
||||
USAGE,
|
||||
error_code,
|
||||
attempts
|
||||
FROM
|
||||
billing_transactions
|
||||
WHERE
|
||||
status = 'unknown'
|
||||
AND category = 'model'
|
||||
AND request_id <> ''
|
||||
AND next_retry_at IS NOT NULL
|
||||
AND next_retry_at <= now()
|
||||
AND (error_code = 'usage_unknown'
|
||||
OR error_code = 'usage_missing'
|
||||
OR error_code = 'usage_incomplete'
|
||||
OR error_code = 'usage_parse_failed'
|
||||
OR error_code = 'usage_read_failed'
|
||||
OR error_code = 'usage_terminal_event_missing'
|
||||
OR error_code = 'stream_interrupted'
|
||||
OR error_code = 'upstream_error_event')
|
||||
ORDER BY
|
||||
started_at
|
||||
LIMIT 100
|
||||
`
|
||||
|
||||
type TransactionsToReconcileRow struct {
|
||||
ID string
|
||||
ResourceID string
|
||||
RequestID string
|
||||
Usage []byte
|
||||
ErrorCode string
|
||||
Attempts int32
|
||||
}
|
||||
|
||||
func (q *Queries) TransactionsToReconcile(ctx context.Context) ([]TransactionsToReconcileRow, error) {
|
||||
rows, err := q.db.Query(ctx, transactionsToReconcile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []TransactionsToReconcileRow{}
|
||||
for rows.Next() {
|
||||
var i TransactionsToReconcileRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ResourceID,
|
||||
&i.RequestID,
|
||||
&i.Usage,
|
||||
&i.ErrorCode,
|
||||
&i.Attempts,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const transactionsToRetry = `-- name: TransactionsToRetry :many
|
||||
SELECT
|
||||
id
|
||||
@@ -2211,6 +2301,18 @@ func (q *Queries) TransactionsToRetry(ctx context.Context) ([]string, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const tryReconciliationLock = `-- name: TryReconciliationLock :one
|
||||
SELECT
|
||||
pg_try_advisory_lock(hashtextextended($1, 42))
|
||||
`
|
||||
|
||||
func (q *Queries) TryReconciliationLock(ctx context.Context, hashtextextended string) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, tryReconciliationLock, hashtextextended)
|
||||
var pg_try_advisory_lock bool
|
||||
err := row.Scan(&pg_try_advisory_lock)
|
||||
return pg_try_advisory_lock, err
|
||||
}
|
||||
|
||||
const trySettlementLock = `-- name: TrySettlementLock :one
|
||||
SELECT
|
||||
pg_try_advisory_lock(hashtextextended($1, 41))
|
||||
|
||||
@@ -23,13 +23,17 @@ type Reservation struct {
|
||||
OutputLimit int64
|
||||
}
|
||||
type Usage struct {
|
||||
Input int64 `json:"input_tokens"`
|
||||
Cached int64 `json:"cached_input_tokens"`
|
||||
Output int64 `json:"output_tokens"`
|
||||
Known bool `json:"known"`
|
||||
Result string `json:"result"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
Input int64 `json:"input_tokens"`
|
||||
Cached int64 `json:"cached_input_tokens"`
|
||||
Output int64 `json:"output_tokens"`
|
||||
Known bool `json:"known"`
|
||||
Stream *bool `json:"stream,omitempty"`
|
||||
Result string `json:"result"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
TerminalEvent string `json:"terminal_event,omitempty"`
|
||||
InitialErrorCode string `json:"initial_error_code,omitempty"`
|
||||
Reconciled bool `json:"reconciled,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) Begin(ctx context.Context, r Request) (Reservation, error) {
|
||||
@@ -466,7 +470,7 @@ func (s *Service) recover(ctx context.Context) error {
|
||||
_, _ = sqlc.New(s.pool).ScheduleRetry(ctx, id)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return s.reconcileUnknown(ctx)
|
||||
}
|
||||
func (s *Service) Run(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
|
||||
@@ -56,3 +56,42 @@ func TestIncompleteUsageIsNotFreeUsage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesStreamPreservesReconciliationEvidence(t *testing.T) {
|
||||
body := "event: response.created\ndata: {\"response\":{\"id\":\"resp_reconcile\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"event: response.failed\ndata: {\"response\":{\"id\":\"resp_reconcile\",\"status\":\"failed\"}}\n\n"
|
||||
got := newUsageCaptureForTest("/v1/responses", true, body).handleStream()
|
||||
if got.Known || got.Result != "failed" || got.ResponseID != "resp_reconcile" {
|
||||
t.Fatalf("失败事件证据不完整: %+v", got)
|
||||
}
|
||||
if got.ErrorCode != "usage_missing" || got.TerminalEvent != "response.failed" {
|
||||
t.Fatalf("失败原因不准确: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesStreamClassifiesUnknownUsage(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
code string
|
||||
}{
|
||||
{
|
||||
name: "缺少终止事件",
|
||||
body: "event: response.created\ndata: {\"response\":{\"id\":\"resp_started\"}}\n\n",
|
||||
code: "usage_terminal_event_missing",
|
||||
},
|
||||
{
|
||||
name: "上游错误事件",
|
||||
body: "event: error\ndata: {\"type\":\"error\",\"message\":\"failed\"}\n\n",
|
||||
code: "upstream_error_event",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := newUsageCaptureForTest("/v1/responses", true, test.body).handleStream()
|
||||
if got.Known || got.ErrorCode != test.code {
|
||||
t.Fatalf("未知用量分类错误: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -176,8 +176,8 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
body, err = billRequest(body, r.URL.Path, reservation.OutputLimit, meta.Stream)
|
||||
if err != nil {
|
||||
pc := &proxyContext{reservation: reservation}
|
||||
p.finish(r.Context(), pc, Call{Known: true, Result: "failed", ErrorCode: "invalid_request"})
|
||||
pc := &proxyContext{reservation: reservation, stream: meta.Stream}
|
||||
p.finish(r.Context(), pc, Call{Known: true, Stream: meta.Stream, Result: "failed", ErrorCode: "invalid_request"})
|
||||
billingError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -258,7 +258,7 @@ func (p *Proxy) rewrite(r *httputil.ProxyRequest) {
|
||||
|
||||
func (p *Proxy) errorHandler(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if pc, ok := r.Context().Value(proxyContextKey{}).(*proxyContext); ok {
|
||||
p.finish(r.Context(), pc, Call{Result: "failed", ErrorCode: "upstream_connection_failed"})
|
||||
p.finish(r.Context(), pc, Call{Stream: pc.stream, Result: "failed", ErrorCode: "upstream_connection_failed"})
|
||||
}
|
||||
p.logger.ErrorContext(r.Context(), "模型上游请求失败", "path", r.URL.Path, "error", err)
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ResponseReconciliationState string
|
||||
|
||||
const (
|
||||
ResponseReconciliationResolved ResponseReconciliationState = "resolved"
|
||||
ResponseReconciliationPending ResponseReconciliationState = "pending"
|
||||
ResponseReconciliationUnsupported ResponseReconciliationState = "unsupported"
|
||||
)
|
||||
|
||||
type ResponseReconciliation struct {
|
||||
State ResponseReconciliationState
|
||||
Call Call
|
||||
}
|
||||
|
||||
type ResponseReconciler struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewResponseReconciler() *ResponseReconciler {
|
||||
return &ResponseReconciler{client: &http.Client{
|
||||
Transport: http.DefaultTransport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func (r *ResponseReconciler) WithTransport(transport http.RoundTripper) *ResponseReconciler {
|
||||
if transport != nil {
|
||||
r.client.Transport = transport
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *ResponseReconciler) Reconcile(ctx context.Context, target Target, responseID string) (ResponseReconciliation, error) {
|
||||
if target.Protocol != "openai_responses" || responseID == "" || responseID == "." || responseID == ".." || strings.ContainsAny(responseID, `/\\`) {
|
||||
return ResponseReconciliation{State: ResponseReconciliationUnsupported}, nil
|
||||
}
|
||||
endpoint, err := parseBaseURL(target.BaseURL)
|
||||
if err != nil {
|
||||
return ResponseReconciliation{}, err
|
||||
}
|
||||
endpoint = endpoint.JoinPath("responses", responseID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return ResponseReconciliation{}, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if target.APIKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+target.APIKey)
|
||||
req.Header.Set("X-Api-Key", target.APIKey)
|
||||
}
|
||||
response, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return ResponseReconciliation{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
switch response.StatusCode {
|
||||
case http.StatusNotFound, http.StatusConflict, http.StatusTooEarly, http.StatusTooManyRequests:
|
||||
return ResponseReconciliation{State: ResponseReconciliationPending}, nil
|
||||
default:
|
||||
if response.StatusCode >= http.StatusInternalServerError {
|
||||
return ResponseReconciliation{State: ResponseReconciliationPending}, nil
|
||||
}
|
||||
return ResponseReconciliation{State: ResponseReconciliationUnsupported}, nil
|
||||
}
|
||||
}
|
||||
|
||||
const maxResponseSize = 32 << 20
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseSize+1))
|
||||
if err != nil {
|
||||
return ResponseReconciliation{}, err
|
||||
}
|
||||
if len(body) > maxResponseSize {
|
||||
return ResponseReconciliation{}, fmt.Errorf("上游响应对账结果超过 %d 字节", maxResponseSize)
|
||||
}
|
||||
stored, err := parseOpenAIResponse(body)
|
||||
if err != nil {
|
||||
return ResponseReconciliation{}, fmt.Errorf("解析上游响应对账结果: %w", err)
|
||||
}
|
||||
if stored.ID != "" && stored.ID != responseID {
|
||||
return ResponseReconciliation{State: ResponseReconciliationUnsupported}, nil
|
||||
}
|
||||
if stored.Status == "queued" || stored.Status == "in_progress" {
|
||||
return ResponseReconciliation{State: ResponseReconciliationPending}, nil
|
||||
}
|
||||
if stored.Usage == nil || !stored.Usage.inputKnown || !stored.Usage.outputKnown {
|
||||
return ResponseReconciliation{State: ResponseReconciliationUnsupported}, nil
|
||||
}
|
||||
|
||||
result := "succeeded"
|
||||
switch stored.Status {
|
||||
case "", "completed":
|
||||
case "failed", "incomplete", "cancelled", "canceled":
|
||||
result = "failed"
|
||||
default:
|
||||
return ResponseReconciliation{State: ResponseReconciliationUnsupported}, nil
|
||||
}
|
||||
requestID := stored.ID
|
||||
if requestID == "" {
|
||||
requestID = responseID
|
||||
}
|
||||
return ResponseReconciliation{
|
||||
State: ResponseReconciliationResolved,
|
||||
Call: Call{
|
||||
RequestID: requestID,
|
||||
Known: true,
|
||||
Result: result,
|
||||
InputTokens: stored.Usage.InputTokens,
|
||||
CachedInputTokens: stored.Usage.InputTokensDetails.CachedTokens,
|
||||
OutputTokens: stored.Usage.OutputTokens,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResponseReconcilerRetrievesUsage(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/gateway/v1/responses/resp_test" || r.URL.RawQuery != "api-version=2026-09-01" {
|
||||
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer upstream-secret" || r.Header.Get("X-Api-Key") != "upstream-secret" {
|
||||
t.Fatal("upstream credentials missing")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":"resp_test",
|
||||
"status":"completed",
|
||||
"usage":{"input_tokens":13,"output_tokens":5,"input_tokens_details":{"cached_tokens":3}}
|
||||
}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
target := testTarget(server.URL + "/gateway/v1?api-version=2026-09-01")
|
||||
target.Protocol = "openai_responses"
|
||||
|
||||
result, err := NewResponseReconciler().Reconcile(context.Background(), target, "resp_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.State != ResponseReconciliationResolved || !result.Call.Known || result.Call.Result != "succeeded" {
|
||||
t.Fatalf("reconciliation = %+v", result)
|
||||
}
|
||||
if result.Call.InputTokens != 13 || result.Call.CachedInputTokens != 3 || result.Call.OutputTokens != 5 {
|
||||
t.Fatalf("usage = %+v", result.Call)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseReconcilerKeepsUncertainResultsPending(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
want ResponseReconciliationState
|
||||
}{
|
||||
{name: "record delayed", status: http.StatusNotFound, want: ResponseReconciliationPending},
|
||||
{name: "still running", status: http.StatusOK, body: `{"id":"resp_test","status":"in_progress"}`, want: ResponseReconciliationPending},
|
||||
{name: "terminal without usage", status: http.StatusOK, body: `{"id":"resp_test","status":"failed"}`, want: ResponseReconciliationUnsupported},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(test.status)
|
||||
_, _ = w.Write([]byte(test.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
target := testTarget(server.URL + "/v1")
|
||||
target.Protocol = "openai_responses"
|
||||
result, err := NewResponseReconciler().Reconcile(context.Background(), target, "resp_test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.State != test.want {
|
||||
t.Fatalf("state = %q, want %q", result.State, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,10 @@ type Call struct {
|
||||
SessionID string
|
||||
RequestID string
|
||||
Known bool
|
||||
Stream bool
|
||||
Result string
|
||||
ErrorCode string
|
||||
TerminalEvent string
|
||||
InputTokens uint64
|
||||
OutputTokens uint64
|
||||
CachedInputTokens uint64
|
||||
@@ -36,6 +38,8 @@ type usageResult struct {
|
||||
CacheCreationInputTokens uint64
|
||||
Known bool
|
||||
Result string
|
||||
ErrorCode string
|
||||
TerminalEvent string
|
||||
}
|
||||
|
||||
func (r usageResult) totalTokens() uint64 {
|
||||
@@ -83,7 +87,7 @@ func (p *Proxy) modifyResponse(response *http.Response) error {
|
||||
}
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
if pc, ok := response.Request.Context().Value(proxyContextKey{}).(*proxyContext); ok {
|
||||
p.finish(response.Request.Context(), pc, Call{Known: response.StatusCode >= 400 && response.StatusCode < 500, Result: "failed", ErrorCode: "upstream_http_error"})
|
||||
p.finish(response.Request.Context(), pc, Call{Known: response.StatusCode >= 400 && response.StatusCode < 500, Stream: pc.stream, Result: "failed", ErrorCode: "upstream_http_error"})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -125,7 +129,9 @@ func (p *Proxy) recordUsage(ctx context.Context, proxyCtx *proxyContext, result
|
||||
UserID: target.UserID,
|
||||
SessionID: target.SessionID,
|
||||
RequestID: result.ResponseID,
|
||||
Known: result.Known, Result: result.Result,
|
||||
Known: result.Known, Stream: proxyCtx.stream, Result: result.Result,
|
||||
ErrorCode: result.ErrorCode,
|
||||
TerminalEvent: result.TerminalEvent,
|
||||
InputTokens: result.InputTokens + result.CacheReadInputTokens + result.CacheCreationInputTokens,
|
||||
OutputTokens: result.OutputTokens,
|
||||
CachedInputTokens: result.CacheReadInputTokens + result.CachedTokens,
|
||||
@@ -135,9 +141,19 @@ func (p *Proxy) recordUsage(ctx context.Context, proxyCtx *proxyContext, result
|
||||
if call.Result == "" {
|
||||
call.Result = "succeeded"
|
||||
}
|
||||
if !call.Known {
|
||||
if !call.Known && call.ErrorCode == "" {
|
||||
call.ErrorCode = "usage_unknown"
|
||||
}
|
||||
if !call.Known {
|
||||
p.logger.WarnContext(ctx, "模型用量无法确定",
|
||||
"transaction_id", proxyCtx.reservation.ID,
|
||||
"model_id", target.ModelID,
|
||||
"stream", proxyCtx.stream,
|
||||
"response_id", result.ResponseID,
|
||||
"terminal_event", result.TerminalEvent,
|
||||
"reason", call.ErrorCode,
|
||||
)
|
||||
}
|
||||
p.finish(ctx, proxyCtx, call)
|
||||
if p.recorder == nil || !result.hasTokens() {
|
||||
return
|
||||
@@ -162,38 +178,64 @@ func (c *usageCapture) handleShadow() {
|
||||
|
||||
func (c *usageCapture) handleStream() usageResult {
|
||||
var result usageResult
|
||||
var inputKnown, outputKnown bool
|
||||
var inputKnown, outputKnown, terminal, usageSeen bool
|
||||
decoder := newSSEDecoder(c.reader)
|
||||
logger := c.logger.With("path", c.ctx.path)
|
||||
transactionID := ""
|
||||
if c.ctx.proxyCtx != nil {
|
||||
transactionID = c.ctx.proxyCtx.reservation.ID
|
||||
}
|
||||
logger := c.logger.With("path", c.ctx.path, "transaction_id", transactionID)
|
||||
for decoder.Next() {
|
||||
event := decoder.Event()
|
||||
switch event.Type {
|
||||
case "response.completed", "response.failed", "response.incomplete":
|
||||
case "response.created", "response.in_progress", "response.completed", "response.failed", "response.incomplete":
|
||||
isTerminal := event.Type == "response.completed" || event.Type == "response.failed" || event.Type == "response.incomplete"
|
||||
if isTerminal {
|
||||
terminal = true
|
||||
result.TerminalEvent = event.Type
|
||||
}
|
||||
if event.Type != "response.completed" {
|
||||
result.Result = "failed"
|
||||
if isTerminal {
|
||||
result.Result = "failed"
|
||||
}
|
||||
}
|
||||
response, err := parseOpenAIResponseEvent(event.Data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Responses 流式用量失败", "error", err)
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Responses 流式事件失败", "event", event.Type, "error", err)
|
||||
if isTerminal {
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
}
|
||||
continue
|
||||
}
|
||||
if response.ID != "" {
|
||||
result.ResponseID = response.ID
|
||||
}
|
||||
if !isTerminal {
|
||||
continue
|
||||
}
|
||||
if response.Usage == nil {
|
||||
continue
|
||||
}
|
||||
usageSeen = true
|
||||
result.Known = response.Usage.inputKnown && response.Usage.outputKnown
|
||||
result.InputTokens = response.Usage.InputTokens
|
||||
result.OutputTokens = response.Usage.OutputTokens
|
||||
result.ResponseID = response.ID
|
||||
result.CachedTokens = response.Usage.InputTokensDetails.CachedTokens
|
||||
case "", "done":
|
||||
if event.Type == "done" {
|
||||
terminal = true
|
||||
result.TerminalEvent = "done"
|
||||
}
|
||||
response, err := parseChatCompletion(event.Data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Chat Completions 流式用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
continue
|
||||
}
|
||||
if response.Usage == nil {
|
||||
continue
|
||||
}
|
||||
usageSeen = true
|
||||
result.Known = response.Usage.complete
|
||||
result.InputTokens = response.Usage.PromptTokens
|
||||
result.OutputTokens = response.Usage.CompletionTokens
|
||||
@@ -203,12 +245,14 @@ func (c *usageCapture) handleStream() usageResult {
|
||||
response, err := parseAnthropicResponse(event.Data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Anthropic message_start 用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
continue
|
||||
}
|
||||
result.ResponseID = response.Message.ID
|
||||
if response.Message.Usage == nil {
|
||||
continue
|
||||
}
|
||||
usageSeen = true
|
||||
inputKnown = response.Message.Usage.inputKnown
|
||||
result.CacheCreationInputTokens = response.Message.Usage.CacheCreationInputTokens
|
||||
result.InputTokens = response.Message.Usage.InputTokens
|
||||
@@ -217,11 +261,13 @@ func (c *usageCapture) handleStream() usageResult {
|
||||
response, err := parseAnthropicResponse(event.Data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Anthropic message_delta 用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
continue
|
||||
}
|
||||
if response.Usage == nil {
|
||||
continue
|
||||
}
|
||||
usageSeen = true
|
||||
if response.Usage.InputTokens > 0 {
|
||||
result.InputTokens = response.Usage.InputTokens
|
||||
}
|
||||
@@ -231,25 +277,49 @@ func (c *usageCapture) handleStream() usageResult {
|
||||
result.CacheReadInputTokens = response.Usage.CacheReadInputTokens
|
||||
}
|
||||
case "message_stop":
|
||||
terminal = true
|
||||
result.TerminalEvent = event.Type
|
||||
result.Known = inputKnown && outputKnown
|
||||
case "error":
|
||||
terminal = true
|
||||
result.Result = "failed"
|
||||
result.Known = false
|
||||
result.ErrorCode = "upstream_error_event"
|
||||
result.TerminalEvent = event.Type
|
||||
}
|
||||
}
|
||||
if err := decoder.Err(); err != nil {
|
||||
result.Result = "failed"
|
||||
result.ErrorCode = "stream_interrupted"
|
||||
logger.WarnContext(c.ctx.ctx, "读取模型流式响应失败", "error", err)
|
||||
}
|
||||
if result.Known {
|
||||
result.ErrorCode = ""
|
||||
} else if result.ErrorCode == "" {
|
||||
switch {
|
||||
case usageSeen:
|
||||
result.ErrorCode = "usage_incomplete"
|
||||
case terminal:
|
||||
result.ErrorCode = "usage_missing"
|
||||
default:
|
||||
result.ErrorCode = "usage_terminal_event_missing"
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (c *usageCapture) handleNonStream() usageResult {
|
||||
var result usageResult
|
||||
logger := c.logger.With("path", c.ctx.path)
|
||||
transactionID := ""
|
||||
if c.ctx.proxyCtx != nil {
|
||||
transactionID = c.ctx.proxyCtx.reservation.ID
|
||||
}
|
||||
logger := c.logger.With("path", c.ctx.path, "transaction_id", transactionID)
|
||||
data, err := io.ReadAll(io.LimitReader(c.reader, 32<<20))
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "读取模型响应副本失败", "error", err)
|
||||
result.Result = "failed"
|
||||
result.ErrorCode = "usage_read_failed"
|
||||
return result
|
||||
}
|
||||
switch c.ctx.path {
|
||||
@@ -257,9 +327,16 @@ func (c *usageCapture) handleNonStream() usageResult {
|
||||
response, err := parseOpenAIResponse(data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Responses 用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
return result
|
||||
}
|
||||
result.ResponseID = response.ID
|
||||
result.TerminalEvent = response.Status
|
||||
if response.Usage == nil {
|
||||
result.ErrorCode = "usage_missing"
|
||||
if response.Status == "failed" || response.Status == "incomplete" {
|
||||
result.Result = "failed"
|
||||
}
|
||||
return result
|
||||
}
|
||||
result.Known = response.Usage.inputKnown && response.Usage.outputKnown
|
||||
@@ -268,29 +345,33 @@ func (c *usageCapture) handleNonStream() usageResult {
|
||||
}
|
||||
result.InputTokens = response.Usage.InputTokens
|
||||
result.OutputTokens = response.Usage.OutputTokens
|
||||
result.ResponseID = response.ID
|
||||
result.CachedTokens = response.Usage.InputTokensDetails.CachedTokens
|
||||
case "/v1/chat/completions":
|
||||
response, err := parseChatCompletion(data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Chat Completions 用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
return result
|
||||
}
|
||||
result.ResponseID = response.ID
|
||||
if response.Usage == nil {
|
||||
result.ErrorCode = "usage_missing"
|
||||
return result
|
||||
}
|
||||
result.Known = response.Usage.complete
|
||||
result.InputTokens = response.Usage.PromptTokens
|
||||
result.OutputTokens = response.Usage.CompletionTokens
|
||||
result.ResponseID = response.ID
|
||||
result.CachedTokens = response.Usage.PromptTokensDetails.CachedTokens
|
||||
case "/v1/messages":
|
||||
response, err := parseAnthropicResponse(data)
|
||||
if err != nil {
|
||||
logger.WarnContext(c.ctx.ctx, "解析 Anthropic 用量失败", "error", err)
|
||||
result.ErrorCode = "usage_parse_failed"
|
||||
return result
|
||||
}
|
||||
result.ResponseID = response.ID
|
||||
if response.Usage == nil {
|
||||
result.ErrorCode = "usage_missing"
|
||||
return result
|
||||
}
|
||||
result.Known = response.Usage.inputKnown && response.Usage.outputKnown
|
||||
@@ -298,7 +379,11 @@ func (c *usageCapture) handleNonStream() usageResult {
|
||||
result.OutputTokens = response.Usage.OutputTokens
|
||||
result.CacheReadInputTokens = response.Usage.CacheReadInputTokens
|
||||
result.CacheCreationInputTokens = response.Usage.CacheCreationInputTokens
|
||||
result.ResponseID = response.ID
|
||||
}
|
||||
if result.Known {
|
||||
result.ErrorCode = ""
|
||||
} else if result.ErrorCode == "" {
|
||||
result.ErrorCode = "usage_incomplete"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user