feat: 支持Gemini-Api接入

This commit is contained in:
shaw
2025-11-23 22:00:13 +08:00
parent b197cba325
commit bae39d5468
13 changed files with 2355 additions and 287 deletions

View File

@@ -1527,7 +1527,15 @@ class ApiKeyService {
permissions: keyData.permissions,
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0),
totalCostLimit: parseFloat(keyData.totalCostLimit || 0),
droidAccountId: keyData.droidAccountId
// 所有平台账户绑定字段
claudeAccountId: keyData.claudeAccountId,
claudeConsoleAccountId: keyData.claudeConsoleAccountId,
geminiAccountId: keyData.geminiAccountId,
openaiAccountId: keyData.openaiAccountId,
bedrockAccountId: keyData.bedrockAccountId,
droidAccountId: keyData.droidAccountId,
azureOpenaiAccountId: keyData.azureOpenaiAccountId,
ccrAccountId: keyData.ccrAccountId
}
} catch (error) {
logger.error('❌ Failed to get API key by ID:', error)
@@ -1670,6 +1678,7 @@ class ApiKeyService {
claude: 'claudeAccountId',
'claude-console': 'claudeConsoleAccountId',
gemini: 'geminiAccountId',
'gemini-api': 'geminiAccountId', // 特殊处理,带 api: 前缀
openai: 'openaiAccountId',
'openai-responses': 'openaiAccountId', // 特殊处理,带 responses: 前缀
azure_openai: 'azureOpenaiAccountId',
@@ -1692,6 +1701,9 @@ class ApiKeyService {
if (accountType === 'openai-responses') {
// OpenAI-Responses 特殊处理:查找 openaiAccountId 字段中带 responses: 前缀的
boundKeys = allKeys.filter((key) => key.openaiAccountId === `responses:${accountId}`)
} else if (accountType === 'gemini-api') {
// Gemini-API 特殊处理:查找 geminiAccountId 字段中带 api: 前缀的
boundKeys = allKeys.filter((key) => key.geminiAccountId === `api:${accountId}`)
} else {
// 其他账号类型正常匹配
boundKeys = allKeys.filter((key) => key[field] === accountId)
@@ -1702,6 +1714,8 @@ class ApiKeyService {
const updates = {}
if (accountType === 'openai-responses') {
updates.openaiAccountId = null
} else if (accountType === 'gemini-api') {
updates.geminiAccountId = null
} else if (accountType === 'claude-console') {
updates.claudeConsoleAccountId = null
} else {

View File

@@ -0,0 +1,586 @@
const { v4: uuidv4 } = require('uuid')
const crypto = require('crypto')
const redis = require('../models/redis')
const logger = require('../utils/logger')
const config = require('../../config/config')
const LRUCache = require('../utils/lruCache')
class GeminiApiAccountService {
constructor() {
// 加密相关常量
this.ENCRYPTION_ALGORITHM = 'aes-256-cbc'
this.ENCRYPTION_SALT = 'gemini-api-salt'
// Redis 键前缀
this.ACCOUNT_KEY_PREFIX = 'gemini_api_account:'
this.SHARED_ACCOUNTS_KEY = 'shared_gemini_api_accounts'
// 🚀 性能优化:缓存派生的加密密钥,避免每次重复计算
this._encryptionKeyCache = null
// 🔄 解密结果缓存,提高解密性能
this._decryptCache = new LRUCache(500)
// 🧹 定期清理缓存每10分钟
setInterval(
() => {
this._decryptCache.cleanup()
logger.info('🧹 Gemini-API decrypt cache cleanup completed', this._decryptCache.getStats())
},
10 * 60 * 1000
)
}
// 创建账户
async createAccount(options = {}) {
const {
name = 'Gemini API Account',
description = '',
apiKey = '', // 必填Google AI Studio API Key
baseUrl = 'https://generativelanguage.googleapis.com', // 默认 Gemini API 基础 URL
proxy = null,
priority = 50, // 调度优先级 (1-100)
isActive = true,
accountType = 'shared', // 'dedicated' or 'shared'
schedulable = true, // 是否可被调度
supportedModels = [], // 支持的模型列表
rateLimitDuration = 60 // 限流时间(分钟)
} = options
// 验证必填字段
if (!apiKey) {
throw new Error('API Key is required for Gemini-API account')
}
// 规范化 baseUrl确保不以 / 结尾)
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
const accountId = uuidv4()
const accountData = {
id: accountId,
platform: 'gemini-api',
name,
description,
baseUrl: normalizedBaseUrl,
apiKey: this._encryptSensitiveData(apiKey),
priority: priority.toString(),
proxy: proxy ? JSON.stringify(proxy) : '',
isActive: isActive.toString(),
accountType,
schedulable: schedulable.toString(),
supportedModels: JSON.stringify(supportedModels),
createdAt: new Date().toISOString(),
lastUsedAt: '',
status: 'active',
errorMessage: '',
// 限流相关
rateLimitedAt: '',
rateLimitStatus: '',
rateLimitDuration: rateLimitDuration.toString()
}
// 保存到 Redis
await this._saveAccount(accountId, accountData)
logger.success(`🚀 Created Gemini-API account: ${name} (${accountId})`)
return {
...accountData,
apiKey: '***' // 返回时隐藏敏感信息
}
}
// 获取账户
async getAccount(accountId) {
const client = redis.getClientSafe()
const key = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
const accountData = await client.hgetall(key)
if (!accountData || !accountData.id) {
return null
}
// 解密敏感数据
accountData.apiKey = this._decryptSensitiveData(accountData.apiKey)
// 解析 JSON 字段
if (accountData.proxy) {
try {
accountData.proxy = JSON.parse(accountData.proxy)
} catch (e) {
accountData.proxy = null
}
}
if (accountData.supportedModels) {
try {
accountData.supportedModels = JSON.parse(accountData.supportedModels)
} catch (e) {
accountData.supportedModels = []
}
}
return accountData
}
// 更新账户
async updateAccount(accountId, updates) {
const account = await this.getAccount(accountId)
if (!account) {
throw new Error('Account not found')
}
// 处理敏感字段加密
if (updates.apiKey) {
updates.apiKey = this._encryptSensitiveData(updates.apiKey)
}
// 处理 JSON 字段
if (updates.proxy !== undefined) {
updates.proxy = updates.proxy ? JSON.stringify(updates.proxy) : ''
}
if (updates.supportedModels !== undefined) {
updates.supportedModels = JSON.stringify(updates.supportedModels)
}
// 规范化 baseUrl
if (updates.baseUrl) {
updates.baseUrl = updates.baseUrl.endsWith('/')
? updates.baseUrl.slice(0, -1)
: updates.baseUrl
}
// 更新 Redis
const client = redis.getClientSafe()
const key = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
await client.hset(key, updates)
logger.info(`📝 Updated Gemini-API account: ${account.name}`)
return { success: true }
}
// 删除账户
async deleteAccount(accountId) {
const client = redis.getClientSafe()
const key = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
// 从共享账户列表中移除
await client.srem(this.SHARED_ACCOUNTS_KEY, accountId)
// 删除账户数据
await client.del(key)
logger.info(`🗑️ Deleted Gemini-API account: ${accountId}`)
return { success: true }
}
// 获取所有账户
async getAllAccounts(includeInactive = false) {
const client = redis.getClientSafe()
const accountIds = await client.smembers(this.SHARED_ACCOUNTS_KEY)
const accounts = []
for (const accountId of accountIds) {
const account = await this.getAccount(accountId)
if (account) {
// 过滤非活跃账户
if (includeInactive || account.isActive === 'true') {
// 隐藏敏感信息
account.apiKey = '***'
// 获取限流状态信息
const rateLimitInfo = this._getRateLimitInfo(account)
// 格式化 rateLimitStatus 为对象
account.rateLimitStatus = rateLimitInfo.isRateLimited
? {
isRateLimited: true,
rateLimitedAt: account.rateLimitedAt || null,
minutesRemaining: rateLimitInfo.remainingMinutes || 0
}
: {
isRateLimited: false,
rateLimitedAt: null,
minutesRemaining: 0
}
// 转换 schedulable 字段为布尔值
account.schedulable = account.schedulable !== 'false'
// 转换 isActive 字段为布尔值
account.isActive = account.isActive === 'true'
account.platform = account.platform || 'gemini-api'
accounts.push(account)
}
}
}
// 直接从 Redis 获取所有账户(包括非共享账户)
const keys = await client.keys(`${this.ACCOUNT_KEY_PREFIX}*`)
for (const key of keys) {
const accountId = key.replace(this.ACCOUNT_KEY_PREFIX, '')
if (!accountIds.includes(accountId)) {
const accountData = await client.hgetall(key)
if (accountData && accountData.id) {
// 过滤非活跃账户
if (includeInactive || accountData.isActive === 'true') {
// 隐藏敏感信息
accountData.apiKey = '***'
// 解析 JSON 字段
if (accountData.proxy) {
try {
accountData.proxy = JSON.parse(accountData.proxy)
} catch (e) {
accountData.proxy = null
}
}
if (accountData.supportedModels) {
try {
accountData.supportedModels = JSON.parse(accountData.supportedModels)
} catch (e) {
accountData.supportedModels = []
}
}
// 获取限流状态信息
const rateLimitInfo = this._getRateLimitInfo(accountData)
// 格式化 rateLimitStatus 为对象
accountData.rateLimitStatus = rateLimitInfo.isRateLimited
? {
isRateLimited: true,
rateLimitedAt: accountData.rateLimitedAt || null,
minutesRemaining: rateLimitInfo.remainingMinutes || 0
}
: {
isRateLimited: false,
rateLimitedAt: null,
minutesRemaining: 0
}
// 转换 schedulable 字段为布尔值
accountData.schedulable = accountData.schedulable !== 'false'
// 转换 isActive 字段为布尔值
accountData.isActive = accountData.isActive === 'true'
accountData.platform = accountData.platform || 'gemini-api'
accounts.push(accountData)
}
}
}
}
return accounts
}
// 标记账户已使用
async markAccountUsed(accountId) {
await this.updateAccount(accountId, {
lastUsedAt: new Date().toISOString()
})
}
// 标记账户限流
async setAccountRateLimited(accountId, isLimited, duration = null) {
const account = await this.getAccount(accountId)
if (!account) {
return
}
if (isLimited) {
const rateLimitDuration = duration || parseInt(account.rateLimitDuration) || 60
const now = new Date()
const resetAt = new Date(now.getTime() + rateLimitDuration * 60000)
await this.updateAccount(accountId, {
rateLimitedAt: now.toISOString(),
rateLimitStatus: 'limited',
rateLimitResetAt: resetAt.toISOString(),
rateLimitDuration: rateLimitDuration.toString(),
status: 'rateLimited',
schedulable: 'false', // 防止被调度
errorMessage: `Rate limited until ${resetAt.toISOString()}`
})
logger.warn(
`⏳ Gemini-API account ${account.name} marked as rate limited for ${rateLimitDuration} minutes (until ${resetAt.toISOString()})`
)
} else {
// 清除限流状态
await this.updateAccount(accountId, {
rateLimitedAt: '',
rateLimitStatus: '',
rateLimitResetAt: '',
status: 'active',
schedulable: 'true',
errorMessage: ''
})
logger.info(`✅ Rate limit cleared for Gemini-API account ${account.name}`)
}
}
// 🚫 标记账户为未授权状态401错误
async markAccountUnauthorized(accountId, reason = 'Gemini API账号认证失败401错误') {
const account = await this.getAccount(accountId)
if (!account) {
return
}
const now = new Date().toISOString()
const currentCount = parseInt(account.unauthorizedCount || '0', 10)
const unauthorizedCount = Number.isFinite(currentCount) ? currentCount + 1 : 1
await this.updateAccount(accountId, {
status: 'unauthorized',
schedulable: 'false',
errorMessage: reason,
unauthorizedAt: now,
unauthorizedCount: unauthorizedCount.toString()
})
logger.warn(
`🚫 Gemini-API account ${account.name || accountId} marked as unauthorized due to 401 error`
)
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: account.name || accountId,
platform: 'gemini-api',
status: 'unauthorized',
errorCode: 'GEMINI_API_UNAUTHORIZED',
reason,
timestamp: now
})
logger.info(
`📢 Webhook notification sent for Gemini-API account ${account.name || accountId} unauthorized state`
)
} catch (webhookError) {
logger.error('Failed to send unauthorized webhook notification:', webhookError)
}
}
// 检查并清除过期的限流状态
async checkAndClearRateLimit(accountId) {
const account = await this.getAccount(accountId)
if (!account || account.rateLimitStatus !== 'limited') {
return false
}
const now = new Date()
let shouldClear = false
// 优先使用 rateLimitResetAt 字段
if (account.rateLimitResetAt) {
const resetAt = new Date(account.rateLimitResetAt)
shouldClear = now >= resetAt
} else {
// 如果没有 rateLimitResetAt使用旧的逻辑
const rateLimitedAt = new Date(account.rateLimitedAt)
const rateLimitDuration = parseInt(account.rateLimitDuration) || 60
shouldClear = now - rateLimitedAt > rateLimitDuration * 60000
}
if (shouldClear) {
// 限流已过期,清除状态
await this.setAccountRateLimited(accountId, false)
return true
}
return false
}
// 切换调度状态
async toggleSchedulable(accountId) {
const account = await this.getAccount(accountId)
if (!account) {
throw new Error('Account not found')
}
const newSchedulableStatus = account.schedulable === 'true' ? 'false' : 'true'
await this.updateAccount(accountId, {
schedulable: newSchedulableStatus
})
logger.info(
`🔄 Toggled schedulable status for Gemini-API account ${account.name}: ${newSchedulableStatus}`
)
return {
success: true,
schedulable: newSchedulableStatus === 'true'
}
}
// 重置账户状态(清除所有异常状态)
async resetAccountStatus(accountId) {
const account = await this.getAccount(accountId)
if (!account) {
throw new Error('Account not found')
}
const updates = {
// 根据是否有有效的 apiKey 来设置 status
status: account.apiKey ? 'active' : 'created',
// 恢复可调度状态
schedulable: 'true',
// 清除错误相关字段
errorMessage: '',
rateLimitedAt: '',
rateLimitStatus: '',
rateLimitResetAt: '',
rateLimitDuration: ''
}
await this.updateAccount(accountId, updates)
logger.info(`✅ Reset all error status for Gemini-API account ${accountId}`)
// 发送 Webhook 通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: account.name || accountId,
platform: 'gemini-api',
status: 'recovered',
errorCode: 'STATUS_RESET',
reason: 'Account status manually reset',
timestamp: new Date().toISOString()
})
logger.info(
`📢 Webhook notification sent for Gemini-API account ${account.name} status reset`
)
} catch (webhookError) {
logger.error('Failed to send status reset webhook notification:', webhookError)
}
return { success: true, message: 'Account status reset successfully' }
}
// API Key 不会过期
isTokenExpired(_account) {
return false
}
// 获取限流信息
_getRateLimitInfo(accountData) {
if (accountData.rateLimitStatus !== 'limited') {
return { isRateLimited: false }
}
const now = new Date()
let willBeAvailableAt
let remainingMinutes
// 优先使用 rateLimitResetAt 字段
if (accountData.rateLimitResetAt) {
willBeAvailableAt = new Date(accountData.rateLimitResetAt)
remainingMinutes = Math.max(0, Math.ceil((willBeAvailableAt - now) / 60000))
} else {
// 如果没有 rateLimitResetAt使用旧的逻辑
const rateLimitedAt = new Date(accountData.rateLimitedAt)
const rateLimitDuration = parseInt(accountData.rateLimitDuration) || 60
const elapsedMinutes = Math.floor((now - rateLimitedAt) / 60000)
remainingMinutes = Math.max(0, rateLimitDuration - elapsedMinutes)
willBeAvailableAt = new Date(rateLimitedAt.getTime() + rateLimitDuration * 60000)
}
return {
isRateLimited: remainingMinutes > 0,
remainingMinutes,
willBeAvailableAt
}
}
// 加密敏感数据
_encryptSensitiveData(text) {
if (!text) {
return ''
}
const key = this._getEncryptionKey()
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(this.ENCRYPTION_ALGORITHM, key, iv)
let encrypted = cipher.update(text)
encrypted = Buffer.concat([encrypted, cipher.final()])
return `${iv.toString('hex')}:${encrypted.toString('hex')}`
}
// 解密敏感数据
_decryptSensitiveData(text) {
if (!text || text === '') {
return ''
}
// 检查缓存
const cacheKey = crypto.createHash('sha256').update(text).digest('hex')
const cached = this._decryptCache.get(cacheKey)
if (cached !== undefined) {
return cached
}
try {
const key = this._getEncryptionKey()
const [ivHex, encryptedHex] = text.split(':')
const iv = Buffer.from(ivHex, 'hex')
const encryptedText = Buffer.from(encryptedHex, 'hex')
const decipher = crypto.createDecipheriv(this.ENCRYPTION_ALGORITHM, key, iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
const result = decrypted.toString()
// 存入缓存5分钟过期
this._decryptCache.set(cacheKey, result, 5 * 60 * 1000)
return result
} catch (error) {
logger.error('Decryption error:', error)
return ''
}
}
// 获取加密密钥
_getEncryptionKey() {
if (!this._encryptionKeyCache) {
this._encryptionKeyCache = crypto.scryptSync(
config.security.encryptionKey,
this.ENCRYPTION_SALT,
32
)
}
return this._encryptionKeyCache
}
// 保存账户到 Redis
async _saveAccount(accountId, accountData) {
const client = redis.getClientSafe()
const key = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
// 保存账户数据
await client.hset(key, accountData)
// 添加到共享账户列表
if (accountData.accountType === 'shared') {
await client.sadd(this.SHARED_ACCOUNTS_KEY, accountId)
}
}
}
module.exports = new GeminiApiAccountService()

View File

@@ -1,4 +1,5 @@
const geminiAccountService = require('./geminiAccountService')
const geminiApiAccountService = require('./geminiApiAccountService')
const accountGroupService = require('./accountGroupService')
const redis = require('../models/redis')
const logger = require('../utils/logger')
@@ -19,35 +20,69 @@ class UnifiedGeminiScheduler {
}
// 🎯 统一调度Gemini账号
async selectAccountForApiKey(apiKeyData, sessionHash = null, requestedModel = null) {
async selectAccountForApiKey(
apiKeyData,
sessionHash = null,
requestedModel = null,
options = {}
) {
const { allowApiAccounts = false } = options
try {
// 如果API Key绑定了专属账户或分组优先使用
if (apiKeyData.geminiAccountId) {
// 检查是否是 Gemini API 账户api: 前缀)
if (apiKeyData.geminiAccountId.startsWith('api:')) {
const accountId = apiKeyData.geminiAccountId.replace('api:', '')
const boundAccount = await geminiApiAccountService.getAccount(accountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
logger.info(
`🎯 Using bound Gemini-API account: ${boundAccount.name} (${accountId}) for API key ${apiKeyData.name}`
)
// 更新账户的最后使用时间
await geminiApiAccountService.markAccountUsed(accountId)
return {
accountId,
accountType: 'gemini-api'
}
} else {
// 提供详细的不可用原因
const reason = !boundAccount
? 'account not found'
: boundAccount.isActive !== 'true'
? `isActive=${boundAccount.isActive}`
: `status=${boundAccount.status}`
logger.warn(
`⚠️ Bound Gemini-API account ${accountId} is not available (${reason}), falling back to pool`
)
}
}
// 检查是否是分组
if (apiKeyData.geminiAccountId.startsWith('group:')) {
else if (apiKeyData.geminiAccountId.startsWith('group:')) {
const groupId = apiKeyData.geminiAccountId.replace('group:', '')
logger.info(
`🎯 API key ${apiKeyData.name} is bound to group ${groupId}, selecting from group`
)
return await this.selectAccountFromGroup(groupId, sessionHash, requestedModel, apiKeyData)
}
// 普通专属账户
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
logger.info(
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId}) for API key ${apiKeyData.name}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(apiKeyData.geminiAccountId)
return {
accountId: apiKeyData.geminiAccountId,
accountType: 'gemini'
// 普通 Gemini OAuth 专属账户
else {
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
logger.info(
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId}) for API key ${apiKeyData.name}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(apiKeyData.geminiAccountId)
return {
accountId: apiKeyData.geminiAccountId,
accountType: 'gemini'
}
} else {
logger.warn(
`⚠️ Bound Gemini account ${apiKeyData.geminiAccountId} is not available, falling back to pool`
)
}
} else {
logger.warn(
`⚠️ Bound Gemini account ${apiKeyData.geminiAccountId} is not available, falling back to pool`
)
}
}
@@ -66,8 +101,12 @@ class UnifiedGeminiScheduler {
logger.info(
`🎯 Using sticky session account: ${mappedAccount.accountId} (${mappedAccount.accountType}) for session ${sessionHash}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(mappedAccount.accountId)
// 更新账户的最后使用时间(根据账户类型调用正确的服务)
if (mappedAccount.accountType === 'gemini-api') {
await geminiApiAccountService.markAccountUsed(mappedAccount.accountId)
} else {
await geminiAccountService.markAccountUsed(mappedAccount.accountId)
}
return mappedAccount
} else {
logger.warn(
@@ -79,7 +118,11 @@ class UnifiedGeminiScheduler {
}
// 获取所有可用账户
const availableAccounts = await this._getAllAvailableAccounts(apiKeyData, requestedModel)
const availableAccounts = await this._getAllAvailableAccounts(
apiKeyData,
requestedModel,
allowApiAccounts
)
if (availableAccounts.length === 0) {
// 提供更详细的错误信息
@@ -114,8 +157,12 @@ class UnifiedGeminiScheduler {
`🎯 Selected account: ${selectedAccount.name} (${selectedAccount.accountId}, ${selectedAccount.accountType}) with priority ${selectedAccount.priority} for API key ${apiKeyData.name}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(selectedAccount.accountId)
// 更新账户的最后使用时间(根据账户类型调用正确的服务)
if (selectedAccount.accountType === 'gemini-api') {
await geminiApiAccountService.markAccountUsed(selectedAccount.accountId)
} else {
await geminiAccountService.markAccountUsed(selectedAccount.accountId)
}
return {
accountId: selectedAccount.accountId,
@@ -128,53 +175,104 @@ class UnifiedGeminiScheduler {
}
// 📋 获取所有可用账户
async _getAllAvailableAccounts(apiKeyData, requestedModel = null) {
async _getAllAvailableAccounts(apiKeyData, requestedModel = null, allowApiAccounts = false) {
const availableAccounts = []
// 如果API Key绑定了专属账户优先返回
if (apiKeyData.geminiAccountId) {
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
const isRateLimited = await this.isAccountRateLimited(boundAccount.id)
if (!isRateLimited) {
// 检查模型支持
if (
requestedModel &&
boundAccount.supportedModels &&
boundAccount.supportedModels.length > 0
) {
// 处理可能带有 models/ 前缀的模型名
const normalizedModel = requestedModel.replace('models/', '')
const modelSupported = boundAccount.supportedModels.some(
(model) => model.replace('models/', '') === normalizedModel
)
if (!modelSupported) {
logger.warn(
`⚠️ Bound Gemini account ${boundAccount.name} does not support model ${requestedModel}`
// 检查是否是 Gemini API 账户api: 前缀)
if (apiKeyData.geminiAccountId.startsWith('api:')) {
const accountId = apiKeyData.geminiAccountId.replace('api:', '')
const boundAccount = await geminiApiAccountService.getAccount(accountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
const isRateLimited = await this.isAccountRateLimited(accountId)
if (!isRateLimited) {
// 检查模型支持
if (
requestedModel &&
boundAccount.supportedModels &&
boundAccount.supportedModels.length > 0
) {
const normalizedModel = requestedModel.replace('models/', '')
const modelSupported = boundAccount.supportedModels.some(
(model) => model.replace('models/', '') === normalizedModel
)
return availableAccounts
if (!modelSupported) {
logger.warn(
`⚠️ Bound Gemini-API account ${boundAccount.name} does not support model ${requestedModel}`
)
return availableAccounts
}
}
}
logger.info(
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId})`
logger.info(`🎯 Using bound Gemini-API account: ${boundAccount.name} (${accountId})`)
return [
{
...boundAccount,
accountId,
accountType: 'gemini-api',
priority: parseInt(boundAccount.priority) || 50,
lastUsedAt: boundAccount.lastUsedAt || '0'
}
]
}
} else {
// 提供详细的不可用原因
const reason = !boundAccount
? 'account not found'
: boundAccount.isActive !== 'true'
? `isActive=${boundAccount.isActive}`
: `status=${boundAccount.status}`
logger.warn(
`⚠️ Bound Gemini-API account ${accountId} is not available in _getAllAvailableAccounts (${reason})`
)
return [
{
...boundAccount,
accountId: boundAccount.id,
accountType: 'gemini',
priority: parseInt(boundAccount.priority) || 50,
lastUsedAt: boundAccount.lastUsedAt || '0'
}
]
}
} else {
logger.warn(`⚠️ Bound Gemini account ${apiKeyData.geminiAccountId} is not available`)
}
// 普通 Gemini OAuth 账户
else if (!apiKeyData.geminiAccountId.startsWith('group:')) {
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
const isRateLimited = await this.isAccountRateLimited(boundAccount.id)
if (!isRateLimited) {
// 检查模型支持
if (
requestedModel &&
boundAccount.supportedModels &&
boundAccount.supportedModels.length > 0
) {
// 处理可能带有 models/ 前缀的模型名
const normalizedModel = requestedModel.replace('models/', '')
const modelSupported = boundAccount.supportedModels.some(
(model) => model.replace('models/', '') === normalizedModel
)
if (!modelSupported) {
logger.warn(
`⚠️ Bound Gemini account ${boundAccount.name} does not support model ${requestedModel}`
)
return availableAccounts
}
}
logger.info(
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId})`
)
return [
{
...boundAccount,
accountId: boundAccount.id,
accountType: 'gemini',
priority: parseInt(boundAccount.priority) || 50,
lastUsedAt: boundAccount.lastUsedAt || '0'
}
]
}
} else {
logger.warn(`⚠️ Bound Gemini account ${apiKeyData.geminiAccountId} is not available`)
}
}
}
// 获取所有Gemini账户共享池
// 获取所有Gemini OAuth账户(共享池)
const geminiAccounts = await geminiAccountService.getAllAccounts()
for (const account of geminiAccounts) {
if (
@@ -223,7 +321,48 @@ class UnifiedGeminiScheduler {
}
}
logger.info(`📊 Total available Gemini accounts: ${availableAccounts.length}`)
// 如果允许调度 Gemini API 账户,则添加到可用列表
if (allowApiAccounts) {
const geminiApiAccounts = await geminiApiAccountService.getAllAccounts()
for (const account of geminiApiAccounts) {
if (
account.isActive === 'true' &&
account.status !== 'error' &&
(account.accountType === 'shared' || !account.accountType) &&
this._isSchedulable(account.schedulable)
) {
// 检查模型支持
if (requestedModel && account.supportedModels && account.supportedModels.length > 0) {
const normalizedModel = requestedModel.replace('models/', '')
const modelSupported = account.supportedModels.some(
(model) => model.replace('models/', '') === normalizedModel
)
if (!modelSupported) {
logger.debug(
`⏭️ Skipping Gemini-API account ${account.name} - doesn't support model ${requestedModel}`
)
continue
}
}
// 检查是否被限流
const isRateLimited = await this.isAccountRateLimited(account.id)
if (!isRateLimited) {
availableAccounts.push({
...account,
accountId: account.id,
accountType: 'gemini-api',
priority: parseInt(account.priority) || 50,
lastUsedAt: account.lastUsedAt || '0'
})
}
}
}
}
logger.info(
`📊 Total available accounts: ${availableAccounts.length} (Gemini OAuth + ${allowApiAccounts ? 'Gemini API' : 'no API accounts'})`
)
return availableAccounts
}
@@ -256,6 +395,17 @@ class UnifiedGeminiScheduler {
return false
}
return !(await this.isAccountRateLimited(accountId))
} else if (accountType === 'gemini-api') {
const account = await geminiApiAccountService.getAccount(accountId)
if (!account || account.isActive !== 'true' || account.status === 'error') {
return false
}
// 检查是否可调度
if (!this._isSchedulable(account.schedulable)) {
logger.info(`🚫 Gemini-API account ${accountId} is not schedulable`)
return false
}
return !(await this.isAccountRateLimited(accountId))
}
return false
} catch (error) {
@@ -344,6 +494,8 @@ class UnifiedGeminiScheduler {
try {
if (accountType === 'gemini') {
await geminiAccountService.setAccountRateLimited(accountId, true)
} else if (accountType === 'gemini-api') {
await geminiApiAccountService.setAccountRateLimited(accountId, true)
}
// 删除会话映射
@@ -366,6 +518,8 @@ class UnifiedGeminiScheduler {
try {
if (accountType === 'gemini') {
await geminiAccountService.setAccountRateLimited(accountId, false)
} else if (accountType === 'gemini-api') {
await geminiApiAccountService.setAccountRateLimited(accountId, false)
}
return { success: true }
@@ -379,9 +533,23 @@ class UnifiedGeminiScheduler {
}
// 🔍 检查账户是否处于限流状态
async isAccountRateLimited(accountId) {
async isAccountRateLimited(accountId, accountType = null) {
try {
const account = await geminiAccountService.getAccount(accountId)
let account = null
// 如果指定了账户类型,直接使用对应服务
if (accountType === 'gemini-api') {
account = await geminiApiAccountService.getAccount(accountId)
} else if (accountType === 'gemini') {
account = await geminiAccountService.getAccount(accountId)
} else {
// 未指定类型,先尝试 gemini再尝试 gemini-api
account = await geminiAccountService.getAccount(accountId)
if (!account) {
account = await geminiApiAccountService.getAccount(accountId)
}
}
if (!account) {
return false
}
@@ -389,7 +557,9 @@ class UnifiedGeminiScheduler {
if (account.rateLimitStatus === 'limited' && account.rateLimitedAt) {
const limitedAt = new Date(account.rateLimitedAt).getTime()
const now = Date.now()
const limitDuration = 60 * 60 * 1000 // 1小时
// 使用账户配置的限流时长,默认1小时
const rateLimitDuration = parseInt(account.rateLimitDuration) || 60
const limitDuration = rateLimitDuration * 60 * 1000
return now < limitedAt + limitDuration
}
@@ -400,7 +570,7 @@ class UnifiedGeminiScheduler {
}
}
// 👥 从分组中选择账户
// 👥 从分组中选择账户(支持 Gemini OAuth 和 Gemini API 两种账户类型)
async selectAccountFromGroup(groupId, sessionHash = null, requestedModel = null) {
try {
// 获取分组信息
@@ -432,8 +602,12 @@ class UnifiedGeminiScheduler {
logger.info(
`🎯 Using sticky session account from group: ${mappedAccount.accountId} (${mappedAccount.accountType}) for session ${sessionHash}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(mappedAccount.accountId)
// 更新账户的最后使用时间(根据账户类型调用正确的服务)
if (mappedAccount.accountType === 'gemini-api') {
await geminiApiAccountService.markAccountUsed(mappedAccount.accountId)
} else {
await geminiAccountService.markAccountUsed(mappedAccount.accountId)
}
return mappedAccount
}
}
@@ -450,9 +624,17 @@ class UnifiedGeminiScheduler {
const availableAccounts = []
// 获取所有成员账户的详细信息
// 获取所有成员账户的详细信息(支持 Gemini OAuth 和 Gemini API 两种类型)
for (const memberId of memberIds) {
const account = await geminiAccountService.getAccount(memberId)
// 首先尝试从 Gemini OAuth 账户服务获取
let account = await geminiAccountService.getAccount(memberId)
let accountType = 'gemini'
// 如果 Gemini OAuth 账户不存在,尝试从 Gemini API 账户服务获取
if (!account) {
account = await geminiApiAccountService.getAccount(memberId)
accountType = 'gemini-api'
}
if (!account) {
logger.warn(`⚠️ Gemini account ${memberId} not found in group ${group.name}`)
@@ -465,13 +647,15 @@ class UnifiedGeminiScheduler {
account.status !== 'error' &&
this._isSchedulable(account.schedulable)
) {
// 检查token是否过期
const isExpired = geminiAccountService.isTokenExpired(account)
if (isExpired && !account.refreshToken) {
logger.warn(
`⚠️ Gemini account ${account.name} in group token expired and no refresh token available`
)
continue
// 对于 Gemini OAuth 账户,检查 token 是否过期
if (accountType === 'gemini') {
const isExpired = geminiAccountService.isTokenExpired(account)
if (isExpired && !account.refreshToken) {
logger.warn(
`⚠️ Gemini account ${account.name} in group token expired and no refresh token available`
)
continue
}
}
// 检查模型支持
@@ -483,19 +667,19 @@ class UnifiedGeminiScheduler {
)
if (!modelSupported) {
logger.debug(
`⏭️ Skipping Gemini account ${account.name} in group - doesn't support model ${requestedModel}`
`⏭️ Skipping ${accountType} account ${account.name} in group - doesn't support model ${requestedModel}`
)
continue
}
}
// 检查是否被限流
const isRateLimited = await this.isAccountRateLimited(account.id)
const isRateLimited = await this.isAccountRateLimited(account.id, accountType)
if (!isRateLimited) {
availableAccounts.push({
...account,
accountId: account.id,
accountType: 'gemini',
accountType,
priority: parseInt(account.priority) || 50,
lastUsedAt: account.lastUsedAt || '0'
})
@@ -529,8 +713,12 @@ class UnifiedGeminiScheduler {
`🎯 Selected account from Gemini group ${group.name}: ${selectedAccount.name} (${selectedAccount.accountId}, ${selectedAccount.accountType}) with priority ${selectedAccount.priority}`
)
// 更新账户的最后使用时间
await geminiAccountService.markAccountUsed(selectedAccount.accountId)
// 更新账户的最后使用时间(根据账户类型调用正确的服务)
if (selectedAccount.accountType === 'gemini-api') {
await geminiApiAccountService.markAccountUsed(selectedAccount.accountId)
} else {
await geminiAccountService.markAccountUsed(selectedAccount.accountId)
}
return {
accountId: selectedAccount.accountId,