46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package ai
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
"senlinai-agent/backend/internal/domain"
|
|
)
|
|
|
|
type Gateway struct {
|
|
db *gorm.DB
|
|
systemKey string
|
|
}
|
|
|
|
type SelectedKey struct {
|
|
Provider string
|
|
APIKey string
|
|
KeyType string
|
|
}
|
|
|
|
func NewGateway(database *gorm.DB, systemKey string) *Gateway {
|
|
return &Gateway{db: database, systemKey: systemKey}
|
|
}
|
|
|
|
func (g *Gateway) SelectKey(userID uint) (SelectedKey, error) {
|
|
var userKey domain.AIKey
|
|
if err := g.db.Where("user_id = ?", userID).First(&userKey).Error; err == nil {
|
|
return SelectedKey{Provider: userKey.Provider, APIKey: userKey.EncryptedAPIKey, KeyType: "user"}, nil
|
|
}
|
|
if g.systemKey == "" {
|
|
return SelectedKey{}, errors.New("no ai key available")
|
|
}
|
|
return SelectedKey{Provider: "openai", APIKey: g.systemKey, KeyType: "system"}, nil
|
|
}
|
|
|
|
func (g *Gateway) RecordCall(userID uint, provider string, usedKeyType string, action string, status string, errText string) error {
|
|
return g.db.Create(&domain.AICallLog{
|
|
UserID: userID,
|
|
Provider: provider,
|
|
UsedKeyType: usedKeyType,
|
|
Action: action,
|
|
Status: status,
|
|
Error: errText,
|
|
}).Error
|
|
}
|