Version: 0.9.80.dev.260506
后端: 1. LLM 独立服务与统一计费出口落地:新增 `cmd/llm`、`client/llm` 与 `services/llm/rpc`,补齐 BillingContext、CreditBalanceGuard、价格规则解析、stream usage 归集与 `credit.charge.requested` outbox 发布,active-scheduler / agent / course / memory / gateway fallback 全部改走 llm zrpc,不再各自本地初始化模型。 2. TokenStore 收口为 Credit 权威账本:新增 credit account / ledger / product / order / price-rule / reward-rule 能力与 Redis 快照缓存,扩展 tokenstore rpc/client 支撑余额快照、消耗看板、商品、订单、流水、价格规则和奖励规则,并接入 LLM charge 事件消费完成 Credit 扣费落账。 3. 计费旧链路下线与网关切口切换:`/token-store` 语义整体切到 `/credit-store`,agent chat 移除旧 TokenQuotaGuard,userauth 的 CheckTokenQuota / AdjustTokenUsage 改为废弃,聊天历史落库不再同步旧 token 额度账本,course 图片解析请求补 user_id 进入新计费口径。 前端: 4. 计划广场从 mock 数据切到真实接口:新增 forum api/types,首页支持真实列表、标签、搜索、防抖、点赞、导入和发布计划,详情页补齐帖子详情、评论树、回复和删除评论链路,同时补上“至少一个标签”的前后端约束与默认标签兜底。 5. 商店页切到 Credit 体系并重做展示:顶部改为余额 + Credit/Token 消耗看板,支持 24h/7d/30d/all 周期切换;套餐区展示原价与当前价;历史区改为当前用户 Credit 流水并支持查看更多,整体视觉和交互同步收口。 仓库: 6. 配置与本地启动体系补齐 llm / outbox 编排:`config.example.yaml` 增加 llm rpc 和统一 outbox service 配置,`dev-common.ps1` 把 llm 纳入多服务依赖并自动建 Kafka topic,`docker-compose.yml` 同步初始化 agent/task/memory/active-scheduler/notification/taskclass-forum/llm/token-store 全量 outbox topic。
This commit is contained in:
@@ -37,6 +37,7 @@ type ImportCoursesResult struct {
|
||||
}
|
||||
|
||||
type CourseImageParseRequest struct {
|
||||
UserID int `json:"user_id"`
|
||||
Filename string `json:"filename"`
|
||||
MIMEType string `json:"mime_type"`
|
||||
ImageBytes []byte `json:"image_bytes"`
|
||||
|
||||
172
backend/shared/contracts/creditstore/types.go
Normal file
172
backend/shared/contracts/creditstore/types.go
Normal file
@@ -0,0 +1,172 @@
|
||||
package creditstore
|
||||
|
||||
// PageResult 是 Credit 领域的分页结果契约。
|
||||
type PageResult struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// CreditBalanceSnapshot 提供给商店页和 LLM 准入 Guard 的余额快照。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只表达 TokenStore 权威账本视角下的 Credit 余额与阻断状态。
|
||||
// 2. snapshot_source 用于说明结果来自 cache 还是 db。
|
||||
// 3. 不承载任何扣费规则细节,避免把价格表语义耦合到余额查询。
|
||||
type CreditBalanceSnapshot struct {
|
||||
UserID uint64 `json:"user_id"`
|
||||
Balance int64 `json:"balance"`
|
||||
TotalRecharged int64 `json:"total_recharged"`
|
||||
TotalRewarded int64 `json:"total_rewarded"`
|
||||
TotalConsumed int64 `json:"total_consumed"`
|
||||
IsBlocked bool `json:"is_blocked"`
|
||||
SnapshotSource string `json:"snapshot_source"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// CreditProductView 是 Credit 商品卡片展示结构。
|
||||
type CreditProductView struct {
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
CreditAmount int64 `json:"credit_amount"`
|
||||
PriceCent int64 `json:"price_cent"`
|
||||
OriginalPriceCent int64 `json:"original_price_cent"`
|
||||
PriceText string `json:"price_text"`
|
||||
Currency string `json:"currency"`
|
||||
Badge string `json:"badge"`
|
||||
Status string `json:"status"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// CreditOrderView 是 Credit 订单展示结构。
|
||||
type CreditOrderView struct {
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
ProductSnapshot string `json:"product_snapshot"`
|
||||
ProductName string `json:"product_name"`
|
||||
Quantity int `json:"quantity"`
|
||||
CreditAmount int64 `json:"credit_amount"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
PriceText string `json:"price_text"`
|
||||
Currency string `json:"currency"`
|
||||
PaymentMode string `json:"payment_mode"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
PaidAt *string `json:"paid_at"`
|
||||
CreditedAt *string `json:"credited_at"`
|
||||
}
|
||||
|
||||
// CreditTransactionView 是 Credit 流水展示结构。
|
||||
type CreditTransactionView struct {
|
||||
TransactionID uint64 `json:"transaction_id"`
|
||||
EventID string `json:"event_id"`
|
||||
Source string `json:"source"`
|
||||
SourceLabel string `json:"source_label"`
|
||||
Direction string `json:"direction"`
|
||||
Amount int64 `json:"amount"`
|
||||
BalanceAfter int64 `json:"balance_after"`
|
||||
Status string `json:"status"`
|
||||
Description string `json:"description"`
|
||||
MetadataJSON string `json:"metadata_json"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
OrderID *uint64 `json:"order_id"`
|
||||
}
|
||||
|
||||
const (
|
||||
// CreditConsumptionPeriod24h 表示统计最近 24 小时内的消耗。
|
||||
CreditConsumptionPeriod24h = "24h"
|
||||
// CreditConsumptionPeriod7d 表示统计最近 7 天内的消耗。
|
||||
CreditConsumptionPeriod7d = "7d"
|
||||
// CreditConsumptionPeriod30d 表示统计最近 30 天内的消耗。
|
||||
CreditConsumptionPeriod30d = "30d"
|
||||
// CreditConsumptionPeriodAll 表示统计全部历史消耗。
|
||||
CreditConsumptionPeriodAll = "all"
|
||||
)
|
||||
|
||||
// CreditConsumptionDashboardView 是商店页顶部消耗看板的展示结构。
|
||||
type CreditConsumptionDashboardView struct {
|
||||
Period string `json:"period"`
|
||||
CreditConsumed int64 `json:"credit_consumed"`
|
||||
TokenConsumed int64 `json:"token_consumed"`
|
||||
}
|
||||
|
||||
// CreditPriceRuleView 是 Credit 计价规则展示结构。
|
||||
type CreditPriceRuleView struct {
|
||||
RuleID uint64 `json:"rule_id"`
|
||||
Scene string `json:"scene"`
|
||||
ProviderName string `json:"provider_name"`
|
||||
ModelName string `json:"model_name"`
|
||||
InputPriceMicros int64 `json:"input_price_micros"`
|
||||
OutputPriceMicros int64 `json:"output_price_micros"`
|
||||
CachedPriceMicros int64 `json:"cached_price_micros"`
|
||||
ReasoningPriceMicros int64 `json:"reasoning_price_micros"`
|
||||
CreditPerYuan int64 `json:"credit_per_yuan"`
|
||||
Status string `json:"status"`
|
||||
Priority int `json:"priority"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// CreditRewardRuleView 是 Credit 奖励规则展示结构。
|
||||
type CreditRewardRuleView struct {
|
||||
RuleID uint64 `json:"rule_id"`
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Amount int64 `json:"amount"`
|
||||
Status string `json:"status"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// CreateCreditOrderRequest 是创建 Credit 订单请求契约。
|
||||
type CreateCreditOrderRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Quantity int `json:"quantity"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
// ListCreditOrdersRequest 是 Credit 订单列表查询契约。
|
||||
type ListCreditOrdersRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// GetCreditConsumptionDashboardRequest 是查询当前用户消耗看板的契约。
|
||||
type GetCreditConsumptionDashboardRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
Period string `json:"period"`
|
||||
}
|
||||
|
||||
// MockPaidCreditOrderRequest 是 Credit 商店 mock paid 请求契约。
|
||||
type MockPaidCreditOrderRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
MockChannel string `json:"mock_channel"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
// ListCreditTransactionsRequest 是当前用户查询自己 Credit 流水的契约。
|
||||
type ListCreditTransactionsRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Source string `json:"source"`
|
||||
Direction string `json:"direction"`
|
||||
}
|
||||
|
||||
// ListCreditPriceRulesRequest 是 Credit 价格规则查询契约。
|
||||
type ListCreditPriceRulesRequest struct {
|
||||
Scene string `json:"scene"`
|
||||
ProviderName string `json:"provider_name"`
|
||||
ModelName string `json:"model_name"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// ListCreditRewardRulesRequest 是 Credit 奖励规则查询契约。
|
||||
type ListCreditRewardRulesRequest struct {
|
||||
Source string `json:"source"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
131
backend/shared/contracts/llm/contracts.go
Normal file
131
backend/shared/contracts/llm/contracts.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
const (
|
||||
ModelAliasLite = "lite"
|
||||
ModelAliasPro = "pro"
|
||||
ModelAliasMax = "max"
|
||||
ModelAliasCourseImageResponses = "course_image_responses"
|
||||
|
||||
DefaultTextModelAlias = ModelAliasPro
|
||||
ProviderNameArk = "ark"
|
||||
)
|
||||
|
||||
// PingRequest 只用于跨进程探活,不承载业务字段。
|
||||
type PingRequest struct{}
|
||||
|
||||
// PingResponse 只用于跨进程探活,不承载业务字段。
|
||||
type PingResponse struct{}
|
||||
|
||||
// BillingContext 是 LLM RPC 透传的计费上下文副本。
|
||||
type BillingContext struct {
|
||||
UserID uint64 `json:"user_id"`
|
||||
EventID string `json:"event_id"`
|
||||
Scene string `json:"scene"`
|
||||
RequestID string `json:"request_id"`
|
||||
ConversationID string `json:"conversation_id"`
|
||||
ModelAlias string `json:"model_alias"`
|
||||
SkipCharge bool `json:"skip_charge"`
|
||||
}
|
||||
|
||||
// GenerateOptions 是文本模型跨进程调用时的最小公共参数。
|
||||
type GenerateOptions struct {
|
||||
Temperature float64 `json:"temperature"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
Thinking string `json:"thinking"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// TextRequest 描述一次非流式文本调用。
|
||||
type TextRequest struct {
|
||||
ModelAlias string `json:"model_alias"`
|
||||
Messages []*schema.Message `json:"messages"`
|
||||
Options GenerateOptions `json:"options"`
|
||||
Billing *BillingContext `json:"billing,omitempty"`
|
||||
}
|
||||
|
||||
// StreamTextRequest 描述一次流式文本调用。
|
||||
type StreamTextRequest struct {
|
||||
ModelAlias string `json:"model_alias"`
|
||||
Messages []*schema.Message `json:"messages"`
|
||||
Options GenerateOptions `json:"options"`
|
||||
Billing *BillingContext `json:"billing,omitempty"`
|
||||
}
|
||||
|
||||
// TextResult 保存文本模型最终输出。
|
||||
type TextResult struct {
|
||||
Text string `json:"text"`
|
||||
Usage *schema.TokenUsage `json:"usage,omitempty"`
|
||||
FinishReason string `json:"finish_reason,omitempty"`
|
||||
}
|
||||
|
||||
// TextResponse 统一包住文本调用结果,便于后续扩字段。
|
||||
type TextResponse struct {
|
||||
Result *TextResult `json:"result,omitempty"`
|
||||
}
|
||||
|
||||
// StreamChunk 是流式返回的最小块协议。
|
||||
type StreamChunk struct {
|
||||
Message *schema.Message `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// ResponsesMessage 描述 Responses 模型单条输入。
|
||||
type ResponsesMessage struct {
|
||||
Role string `json:"role"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL string `json:"image_url,omitempty"`
|
||||
ImageDetail string `json:"image_detail,omitempty"`
|
||||
}
|
||||
|
||||
// ResponsesOptions 描述 Responses 模型公共参数。
|
||||
type ResponsesOptions struct {
|
||||
Model string `json:"model,omitempty"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
MaxOutputTokens int `json:"max_output_tokens"`
|
||||
Thinking string `json:"thinking"`
|
||||
TextFormat string `json:"text_format,omitempty"`
|
||||
}
|
||||
|
||||
// ResponsesRequest 描述一次 Responses 文本调用。
|
||||
type ResponsesRequest struct {
|
||||
ModelAlias string `json:"model_alias"`
|
||||
Messages []ResponsesMessage `json:"messages"`
|
||||
Options ResponsesOptions `json:"options"`
|
||||
Billing *BillingContext `json:"billing,omitempty"`
|
||||
}
|
||||
|
||||
// ResponsesUsage 是 Responses 结果里的最小 usage 结构。
|
||||
type ResponsesUsage struct {
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
}
|
||||
|
||||
// ResponsesResult 统一承载 Responses 输出。
|
||||
type ResponsesResult struct {
|
||||
Text string `json:"text"`
|
||||
Status string `json:"status,omitempty"`
|
||||
IncompleteReason string `json:"incomplete_reason,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
Usage *ResponsesUsage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
// ResponsesResponse 统一包住 Responses 结果。
|
||||
type ResponsesResponse struct {
|
||||
Result *ResponsesResult `json:"result,omitempty"`
|
||||
}
|
||||
|
||||
// NormalizeModelAlias 负责把空别名收敛到默认文本模型。
|
||||
func NormalizeModelAlias(raw string) string {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return DefaultTextModelAlias
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package tokenstore
|
||||
|
||||
// PageResult 是 token-store 分页响应的跨层契约。
|
||||
type PageResult struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
// TokenSummary 是 Token 商店概览响应。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. P0 展示 token-store 已记录的获取事实;
|
||||
// 2. 不承诺这些 Token 已经同步到 user/auth 权威额度;
|
||||
// 3. 后续接入 user/auth 后可把 QuotaSyncStatus 调整为 synced。
|
||||
type TokenSummary struct {
|
||||
RecordedTokenTotal int64 `json:"recorded_token_total"`
|
||||
AppliedTokenTotal int64 `json:"applied_token_total"`
|
||||
PendingApplyTokenTotal int64 `json:"pending_apply_token_total"`
|
||||
QuotaSyncStatus string `json:"quota_sync_status"`
|
||||
Tip string `json:"tip"`
|
||||
}
|
||||
|
||||
// TokenProductView 是商品卡片展示结构。
|
||||
type TokenProductView struct {
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
TokenAmount int64 `json:"token_amount"`
|
||||
PriceCent int64 `json:"price_cent"`
|
||||
PriceText string `json:"price_text"`
|
||||
Currency string `json:"currency"`
|
||||
Badge string `json:"badge"`
|
||||
Status string `json:"status"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// TokenGrantView 是 Token 获取记录展示结构。
|
||||
type TokenGrantView struct {
|
||||
GrantID uint64 `json:"grant_id"`
|
||||
EventID string `json:"event_id"`
|
||||
Source string `json:"source"`
|
||||
SourceLabel string `json:"source_label"`
|
||||
Amount int64 `json:"amount"`
|
||||
Status string `json:"status"`
|
||||
QuotaApplied bool `json:"quota_applied"`
|
||||
Description string `json:"description"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// TokenOrderView 是订单展示结构。
|
||||
type TokenOrderView struct {
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
Status string `json:"status"`
|
||||
ProductSnapshot string `json:"product_snapshot"`
|
||||
ProductName string `json:"product_name"`
|
||||
Quantity int `json:"quantity"`
|
||||
TokenAmount int64 `json:"token_amount"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
PriceText string `json:"price_text"`
|
||||
Currency string `json:"currency"`
|
||||
PaymentMode string `json:"payment_mode"`
|
||||
Grant *TokenGrantView `json:"grant"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
PaidAt *string `json:"paid_at"`
|
||||
GrantedAt *string `json:"granted_at"`
|
||||
}
|
||||
|
||||
// CreateTokenOrderRequest 是创建订单请求契约。
|
||||
type CreateTokenOrderRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
ProductID uint64 `json:"product_id"`
|
||||
Quantity int `json:"quantity"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
// ListTokenOrdersRequest 是订单列表查询契约。
|
||||
type ListTokenOrdersRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// MockPaidOrderRequest 是 P0 mock paid 请求契约。
|
||||
type MockPaidOrderRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
MockChannel string `json:"mock_channel"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
}
|
||||
|
||||
// ListTokenGrantsRequest 是 Token 获取记录列表查询契约。
|
||||
type ListTokenGrantsRequest struct {
|
||||
ActorUserID uint64 `json:"actor_user_id"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
// RecordForumRewardGrantRequest 是论坛奖励入账的内部 RPC 契约。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只描述一条待记录到 token_grants 的论坛奖励事实;
|
||||
// 2. 不携带最终奖励金额,金额由 token-store 按 source 和配置解析;
|
||||
// 3. source_ref_id 使用字符串承接 post_id / import_id,服务层再按当前库表结构落成整数。
|
||||
type RecordForumRewardGrantRequest struct {
|
||||
EventID string `json:"event_id"`
|
||||
ReceiverUserID uint64 `json:"receiver_user_id"`
|
||||
Source string `json:"source"`
|
||||
SourceRefID string `json:"source_ref_id"`
|
||||
}
|
||||
|
||||
// TokenGrantRecord 是 token-store 内部发放出口使用的获取事实。
|
||||
type TokenGrantRecord struct {
|
||||
EventID string `json:"event_id"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
Source string `json:"source"`
|
||||
SourceRefID uint64 `json:"source_ref_id"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
Amount int64 `json:"amount"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
@@ -46,23 +46,3 @@ type ValidateAccessTokenResponse struct {
|
||||
JTI string `json:"jti"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// CheckTokenQuotaRequest 是 agent/chat 进入业务前的额度门禁请求。
|
||||
type CheckTokenQuotaRequest struct {
|
||||
UserID int `json:"user_id"`
|
||||
}
|
||||
|
||||
// AdjustTokenUsageRequest 是业务链路回写用户 token 账本的请求。
|
||||
type AdjustTokenUsageRequest struct {
|
||||
EventID string `json:"event_id"`
|
||||
UserID int `json:"user_id"`
|
||||
TokenDelta int `json:"token_delta"`
|
||||
}
|
||||
|
||||
// CheckTokenQuotaResponse 返回额度门禁判断结果。
|
||||
type CheckTokenQuotaResponse struct {
|
||||
Allowed bool `json:"allowed"`
|
||||
TokenLimit int `json:"token_limit"`
|
||||
TokenUsage int `json:"token_usage"`
|
||||
LastResetAt time.Time `json:"last_reset_at"`
|
||||
}
|
||||
|
||||
91
backend/shared/events/credit.go
Normal file
91
backend/shared/events/credit.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// CreditChargeRequestedEventType 表示 LLM 服务已经拿到最终 usage,等待 TokenStore 异步结算。
|
||||
CreditChargeRequestedEventType = "credit.charge.requested"
|
||||
// CreditChargeEventVersion 是当前 Credit 扣费事件版本。
|
||||
CreditChargeEventVersion = "v1"
|
||||
)
|
||||
|
||||
// CreditChargeRequestedPayload 是 LLM -> TokenStore 的统一扣费事件。
|
||||
//
|
||||
// 职责边界:
|
||||
// 1. 只表达“一次已经完成的模型调用需要如何结算”,不承载准入决策;
|
||||
// 2. event_id 是最终幂等键,LLM outbox 重试和 TokenStore 记账都依赖它去重;
|
||||
// 3. credit_cost / rmb_cost_micros 在 LLM 侧就要算好,TokenStore 只负责权威落账。
|
||||
type CreditChargeRequestedPayload struct {
|
||||
EventID string `json:"event_id"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
Scene string `json:"scene"`
|
||||
RequestID string `json:"request_id"`
|
||||
ConversationID string `json:"conversation_id"`
|
||||
ModelAlias string `json:"model_alias"`
|
||||
ProviderName string `json:"provider_name"`
|
||||
ModelName string `json:"model_name"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
CachedTokens int64 `json:"cached_tokens"`
|
||||
ReasoningTokens int64 `json:"reasoning_tokens"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
RMBCostMicros int64 `json:"rmb_cost_micros"`
|
||||
CreditCost int64 `json:"credit_cost"`
|
||||
TriggeredAt time.Time `json:"triggered_at"`
|
||||
SkipCharge bool `json:"skip_charge,omitempty"`
|
||||
}
|
||||
|
||||
// EventType 返回当前 payload 对应的标准事件类型。
|
||||
func (p CreditChargeRequestedPayload) EventType() string {
|
||||
return CreditChargeRequestedEventType
|
||||
}
|
||||
|
||||
// MessageKey 返回 Kafka / outbox 统一消息键。
|
||||
func (p CreditChargeRequestedPayload) MessageKey() string {
|
||||
return strings.TrimSpace(p.EventID)
|
||||
}
|
||||
|
||||
// AggregateID 返回扣费事件聚合键。
|
||||
func (p CreditChargeRequestedPayload) AggregateID() string {
|
||||
if p.UserID <= 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("user:%d", p.UserID)
|
||||
}
|
||||
|
||||
// Validate 校验扣费事件最小字段集。
|
||||
func (p CreditChargeRequestedPayload) Validate() error {
|
||||
if strings.TrimSpace(p.EventID) == "" {
|
||||
return errors.New("credit charge event_id 不能为空")
|
||||
}
|
||||
if p.UserID == 0 {
|
||||
return errors.New("credit charge user_id 不能为空")
|
||||
}
|
||||
if strings.TrimSpace(p.Scene) == "" {
|
||||
return errors.New("credit charge scene 不能为空")
|
||||
}
|
||||
if strings.TrimSpace(p.ProviderName) == "" {
|
||||
return errors.New("credit charge provider_name 不能为空")
|
||||
}
|
||||
if strings.TrimSpace(p.ModelName) == "" {
|
||||
return errors.New("credit charge model_name 不能为空")
|
||||
}
|
||||
if p.TriggeredAt.IsZero() {
|
||||
return errors.New("credit charge triggered_at 不能为空")
|
||||
}
|
||||
if p.SkipCharge {
|
||||
return nil
|
||||
}
|
||||
if p.CreditCost < 0 {
|
||||
return errors.New("credit charge credit_cost 不能为负数")
|
||||
}
|
||||
if p.RMBCostMicros < 0 {
|
||||
return errors.New("credit charge rmb_cost_micros 不能为负数")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -16,6 +16,7 @@ const (
|
||||
ServiceActiveScheduler = "active-scheduler"
|
||||
ServiceNotification = "notification"
|
||||
ServiceTaskClassForum = "taskclass-forum"
|
||||
ServiceLLM = "llm"
|
||||
ServiceTokenStore = "token-store"
|
||||
)
|
||||
|
||||
@@ -91,6 +92,12 @@ func LoadServiceConfigs() map[string]ServiceConfig {
|
||||
GroupID: "smartflow-taskclass-forum-outbox-consumer",
|
||||
TableName: "taskclass_forum_outbox_messages",
|
||||
},
|
||||
ServiceLLM: {
|
||||
Name: ServiceLLM,
|
||||
Topic: "smartflow.llm.outbox",
|
||||
GroupID: "smartflow-llm-outbox-consumer",
|
||||
TableName: "llm_outbox_messages",
|
||||
},
|
||||
ServiceTokenStore: {
|
||||
Name: ServiceTokenStore,
|
||||
Topic: "smartflow.token-store.outbox",
|
||||
|
||||
@@ -11,6 +11,7 @@ const (
|
||||
ServiceNameActiveScheduler = "active-scheduler"
|
||||
ServiceNameNotification = "notification"
|
||||
ServiceNameTaskClassForum = "taskclass-forum"
|
||||
ServiceNameLLM = "llm"
|
||||
ServiceNameTokenStore = "token-store"
|
||||
)
|
||||
|
||||
@@ -64,6 +65,12 @@ var builtinServiceRoutes = map[string]ServiceRoute{
|
||||
Topic: "smartflow.taskclass-forum.outbox",
|
||||
GroupID: "smartflow-taskclass-forum-outbox-consumer",
|
||||
},
|
||||
ServiceNameLLM: {
|
||||
ServiceName: ServiceNameLLM,
|
||||
TableName: "llm_outbox_messages",
|
||||
Topic: "smartflow.llm.outbox",
|
||||
GroupID: "smartflow-llm-outbox-consumer",
|
||||
},
|
||||
ServiceNameTokenStore: {
|
||||
ServiceName: ServiceNameTokenStore,
|
||||
TableName: "token_store_outbox_messages",
|
||||
@@ -86,6 +93,7 @@ func DefaultServiceRoutes() []ServiceRoute {
|
||||
builtinServiceRoutes[ServiceNameActiveScheduler],
|
||||
builtinServiceRoutes[ServiceNameNotification],
|
||||
builtinServiceRoutes[ServiceNameTaskClassForum],
|
||||
builtinServiceRoutes[ServiceNameLLM],
|
||||
builtinServiceRoutes[ServiceNameTokenStore],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,23 +24,9 @@ type AccessTokenValidator interface {
|
||||
ValidateAccessToken(ctx context.Context, accessToken string) (*contracts.ValidateAccessTokenResponse, error)
|
||||
}
|
||||
|
||||
// TokenQuotaChecker 是 agent/chat 入口做额度门禁时依赖的最小接口。
|
||||
// 职责边界:只判断当前用户是否允许继续消费 token,不负责 token 入账。
|
||||
type TokenQuotaChecker interface {
|
||||
CheckTokenQuota(ctx context.Context, userID int) (*contracts.CheckTokenQuotaResponse, error)
|
||||
}
|
||||
|
||||
// TokenUsageAdjuster 是业务链路回写 token 账本时依赖的最小接口。
|
||||
// 职责边界:只做 token 账本增量调整,不承载鉴权与登录逻辑。
|
||||
type TokenUsageAdjuster interface {
|
||||
AdjustTokenUsage(ctx context.Context, req contracts.AdjustTokenUsageRequest) (*contracts.CheckTokenQuotaResponse, error)
|
||||
}
|
||||
|
||||
// UserAuthClient 组合当前阶段需要的 user/auth 能力。
|
||||
// 职责边界:作为统一装配口径,避免 gateway 和 core service 各自维护一份接口。
|
||||
type UserAuthClient interface {
|
||||
UserCommandClient
|
||||
AccessTokenValidator
|
||||
TokenQuotaChecker
|
||||
TokenUsageAdjuster
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user