Files
synapse/internal/components/libra/libra.go
2026-06-28 03:24:26 +08:00

474 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package libra 灵衡 - 价值结算与激励层
//
// 权衡利弊,计量公平。此层负责将 Agent 间的
// "智力贡献"与"资源消耗"通证化,动态定价,
// 让多智能体经济具备自驱的盈亏平衡,
// 而非单一中心补贴。
package libra
import (
"context"
"encoding/json"
"fmt"
"log"
"sync"
"time"
"synapse/pkg/types"
)
// =============================================================================
// Accounting - 记账
// =============================================================================
// TransactionType 交易类型
type TransactionType string
const (
TxTaskExecution TransactionType = "task_execution" // 任务执行
TxDataSharing TransactionType = "data_sharing" // 数据共享
TxAPIInvocation TransactionType = "api_invocation" // API 调用
TxGroupContribution TransactionType = "group_contribution" // 群组贡献
TxDeposit TransactionType = "deposit" // 充值
TxWithdraw TransactionType = "withdraw" // 提现
TxReward TransactionType = "reward" // 奖励
TxPenalty TransactionType = "penalty" // 惩罚
)
// Transaction 交易记录
type Transaction struct {
TxID string `json:"tx_id"`
Type TransactionType `json:"type"`
FromAgentID string `json:"from_agent_id"`
ToAgentID string `json:"to_agent_id"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
Description string `json:"description"`
TaskID string `json:"task_id,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Timestamp time.Time `json:"timestamp"`
Status TransactionStatus `json:"status"`
}
// TransactionStatus 交易状态
type TransactionStatus string
const (
TxStatusPending TransactionStatus = "pending"
TxStatusCompleted TransactionStatus = "completed"
TxStatusFailed TransactionStatus = "failed"
TxStatusReverted TransactionStatus = "reverted"
)
// Account 账户
type Account struct {
AgentID string `json:"agent_id"`
Balance map[string]float64 `json:"balance"` // currency -> amount
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// Ledger 账本
type Ledger struct {
mu sync.RWMutex
accounts map[string]*Account // agent_id -> account
transactions []Transaction
config *LedgerConfig
}
// LedgerConfig 账本配置
type LedgerConfig struct {
DefaultCurrency string
InitialBalance map[string]float64
}
// DefaultLedgerConfig 返回默认账本配置
func DefaultLedgerConfig() *LedgerConfig {
return &LedgerConfig{
DefaultCurrency: "SYN",
InitialBalance: map[string]float64{
"SYN": 1000.0,
},
}
}
// NewLedger 创建账本
func NewLedger(config *LedgerConfig) *Ledger {
if config == nil {
config = DefaultLedgerConfig()
}
return &Ledger{
accounts: make(map[string]*Account),
transactions: make([]Transaction, 0),
config: config,
}
}
// CreateAccount 创建账户
func (l *Ledger) CreateAccount(agentID string) (*Account, error) {
l.mu.Lock()
defer l.mu.Unlock()
if _, exists := l.accounts[agentID]; exists {
return nil, fmt.Errorf("account for agent %s already exists", agentID)
}
account := &Account{
AgentID: agentID,
Balance: make(map[string]float64),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Metadata: make(map[string]interface{}),
}
// 初始余额
for currency, amount := range l.config.InitialBalance {
account.Balance[currency] = amount
}
l.accounts[agentID] = account
log.Printf("[灵衡] 创建账户: %s (初始余额: %v)", agentID, account.Balance)
return account, nil
}
// GetBalance 获取余额
func (l *Ledger) GetBalance(agentID string) (map[string]float64, error) {
l.mu.RLock()
defer l.mu.RUnlock()
account, ok := l.accounts[agentID]
if !ok {
return nil, fmt.Errorf("account for agent %s not found", agentID)
}
balance := make(map[string]float64)
for k, v := range account.Balance {
balance[k] = v
}
return balance, nil
}
// Transfer 转账
func (l *Ledger) Transfer(fromAgentID, toAgentID string, amount float64, currency string, txType TransactionType, description string, taskID string, metadata map[string]interface{}) (*Transaction, error) {
l.mu.Lock()
defer l.mu.Unlock()
// 检查账户
fromAccount, ok := l.accounts[fromAgentID]
if !ok {
return nil, fmt.Errorf("sender account not found")
}
toAccount, ok := l.accounts[toAgentID]
if !ok {
return nil, fmt.Errorf("receiver account not found")
}
// 检查余额
if fromAccount.Balance[currency] < amount {
return nil, fmt.Errorf("insufficient balance")
}
// 创建交易
tx := Transaction{
TxID: fmt.Sprintf("tx-%d", time.Now().UnixNano()),
Type: txType,
FromAgentID: fromAgentID,
ToAgentID: toAgentID,
Amount: amount,
Currency: currency,
Description: description,
TaskID: taskID,
Metadata: metadata,
Timestamp: time.Now(),
Status: TxStatusCompleted,
}
// 执行转账
fromAccount.Balance[currency] -= amount
toAccount.Balance[currency] += amount
fromAccount.UpdatedAt = time.Now()
toAccount.UpdatedAt = time.Now()
l.transactions = append(l.transactions, tx)
log.Printf("[灵衡] 转账: %s -> %s: %.2f %s (%s)",
fromAgentID, toAgentID, amount, currency, description)
return &tx, nil
}
// GetAccount 获取账户
func (l *Ledger) GetAccount(agentID string) (*Account, error) {
l.mu.RLock()
defer l.mu.RUnlock()
account, ok := l.accounts[agentID]
if !ok {
return nil, fmt.Errorf("account for agent %s not found", agentID)
}
return account, nil
}
// GetTransactionHistory 获取交易历史
func (l *Ledger) GetTransactionHistory(agentID string, limit int) []Transaction {
l.mu.RLock()
defer l.mu.RUnlock()
var history []Transaction
for i := len(l.transactions) - 1; i >= 0 && len(history) < limit; i-- {
tx := l.transactions[i]
if tx.FromAgentID == agentID || tx.ToAgentID == agentID {
history = append(history, tx)
}
}
return history
}
// =============================================================================
// Pricing - 定价
// =============================================================================
// PricingEngine 定价引擎
type PricingEngine struct {
mu sync.RWMutex
prices map[string]map[string]float64 // task_type -> capability -> price
config *PricingConfig
}
// PricingConfig 定价配置
type PricingConfig struct {
BasePrice map[string]float64
}
// DefaultPricingConfig 返回默认定价配置
func DefaultPricingConfig() *PricingConfig {
return &PricingConfig{
BasePrice: map[string]float64{
"text_generation": 1.0,
"image_generation": 5.0,
"video_generation": 20.0,
"audio_generation": 3.0,
"analysis": 2.0,
"translation": 1.5,
},
}
}
// NewPricingEngine 创建定价引擎
func NewPricingEngine(config *PricingConfig) *PricingEngine {
if config == nil {
config = DefaultPricingConfig()
}
return &PricingEngine{
prices: make(map[string]map[string]float64),
config: config,
}
}
// SetPrice 设置价格
func (pe *PricingEngine) SetPrice(taskType, capability string, price float64) {
pe.mu.Lock()
defer pe.mu.Unlock()
if _, ok := pe.prices[taskType]; !ok {
pe.prices[taskType] = make(map[string]float64)
}
pe.prices[taskType][capability] = price
}
// GetPrice 获取价格
func (pe *PricingEngine) GetPrice(taskType string) float64 {
pe.mu.RLock()
defer pe.mu.RUnlock()
// 先查自定义价格
if caps, ok := pe.prices[taskType]; ok {
if price, ok := caps["default"]; ok {
return price
}
}
// 再查基础价格
if price, ok := pe.config.BasePrice[taskType]; ok {
return price
}
// 默认价格
return 1.0
}
// CalculateCost 计算任务成本
func (pe *PricingEngine) CalculateCost(taskType string, complexity int, duration time.Duration) float64 {
basePrice := pe.GetPrice(taskType)
// 复杂度系数
complexityFactor := 1.0
if complexity > 0 {
complexityFactor = float64(complexity) * 0.5
}
// 时长系数(每秒0.01)
durationFactor := duration.Seconds() * 0.01
return basePrice*complexityFactor + durationFactor
}
// =============================================================================
// Settlement - 结算
// =============================================================================
// SettlementEngine 结算引擎
type SettlementEngine struct {
ledger *Ledger
pricing *PricingEngine
config *SettlementConfig
}
// SettlementConfig 结算配置
type SettlementConfig struct {
AutoSettlement bool
SettlementInterval time.Duration
}
// DefaultSettlementConfig 返回默认结算配置
func DefaultSettlementConfig() *SettlementConfig {
return &SettlementConfig{
AutoSettlement: true,
SettlementInterval: 1 * time.Hour,
}
}
// NewSettlementEngine 创建结算引擎
func NewSettlementEngine(ledger *Ledger, pricing *PricingEngine, config *SettlementConfig) *SettlementEngine {
if config == nil {
config = DefaultSettlementConfig()
}
return &SettlementEngine{
ledger: ledger,
pricing: pricing,
config: config,
}
}
// SettleTask 结算任务
func (se *SettlementEngine) SettleTask(taskID string, fromAgentID, toAgentID string, taskType string, complexity int, duration time.Duration, resultQuality float64) (*Transaction, error) {
// 计算成本
cost := se.pricing.CalculateCost(taskType, complexity, duration)
// 质量调整
adjustedCost := cost * resultQuality
log.Printf("[灵衡] 任务结算: %s (成本: %.2f, 质量系数: %.2f, 最终: %.2f)",
taskID, cost, resultQuality, adjustedCost)
// 执行转账
return se.ledger.Transfer(
fromAgentID,
toAgentID,
adjustedCost,
"SYN",
TxTaskExecution,
fmt.Sprintf("任务执行: %s", taskType),
taskID,
map[string]interface{}{
"task_type": taskType,
"complexity": complexity,
"duration_s": duration.Seconds(),
"quality": resultQuality,
"base_cost": cost,
},
)
}
// SettleGroupTask 结算群组任务(分摊费用)
func (se *SettlementEngine) SettleGroupTask(taskID string, coordinatorID string, workerIDs []string, taskType string, totalCost float64, shares map[string]float64) error {
// 协调者支付总费用,工作者按比例分配
for workerID, share := range shares {
amount := totalCost * share
_, err := se.ledger.Transfer(
coordinatorID,
workerID,
amount,
"SYN",
TxGroupContribution,
fmt.Sprintf("群组任务分成: %s", taskType),
taskID,
map[string]interface{}{
"share": share,
"amount": amount,
},
)
if err != nil {
return fmt.Errorf("settle worker %s failed: %w", workerID, err)
}
}
log.Printf("[灵衡] 群组任务结算: %s (总费用: %.2f, 工作者: %d)",
taskID, totalCost, len(workerIDs))
return nil
}
// Reward 奖励
func (se *SettlementEngine) Reward(agentID string, amount float64, reason string) (*Transaction, error) {
// 创建系统账户(简化处理)
if _, err := se.ledger.GetAccount("system"); err != nil {
se.ledger.CreateAccount("system")
}
return se.ledger.Transfer(
"system",
agentID,
amount,
"SYN",
TxReward,
reason,
"",
nil,
)
}
// =============================================================================
// Libra - 灵衡整体入口
// =============================================================================
// Libra 灵衡 - 价值结算与激励
type Libra struct {
Ledger *Ledger
Pricing *PricingEngine
Settlement *SettlementEngine
}
// NewLibra 创建灵衡
func NewLibra() *Libra {
ledger := NewLedger(nil)
pricing := NewPricingEngine(nil)
settlement := NewSettlementEngine(ledger, pricing, nil)
return &Libra{
Ledger: ledger,
Pricing: pricing,
Settlement: settlement,
}
}
// RegisterAgent 注册 Agent(创建账户)
func (l *Libra) RegisterAgent(agentID string) error {
_, err := l.Ledger.CreateAccount(agentID)
return err
}
// PayForTask 为任务付费
func (l *Libra) PayForTask(ctx context.Context, fromAgentID, toAgentID string, msg *types.UnifiedSynapseMessage, duration time.Duration, quality float64) error {
return nil // 简化实现
}
// ToJSON 导出为 JSON
func (tx *Transaction) ToJSON() string {
data, _ := json.MarshalIndent(tx, "", " ")
return string(data)
}