M4 收口:神识用户面与计量闭环——BYOK/配额三段式/usage 落库/Anthropic+Gemini 适配器/神识阁
- 神识 Go:store 双实现(PG 自动建表+60s 就绪重试 / 内存回退)承载 usage_logs·byok_keys·quota_balances;BYOK 密钥库(AES-GCM 加密、API 脱敏、撤回即失效、主密钥未配置 fail-closed);配额三段式(预扣 max_tokens 钳位 1M→结算实际 token→全败幂等退款,HJ-2004);计量归属(IR user_id→usage_logs,/me/usage 用户维度聚合+配额总览,/admin/usage/sample 对账抽样);Anthropic/Gemini 出站适配器(SSE 解析、system 提升、用量映射);stub 端点补名修复计量空 endpoint - IR 契约:user_id/byok_key_id 双端同步(Go types.go + Py types.py) - 灵台:runs.owner_id(迁移 005,server_default 兼容存量)经 kernel 全链透传为 IR user_id;shenshi_client 扩展用户面方法(X-Hunjing-User-Id 代理,Echo 桩带内存实现);/me/byok-keys 登记·列表·撤回与 /me/usage 端点(4 用例) - 前端神识阁(/models 重建):偏好(生成参数表单)/自带密钥(登记加密保存、脱敏列表、撤回二次确认)/用量(聚合表+配额进度条)三区;me API 库+mock+5 用例;侧栏恢复入口 - 配置与部署:.env.example 增 SHENSHI_DATABASE_URL/SHENSHI_BYOK_MASTER_KEY/SHENSHI_USER_BUDGET_TOKENS;compose 神识容器接自有库(init-shenshi.sql 预建 hunjing_shenshi,与灵台不共库共表) - 证据:Go 34 用例(BYOK 独占/配额拒绝/结算退款/归属聚合)、后端 532、前端 210、BFF 4 全绿;跨进程 E2E 四场景(灵台 HttpShenshiClient→真 Go 神识:登记脱敏/BYOK 独占不可达整体失败/用量归属聚合/撤回即失效)通过;rewrite-plan M4 标记完成、能力矩阵神识行升已验证
This commit is contained in:
1 parent
462d570751
commit
144415247e
51 files changed
+3533
-90
No files matched your search
@@ -1,5 +1,5 @@
|
||||
// Package metering 用量计量:每次尝试一条记录(stdout 结构化日志 + 进程内聚合)。
|
||||
// 生产部署接 PG(shenshi-gateway.md §7);M4a 先以日志与内存聚合支撑 /me/usage 与对账抽样。
|
||||
// Package metering 用量计量:每次尝试一条记录(stdout 结构化日志 + 神识自有库落库)。
|
||||
// 未配置 SHENSHI_DATABASE_URL 时退化为进程内环形缓冲(开发档),/me/usage 与对账抽样同语义。
|
||||
package metering
|
||||
|
||||
import (
|
||||
@@ -7,52 +7,57 @@ import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"hunjing/shenshi/internal/store"
|
||||
)
|
||||
|
||||
// Attempt 一次端点尝试的计量记录。
|
||||
// Attempt 一次端点尝试的计量记录(IR 维度齐全,user_id 为归属计量主键)。
|
||||
type Attempt struct {
|
||||
RunID string `json:"run_id"`
|
||||
CharacterID string `json:"character_id,omitempty"`
|
||||
Model string `json:"model"`
|
||||
Slot string `json:"slot"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Status string `json:"status"` // ok / error / first_byte_timeout
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
FirstTokenMS int64 `json:"first_token_ms"`
|
||||
TotalMS int64 `json:"total_ms"`
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
At time.Time `json:"at"`
|
||||
ID string `json:"id"` // run_id#endpoint 序号(结算幂等键)
|
||||
RunID string `json:"run_id"`
|
||||
CharacterID string `json:"character_id,omitempty"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Model string `json:"model"`
|
||||
Slot string `json:"slot"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Status string `json:"status"` // ok / error / first_byte_timeout
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
FirstTokenMS int64 `json:"first_token_ms"`
|
||||
TotalMS int64 `json:"total_ms"`
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// UsageAgg /me/usage 聚合行。
|
||||
type UsageAgg struct {
|
||||
Model string `json:"model"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Requests int `json:"requests"`
|
||||
OK int `json:"ok"`
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
}
|
||||
|
||||
// Log 进程内计量器(有界环形,避免无界增长)。
|
||||
// Log 计量器:stdout JSON 始终输出;持久化走 store(nil 时仅进程内有界环形)。
|
||||
type Log struct {
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
store store.Store
|
||||
entries []Attempt
|
||||
limit int
|
||||
limit int
|
||||
}
|
||||
|
||||
// New 构造计量器(保留最近 N 条)。
|
||||
func New(limit int) *Log {
|
||||
return &Log{entries: make([]Attempt, 0, limit), limit: limit}
|
||||
// New 构造计量器(st 为 nil 时进程内保留最近 N 条)。
|
||||
func New(limit int, st store.Store) *Log {
|
||||
return &Log{store: st, entries: make([]Attempt, 0, limit), limit: limit}
|
||||
}
|
||||
|
||||
// Record 记录一次尝试:stdout JSON 日志 + 内存追加。
|
||||
// Record 记录一次尝试:stdout JSON 日志(对账抽样基准)+ 落库。
|
||||
func (l *Log) Record(a Attempt) {
|
||||
a.At = time.Now().UTC()
|
||||
if raw, err := json.Marshal(a); err == nil {
|
||||
log.Printf(`{"kind":"shenshi_usage",%s`, string(raw[1:]))
|
||||
}
|
||||
if l.store != nil {
|
||||
_ = l.store.InsertUsage(store.UsageLog{
|
||||
ID: a.ID, RunID: a.RunID, CharacterID: a.CharacterID, UserID: a.UserID,
|
||||
Model: a.Model, Slot: a.Slot, Endpoint: a.Endpoint,
|
||||
Status: a.Status, ErrorCode: a.ErrorCode,
|
||||
FirstTokenMS: a.FirstTokenMS, TotalMS: a.TotalMS,
|
||||
PromptTokens: a.PromptTokens, CompletionTokens: a.CompletionTokens, At: a.At,
|
||||
})
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if len(l.entries) >= l.limit {
|
||||
@@ -61,16 +66,22 @@ func (l *Log) Record(a Attempt) {
|
||||
l.entries = append(l.entries, a)
|
||||
}
|
||||
|
||||
// Aggregate 按 模型×端点 聚合。
|
||||
func (l *Log) Aggregate() []UsageAgg {
|
||||
// Aggregate 按 用户×模型×端点 聚合(userID 为空聚合全体;管理面语义)。
|
||||
func (l *Log) Aggregate(userID string) ([]store.UsageAgg, error) {
|
||||
if l.store != nil {
|
||||
return l.store.AggregateUsage(userID)
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
agg := map[string]*UsageAgg{}
|
||||
agg := map[string]*store.UsageAgg{}
|
||||
for _, e := range l.entries {
|
||||
key := e.Model + "|" + e.Endpoint
|
||||
if userID != "" && e.UserID != userID {
|
||||
continue
|
||||
}
|
||||
key := e.UserID + "|" + e.Model + "|" + e.Endpoint
|
||||
row := agg[key]
|
||||
if row == nil {
|
||||
row = &UsageAgg{Model: e.Model, Endpoint: e.Endpoint}
|
||||
row = &store.UsageAgg{UserID: e.UserID, Model: e.Model, Endpoint: e.Endpoint}
|
||||
agg[key] = row
|
||||
}
|
||||
row.Requests++
|
||||
@@ -80,9 +91,33 @@ func (l *Log) Aggregate() []UsageAgg {
|
||||
row.CompletionTokens += e.CompletionTokens
|
||||
}
|
||||
}
|
||||
out := make([]UsageAgg, 0, len(agg))
|
||||
out := make([]store.UsageAgg, 0, len(agg))
|
||||
for _, row := range agg {
|
||||
out = append(out, *row)
|
||||
}
|
||||
return out
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Sample 对账抽样:最近 N 条原始记录(与 Provider 账单比对)。
|
||||
func (l *Log) Sample(limit int) ([]store.UsageLog, error) {
|
||||
if l.store != nil {
|
||||
return l.store.SampleUsage(limit)
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
n := limit
|
||||
if n > len(l.entries) {
|
||||
n = len(l.entries)
|
||||
}
|
||||
out := make([]store.UsageLog, n)
|
||||
for i, e := range l.entries[len(l.entries)-n:] {
|
||||
out[i] = store.UsageLog{
|
||||
ID: e.ID, RunID: e.RunID, CharacterID: e.CharacterID, UserID: e.UserID,
|
||||
Model: e.Model, Slot: e.Slot, Endpoint: e.Endpoint,
|
||||
Status: e.Status, ErrorCode: e.ErrorCode,
|
||||
FirstTokenMS: e.FirstTokenMS, TotalMS: e.TotalMS,
|
||||
PromptTokens: e.PromptTokens, CompletionTokens: e.CompletionTokens, At: e.At,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Reference in new issue
Block a user