mirror of
https://github.com/Wei-Shaw/claude-relay-service.git
synced 2026-01-22 16:43:35 +00:00
feat: 支持Gemini-Api接入
This commit is contained in:
@@ -4366,6 +4366,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
|
|||||||
'openai',
|
'openai',
|
||||||
'openai-responses',
|
'openai-responses',
|
||||||
'gemini',
|
'gemini',
|
||||||
|
'gemini-api',
|
||||||
'droid'
|
'droid'
|
||||||
]
|
]
|
||||||
if (!allowedPlatforms.includes(platform)) {
|
if (!allowedPlatforms.includes(platform)) {
|
||||||
@@ -4378,6 +4379,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
|
|||||||
const accountTypeMap = {
|
const accountTypeMap = {
|
||||||
openai: 'openai',
|
openai: 'openai',
|
||||||
'openai-responses': 'openai-responses',
|
'openai-responses': 'openai-responses',
|
||||||
|
'gemini-api': 'gemini-api',
|
||||||
droid: 'droid'
|
droid: 'droid'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4387,6 +4389,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
|
|||||||
openai: 'gpt-4o-mini-2024-07-18',
|
openai: 'gpt-4o-mini-2024-07-18',
|
||||||
'openai-responses': 'gpt-4o-mini-2024-07-18',
|
'openai-responses': 'gpt-4o-mini-2024-07-18',
|
||||||
gemini: 'gemini-1.5-flash',
|
gemini: 'gemini-1.5-flash',
|
||||||
|
'gemini-api': 'gemini-2.0-flash',
|
||||||
droid: 'unknown'
|
droid: 'unknown'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4411,6 +4414,11 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
|
|||||||
case 'gemini':
|
case 'gemini':
|
||||||
accountData = await geminiAccountService.getAccount(accountId)
|
accountData = await geminiAccountService.getAccount(accountId)
|
||||||
break
|
break
|
||||||
|
case 'gemini-api': {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
accountData = await geminiApiAccountService.getAccount(accountId)
|
||||||
|
break
|
||||||
|
}
|
||||||
case 'droid':
|
case 'droid':
|
||||||
accountData = await droidAccountService.getAccount(accountId)
|
accountData = await droidAccountService.getAccount(accountId)
|
||||||
break
|
break
|
||||||
@@ -9181,4 +9189,401 @@ router.post('/droid-accounts/:id/refresh-token', authenticateAdmin, async (req,
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ==================== Gemini-API 账户管理 API ====================
|
||||||
|
|
||||||
|
// 获取所有 Gemini-API 账户
|
||||||
|
router.get('/gemini-api-accounts', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { platform, groupId } = req.query
|
||||||
|
let accounts = await geminiApiAccountService.getAllAccounts(true)
|
||||||
|
|
||||||
|
// 根据查询参数进行筛选
|
||||||
|
if (platform && platform !== 'gemini-api') {
|
||||||
|
accounts = []
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据分组ID筛选
|
||||||
|
if (groupId) {
|
||||||
|
const group = await accountGroupService.getGroup(groupId)
|
||||||
|
if (group && group.platform === 'gemini' && group.memberIds && group.memberIds.length > 0) {
|
||||||
|
accounts = accounts.filter((account) => group.memberIds.includes(account.id))
|
||||||
|
} else {
|
||||||
|
accounts = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理使用统计和绑定的 API Key 数量
|
||||||
|
const accountsWithStats = await Promise.all(
|
||||||
|
accounts.map(async (account) => {
|
||||||
|
// 检查并清除过期的限流状态
|
||||||
|
await geminiApiAccountService.checkAndClearRateLimit(account.id)
|
||||||
|
|
||||||
|
// 获取使用统计信息
|
||||||
|
let usageStats
|
||||||
|
try {
|
||||||
|
usageStats = await redis.getAccountUsageStats(account.id, 'gemini-api')
|
||||||
|
} catch (error) {
|
||||||
|
logger.debug(`Failed to get usage stats for Gemini-API account ${account.id}:`, error)
|
||||||
|
usageStats = {
|
||||||
|
daily: { requests: 0, tokens: 0, allTokens: 0 },
|
||||||
|
total: { requests: 0, tokens: 0, allTokens: 0 },
|
||||||
|
monthly: { requests: 0, tokens: 0, allTokens: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算绑定的API Key数量(支持 api: 前缀)
|
||||||
|
const allKeys = await redis.getAllApiKeys()
|
||||||
|
let boundCount = 0
|
||||||
|
|
||||||
|
for (const key of allKeys) {
|
||||||
|
if (key.geminiAccountId) {
|
||||||
|
// 检查是否绑定了此 Gemini-API 账户(支持 api: 前缀)
|
||||||
|
if (key.geminiAccountId === `api:${account.id}`) {
|
||||||
|
boundCount++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...account,
|
||||||
|
usage: {
|
||||||
|
daily: usageStats.daily,
|
||||||
|
total: usageStats.total,
|
||||||
|
averages: usageStats.averages || usageStats.monthly
|
||||||
|
},
|
||||||
|
boundApiKeys: boundCount
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
res.json({ success: true, data: accountsWithStats })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get Gemini-API accounts:', error)
|
||||||
|
res.status(500).json({ success: false, message: error.message })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建 Gemini-API 账户
|
||||||
|
router.post('/gemini-api-accounts', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { accountType, groupId, groupIds } = req.body
|
||||||
|
|
||||||
|
// 验证accountType的有效性
|
||||||
|
if (accountType && !['shared', 'dedicated', 'group'].includes(accountType)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid account type. Must be "shared", "dedicated" or "group"'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果是分组类型,验证groupId或groupIds
|
||||||
|
if (accountType === 'group' && !groupId && (!groupIds || groupIds.length === 0)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Group ID or Group IDs are required for group type accounts'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await geminiApiAccountService.createAccount(req.body)
|
||||||
|
|
||||||
|
// 如果是分组类型,将账户添加到分组
|
||||||
|
if (accountType === 'group') {
|
||||||
|
if (groupIds && groupIds.length > 0) {
|
||||||
|
// 使用多分组设置
|
||||||
|
await accountGroupService.setAccountGroups(account.id, groupIds, 'gemini')
|
||||||
|
} else if (groupId) {
|
||||||
|
// 兼容单分组模式
|
||||||
|
await accountGroupService.addAccountToGroup(account.id, groupId, 'gemini')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.success(
|
||||||
|
`🏢 Admin created new Gemini-API account: ${account.name} (${accountType || 'shared'})`
|
||||||
|
)
|
||||||
|
|
||||||
|
res.json({ success: true, data: account })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to create Gemini-API account:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 获取单个 Gemini-API 账户
|
||||||
|
router.get('/gemini-api-accounts/:id', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
const account = await geminiApiAccountService.getAccount(id)
|
||||||
|
|
||||||
|
if (!account) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Account not found'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 隐藏敏感信息
|
||||||
|
account.apiKey = '***'
|
||||||
|
|
||||||
|
res.json({ success: true, data: account })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to get Gemini-API account:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 更新 Gemini-API 账户
|
||||||
|
router.put('/gemini-api-accounts/:id', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
const updates = req.body
|
||||||
|
|
||||||
|
// 验证priority的有效性(1-100)
|
||||||
|
if (updates.priority !== undefined) {
|
||||||
|
const priority = parseInt(updates.priority)
|
||||||
|
if (isNaN(priority) || priority < 1 || priority > 100) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Priority must be a number between 1 and 100'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证accountType的有效性
|
||||||
|
if (updates.accountType && !['shared', 'dedicated', 'group'].includes(updates.accountType)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid account type. Must be "shared", "dedicated" or "group"'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果更新为分组类型,验证groupId或groupIds
|
||||||
|
if (
|
||||||
|
updates.accountType === 'group' &&
|
||||||
|
!updates.groupId &&
|
||||||
|
(!updates.groupIds || updates.groupIds.length === 0)
|
||||||
|
) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Group ID or Group IDs are required for group type accounts'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取账户当前信息以处理分组变更
|
||||||
|
const currentAccount = await geminiApiAccountService.getAccount(id)
|
||||||
|
if (!currentAccount) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Account not found'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理分组的变更
|
||||||
|
if (updates.accountType !== undefined) {
|
||||||
|
// 如果之前是分组类型,需要从所有分组中移除
|
||||||
|
if (currentAccount.accountType === 'group') {
|
||||||
|
await accountGroupService.removeAccountFromAllGroups(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果新类型是分组,添加到新分组
|
||||||
|
if (updates.accountType === 'group') {
|
||||||
|
// 处理多分组/单分组的兼容性
|
||||||
|
if (Object.prototype.hasOwnProperty.call(updates, 'groupIds')) {
|
||||||
|
if (updates.groupIds && updates.groupIds.length > 0) {
|
||||||
|
// 使用多分组设置
|
||||||
|
await accountGroupService.setAccountGroups(id, updates.groupIds, 'gemini')
|
||||||
|
}
|
||||||
|
} else if (updates.groupId) {
|
||||||
|
// 兼容单分组模式
|
||||||
|
await accountGroupService.addAccountToGroup(id, updates.groupId, 'gemini')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await geminiApiAccountService.updateAccount(id, updates)
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
return res.status(400).json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.success(`📝 Admin updated Gemini-API account: ${currentAccount.name}`)
|
||||||
|
|
||||||
|
res.json({ success: true, ...result })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to update Gemini-API account:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 删除 Gemini-API 账户
|
||||||
|
router.delete('/gemini-api-accounts/:id', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
const account = await geminiApiAccountService.getAccount(id)
|
||||||
|
if (!account) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Account not found'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动解绑所有绑定的 API Keys(支持 api: 前缀)
|
||||||
|
const unboundCount = await apiKeyService.unbindAccountFromAllKeys(id, 'gemini-api')
|
||||||
|
|
||||||
|
// 检查是否在分组中
|
||||||
|
const groups = await accountGroupService.getAllGroups()
|
||||||
|
for (const group of groups) {
|
||||||
|
if (group.platform === 'gemini' && group.memberIds && group.memberIds.includes(id)) {
|
||||||
|
await accountGroupService.removeMemberFromGroup(group.id, id)
|
||||||
|
logger.info(`Removed Gemini-API account ${id} from group ${group.id}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await geminiApiAccountService.deleteAccount(id)
|
||||||
|
|
||||||
|
let message = 'Gemini-API账号已成功删除'
|
||||||
|
if (unboundCount > 0) {
|
||||||
|
message += `,${unboundCount} 个 API Key 已切换为共享池模式`
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.success(`✅ ${message}`)
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
...result,
|
||||||
|
message,
|
||||||
|
unboundKeys: unboundCount
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to delete Gemini-API account:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 切换 Gemini-API 账户调度状态
|
||||||
|
router.put('/gemini-api-accounts/:id/toggle-schedulable', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
const result = await geminiApiAccountService.toggleSchedulable(id)
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
return res.status(400).json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 仅在停止调度时发送通知
|
||||||
|
if (!result.schedulable) {
|
||||||
|
await webhookNotifier.sendAccountEvent('account.status_changed', {
|
||||||
|
accountId: id,
|
||||||
|
platform: 'gemini-api',
|
||||||
|
schedulable: result.schedulable,
|
||||||
|
changedBy: 'admin',
|
||||||
|
action: 'stopped_scheduling'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to toggle Gemini-API account schedulable status:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 切换 Gemini-API 账户激活状态
|
||||||
|
router.put('/gemini-api-accounts/:id/toggle', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
const account = await geminiApiAccountService.getAccount(id)
|
||||||
|
if (!account) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Account not found'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const newActiveStatus = account.isActive === 'true' ? 'false' : 'true'
|
||||||
|
await geminiApiAccountService.updateAccount(id, {
|
||||||
|
isActive: newActiveStatus
|
||||||
|
})
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
isActive: newActiveStatus === 'true'
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to toggle Gemini-API account status:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 重置 Gemini-API 账户限流状态
|
||||||
|
router.post('/gemini-api-accounts/:id/reset-rate-limit', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
await geminiApiAccountService.updateAccount(id, {
|
||||||
|
rateLimitedAt: '',
|
||||||
|
rateLimitStatus: '',
|
||||||
|
status: 'active',
|
||||||
|
errorMessage: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`🔄 Admin manually reset rate limit for Gemini-API account ${id}`)
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
message: 'Rate limit reset successfully'
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to reset Gemini-API account rate limit:', error)
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 重置 Gemini-API 账户状态(清除所有异常状态)
|
||||||
|
router.post('/gemini-api-accounts/:id/reset-status', authenticateAdmin, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
const result = await geminiApiAccountService.resetAccountStatus(id)
|
||||||
|
|
||||||
|
logger.success(`✅ Admin reset status for Gemini-API account: ${id}`)
|
||||||
|
return res.json({ success: true, data: result })
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('❌ Failed to reset Gemini-API account status:', error)
|
||||||
|
return res.status(500).json({ error: 'Failed to reset status', message: error.message })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
module.exports = router
|
module.exports = router
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ const router = express.Router()
|
|||||||
const logger = require('../utils/logger')
|
const logger = require('../utils/logger')
|
||||||
const { authenticateApiKey } = require('../middleware/auth')
|
const { authenticateApiKey } = require('../middleware/auth')
|
||||||
const geminiAccountService = require('../services/geminiAccountService')
|
const geminiAccountService = require('../services/geminiAccountService')
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
const { sendGeminiRequest, getAvailableModels } = require('../services/geminiRelayService')
|
const { sendGeminiRequest, getAvailableModels } = require('../services/geminiRelayService')
|
||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
const sessionHelper = require('../utils/sessionHelper')
|
const sessionHelper = require('../utils/sessionHelper')
|
||||||
@@ -10,6 +11,8 @@ const unifiedGeminiScheduler = require('../services/unifiedGeminiScheduler')
|
|||||||
const apiKeyService = require('../services/apiKeyService')
|
const apiKeyService = require('../services/apiKeyService')
|
||||||
const { updateRateLimitCounters } = require('../utils/rateLimitHelper')
|
const { updateRateLimitCounters } = require('../utils/rateLimitHelper')
|
||||||
const { parseSSELine } = require('../utils/sseParser')
|
const { parseSSELine } = require('../utils/sseParser')
|
||||||
|
const axios = require('axios')
|
||||||
|
const ProxyHelper = require('../utils/proxyHelper')
|
||||||
// const { OAuth2Client } = require('google-auth-library'); // OAuth2Client is not used in this file
|
// const { OAuth2Client } = require('google-auth-library'); // OAuth2Client is not used in this file
|
||||||
|
|
||||||
// 生成会话哈希
|
// 生成会话哈希
|
||||||
@@ -77,6 +80,9 @@ async function applyRateLimitTracking(req, usageSummary, model, context = '') {
|
|||||||
router.post('/messages', authenticateApiKey, async (req, res) => {
|
router.post('/messages', authenticateApiKey, async (req, res) => {
|
||||||
const startTime = Date.now()
|
const startTime = Date.now()
|
||||||
let abortController = null
|
let abortController = null
|
||||||
|
let accountId
|
||||||
|
let accountType
|
||||||
|
let sessionHash
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const apiKeyData = req.apiKey
|
const apiKeyData = req.apiKey
|
||||||
@@ -111,18 +117,17 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 生成会话哈希用于粘性会话
|
// 生成会话哈希用于粘性会话
|
||||||
const sessionHash = generateSessionHash(req)
|
sessionHash = generateSessionHash(req)
|
||||||
|
|
||||||
// 使用统一调度选择可用的 Gemini 账户(传递请求的模型)
|
// 使用统一调度选择可用的 Gemini 账户(传递请求的模型)
|
||||||
let accountId
|
|
||||||
try {
|
try {
|
||||||
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||||
apiKeyData,
|
apiKeyData,
|
||||||
sessionHash,
|
sessionHash,
|
||||||
model // 传递请求的模型进行过滤
|
model, // 传递请求的模型进行过滤
|
||||||
|
{ allowApiAccounts: true } // 允许调度 API 账户
|
||||||
)
|
)
|
||||||
const { accountId: selectedAccountId } = schedulerResult
|
;({ accountId, accountType } = schedulerResult)
|
||||||
accountId = selectedAccountId
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to select Gemini account:', error)
|
logger.error('Failed to select Gemini account:', error)
|
||||||
return res.status(503).json({
|
return res.status(503).json({
|
||||||
@@ -133,22 +138,39 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 判断账户类型:根据 accountType 判断,而非 accountId 前缀
|
||||||
|
const isApiAccount = accountType === 'gemini-api'
|
||||||
|
|
||||||
// 获取账户详情
|
// 获取账户详情
|
||||||
const account = await geminiAccountService.getAccount(accountId)
|
let account
|
||||||
if (!account) {
|
if (isApiAccount) {
|
||||||
return res.status(503).json({
|
account = await geminiApiAccountService.getAccount(accountId)
|
||||||
error: {
|
if (!account) {
|
||||||
message: 'Selected account not found',
|
return res.status(503).json({
|
||||||
type: 'service_unavailable'
|
error: {
|
||||||
}
|
message: 'Gemini API account not found',
|
||||||
})
|
type: 'service_unavailable'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
logger.info(`Using Gemini API account: ${account.id} for API key: ${apiKeyData.id}`)
|
||||||
|
// 标记 API 账户被使用
|
||||||
|
await geminiApiAccountService.markAccountUsed(account.id)
|
||||||
|
} else {
|
||||||
|
account = await geminiAccountService.getAccount(accountId)
|
||||||
|
if (!account) {
|
||||||
|
return res.status(503).json({
|
||||||
|
error: {
|
||||||
|
message: 'Gemini OAuth account not found',
|
||||||
|
type: 'service_unavailable'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
logger.info(`Using Gemini OAuth account: ${account.id} for API key: ${apiKeyData.id}`)
|
||||||
|
// 标记 OAuth 账户被使用
|
||||||
|
await geminiAccountService.markAccountUsed(account.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(`Using Gemini account: ${account.id} for API key: ${apiKeyData.id}`)
|
|
||||||
|
|
||||||
// 标记账户被使用
|
|
||||||
await geminiAccountService.markAccountUsed(account.id)
|
|
||||||
|
|
||||||
// 创建中止控制器
|
// 创建中止控制器
|
||||||
abortController = new AbortController()
|
abortController = new AbortController()
|
||||||
|
|
||||||
@@ -160,20 +182,126 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// 发送请求到 Gemini
|
let geminiResponse
|
||||||
const geminiResponse = await sendGeminiRequest({
|
|
||||||
messages,
|
if (isApiAccount) {
|
||||||
model,
|
// API 账户:直接调用 Google Gemini API
|
||||||
temperature,
|
// 转换 OpenAI 格式的 messages 为 Gemini 格式的 contents
|
||||||
maxTokens: max_tokens,
|
const contents = messages.map((msg) => ({
|
||||||
stream,
|
role: msg.role === 'assistant' ? 'model' : msg.role,
|
||||||
accessToken: account.accessToken,
|
parts: [{ text: msg.content }]
|
||||||
proxy: account.proxy,
|
}))
|
||||||
apiKeyId: apiKeyData.id,
|
|
||||||
signal: abortController.signal,
|
const requestBody = {
|
||||||
projectId: account.projectId,
|
contents,
|
||||||
accountId: account.id
|
generationConfig: {
|
||||||
})
|
temperature,
|
||||||
|
maxOutputTokens: max_tokens,
|
||||||
|
topP: 0.95,
|
||||||
|
topK: 40
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析代理配置
|
||||||
|
let proxyConfig = null
|
||||||
|
if (account.proxy) {
|
||||||
|
try {
|
||||||
|
proxyConfig =
|
||||||
|
typeof account.proxy === 'string' ? JSON.parse(account.proxy) : account.proxy
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn('Failed to parse proxy configuration:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiUrl = stream
|
||||||
|
? `${account.baseUrl}/v1beta/models/${model}:streamGenerateContent?key=${account.apiKey}&alt=sse`
|
||||||
|
: `${account.baseUrl}/v1beta/models/${model}:generateContent?key=${account.apiKey}`
|
||||||
|
|
||||||
|
const axiosConfig = {
|
||||||
|
method: 'POST',
|
||||||
|
url: apiUrl,
|
||||||
|
data: requestBody,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
responseType: stream ? 'stream' : 'json',
|
||||||
|
signal: abortController.signal
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加代理配置
|
||||||
|
if (proxyConfig) {
|
||||||
|
const proxyHelper = new ProxyHelper()
|
||||||
|
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
|
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const apiResponse = await axios(axiosConfig)
|
||||||
|
if (stream) {
|
||||||
|
geminiResponse = apiResponse.data
|
||||||
|
} else {
|
||||||
|
// 转换为 OpenAI 兼容格式
|
||||||
|
const geminiData = apiResponse.data
|
||||||
|
geminiResponse = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
object: 'chat.completion',
|
||||||
|
created: Math.floor(Date.now() / 1000),
|
||||||
|
model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
message: {
|
||||||
|
role: 'assistant',
|
||||||
|
content:
|
||||||
|
geminiData.candidates?.[0]?.content?.parts?.[0]?.text || 'No response generated'
|
||||||
|
},
|
||||||
|
finish_reason: 'stop'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
usage: {
|
||||||
|
prompt_tokens: geminiData.usageMetadata?.promptTokenCount || 0,
|
||||||
|
completion_tokens: geminiData.usageMetadata?.candidatesTokenCount || 0,
|
||||||
|
total_tokens: geminiData.usageMetadata?.totalTokenCount || 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录使用统计
|
||||||
|
if (geminiData.usageMetadata) {
|
||||||
|
await apiKeyService.recordUsage(
|
||||||
|
apiKeyData.id,
|
||||||
|
geminiData.usageMetadata.promptTokenCount || 0,
|
||||||
|
geminiData.usageMetadata.candidatesTokenCount || 0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
model,
|
||||||
|
accountId // 使用原始 accountId(含 api: 前缀)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Gemini API request failed:', {
|
||||||
|
status: error.response?.status,
|
||||||
|
statusText: error.response?.statusText,
|
||||||
|
data: error.response?.data
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用现有的 sendGeminiRequest
|
||||||
|
geminiResponse = await sendGeminiRequest({
|
||||||
|
messages,
|
||||||
|
model,
|
||||||
|
temperature,
|
||||||
|
maxTokens: max_tokens,
|
||||||
|
stream,
|
||||||
|
accessToken: account.accessToken,
|
||||||
|
proxy: account.proxy,
|
||||||
|
apiKeyId: apiKeyData.id,
|
||||||
|
signal: abortController.signal,
|
||||||
|
projectId: account.projectId,
|
||||||
|
accountId: account.id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
if (stream) {
|
if (stream) {
|
||||||
// 设置流式响应头
|
// 设置流式响应头
|
||||||
@@ -182,15 +310,90 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
|
|||||||
res.setHeader('Connection', 'keep-alive')
|
res.setHeader('Connection', 'keep-alive')
|
||||||
res.setHeader('X-Accel-Buffering', 'no')
|
res.setHeader('X-Accel-Buffering', 'no')
|
||||||
|
|
||||||
// 流式传输响应
|
if (isApiAccount) {
|
||||||
for await (const chunk of geminiResponse) {
|
// API 账户:处理 SSE 流并记录使用统计
|
||||||
if (abortController.signal.aborted) {
|
let totalUsage = {
|
||||||
break
|
promptTokenCount: 0,
|
||||||
|
candidatesTokenCount: 0,
|
||||||
|
totalTokenCount: 0
|
||||||
}
|
}
|
||||||
res.write(chunk)
|
|
||||||
}
|
|
||||||
|
|
||||||
res.end()
|
geminiResponse.on('data', (chunk) => {
|
||||||
|
try {
|
||||||
|
const chunkStr = chunk.toString()
|
||||||
|
res.write(chunkStr)
|
||||||
|
|
||||||
|
// 尝试从 SSE 流中提取 usage 数据
|
||||||
|
const lines = chunkStr.split('\n')
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.startsWith('data:')) {
|
||||||
|
const data = line.substring(5).trim()
|
||||||
|
if (data && data !== '[DONE]') {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(data)
|
||||||
|
if (parsed.usageMetadata || parsed.response?.usageMetadata) {
|
||||||
|
totalUsage = parsed.usageMetadata || parsed.response.usageMetadata
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 解析失败,忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Error processing stream chunk:', error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
geminiResponse.on('end', () => {
|
||||||
|
res.end()
|
||||||
|
|
||||||
|
// 异步记录使用统计
|
||||||
|
if (totalUsage.totalTokenCount > 0) {
|
||||||
|
apiKeyService
|
||||||
|
.recordUsage(
|
||||||
|
apiKeyData.id,
|
||||||
|
totalUsage.promptTokenCount || 0,
|
||||||
|
totalUsage.candidatesTokenCount || 0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
model,
|
||||||
|
accountId // 使用原始 accountId(含 api: 前缀)
|
||||||
|
)
|
||||||
|
.then(() => {
|
||||||
|
logger.info(
|
||||||
|
`📊 Recorded Gemini API stream usage - Input: ${totalUsage.promptTokenCount}, Output: ${totalUsage.candidatesTokenCount}`
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
logger.error('Failed to record Gemini API usage:', error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
geminiResponse.on('error', (error) => {
|
||||||
|
logger.error('Stream error:', error)
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.status(500).json({
|
||||||
|
error: {
|
||||||
|
message: error.message || 'Stream error',
|
||||||
|
type: 'api_error'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
res.end()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用原有的流式传输逻辑
|
||||||
|
for await (const chunk of geminiResponse) {
|
||||||
|
if (abortController.signal.aborted) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
res.write(chunk)
|
||||||
|
}
|
||||||
|
res.end()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// 非流式响应
|
// 非流式响应
|
||||||
res.json(geminiResponse)
|
res.json(geminiResponse)
|
||||||
@@ -202,14 +405,24 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
|
|||||||
logger.error('Gemini request error:', error)
|
logger.error('Gemini request error:', error)
|
||||||
|
|
||||||
// 处理速率限制
|
// 处理速率限制
|
||||||
if (error.status === 429) {
|
const errorStatus = error.response?.status || error.status
|
||||||
if (req.apiKey && req.account) {
|
if (errorStatus === 429 && accountId) {
|
||||||
await geminiAccountService.setAccountRateLimited(req.account.id, true)
|
try {
|
||||||
|
// 使用已有的 accountType 变量,而非检查前缀
|
||||||
|
const rateLimitAccountType = accountType || 'gemini'
|
||||||
|
await unifiedGeminiScheduler.markAccountRateLimited(
|
||||||
|
accountId,
|
||||||
|
rateLimitAccountType,
|
||||||
|
sessionHash
|
||||||
|
)
|
||||||
|
logger.warn(`⚠️ Gemini account ${accountId} rate limited (/messages), marking as limited`)
|
||||||
|
} catch (limitError) {
|
||||||
|
logger.warn('Failed to mark account as rate limited:', limitError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回错误响应
|
// 返回错误响应
|
||||||
const status = error.status || 500
|
const status = errorStatus || 500
|
||||||
const errorResponse = {
|
const errorResponse = {
|
||||||
error: error.error || {
|
error: error.error || {
|
||||||
message: error.message || 'Internal server error',
|
message: error.message || 'Internal server error',
|
||||||
@@ -700,13 +913,38 @@ async function handleGenerateContent(req, res) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用统一调度选择账号
|
// 使用统一调度选择账号(v1internal 不允许 API 账户)
|
||||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||||
req.apiKey,
|
req.apiKey,
|
||||||
sessionHash,
|
sessionHash,
|
||||||
model
|
model
|
||||||
|
// 不传 allowApiAccounts: true,所以不会调度 API 账户
|
||||||
)
|
)
|
||||||
|
const { accountId, accountType } = schedulerResult
|
||||||
|
|
||||||
|
// v1internal 路由只支持 OAuth 账户,不支持 API Key 账户
|
||||||
|
if (accountType === 'gemini-api') {
|
||||||
|
logger.error(`❌ v1internal routes do not support Gemini API accounts. Account: ${accountId}`)
|
||||||
|
return res.status(400).json({
|
||||||
|
error: {
|
||||||
|
message:
|
||||||
|
'This endpoint only supports Gemini OAuth accounts. Gemini API Key accounts are not compatible with v1internal format.',
|
||||||
|
type: 'invalid_account_type'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const account = await geminiAccountService.getAccount(accountId)
|
const account = await geminiAccountService.getAccount(accountId)
|
||||||
|
if (!account) {
|
||||||
|
logger.error(`❌ Gemini account not found: ${accountId}`)
|
||||||
|
return res.status(404).json({
|
||||||
|
error: {
|
||||||
|
message: 'Gemini account not found',
|
||||||
|
type: 'account_not_found'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const { accessToken, refreshToken } = account
|
const { accessToken, refreshToken } = account
|
||||||
|
|
||||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||||
@@ -854,13 +1092,38 @@ async function handleStreamGenerateContent(req, res) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用统一调度选择账号
|
// 使用统一调度选择账号(v1internal 不允许 API 账户)
|
||||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||||
req.apiKey,
|
req.apiKey,
|
||||||
sessionHash,
|
sessionHash,
|
||||||
model
|
model
|
||||||
|
// 不传 allowApiAccounts: true,所以不会调度 API 账户
|
||||||
)
|
)
|
||||||
|
const { accountId, accountType } = schedulerResult
|
||||||
|
|
||||||
|
// v1internal 路由只支持 OAuth 账户,不支持 API Key 账户
|
||||||
|
if (accountType === 'gemini-api') {
|
||||||
|
logger.error(`❌ v1internal routes do not support Gemini API accounts. Account: ${accountId}`)
|
||||||
|
return res.status(400).json({
|
||||||
|
error: {
|
||||||
|
message:
|
||||||
|
'This endpoint only supports Gemini OAuth accounts. Gemini API Key accounts are not compatible with v1internal format.',
|
||||||
|
type: 'invalid_account_type'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const account = await geminiAccountService.getAccount(accountId)
|
const account = await geminiAccountService.getAccount(accountId)
|
||||||
|
if (!account) {
|
||||||
|
logger.error(`❌ Gemini account not found: ${accountId}`)
|
||||||
|
return res.status(404).json({
|
||||||
|
error: {
|
||||||
|
message: 'Gemini account not found',
|
||||||
|
type: 'account_not_found'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const { accessToken, refreshToken } = account
|
const { accessToken, refreshToken } = account
|
||||||
|
|
||||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ const router = express.Router()
|
|||||||
const { authenticateApiKey } = require('../middleware/auth')
|
const { authenticateApiKey } = require('../middleware/auth')
|
||||||
const logger = require('../utils/logger')
|
const logger = require('../utils/logger')
|
||||||
const geminiAccountService = require('../services/geminiAccountService')
|
const geminiAccountService = require('../services/geminiAccountService')
|
||||||
|
const geminiApiAccountService = require('../services/geminiApiAccountService')
|
||||||
const unifiedGeminiScheduler = require('../services/unifiedGeminiScheduler')
|
const unifiedGeminiScheduler = require('../services/unifiedGeminiScheduler')
|
||||||
const apiKeyService = require('../services/apiKeyService')
|
const apiKeyService = require('../services/apiKeyService')
|
||||||
const sessionHelper = require('../utils/sessionHelper')
|
const sessionHelper = require('../utils/sessionHelper')
|
||||||
|
const axios = require('axios')
|
||||||
|
const ProxyHelper = require('../utils/proxyHelper')
|
||||||
|
|
||||||
// 导入 geminiRoutes 中导出的处理函数
|
// 导入 geminiRoutes 中导出的处理函数
|
||||||
const { handleLoadCodeAssist, handleOnboardUser, handleCountTokens } = require('./geminiRoutes')
|
const { handleLoadCodeAssist, handleOnboardUser, handleCountTokens } = require('./geminiRoutes')
|
||||||
@@ -136,6 +139,8 @@ async function normalizeAxiosStreamError(error) {
|
|||||||
async function handleStandardGenerateContent(req, res) {
|
async function handleStandardGenerateContent(req, res) {
|
||||||
let account = null
|
let account = null
|
||||||
let sessionHash = null
|
let sessionHash = null
|
||||||
|
let accountId = null // 提升到外部作用域
|
||||||
|
let isApiAccount = false // 提升到外部作用域
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!ensureGeminiPermission(req, res)) {
|
if (!ensureGeminiPermission(req, res)) {
|
||||||
@@ -210,20 +215,48 @@ async function handleStandardGenerateContent(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 使用统一调度选择账号
|
// 使用统一调度选择账号
|
||||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||||
req.apiKey,
|
req.apiKey,
|
||||||
sessionHash,
|
sessionHash,
|
||||||
model
|
model,
|
||||||
|
{ allowApiAccounts: true } // 允许调度 API 账户
|
||||||
)
|
)
|
||||||
account = await geminiAccountService.getAccount(accountId)
|
;({ accountId } = schedulerResult)
|
||||||
const { accessToken, refreshToken } = account
|
const { accountType } = schedulerResult
|
||||||
|
|
||||||
|
// 判断账户类型:根据 accountType 判断,而非 accountId 前缀
|
||||||
|
isApiAccount = accountType === 'gemini-api' // 赋值而不是声明
|
||||||
|
const actualAccountId = accountId // accountId 已经是实际 ID,无需处理前缀
|
||||||
|
|
||||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
||||||
logger.info(`Standard Gemini API generateContent request (${version})`, {
|
|
||||||
model,
|
if (isApiAccount) {
|
||||||
projectId: account.projectId,
|
// Gemini API 账户:使用 API Key 直接请求
|
||||||
apiKeyId: req.apiKey?.id || 'unknown'
|
account = await geminiApiAccountService.getAccount(actualAccountId)
|
||||||
})
|
if (!account) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: {
|
||||||
|
message: 'Gemini API account not found',
|
||||||
|
type: 'account_not_found'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`Standard Gemini API generateContent request (${version}) - API Key Account`, {
|
||||||
|
model,
|
||||||
|
accountId: actualAccountId,
|
||||||
|
apiKeyId: req.apiKey?.id || 'unknown'
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用原有流程
|
||||||
|
account = await geminiAccountService.getAccount(actualAccountId)
|
||||||
|
|
||||||
|
logger.info(`Standard Gemini API generateContent request (${version}) - OAuth Account`, {
|
||||||
|
model,
|
||||||
|
projectId: account.projectId,
|
||||||
|
apiKeyId: req.apiKey?.id || 'unknown'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// 解析账户的代理配置
|
// 解析账户的代理配置
|
||||||
let proxyConfig = null
|
let proxyConfig = null
|
||||||
@@ -235,63 +268,106 @@ async function handleStandardGenerateContent(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const client = await geminiAccountService.getOauthClient(accessToken, refreshToken, proxyConfig)
|
let response
|
||||||
|
|
||||||
// 项目ID优先级:账户配置的项目ID > 临时项目ID > 尝试获取
|
if (isApiAccount) {
|
||||||
let effectiveProjectId = account.projectId || account.tempProjectId || null
|
// Gemini API 账户:直接使用 API Key 请求
|
||||||
|
// baseUrl 填写域名,如 https://generativelanguage.googleapis.com,版本固定为 v1beta
|
||||||
|
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:generateContent?key=${account.apiKey}`
|
||||||
|
|
||||||
// 如果没有任何项目ID,尝试调用 loadCodeAssist 获取
|
// 构建 Axios 配置
|
||||||
if (!effectiveProjectId) {
|
const axiosConfig = {
|
||||||
try {
|
method: 'POST',
|
||||||
logger.info('📋 No projectId available, attempting to fetch from loadCodeAssist...')
|
url: apiUrl,
|
||||||
const loadResponse = await geminiAccountService.loadCodeAssist(client, null, proxyConfig)
|
data: actualRequestData,
|
||||||
|
headers: {
|
||||||
if (loadResponse.cloudaicompanionProject) {
|
'Content-Type': 'application/json'
|
||||||
effectiveProjectId = loadResponse.cloudaicompanionProject
|
|
||||||
// 保存临时项目ID
|
|
||||||
await geminiAccountService.updateTempProjectId(accountId, effectiveProjectId)
|
|
||||||
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
|
|
||||||
}
|
}
|
||||||
} catch (loadError) {
|
|
||||||
logger.warn('Failed to fetch projectId from loadCodeAssist:', loadError.message)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 如果还是没有项目ID,返回错误
|
// 添加代理配置
|
||||||
if (!effectiveProjectId) {
|
if (proxyConfig) {
|
||||||
return res.status(403).json({
|
const proxyHelper = new ProxyHelper()
|
||||||
error: {
|
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
message:
|
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
'This account requires a project ID to be configured. Please configure a project ID in the account settings.',
|
}
|
||||||
type: 'configuration_required'
|
|
||||||
|
try {
|
||||||
|
const apiResponse = await axios(axiosConfig)
|
||||||
|
response = { response: apiResponse.data }
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Gemini API request failed:', {
|
||||||
|
status: error.response?.status,
|
||||||
|
statusText: error.response?.statusText,
|
||||||
|
data: error.response?.data
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用原有流程
|
||||||
|
const { accessToken, refreshToken } = account
|
||||||
|
const client = await geminiAccountService.getOauthClient(
|
||||||
|
accessToken,
|
||||||
|
refreshToken,
|
||||||
|
proxyConfig
|
||||||
|
)
|
||||||
|
|
||||||
|
// 项目ID优先级:账户配置的项目ID > 临时项目ID > 尝试获取
|
||||||
|
let effectiveProjectId = account.projectId || account.tempProjectId || null
|
||||||
|
|
||||||
|
// 如果没有任何项目ID,尝试调用 loadCodeAssist 获取
|
||||||
|
if (!effectiveProjectId) {
|
||||||
|
try {
|
||||||
|
logger.info('📋 No projectId available, attempting to fetch from loadCodeAssist...')
|
||||||
|
const loadResponse = await geminiAccountService.loadCodeAssist(client, null, proxyConfig)
|
||||||
|
|
||||||
|
if (loadResponse.cloudaicompanionProject) {
|
||||||
|
effectiveProjectId = loadResponse.cloudaicompanionProject
|
||||||
|
// 保存临时项目ID
|
||||||
|
await geminiAccountService.updateTempProjectId(actualAccountId, effectiveProjectId)
|
||||||
|
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
|
||||||
|
}
|
||||||
|
} catch (loadError) {
|
||||||
|
logger.warn('Failed to fetch projectId from loadCodeAssist:', loadError.message)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果还是没有项目ID,返回错误
|
||||||
|
if (!effectiveProjectId) {
|
||||||
|
return res.status(403).json({
|
||||||
|
error: {
|
||||||
|
message:
|
||||||
|
'This account requires a project ID to be configured. Please configure a project ID in the account settings.',
|
||||||
|
type: 'configuration_required'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('📋 Standard API 项目ID处理逻辑', {
|
||||||
|
accountProjectId: account.projectId,
|
||||||
|
tempProjectId: account.tempProjectId,
|
||||||
|
effectiveProjectId,
|
||||||
|
decision: account.projectId
|
||||||
|
? '使用账户配置'
|
||||||
|
: account.tempProjectId
|
||||||
|
? '使用临时项目ID'
|
||||||
|
: '从loadCodeAssist获取'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 生成一个符合 Gemini CLI 格式的 user_prompt_id
|
||||||
|
const userPromptId = `${require('crypto').randomUUID()}########0`
|
||||||
|
|
||||||
|
// 调用内部 API(cloudcode-pa)
|
||||||
|
response = await geminiAccountService.generateContent(
|
||||||
|
client,
|
||||||
|
{ model, request: actualRequestData },
|
||||||
|
userPromptId, // 使用生成的 user_prompt_id
|
||||||
|
effectiveProjectId, // 使用处理后的项目ID
|
||||||
|
req.apiKey?.id, // 使用 API Key ID 作为 session ID
|
||||||
|
proxyConfig
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info('📋 Standard API 项目ID处理逻辑', {
|
|
||||||
accountProjectId: account.projectId,
|
|
||||||
tempProjectId: account.tempProjectId,
|
|
||||||
effectiveProjectId,
|
|
||||||
decision: account.projectId
|
|
||||||
? '使用账户配置'
|
|
||||||
: account.tempProjectId
|
|
||||||
? '使用临时项目ID'
|
|
||||||
: '从loadCodeAssist获取'
|
|
||||||
})
|
|
||||||
|
|
||||||
// 生成一个符合 Gemini CLI 格式的 user_prompt_id
|
|
||||||
const userPromptId = `${require('crypto').randomUUID()}########0`
|
|
||||||
|
|
||||||
// 调用内部 API(cloudcode-pa)
|
|
||||||
const response = await geminiAccountService.generateContent(
|
|
||||||
client,
|
|
||||||
{ model, request: actualRequestData },
|
|
||||||
userPromptId, // 使用生成的 user_prompt_id
|
|
||||||
effectiveProjectId, // 使用处理后的项目ID
|
|
||||||
req.apiKey?.id, // 使用 API Key ID 作为 session ID
|
|
||||||
proxyConfig
|
|
||||||
)
|
|
||||||
|
|
||||||
// 记录使用统计
|
// 记录使用统计
|
||||||
if (response?.response?.usageMetadata) {
|
if (response?.response?.usageMetadata) {
|
||||||
try {
|
try {
|
||||||
@@ -303,7 +379,7 @@ async function handleStandardGenerateContent(req, res) {
|
|||||||
0, // cacheCreateTokens
|
0, // cacheCreateTokens
|
||||||
0, // cacheReadTokens
|
0, // cacheReadTokens
|
||||||
model,
|
model,
|
||||||
account.id
|
accountId // 账户 ID
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
`📊 Recorded Gemini usage - Input: ${usage.promptTokenCount}, Output: ${usage.candidatesTokenCount}, Total: ${usage.totalTokenCount}`
|
`📊 Recorded Gemini usage - Input: ${usage.promptTokenCount}, Output: ${usage.candidatesTokenCount}, Total: ${usage.totalTokenCount}`
|
||||||
@@ -327,10 +403,15 @@ async function handleStandardGenerateContent(req, res) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// 处理速率限制
|
// 处理速率限制
|
||||||
if (error.response?.status === 429) {
|
if (error.response?.status === 429 && accountId) {
|
||||||
logger.warn(`⚠️ Gemini account ${account.id} rate limited (Standard API), marking as limited`)
|
logger.warn(`⚠️ Gemini account ${accountId} rate limited (Standard API), marking as limited`)
|
||||||
try {
|
try {
|
||||||
await unifiedGeminiScheduler.markAccountRateLimited(account.id, 'gemini', sessionHash)
|
const rateLimitAccountType = isApiAccount ? 'gemini-api' : 'gemini'
|
||||||
|
await unifiedGeminiScheduler.markAccountRateLimited(
|
||||||
|
accountId, // 账户 ID
|
||||||
|
rateLimitAccountType,
|
||||||
|
sessionHash
|
||||||
|
)
|
||||||
} catch (limitError) {
|
} catch (limitError) {
|
||||||
logger.warn('Failed to mark account as rate limited in scheduler:', limitError)
|
logger.warn('Failed to mark account as rate limited in scheduler:', limitError)
|
||||||
}
|
}
|
||||||
@@ -350,6 +431,8 @@ async function handleStandardStreamGenerateContent(req, res) {
|
|||||||
let abortController = null
|
let abortController = null
|
||||||
let account = null
|
let account = null
|
||||||
let sessionHash = null
|
let sessionHash = null
|
||||||
|
let accountId = null // 提升到外部作用域
|
||||||
|
let isApiAccount = false // 提升到外部作用域
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!ensureGeminiPermission(req, res)) {
|
if (!ensureGeminiPermission(req, res)) {
|
||||||
@@ -424,20 +507,54 @@ async function handleStandardStreamGenerateContent(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 使用统一调度选择账号
|
// 使用统一调度选择账号
|
||||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||||
req.apiKey,
|
req.apiKey,
|
||||||
sessionHash,
|
sessionHash,
|
||||||
model
|
model,
|
||||||
|
{ allowApiAccounts: true } // 允许调度 API 账户
|
||||||
)
|
)
|
||||||
account = await geminiAccountService.getAccount(accountId)
|
;({ accountId } = schedulerResult)
|
||||||
const { accessToken, refreshToken } = account
|
const { accountType } = schedulerResult
|
||||||
|
|
||||||
|
// 判断账户类型:根据 accountType 判断,而非 accountId 前缀
|
||||||
|
isApiAccount = accountType === 'gemini-api' // 赋值而不是声明
|
||||||
|
const actualAccountId = accountId // accountId 已经是实际 ID,无需处理前缀
|
||||||
|
|
||||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
||||||
logger.info(`Standard Gemini API streamGenerateContent request (${version})`, {
|
|
||||||
model,
|
if (isApiAccount) {
|
||||||
projectId: account.projectId,
|
// Gemini API 账户:使用 API Key 直接请求
|
||||||
apiKeyId: req.apiKey?.id || 'unknown'
|
account = await geminiApiAccountService.getAccount(actualAccountId)
|
||||||
})
|
if (!account) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: {
|
||||||
|
message: 'Gemini API account not found',
|
||||||
|
type: 'account_not_found'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`Standard Gemini API streamGenerateContent request (${version}) - API Key Account`,
|
||||||
|
{
|
||||||
|
model,
|
||||||
|
accountId: actualAccountId,
|
||||||
|
apiKeyId: req.apiKey?.id || 'unknown'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用原有流程
|
||||||
|
account = await geminiAccountService.getAccount(actualAccountId)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`Standard Gemini API streamGenerateContent request (${version}) - OAuth Account`,
|
||||||
|
{
|
||||||
|
model,
|
||||||
|
projectId: account.projectId,
|
||||||
|
apiKeyId: req.apiKey?.id || 'unknown'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// 创建中止控制器
|
// 创建中止控制器
|
||||||
abortController = new AbortController()
|
abortController = new AbortController()
|
||||||
@@ -460,64 +577,109 @@ async function handleStandardStreamGenerateContent(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const client = await geminiAccountService.getOauthClient(accessToken, refreshToken, proxyConfig)
|
let streamResponse
|
||||||
|
|
||||||
// 项目ID优先级:账户配置的项目ID > 临时项目ID > 尝试获取
|
if (isApiAccount) {
|
||||||
let effectiveProjectId = account.projectId || account.tempProjectId || null
|
// Gemini API 账户:直接使用 API Key 请求流式接口
|
||||||
|
// baseUrl 填写域名,版本固定为 v1beta
|
||||||
|
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:streamGenerateContent?key=${account.apiKey}&alt=sse`
|
||||||
|
|
||||||
// 如果没有任何项目ID,尝试调用 loadCodeAssist 获取
|
// 构建 Axios 配置
|
||||||
if (!effectiveProjectId) {
|
const axiosConfig = {
|
||||||
try {
|
method: 'POST',
|
||||||
logger.info('📋 No projectId available, attempting to fetch from loadCodeAssist...')
|
url: apiUrl,
|
||||||
const loadResponse = await geminiAccountService.loadCodeAssist(client, null, proxyConfig)
|
data: actualRequestData,
|
||||||
|
headers: {
|
||||||
if (loadResponse.cloudaicompanionProject) {
|
'Content-Type': 'application/json'
|
||||||
effectiveProjectId = loadResponse.cloudaicompanionProject
|
},
|
||||||
// 保存临时项目ID
|
responseType: 'stream',
|
||||||
await geminiAccountService.updateTempProjectId(accountId, effectiveProjectId)
|
signal: abortController.signal
|
||||||
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
|
|
||||||
}
|
|
||||||
} catch (loadError) {
|
|
||||||
logger.warn('Failed to fetch projectId from loadCodeAssist:', loadError.message)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 如果还是没有项目ID,返回错误
|
// 添加代理配置
|
||||||
if (!effectiveProjectId) {
|
if (proxyConfig) {
|
||||||
return res.status(403).json({
|
const proxyHelper = new ProxyHelper()
|
||||||
error: {
|
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
message:
|
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||||
'This account requires a project ID to be configured. Please configure a project ID in the account settings.',
|
}
|
||||||
type: 'configuration_required'
|
|
||||||
|
try {
|
||||||
|
const apiResponse = await axios(axiosConfig)
|
||||||
|
streamResponse = apiResponse.data
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Gemini API stream request failed:', {
|
||||||
|
status: error.response?.status,
|
||||||
|
statusText: error.response?.statusText,
|
||||||
|
data: error.response?.data
|
||||||
|
})
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// OAuth 账户:使用原有流程
|
||||||
|
const { accessToken, refreshToken } = account
|
||||||
|
const client = await geminiAccountService.getOauthClient(
|
||||||
|
accessToken,
|
||||||
|
refreshToken,
|
||||||
|
proxyConfig
|
||||||
|
)
|
||||||
|
|
||||||
|
// 项目ID优先级:账户配置的项目ID > 临时项目ID > 尝试获取
|
||||||
|
let effectiveProjectId = account.projectId || account.tempProjectId || null
|
||||||
|
|
||||||
|
// 如果没有任何项目ID,尝试调用 loadCodeAssist 获取
|
||||||
|
if (!effectiveProjectId) {
|
||||||
|
try {
|
||||||
|
logger.info('📋 No projectId available, attempting to fetch from loadCodeAssist...')
|
||||||
|
const loadResponse = await geminiAccountService.loadCodeAssist(client, null, proxyConfig)
|
||||||
|
|
||||||
|
if (loadResponse.cloudaicompanionProject) {
|
||||||
|
effectiveProjectId = loadResponse.cloudaicompanionProject
|
||||||
|
// 保存临时项目ID
|
||||||
|
await geminiAccountService.updateTempProjectId(actualAccountId, effectiveProjectId)
|
||||||
|
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
|
||||||
|
}
|
||||||
|
} catch (loadError) {
|
||||||
|
logger.warn('Failed to fetch projectId from loadCodeAssist:', loadError.message)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果还是没有项目ID,返回错误
|
||||||
|
if (!effectiveProjectId) {
|
||||||
|
return res.status(403).json({
|
||||||
|
error: {
|
||||||
|
message:
|
||||||
|
'This account requires a project ID to be configured. Please configure a project ID in the account settings.',
|
||||||
|
type: 'configuration_required'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('📋 Standard API 流式项目ID处理逻辑', {
|
||||||
|
accountProjectId: account.projectId,
|
||||||
|
tempProjectId: account.tempProjectId,
|
||||||
|
effectiveProjectId,
|
||||||
|
decision: account.projectId
|
||||||
|
? '使用账户配置'
|
||||||
|
: account.tempProjectId
|
||||||
|
? '使用临时项目ID'
|
||||||
|
: '从loadCodeAssist获取'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 生成一个符合 Gemini CLI 格式的 user_prompt_id
|
||||||
|
const userPromptId = `${require('crypto').randomUUID()}########0`
|
||||||
|
|
||||||
|
// 调用内部 API(cloudcode-pa)的流式接口
|
||||||
|
streamResponse = await geminiAccountService.generateContentStream(
|
||||||
|
client,
|
||||||
|
{ model, request: actualRequestData },
|
||||||
|
userPromptId, // 使用生成的 user_prompt_id
|
||||||
|
effectiveProjectId, // 使用处理后的项目ID
|
||||||
|
req.apiKey?.id, // 使用 API Key ID 作为 session ID
|
||||||
|
abortController.signal,
|
||||||
|
proxyConfig
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info('📋 Standard API 流式项目ID处理逻辑', {
|
|
||||||
accountProjectId: account.projectId,
|
|
||||||
tempProjectId: account.tempProjectId,
|
|
||||||
effectiveProjectId,
|
|
||||||
decision: account.projectId
|
|
||||||
? '使用账户配置'
|
|
||||||
: account.tempProjectId
|
|
||||||
? '使用临时项目ID'
|
|
||||||
: '从loadCodeAssist获取'
|
|
||||||
})
|
|
||||||
|
|
||||||
// 生成一个符合 Gemini CLI 格式的 user_prompt_id
|
|
||||||
const userPromptId = `${require('crypto').randomUUID()}########0`
|
|
||||||
|
|
||||||
// 调用内部 API(cloudcode-pa)的流式接口
|
|
||||||
const streamResponse = await geminiAccountService.generateContentStream(
|
|
||||||
client,
|
|
||||||
{ model, request: actualRequestData },
|
|
||||||
userPromptId, // 使用生成的 user_prompt_id
|
|
||||||
effectiveProjectId, // 使用处理后的项目ID
|
|
||||||
req.apiKey?.id, // 使用 API Key ID 作为 session ID
|
|
||||||
abortController.signal,
|
|
||||||
proxyConfig
|
|
||||||
)
|
|
||||||
|
|
||||||
// 设置 SSE 响应头
|
// 设置 SSE 响应头
|
||||||
res.setHeader('Content-Type', 'text/event-stream')
|
res.setHeader('Content-Type', 'text/event-stream')
|
||||||
res.setHeader('Cache-Control', 'no-cache')
|
res.setHeader('Cache-Control', 'no-cache')
|
||||||
@@ -672,7 +834,7 @@ async function handleStandardStreamGenerateContent(req, res) {
|
|||||||
0, // cacheCreateTokens
|
0, // cacheCreateTokens
|
||||||
0, // cacheReadTokens
|
0, // cacheReadTokens
|
||||||
model,
|
model,
|
||||||
account.id
|
accountId // 使用原始 accountId(含前缀)
|
||||||
)
|
)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -743,12 +905,17 @@ async function handleStandardStreamGenerateContent(req, res) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// 处理速率限制
|
// 处理速率限制
|
||||||
if (error.response?.status === 429) {
|
if (error.response?.status === 429 && accountId) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`⚠️ Gemini account ${account.id} rate limited (Standard Stream API), marking as limited`
|
`⚠️ Gemini account ${accountId} rate limited (Standard Stream API), marking as limited`
|
||||||
)
|
)
|
||||||
try {
|
try {
|
||||||
await unifiedGeminiScheduler.markAccountRateLimited(account.id, 'gemini', sessionHash)
|
const rateLimitAccountType = isApiAccount ? 'gemini-api' : 'gemini'
|
||||||
|
await unifiedGeminiScheduler.markAccountRateLimited(
|
||||||
|
accountId, // 账户 ID
|
||||||
|
rateLimitAccountType,
|
||||||
|
sessionHash
|
||||||
|
)
|
||||||
} catch (limitError) {
|
} catch (limitError) {
|
||||||
logger.warn('Failed to mark account as rate limited in scheduler:', limitError)
|
logger.warn('Failed to mark account as rate limited in scheduler:', limitError)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1527,7 +1527,15 @@ class ApiKeyService {
|
|||||||
permissions: keyData.permissions,
|
permissions: keyData.permissions,
|
||||||
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0),
|
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0),
|
||||||
totalCostLimit: parseFloat(keyData.totalCostLimit || 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) {
|
} catch (error) {
|
||||||
logger.error('❌ Failed to get API key by ID:', error)
|
logger.error('❌ Failed to get API key by ID:', error)
|
||||||
@@ -1670,6 +1678,7 @@ class ApiKeyService {
|
|||||||
claude: 'claudeAccountId',
|
claude: 'claudeAccountId',
|
||||||
'claude-console': 'claudeConsoleAccountId',
|
'claude-console': 'claudeConsoleAccountId',
|
||||||
gemini: 'geminiAccountId',
|
gemini: 'geminiAccountId',
|
||||||
|
'gemini-api': 'geminiAccountId', // 特殊处理,带 api: 前缀
|
||||||
openai: 'openaiAccountId',
|
openai: 'openaiAccountId',
|
||||||
'openai-responses': 'openaiAccountId', // 特殊处理,带 responses: 前缀
|
'openai-responses': 'openaiAccountId', // 特殊处理,带 responses: 前缀
|
||||||
azure_openai: 'azureOpenaiAccountId',
|
azure_openai: 'azureOpenaiAccountId',
|
||||||
@@ -1692,6 +1701,9 @@ class ApiKeyService {
|
|||||||
if (accountType === 'openai-responses') {
|
if (accountType === 'openai-responses') {
|
||||||
// OpenAI-Responses 特殊处理:查找 openaiAccountId 字段中带 responses: 前缀的
|
// OpenAI-Responses 特殊处理:查找 openaiAccountId 字段中带 responses: 前缀的
|
||||||
boundKeys = allKeys.filter((key) => key.openaiAccountId === `responses:${accountId}`)
|
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 {
|
} else {
|
||||||
// 其他账号类型正常匹配
|
// 其他账号类型正常匹配
|
||||||
boundKeys = allKeys.filter((key) => key[field] === accountId)
|
boundKeys = allKeys.filter((key) => key[field] === accountId)
|
||||||
@@ -1702,6 +1714,8 @@ class ApiKeyService {
|
|||||||
const updates = {}
|
const updates = {}
|
||||||
if (accountType === 'openai-responses') {
|
if (accountType === 'openai-responses') {
|
||||||
updates.openaiAccountId = null
|
updates.openaiAccountId = null
|
||||||
|
} else if (accountType === 'gemini-api') {
|
||||||
|
updates.geminiAccountId = null
|
||||||
} else if (accountType === 'claude-console') {
|
} else if (accountType === 'claude-console') {
|
||||||
updates.claudeConsoleAccountId = null
|
updates.claudeConsoleAccountId = null
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
586
src/services/geminiApiAccountService.js
Normal file
586
src/services/geminiApiAccountService.js
Normal 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()
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
const geminiAccountService = require('./geminiAccountService')
|
const geminiAccountService = require('./geminiAccountService')
|
||||||
|
const geminiApiAccountService = require('./geminiApiAccountService')
|
||||||
const accountGroupService = require('./accountGroupService')
|
const accountGroupService = require('./accountGroupService')
|
||||||
const redis = require('../models/redis')
|
const redis = require('../models/redis')
|
||||||
const logger = require('../utils/logger')
|
const logger = require('../utils/logger')
|
||||||
@@ -19,35 +20,69 @@ class UnifiedGeminiScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 🎯 统一调度Gemini账号
|
// 🎯 统一调度Gemini账号
|
||||||
async selectAccountForApiKey(apiKeyData, sessionHash = null, requestedModel = null) {
|
async selectAccountForApiKey(
|
||||||
|
apiKeyData,
|
||||||
|
sessionHash = null,
|
||||||
|
requestedModel = null,
|
||||||
|
options = {}
|
||||||
|
) {
|
||||||
|
const { allowApiAccounts = false } = options
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 如果API Key绑定了专属账户或分组,优先使用
|
// 如果API Key绑定了专属账户或分组,优先使用
|
||||||
if (apiKeyData.geminiAccountId) {
|
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:', '')
|
const groupId = apiKeyData.geminiAccountId.replace('group:', '')
|
||||||
logger.info(
|
logger.info(
|
||||||
`🎯 API key ${apiKeyData.name} is bound to group ${groupId}, selecting from group`
|
`🎯 API key ${apiKeyData.name} is bound to group ${groupId}, selecting from group`
|
||||||
)
|
)
|
||||||
return await this.selectAccountFromGroup(groupId, sessionHash, requestedModel, apiKeyData)
|
return await this.selectAccountFromGroup(groupId, sessionHash, requestedModel, apiKeyData)
|
||||||
}
|
}
|
||||||
|
// 普通 Gemini OAuth 专属账户
|
||||||
// 普通专属账户
|
else {
|
||||||
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
|
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
|
||||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||||
logger.info(
|
logger.info(
|
||||||
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId}) for API key ${apiKeyData.name}`
|
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId}) for API key ${apiKeyData.name}`
|
||||||
)
|
)
|
||||||
// 更新账户的最后使用时间
|
// 更新账户的最后使用时间
|
||||||
await geminiAccountService.markAccountUsed(apiKeyData.geminiAccountId)
|
await geminiAccountService.markAccountUsed(apiKeyData.geminiAccountId)
|
||||||
return {
|
return {
|
||||||
accountId: apiKeyData.geminiAccountId,
|
accountId: apiKeyData.geminiAccountId,
|
||||||
accountType: 'gemini'
|
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(
|
logger.info(
|
||||||
`🎯 Using sticky session account: ${mappedAccount.accountId} (${mappedAccount.accountType}) for session ${sessionHash}`
|
`🎯 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
|
return mappedAccount
|
||||||
} else {
|
} else {
|
||||||
logger.warn(
|
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) {
|
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}`
|
`🎯 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 {
|
return {
|
||||||
accountId: selectedAccount.accountId,
|
accountId: selectedAccount.accountId,
|
||||||
@@ -128,53 +175,104 @@ class UnifiedGeminiScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 📋 获取所有可用账户
|
// 📋 获取所有可用账户
|
||||||
async _getAllAvailableAccounts(apiKeyData, requestedModel = null) {
|
async _getAllAvailableAccounts(apiKeyData, requestedModel = null, allowApiAccounts = false) {
|
||||||
const availableAccounts = []
|
const availableAccounts = []
|
||||||
|
|
||||||
// 如果API Key绑定了专属账户,优先返回
|
// 如果API Key绑定了专属账户,优先返回
|
||||||
if (apiKeyData.geminiAccountId) {
|
if (apiKeyData.geminiAccountId) {
|
||||||
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
|
// 检查是否是 Gemini API 账户(api: 前缀)
|
||||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
if (apiKeyData.geminiAccountId.startsWith('api:')) {
|
||||||
const isRateLimited = await this.isAccountRateLimited(boundAccount.id)
|
const accountId = apiKeyData.geminiAccountId.replace('api:', '')
|
||||||
if (!isRateLimited) {
|
const boundAccount = await geminiApiAccountService.getAccount(accountId)
|
||||||
// 检查模型支持
|
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||||
if (
|
const isRateLimited = await this.isAccountRateLimited(accountId)
|
||||||
requestedModel &&
|
if (!isRateLimited) {
|
||||||
boundAccount.supportedModels &&
|
// 检查模型支持
|
||||||
boundAccount.supportedModels.length > 0
|
if (
|
||||||
) {
|
requestedModel &&
|
||||||
// 处理可能带有 models/ 前缀的模型名
|
boundAccount.supportedModels &&
|
||||||
const normalizedModel = requestedModel.replace('models/', '')
|
boundAccount.supportedModels.length > 0
|
||||||
const modelSupported = boundAccount.supportedModels.some(
|
) {
|
||||||
(model) => model.replace('models/', '') === normalizedModel
|
const normalizedModel = requestedModel.replace('models/', '')
|
||||||
)
|
const modelSupported = boundAccount.supportedModels.some(
|
||||||
if (!modelSupported) {
|
(model) => model.replace('models/', '') === normalizedModel
|
||||||
logger.warn(
|
|
||||||
`⚠️ Bound Gemini account ${boundAccount.name} does not support model ${requestedModel}`
|
|
||||||
)
|
)
|
||||||
return availableAccounts
|
if (!modelSupported) {
|
||||||
|
logger.warn(
|
||||||
|
`⚠️ Bound Gemini-API account ${boundAccount.name} does not support model ${requestedModel}`
|
||||||
|
)
|
||||||
|
return availableAccounts
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(
|
logger.info(`🎯 Using bound Gemini-API account: ${boundAccount.name} (${accountId})`)
|
||||||
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId})`
|
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()
|
const geminiAccounts = await geminiAccountService.getAllAccounts()
|
||||||
for (const account of geminiAccounts) {
|
for (const account of geminiAccounts) {
|
||||||
if (
|
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
|
return availableAccounts
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,6 +395,17 @@ class UnifiedGeminiScheduler {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return !(await this.isAccountRateLimited(accountId))
|
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
|
return false
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -344,6 +494,8 @@ class UnifiedGeminiScheduler {
|
|||||||
try {
|
try {
|
||||||
if (accountType === 'gemini') {
|
if (accountType === 'gemini') {
|
||||||
await geminiAccountService.setAccountRateLimited(accountId, true)
|
await geminiAccountService.setAccountRateLimited(accountId, true)
|
||||||
|
} else if (accountType === 'gemini-api') {
|
||||||
|
await geminiApiAccountService.setAccountRateLimited(accountId, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除会话映射
|
// 删除会话映射
|
||||||
@@ -366,6 +518,8 @@ class UnifiedGeminiScheduler {
|
|||||||
try {
|
try {
|
||||||
if (accountType === 'gemini') {
|
if (accountType === 'gemini') {
|
||||||
await geminiAccountService.setAccountRateLimited(accountId, false)
|
await geminiAccountService.setAccountRateLimited(accountId, false)
|
||||||
|
} else if (accountType === 'gemini-api') {
|
||||||
|
await geminiApiAccountService.setAccountRateLimited(accountId, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true }
|
return { success: true }
|
||||||
@@ -379,9 +533,23 @@ class UnifiedGeminiScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 🔍 检查账户是否处于限流状态
|
// 🔍 检查账户是否处于限流状态
|
||||||
async isAccountRateLimited(accountId) {
|
async isAccountRateLimited(accountId, accountType = null) {
|
||||||
try {
|
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) {
|
if (!account) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -389,7 +557,9 @@ class UnifiedGeminiScheduler {
|
|||||||
if (account.rateLimitStatus === 'limited' && account.rateLimitedAt) {
|
if (account.rateLimitStatus === 'limited' && account.rateLimitedAt) {
|
||||||
const limitedAt = new Date(account.rateLimitedAt).getTime()
|
const limitedAt = new Date(account.rateLimitedAt).getTime()
|
||||||
const now = Date.now()
|
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
|
return now < limitedAt + limitDuration
|
||||||
}
|
}
|
||||||
@@ -400,7 +570,7 @@ class UnifiedGeminiScheduler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 👥 从分组中选择账户
|
// 👥 从分组中选择账户(支持 Gemini OAuth 和 Gemini API 两种账户类型)
|
||||||
async selectAccountFromGroup(groupId, sessionHash = null, requestedModel = null) {
|
async selectAccountFromGroup(groupId, sessionHash = null, requestedModel = null) {
|
||||||
try {
|
try {
|
||||||
// 获取分组信息
|
// 获取分组信息
|
||||||
@@ -432,8 +602,12 @@ class UnifiedGeminiScheduler {
|
|||||||
logger.info(
|
logger.info(
|
||||||
`🎯 Using sticky session account from group: ${mappedAccount.accountId} (${mappedAccount.accountType}) for session ${sessionHash}`
|
`🎯 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
|
return mappedAccount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -450,9 +624,17 @@ class UnifiedGeminiScheduler {
|
|||||||
|
|
||||||
const availableAccounts = []
|
const availableAccounts = []
|
||||||
|
|
||||||
// 获取所有成员账户的详细信息
|
// 获取所有成员账户的详细信息(支持 Gemini OAuth 和 Gemini API 两种类型)
|
||||||
for (const memberId of memberIds) {
|
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) {
|
if (!account) {
|
||||||
logger.warn(`⚠️ Gemini account ${memberId} not found in group ${group.name}`)
|
logger.warn(`⚠️ Gemini account ${memberId} not found in group ${group.name}`)
|
||||||
@@ -465,13 +647,15 @@ class UnifiedGeminiScheduler {
|
|||||||
account.status !== 'error' &&
|
account.status !== 'error' &&
|
||||||
this._isSchedulable(account.schedulable)
|
this._isSchedulable(account.schedulable)
|
||||||
) {
|
) {
|
||||||
// 检查token是否过期
|
// 对于 Gemini OAuth 账户,检查 token 是否过期
|
||||||
const isExpired = geminiAccountService.isTokenExpired(account)
|
if (accountType === 'gemini') {
|
||||||
if (isExpired && !account.refreshToken) {
|
const isExpired = geminiAccountService.isTokenExpired(account)
|
||||||
logger.warn(
|
if (isExpired && !account.refreshToken) {
|
||||||
`⚠️ Gemini account ${account.name} in group token expired and no refresh token available`
|
logger.warn(
|
||||||
)
|
`⚠️ Gemini account ${account.name} in group token expired and no refresh token available`
|
||||||
continue
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查模型支持
|
// 检查模型支持
|
||||||
@@ -483,19 +667,19 @@ class UnifiedGeminiScheduler {
|
|||||||
)
|
)
|
||||||
if (!modelSupported) {
|
if (!modelSupported) {
|
||||||
logger.debug(
|
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
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否被限流
|
// 检查是否被限流
|
||||||
const isRateLimited = await this.isAccountRateLimited(account.id)
|
const isRateLimited = await this.isAccountRateLimited(account.id, accountType)
|
||||||
if (!isRateLimited) {
|
if (!isRateLimited) {
|
||||||
availableAccounts.push({
|
availableAccounts.push({
|
||||||
...account,
|
...account,
|
||||||
accountId: account.id,
|
accountId: account.id,
|
||||||
accountType: 'gemini',
|
accountType,
|
||||||
priority: parseInt(account.priority) || 50,
|
priority: parseInt(account.priority) || 50,
|
||||||
lastUsedAt: account.lastUsedAt || '0'
|
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}`
|
`🎯 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 {
|
return {
|
||||||
accountId: selectedAccount.accountId,
|
accountId: selectedAccount.accountId,
|
||||||
|
|||||||
@@ -477,6 +477,37 @@
|
|||||||
<i class="fas fa-check text-xs text-white"></i>
|
<i class="fas fa-check text-xs text-white"></i>
|
||||||
</div>
|
</div>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
<label
|
||||||
|
class="group relative flex cursor-pointer items-center rounded-md border p-2 transition-all"
|
||||||
|
:class="[
|
||||||
|
form.platform === 'gemini-api'
|
||||||
|
? 'border-amber-500 bg-amber-50 dark:border-amber-400 dark:bg-amber-900/30'
|
||||||
|
: 'border-gray-300 bg-white hover:border-amber-400 hover:bg-amber-50/50 dark:border-gray-600 dark:bg-gray-700 dark:hover:border-amber-500 dark:hover:bg-amber-900/20'
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model="form.platform"
|
||||||
|
class="sr-only"
|
||||||
|
type="radio"
|
||||||
|
value="gemini-api"
|
||||||
|
/>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<i class="fas fa-key text-sm text-amber-600 dark:text-amber-400"></i>
|
||||||
|
<div>
|
||||||
|
<span class="block text-xs font-medium text-gray-900 dark:text-gray-100"
|
||||||
|
>Gemini API</span
|
||||||
|
>
|
||||||
|
<span class="text-xs text-gray-500 dark:text-gray-400">API Key</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="form.platform === 'gemini-api'"
|
||||||
|
class="absolute right-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-amber-500"
|
||||||
|
>
|
||||||
|
<i class="fas fa-check text-xs text-white"></i>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Droid 子选项 -->
|
<!-- Droid 子选项 -->
|
||||||
@@ -519,7 +550,8 @@
|
|||||||
form.platform !== 'ccr' &&
|
form.platform !== 'ccr' &&
|
||||||
form.platform !== 'bedrock' &&
|
form.platform !== 'bedrock' &&
|
||||||
form.platform !== 'azure_openai' &&
|
form.platform !== 'azure_openai' &&
|
||||||
form.platform !== 'openai-responses'
|
form.platform !== 'openai-responses' &&
|
||||||
|
form.platform !== 'gemini-api'
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
@@ -641,8 +673,8 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 到期时间 - 仅在创建账户时显示,编辑时使用独立的过期时间编辑弹窗 -->
|
<!-- 到期时间 - 仅在创建账户时显示,编辑时使用独立的过期时间编辑弹窗,Gemini API 不需要 -->
|
||||||
<div v-if="!isEdit">
|
<div v-if="!isEdit && form.platform !== 'gemini-api'">
|
||||||
<label class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
<label class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
>到期时间 (可选)</label
|
>到期时间 (可选)</label
|
||||||
>
|
>
|
||||||
@@ -1483,6 +1515,63 @@
|
|||||||
<input v-model.number="form.rateLimitDuration" type="hidden" value="60" />
|
<input v-model.number="form.rateLimitDuration" type="hidden" value="60" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Gemini API 配置 -->
|
||||||
|
<div v-if="form.platform === 'gemini-api' && !isEdit" class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
|
>API 基础地址 *</label
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model="form.baseUrl"
|
||||||
|
class="form-input w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:placeholder-gray-400"
|
||||||
|
placeholder="https://generativelanguage.googleapis.com"
|
||||||
|
required
|
||||||
|
type="url"
|
||||||
|
/>
|
||||||
|
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
填写 API 基础地址(可包含路径前缀),系统会自动拼接
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>/v1beta/models/{model}:generateContent</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||||
|
官方:
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>https://generativelanguage.googleapis.com</code
|
||||||
|
>
|
||||||
|
| 上游为 CRS:
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>https://your-crs.com/gemini</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
|
>API 密钥 *</label
|
||||||
|
>
|
||||||
|
<div class="relative">
|
||||||
|
<input
|
||||||
|
v-model="form.apiKey"
|
||||||
|
class="form-input w-full border-gray-300 pr-10 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:placeholder-gray-400"
|
||||||
|
placeholder="AIzaSy..."
|
||||||
|
required
|
||||||
|
:type="showApiKey ? 'text' : 'password'"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-400"
|
||||||
|
type="button"
|
||||||
|
@click="showApiKey = !showApiKey"
|
||||||
|
>
|
||||||
|
<i :class="showApiKey ? 'fas fa-eye-slash' : 'fas fa-eye'" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
从 Google AI Studio 获取的 API 密钥
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Claude 订阅类型选择 -->
|
<!-- Claude 订阅类型选择 -->
|
||||||
<div v-if="form.platform === 'claude'">
|
<div v-if="form.platform === 'claude'">
|
||||||
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
@@ -1905,7 +1994,8 @@
|
|||||||
form.platform !== 'ccr' &&
|
form.platform !== 'ccr' &&
|
||||||
form.platform !== 'bedrock' &&
|
form.platform !== 'bedrock' &&
|
||||||
form.platform !== 'azure_openai' &&
|
form.platform !== 'azure_openai' &&
|
||||||
form.platform !== 'openai-responses'
|
form.platform !== 'openai-responses' &&
|
||||||
|
form.platform !== 'gemini-api'
|
||||||
"
|
"
|
||||||
class="btn btn-primary flex-1 px-6 py-3 font-semibold"
|
class="btn btn-primary flex-1 px-6 py-3 font-semibold"
|
||||||
:disabled="loading"
|
:disabled="loading"
|
||||||
@@ -2926,6 +3016,59 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Gemini API 特定字段(编辑模式)-->
|
||||||
|
<div v-if="form.platform === 'gemini-api'" class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
|
>API 基础地址</label
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
v-model="form.baseUrl"
|
||||||
|
class="form-input w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200"
|
||||||
|
placeholder="https://generativelanguage.googleapis.com"
|
||||||
|
type="url"
|
||||||
|
/>
|
||||||
|
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
填写 API 基础地址(可包含路径前缀),系统会自动拼接
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>/v1beta/models/{model}:generateContent</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||||
|
官方:
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>https://generativelanguage.googleapis.com</code
|
||||||
|
>
|
||||||
|
| 上游为 CRS:
|
||||||
|
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||||
|
>https://your-crs.com/gemini</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||||
|
>API 密钥</label
|
||||||
|
>
|
||||||
|
<div class="relative">
|
||||||
|
<input
|
||||||
|
v-model="form.apiKey"
|
||||||
|
class="form-input w-full border-gray-300 pr-10 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200"
|
||||||
|
placeholder="留空表示不更新"
|
||||||
|
:type="showApiKey ? 'text' : 'password'"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-400"
|
||||||
|
type="button"
|
||||||
|
@click="showApiKey = !showApiKey"
|
||||||
|
>
|
||||||
|
<i :class="showApiKey ? 'fas fa-eye-slash' : 'fas fa-eye'" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">留空表示不更新 API Key</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Bedrock 特定字段(编辑模式)-->
|
<!-- Bedrock 特定字段(编辑模式)-->
|
||||||
<div v-if="form.platform === 'bedrock'" class="space-y-4">
|
<div v-if="form.platform === 'bedrock'" class="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -3410,7 +3553,7 @@ const determinePlatformGroup = (platform) => {
|
|||||||
return 'claude'
|
return 'claude'
|
||||||
} else if (['openai', 'openai-responses', 'azure_openai'].includes(platform)) {
|
} else if (['openai', 'openai-responses', 'azure_openai'].includes(platform)) {
|
||||||
return 'openai'
|
return 'openai'
|
||||||
} else if (platform === 'gemini') {
|
} else if (['gemini', 'gemini-api'].includes(platform)) {
|
||||||
return 'gemini'
|
return 'gemini'
|
||||||
} else if (platform === 'droid') {
|
} else if (platform === 'droid') {
|
||||||
return 'droid'
|
return 'droid'
|
||||||
@@ -4333,10 +4476,19 @@ const createAccount = async () => {
|
|||||||
}
|
}
|
||||||
// Claude Console、CCR、OpenAI-Responses 等其他平台不需要 Token 验证
|
// Claude Console、CCR、OpenAI-Responses 等其他平台不需要 Token 验证
|
||||||
} else if (form.value.addType === 'apikey') {
|
} else if (form.value.addType === 'apikey') {
|
||||||
const apiKeys = parseApiKeysInput(form.value.apiKeysInput)
|
// Gemini API 使用单个 apiKey 字段
|
||||||
if (apiKeys.length === 0) {
|
if (form.value.platform === 'gemini-api') {
|
||||||
errors.value.apiKeys = '请至少填写一个 API Key'
|
if (!form.value.apiKey || form.value.apiKey.trim() === '') {
|
||||||
hasError = true
|
errors.value.apiKey = '请填写 API Key'
|
||||||
|
hasError = true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 其他平台(如 Droid)使用多 API Key 输入
|
||||||
|
const apiKeys = parseApiKeysInput(form.value.apiKeysInput)
|
||||||
|
if (apiKeys.length === 0) {
|
||||||
|
errors.value.apiKeys = '请至少填写一个 API Key'
|
||||||
|
hasError = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4500,6 +4652,14 @@ const createAccount = async () => {
|
|||||||
data.rateLimitDuration = 60 // 默认值60,不从用户输入获取
|
data.rateLimitDuration = 60 // 默认值60,不从用户输入获取
|
||||||
data.dailyQuota = form.value.dailyQuota || 0
|
data.dailyQuota = form.value.dailyQuota || 0
|
||||||
data.quotaResetTime = form.value.quotaResetTime || '00:00'
|
data.quotaResetTime = form.value.quotaResetTime || '00:00'
|
||||||
|
} else if (form.value.platform === 'gemini-api') {
|
||||||
|
// Gemini API 账户特定数据
|
||||||
|
data.baseUrl = form.value.baseUrl || 'https://generativelanguage.googleapis.com'
|
||||||
|
data.apiKey = form.value.apiKey
|
||||||
|
data.priority = form.value.priority || 50
|
||||||
|
data.supportedModels = Array.isArray(form.value.supportedModels)
|
||||||
|
? form.value.supportedModels
|
||||||
|
: []
|
||||||
} else if (form.value.platform === 'bedrock') {
|
} else if (form.value.platform === 'bedrock') {
|
||||||
// Bedrock 账户特定数据 - 构造 awsCredentials 对象
|
// Bedrock 账户特定数据 - 构造 awsCredentials 对象
|
||||||
data.awsCredentials = {
|
data.awsCredentials = {
|
||||||
@@ -4545,6 +4705,8 @@ const createAccount = async () => {
|
|||||||
result = await accountsStore.createAzureOpenAIAccount(data)
|
result = await accountsStore.createAzureOpenAIAccount(data)
|
||||||
} else if (form.value.platform === 'gemini') {
|
} else if (form.value.platform === 'gemini') {
|
||||||
result = await accountsStore.createGeminiAccount(data)
|
result = await accountsStore.createGeminiAccount(data)
|
||||||
|
} else if (form.value.platform === 'gemini-api') {
|
||||||
|
result = await accountsStore.createGeminiApiAccount(data)
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`不支持的平台: ${form.value.platform}`)
|
throw new Error(`不支持的平台: ${form.value.platform}`)
|
||||||
}
|
}
|
||||||
@@ -4851,6 +5013,19 @@ const updateAccount = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gemini API 特定更新
|
||||||
|
if (props.account.platform === 'gemini-api') {
|
||||||
|
data.baseUrl = form.value.baseUrl || 'https://generativelanguage.googleapis.com'
|
||||||
|
// 只有当有新的 API Key 时才更新
|
||||||
|
if (form.value.apiKey && form.value.apiKey.trim()) {
|
||||||
|
data.apiKey = form.value.apiKey
|
||||||
|
}
|
||||||
|
data.priority = form.value.priority || 50
|
||||||
|
data.supportedModels = Array.isArray(form.value.supportedModels)
|
||||||
|
? form.value.supportedModels
|
||||||
|
: []
|
||||||
|
}
|
||||||
|
|
||||||
if (props.account.platform === 'claude') {
|
if (props.account.platform === 'claude') {
|
||||||
await accountsStore.updateClaudeAccount(props.account.id, data)
|
await accountsStore.updateClaudeAccount(props.account.id, data)
|
||||||
} else if (props.account.platform === 'claude-console') {
|
} else if (props.account.platform === 'claude-console') {
|
||||||
@@ -4865,6 +5040,8 @@ const updateAccount = async () => {
|
|||||||
await accountsStore.updateAzureOpenAIAccount(props.account.id, data)
|
await accountsStore.updateAzureOpenAIAccount(props.account.id, data)
|
||||||
} else if (props.account.platform === 'gemini') {
|
} else if (props.account.platform === 'gemini') {
|
||||||
await accountsStore.updateGeminiAccount(props.account.id, data)
|
await accountsStore.updateGeminiAccount(props.account.id, data)
|
||||||
|
} else if (props.account.platform === 'gemini-api') {
|
||||||
|
await accountsStore.updateGeminiApiAccount(props.account.id, data)
|
||||||
} else if (props.account.platform === 'droid') {
|
} else if (props.account.platform === 'droid') {
|
||||||
await accountsStore.updateDroidAccount(props.account.id, data)
|
await accountsStore.updateDroidAccount(props.account.id, data)
|
||||||
} else {
|
} else {
|
||||||
@@ -4986,6 +5163,10 @@ const filteredGroups = computed(() => {
|
|||||||
else if (form.value.platform === 'openai-responses') {
|
else if (form.value.platform === 'openai-responses') {
|
||||||
platformFilter = 'openai'
|
platformFilter = 'openai'
|
||||||
}
|
}
|
||||||
|
// Gemini-API 使用 Gemini 分组
|
||||||
|
else if (form.value.platform === 'gemini-api') {
|
||||||
|
platformFilter = 'gemini'
|
||||||
|
}
|
||||||
return groups.value.filter((g) => g.platform === platformFilter)
|
return groups.value.filter((g) => g.platform === platformFilter)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -5064,6 +5245,9 @@ watch(
|
|||||||
} else if (newPlatform === 'openai') {
|
} else if (newPlatform === 'openai') {
|
||||||
// 切换到 OpenAI 时,使用 OAuth 作为默认方式
|
// 切换到 OpenAI 时,使用 OAuth 作为默认方式
|
||||||
form.value.addType = 'oauth'
|
form.value.addType = 'oauth'
|
||||||
|
} else if (newPlatform === 'gemini-api' || newPlatform === 'azure_openai') {
|
||||||
|
// 切换到 Gemini API 或 Azure OpenAI 时,使用 apikey 模式(直接创建,不需要 OAuth 流程)
|
||||||
|
form.value.addType = 'apikey'
|
||||||
}
|
}
|
||||||
|
|
||||||
// 平台变化时,清空分组选择
|
// 平台变化时,清空分组选择
|
||||||
|
|||||||
@@ -353,6 +353,7 @@ const platformLabelMap = {
|
|||||||
openai: 'OpenAI',
|
openai: 'OpenAI',
|
||||||
'openai-responses': 'OpenAI Responses',
|
'openai-responses': 'OpenAI Responses',
|
||||||
gemini: 'Gemini',
|
gemini: 'Gemini',
|
||||||
|
'gemini-api': 'Gemini API',
|
||||||
droid: 'Droid'
|
droid: 'Droid'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1012,6 +1012,7 @@ const refreshAccounts = async () => {
|
|||||||
claudeData,
|
claudeData,
|
||||||
claudeConsoleData,
|
claudeConsoleData,
|
||||||
geminiData,
|
geminiData,
|
||||||
|
geminiApiData,
|
||||||
openaiData,
|
openaiData,
|
||||||
openaiResponsesData,
|
openaiResponsesData,
|
||||||
bedrockData,
|
bedrockData,
|
||||||
@@ -1021,6 +1022,7 @@ const refreshAccounts = async () => {
|
|||||||
apiClient.get('/admin/claude-accounts'),
|
apiClient.get('/admin/claude-accounts'),
|
||||||
apiClient.get('/admin/claude-console-accounts'),
|
apiClient.get('/admin/claude-console-accounts'),
|
||||||
apiClient.get('/admin/gemini-accounts'),
|
apiClient.get('/admin/gemini-accounts'),
|
||||||
|
apiClient.get('/admin/gemini-api-accounts'),
|
||||||
apiClient.get('/admin/openai-accounts'),
|
apiClient.get('/admin/openai-accounts'),
|
||||||
apiClient.get('/admin/openai-responses-accounts'),
|
apiClient.get('/admin/openai-responses-accounts'),
|
||||||
apiClient.get('/admin/bedrock-accounts'),
|
apiClient.get('/admin/bedrock-accounts'),
|
||||||
@@ -1053,13 +1055,31 @@ const refreshAccounts = async () => {
|
|||||||
|
|
||||||
localAccounts.value.claude = claudeAccounts
|
localAccounts.value.claude = claudeAccounts
|
||||||
|
|
||||||
|
// 合并 Gemini OAuth 和 Gemini API 账号
|
||||||
|
const geminiAccounts = []
|
||||||
|
|
||||||
if (geminiData.success) {
|
if (geminiData.success) {
|
||||||
localAccounts.value.gemini = (geminiData.data || []).map((account) => ({
|
;(geminiData.data || []).forEach((account) => {
|
||||||
...account,
|
geminiAccounts.push({
|
||||||
isDedicated: account.accountType === 'dedicated'
|
...account,
|
||||||
}))
|
platform: 'gemini',
|
||||||
|
isDedicated: account.accountType === 'dedicated'
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (geminiApiData.success) {
|
||||||
|
;(geminiApiData.data || []).forEach((account) => {
|
||||||
|
geminiAccounts.push({
|
||||||
|
...account,
|
||||||
|
platform: 'gemini-api',
|
||||||
|
isDedicated: account.accountType === 'dedicated'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
localAccounts.value.gemini = geminiAccounts
|
||||||
|
|
||||||
// 合并 OpenAI 和 OpenAI-Responses 账号
|
// 合并 OpenAI 和 OpenAI-Responses 账号
|
||||||
const openaiAccounts = []
|
const openaiAccounts = []
|
||||||
|
|
||||||
@@ -1159,6 +1179,25 @@ onMounted(async () => {
|
|||||||
|
|
||||||
// 初始化账号数据
|
// 初始化账号数据
|
||||||
if (props.accounts) {
|
if (props.accounts) {
|
||||||
|
// 合并 Gemini OAuth 和 Gemini API 账号
|
||||||
|
const geminiAccounts = []
|
||||||
|
if (props.accounts.gemini) {
|
||||||
|
props.accounts.gemini.forEach((account) => {
|
||||||
|
geminiAccounts.push({
|
||||||
|
...account,
|
||||||
|
platform: 'gemini'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (props.accounts.geminiApi) {
|
||||||
|
props.accounts.geminiApi.forEach((account) => {
|
||||||
|
geminiAccounts.push({
|
||||||
|
...account,
|
||||||
|
platform: 'gemini-api'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// 合并 OpenAI 和 OpenAI-Responses 账号
|
// 合并 OpenAI 和 OpenAI-Responses 账号
|
||||||
const openaiAccounts = []
|
const openaiAccounts = []
|
||||||
if (props.accounts.openai) {
|
if (props.accounts.openai) {
|
||||||
@@ -1180,7 +1219,7 @@ onMounted(async () => {
|
|||||||
|
|
||||||
localAccounts.value = {
|
localAccounts.value = {
|
||||||
claude: props.accounts.claude || [],
|
claude: props.accounts.claude || [],
|
||||||
gemini: props.accounts.gemini || [],
|
gemini: geminiAccounts,
|
||||||
openai: openaiAccounts,
|
openai: openaiAccounts,
|
||||||
bedrock: props.accounts.bedrock || [],
|
bedrock: props.accounts.bedrock || [],
|
||||||
droid: (props.accounts.droid || []).map((account) => ({
|
droid: (props.accounts.droid || []).map((account) => ({
|
||||||
|
|||||||
@@ -128,7 +128,9 @@
|
|||||||
? 'OpenAI 专属账号'
|
? 'OpenAI 专属账号'
|
||||||
: platform === 'droid'
|
: platform === 'droid'
|
||||||
? 'Droid 专属账号'
|
? 'Droid 专属账号'
|
||||||
: 'OAuth 专属账号'
|
: platform === 'gemini'
|
||||||
|
? 'Gemini OAuth 专属账号'
|
||||||
|
: 'OAuth 专属账号'
|
||||||
}}
|
}}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -239,6 +241,45 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Gemini-API 账号(仅 Gemini) -->
|
||||||
|
<div v-if="platform === 'gemini' && filteredGeminiApiAccounts.length > 0">
|
||||||
|
<div
|
||||||
|
class="bg-gray-50 px-4 py-2 text-xs font-semibold text-gray-500 dark:bg-gray-700 dark:text-gray-400"
|
||||||
|
>
|
||||||
|
Gemini-API 专属账号
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="account in filteredGeminiApiAccounts"
|
||||||
|
:key="account.id"
|
||||||
|
class="cursor-pointer px-4 py-2 transition-colors hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||||
|
:class="{
|
||||||
|
'bg-blue-50 dark:bg-blue-900/20': modelValue === `api:${account.id}`
|
||||||
|
}"
|
||||||
|
@click="selectAccount(`api:${account.id}`)"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<span class="text-gray-700 dark:text-gray-300">{{ account.name }}</span>
|
||||||
|
<span
|
||||||
|
class="ml-2 rounded-full px-2 py-0.5 text-xs"
|
||||||
|
:class="
|
||||||
|
account.isActive === 'true' || account.isActive === true
|
||||||
|
? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
|
||||||
|
: account.status === 'rate_limited'
|
||||||
|
? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400'
|
||||||
|
: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
{{ getAccountStatusText(account) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span class="text-xs text-gray-400 dark:text-gray-500">
|
||||||
|
{{ formatDate(account.createdAt) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 无搜索结果 -->
|
<!-- 无搜索结果 -->
|
||||||
<div
|
<div
|
||||||
v-if="searchQuery && !hasResults"
|
v-if="searchQuery && !hasResults"
|
||||||
@@ -341,6 +382,13 @@ const selectedLabel = computed(() => {
|
|||||||
return account ? `${account.name} (${getAccountStatusText(account)})` : ''
|
return account ? `${account.name} (${getAccountStatusText(account)})` : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gemini-API 账号
|
||||||
|
if (props.modelValue.startsWith('api:')) {
|
||||||
|
const accountId = props.modelValue.substring(4)
|
||||||
|
const account = props.accounts.find((a) => a.id === accountId && a.platform === 'gemini-api')
|
||||||
|
return account ? `${account.name} (${getAccountStatusText(account)})` : ''
|
||||||
|
}
|
||||||
|
|
||||||
// OAuth 账号
|
// OAuth 账号
|
||||||
const account = props.accounts.find((a) => a.id === props.modelValue)
|
const account = props.accounts.find((a) => a.id === props.modelValue)
|
||||||
return account ? `${account.name} (${getAccountStatusText(account)})` : ''
|
return account ? `${account.name} (${getAccountStatusText(account)})` : ''
|
||||||
@@ -421,10 +469,14 @@ const filteredOAuthAccounts = computed(() => {
|
|||||||
accounts = sortedAccounts.value.filter((a) => a.platform === 'openai')
|
accounts = sortedAccounts.value.filter((a) => a.platform === 'openai')
|
||||||
} else if (props.platform === 'droid') {
|
} else if (props.platform === 'droid') {
|
||||||
accounts = sortedAccounts.value.filter((a) => a.platform === 'droid')
|
accounts = sortedAccounts.value.filter((a) => a.platform === 'droid')
|
||||||
|
} else if (props.platform === 'gemini') {
|
||||||
|
// 对于 Gemini,只显示 OAuth 类型的账号(排除 gemini-api)
|
||||||
|
accounts = sortedAccounts.value.filter((a) => a.platform === 'gemini')
|
||||||
} else {
|
} else {
|
||||||
// 其他平台显示所有非特殊类型的账号
|
// 其他平台显示所有非特殊类型的账号
|
||||||
accounts = sortedAccounts.value.filter(
|
accounts = sortedAccounts.value.filter(
|
||||||
(a) => !['claude-oauth', 'claude-console', 'openai-responses'].includes(a.platform)
|
(a) =>
|
||||||
|
!['claude-oauth', 'claude-console', 'openai-responses', 'gemini-api'].includes(a.platform)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -464,13 +516,28 @@ const filteredOpenAIResponsesAccounts = computed(() => {
|
|||||||
return accounts
|
return accounts
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 过滤的 Gemini-API 账号
|
||||||
|
const filteredGeminiApiAccounts = computed(() => {
|
||||||
|
if (props.platform !== 'gemini') return []
|
||||||
|
|
||||||
|
let accounts = sortedAccounts.value.filter((a) => a.platform === 'gemini-api')
|
||||||
|
|
||||||
|
if (searchQuery.value) {
|
||||||
|
const query = searchQuery.value.toLowerCase()
|
||||||
|
accounts = accounts.filter((account) => account.name.toLowerCase().includes(query))
|
||||||
|
}
|
||||||
|
|
||||||
|
return accounts
|
||||||
|
})
|
||||||
|
|
||||||
// 是否有搜索结果
|
// 是否有搜索结果
|
||||||
const hasResults = computed(() => {
|
const hasResults = computed(() => {
|
||||||
return (
|
return (
|
||||||
filteredGroups.value.length > 0 ||
|
filteredGroups.value.length > 0 ||
|
||||||
filteredOAuthAccounts.value.length > 0 ||
|
filteredOAuthAccounts.value.length > 0 ||
|
||||||
filteredConsoleAccounts.value.length > 0 ||
|
filteredConsoleAccounts.value.length > 0 ||
|
||||||
filteredOpenAIResponsesAccounts.value.length > 0
|
filteredOpenAIResponsesAccounts.value.length > 0 ||
|
||||||
|
filteredGeminiApiAccounts.value.length > 0
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -374,6 +374,26 @@ export const useAccountsStore = defineStore('accounts', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 创建Gemini API账户
|
||||||
|
const createGeminiApiAccount = async (data) => {
|
||||||
|
loading.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post('/admin/gemini-api-accounts', data)
|
||||||
|
if (response.success) {
|
||||||
|
await fetchGeminiAccounts()
|
||||||
|
return response.data
|
||||||
|
} else {
|
||||||
|
throw new Error(response.message || '创建Gemini API账户失败')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err.message
|
||||||
|
throw err
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 更新Claude账户
|
// 更新Claude账户
|
||||||
const updateClaudeAccount = async (id, data) => {
|
const updateClaudeAccount = async (id, data) => {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
@@ -514,6 +534,26 @@ export const useAccountsStore = defineStore('accounts', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新Gemini API账户
|
||||||
|
const updateGeminiApiAccount = async (id, data) => {
|
||||||
|
loading.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
const response = await apiClient.put(`/admin/gemini-api-accounts/${id}`, data)
|
||||||
|
if (response.success) {
|
||||||
|
await fetchGeminiAccounts()
|
||||||
|
return response
|
||||||
|
} else {
|
||||||
|
throw new Error(response.message || '更新Gemini API账户失败')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err.message
|
||||||
|
throw err
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 切换账户状态
|
// 切换账户状态
|
||||||
const toggleAccount = async (platform, id) => {
|
const toggleAccount = async (platform, id) => {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
@@ -858,6 +898,7 @@ export const useAccountsStore = defineStore('accounts', () => {
|
|||||||
updateDroidAccount,
|
updateDroidAccount,
|
||||||
createAzureOpenAIAccount,
|
createAzureOpenAIAccount,
|
||||||
createOpenAIResponsesAccount,
|
createOpenAIResponsesAccount,
|
||||||
|
createGeminiApiAccount,
|
||||||
updateClaudeAccount,
|
updateClaudeAccount,
|
||||||
updateClaudeConsoleAccount,
|
updateClaudeConsoleAccount,
|
||||||
updateBedrockAccount,
|
updateBedrockAccount,
|
||||||
@@ -865,6 +906,7 @@ export const useAccountsStore = defineStore('accounts', () => {
|
|||||||
updateOpenAIAccount,
|
updateOpenAIAccount,
|
||||||
updateAzureOpenAIAccount,
|
updateAzureOpenAIAccount,
|
||||||
updateOpenAIResponsesAccount,
|
updateOpenAIResponsesAccount,
|
||||||
|
updateGeminiApiAccount,
|
||||||
toggleAccount,
|
toggleAccount,
|
||||||
deleteAccount,
|
deleteAccount,
|
||||||
refreshClaudeToken,
|
refreshClaudeToken,
|
||||||
|
|||||||
@@ -572,6 +572,19 @@
|
|||||||
<span>x{{ getDroidApiKeyCount(account) }}</span>
|
<span>x{{ getDroidApiKeyCount(account) }}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="account.platform === 'gemini-api'"
|
||||||
|
class="flex items-center gap-1.5 rounded-lg border border-amber-200 bg-gradient-to-r from-amber-100 to-yellow-100 px-2.5 py-1 dark:border-amber-700 dark:from-amber-900/20 dark:to-yellow-900/20"
|
||||||
|
>
|
||||||
|
<i class="fas fa-robot text-xs text-amber-700 dark:text-amber-400" />
|
||||||
|
<span class="text-xs font-semibold text-amber-800 dark:text-amber-300"
|
||||||
|
>Gemini-API</span
|
||||||
|
>
|
||||||
|
<span class="mx-1 h-4 w-px bg-amber-300 dark:bg-amber-600" />
|
||||||
|
<span class="text-xs font-medium text-amber-700 dark:text-amber-400"
|
||||||
|
>API Key</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-else
|
v-else
|
||||||
class="flex items-center gap-1.5 rounded-lg border border-gray-200 bg-gradient-to-r from-gray-100 to-gray-200 px-2.5 py-1"
|
class="flex items-center gap-1.5 rounded-lg border border-gray-200 bg-gradient-to-r from-gray-100 to-gray-200 px-2.5 py-1"
|
||||||
@@ -725,7 +738,8 @@
|
|||||||
account.platform === 'openai-responses' ||
|
account.platform === 'openai-responses' ||
|
||||||
account.platform === 'azure_openai' ||
|
account.platform === 'azure_openai' ||
|
||||||
account.platform === 'ccr' ||
|
account.platform === 'ccr' ||
|
||||||
account.platform === 'droid'
|
account.platform === 'droid' ||
|
||||||
|
account.platform === 'gemini-api'
|
||||||
"
|
"
|
||||||
class="flex items-center gap-2"
|
class="flex items-center gap-2"
|
||||||
>
|
>
|
||||||
@@ -1832,7 +1846,8 @@ const supportedUsagePlatforms = [
|
|||||||
'openai',
|
'openai',
|
||||||
'openai-responses',
|
'openai-responses',
|
||||||
'gemini',
|
'gemini',
|
||||||
'droid'
|
'droid',
|
||||||
|
'gemini-api'
|
||||||
]
|
]
|
||||||
|
|
||||||
// 过期时间编辑弹窗状态
|
// 过期时间编辑弹窗状态
|
||||||
@@ -1859,6 +1874,7 @@ const platformOptions = ref([
|
|||||||
{ value: 'claude', label: 'Claude', icon: 'fa-brain' },
|
{ value: 'claude', label: 'Claude', icon: 'fa-brain' },
|
||||||
{ value: 'claude-console', label: 'Claude Console', icon: 'fa-terminal' },
|
{ value: 'claude-console', label: 'Claude Console', icon: 'fa-terminal' },
|
||||||
{ value: 'gemini', label: 'Gemini', icon: 'fab fa-google' },
|
{ value: 'gemini', label: 'Gemini', icon: 'fab fa-google' },
|
||||||
|
{ value: 'gemini-api', label: 'Gemini API', icon: 'fa-key' },
|
||||||
{ value: 'openai', label: 'OpenAi', icon: 'fa-openai' },
|
{ value: 'openai', label: 'OpenAi', icon: 'fa-openai' },
|
||||||
{ value: 'azure_openai', label: 'Azure OpenAI', icon: 'fab fa-microsoft' },
|
{ value: 'azure_openai', label: 'Azure OpenAI', icon: 'fab fa-microsoft' },
|
||||||
{ value: 'bedrock', label: 'Bedrock', icon: 'fab fa-aws' },
|
{ value: 'bedrock', label: 'Bedrock', icon: 'fab fa-aws' },
|
||||||
@@ -2189,7 +2205,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
apiClient.get('/admin/azure-openai-accounts', { params }),
|
apiClient.get('/admin/azure-openai-accounts', { params }),
|
||||||
apiClient.get('/admin/openai-responses-accounts', { params }),
|
apiClient.get('/admin/openai-responses-accounts', { params }),
|
||||||
apiClient.get('/admin/ccr-accounts', { params }),
|
apiClient.get('/admin/ccr-accounts', { params }),
|
||||||
apiClient.get('/admin/droid-accounts', { params })
|
apiClient.get('/admin/droid-accounts', { params }),
|
||||||
|
apiClient.get('/admin/gemini-api-accounts', { params })
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// 只请求指定平台,其他平台设为null占位
|
// 只请求指定平台,其他平台设为null占位
|
||||||
@@ -2204,7 +2221,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'claude-console':
|
case 'claude-console':
|
||||||
@@ -2217,7 +2235,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'bedrock':
|
case 'bedrock':
|
||||||
@@ -2230,7 +2249,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'gemini':
|
case 'gemini':
|
||||||
@@ -2243,7 +2263,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'openai':
|
case 'openai':
|
||||||
@@ -2256,7 +2277,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'azure_openai':
|
case 'azure_openai':
|
||||||
@@ -2269,7 +2291,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
apiClient.get('/admin/azure-openai-accounts', { params }),
|
apiClient.get('/admin/azure-openai-accounts', { params }),
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'openai-responses':
|
case 'openai-responses':
|
||||||
@@ -2282,7 +2305,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
apiClient.get('/admin/openai-responses-accounts', { params }),
|
apiClient.get('/admin/openai-responses-accounts', { params }),
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'ccr':
|
case 'ccr':
|
||||||
@@ -2295,7 +2319,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure 占位
|
Promise.resolve({ success: true, data: [] }), // azure 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
apiClient.get('/admin/ccr-accounts', { params }),
|
apiClient.get('/admin/ccr-accounts', { params }),
|
||||||
Promise.resolve({ success: true, data: [] }) // droid 占位
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
case 'droid':
|
case 'droid':
|
||||||
@@ -2308,7 +2333,22 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }), // azure 占位
|
Promise.resolve({ success: true, data: [] }), // azure 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
apiClient.get('/admin/droid-accounts', { params })
|
apiClient.get('/admin/droid-accounts', { params }),
|
||||||
|
Promise.resolve({ success: true, data: [] }) // gemini-api 占位
|
||||||
|
)
|
||||||
|
break
|
||||||
|
case 'gemini-api':
|
||||||
|
requests.push(
|
||||||
|
Promise.resolve({ success: true, data: [] }), // claude 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // claude-console 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // bedrock 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // gemini 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // openai 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // azure-openai 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // openai-responses 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // ccr 占位
|
||||||
|
Promise.resolve({ success: true, data: [] }), // droid 占位
|
||||||
|
apiClient.get('/admin/gemini-api-accounts', { params })
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
default:
|
default:
|
||||||
@@ -2322,6 +2362,7 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
Promise.resolve({ success: true, data: [] }),
|
Promise.resolve({ success: true, data: [] }),
|
||||||
Promise.resolve({ success: true, data: [] }),
|
Promise.resolve({ success: true, data: [] }),
|
||||||
Promise.resolve({ success: true, data: [] }),
|
Promise.resolve({ success: true, data: [] }),
|
||||||
|
Promise.resolve({ success: true, data: [] }),
|
||||||
Promise.resolve({ success: true, data: [] })
|
Promise.resolve({ success: true, data: [] })
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
@@ -2343,7 +2384,8 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
azureOpenaiData,
|
azureOpenaiData,
|
||||||
openaiResponsesData,
|
openaiResponsesData,
|
||||||
ccrData,
|
ccrData,
|
||||||
droidData
|
droidData,
|
||||||
|
geminiApiData
|
||||||
] = await Promise.all(requests)
|
] = await Promise.all(requests)
|
||||||
|
|
||||||
const allAccounts = []
|
const allAccounts = []
|
||||||
@@ -2449,6 +2491,20 @@ const loadAccounts = async (forceReload = false) => {
|
|||||||
allAccounts.push(...droidAccounts)
|
allAccounts.push(...droidAccounts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gemini API 账户
|
||||||
|
if (geminiApiData && geminiApiData.success) {
|
||||||
|
const geminiApiAccounts = (geminiApiData.data || []).map((acc) => {
|
||||||
|
// 计算每个Gemini-API账户绑定的API Key数量
|
||||||
|
// Gemini-API账户使用 api: 前缀
|
||||||
|
const boundApiKeysCount = apiKeys.value.filter(
|
||||||
|
(key) => key.geminiAccountId === `api:${acc.id}`
|
||||||
|
).length
|
||||||
|
// 后端已经包含了groupInfos,直接使用
|
||||||
|
return { ...acc, platform: 'gemini-api', boundApiKeysCount }
|
||||||
|
})
|
||||||
|
allAccounts.push(...geminiApiAccounts)
|
||||||
|
}
|
||||||
|
|
||||||
// 根据分组筛选器过滤账户
|
// 根据分组筛选器过滤账户
|
||||||
let filteredAccounts = allAccounts
|
let filteredAccounts = allAccounts
|
||||||
if (groupFilter.value !== 'all') {
|
if (groupFilter.value !== 'all') {
|
||||||
@@ -2788,7 +2844,8 @@ const getBoundApiKeysForAccount = (account) => {
|
|||||||
key.geminiAccountId === accountId ||
|
key.geminiAccountId === accountId ||
|
||||||
key.openaiAccountId === accountId ||
|
key.openaiAccountId === accountId ||
|
||||||
key.azureOpenaiAccountId === accountId ||
|
key.azureOpenaiAccountId === accountId ||
|
||||||
key.openaiAccountId === `responses:${accountId}`
|
key.openaiAccountId === `responses:${accountId}` ||
|
||||||
|
key.geminiAccountId === `api:${accountId}`
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -2813,6 +2870,8 @@ const resolveAccountDeleteEndpoint = (account) => {
|
|||||||
return `/admin/gemini-accounts/${account.id}`
|
return `/admin/gemini-accounts/${account.id}`
|
||||||
case 'droid':
|
case 'droid':
|
||||||
return `/admin/droid-accounts/${account.id}`
|
return `/admin/droid-accounts/${account.id}`
|
||||||
|
case 'gemini-api':
|
||||||
|
return `/admin/gemini-api-accounts/${account.id}`
|
||||||
default:
|
default:
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -2993,6 +3052,8 @@ const resetAccountStatus = async (account) => {
|
|||||||
endpoint = `/admin/ccr-accounts/${account.id}/reset-status`
|
endpoint = `/admin/ccr-accounts/${account.id}/reset-status`
|
||||||
} else if (account.platform === 'droid') {
|
} else if (account.platform === 'droid') {
|
||||||
endpoint = `/admin/droid-accounts/${account.id}/reset-status`
|
endpoint = `/admin/droid-accounts/${account.id}/reset-status`
|
||||||
|
} else if (account.platform === 'gemini-api') {
|
||||||
|
endpoint = `/admin/gemini-api-accounts/${account.id}/reset-status`
|
||||||
} else {
|
} else {
|
||||||
showToast('不支持的账户类型', 'error')
|
showToast('不支持的账户类型', 'error')
|
||||||
account.isResetting = false
|
account.isResetting = false
|
||||||
@@ -3041,6 +3102,8 @@ const toggleSchedulable = async (account) => {
|
|||||||
endpoint = `/admin/ccr-accounts/${account.id}/toggle-schedulable`
|
endpoint = `/admin/ccr-accounts/${account.id}/toggle-schedulable`
|
||||||
} else if (account.platform === 'droid') {
|
} else if (account.platform === 'droid') {
|
||||||
endpoint = `/admin/droid-accounts/${account.id}/toggle-schedulable`
|
endpoint = `/admin/droid-accounts/${account.id}/toggle-schedulable`
|
||||||
|
} else if (account.platform === 'gemini-api') {
|
||||||
|
endpoint = `/admin/gemini-api-accounts/${account.id}/toggle-schedulable`
|
||||||
} else {
|
} else {
|
||||||
showToast('该账户类型暂不支持调度控制', 'warning')
|
showToast('该账户类型暂不支持调度控制', 'warning')
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -2287,6 +2287,7 @@ const loadAccounts = async () => {
|
|||||||
claudeData,
|
claudeData,
|
||||||
claudeConsoleData,
|
claudeConsoleData,
|
||||||
geminiData,
|
geminiData,
|
||||||
|
geminiApiData,
|
||||||
openaiData,
|
openaiData,
|
||||||
openaiResponsesData,
|
openaiResponsesData,
|
||||||
bedrockData,
|
bedrockData,
|
||||||
@@ -2296,6 +2297,7 @@ const loadAccounts = async () => {
|
|||||||
apiClient.get('/admin/claude-accounts'),
|
apiClient.get('/admin/claude-accounts'),
|
||||||
apiClient.get('/admin/claude-console-accounts'),
|
apiClient.get('/admin/claude-console-accounts'),
|
||||||
apiClient.get('/admin/gemini-accounts'),
|
apiClient.get('/admin/gemini-accounts'),
|
||||||
|
apiClient.get('/admin/gemini-api-accounts'), // 加载 Gemini-API 账号
|
||||||
apiClient.get('/admin/openai-accounts'),
|
apiClient.get('/admin/openai-accounts'),
|
||||||
apiClient.get('/admin/openai-responses-accounts'), // 加载 OpenAI-Responses 账号
|
apiClient.get('/admin/openai-responses-accounts'), // 加载 OpenAI-Responses 账号
|
||||||
apiClient.get('/admin/bedrock-accounts'),
|
apiClient.get('/admin/bedrock-accounts'),
|
||||||
@@ -2328,13 +2330,31 @@ const loadAccounts = async () => {
|
|||||||
|
|
||||||
accounts.value.claude = claudeAccounts
|
accounts.value.claude = claudeAccounts
|
||||||
|
|
||||||
|
// 合并 Gemini OAuth 和 Gemini API 账户
|
||||||
|
const geminiAccounts = []
|
||||||
|
|
||||||
if (geminiData.success) {
|
if (geminiData.success) {
|
||||||
accounts.value.gemini = (geminiData.data || []).map((account) => ({
|
;(geminiData.data || []).forEach((account) => {
|
||||||
...account,
|
geminiAccounts.push({
|
||||||
isDedicated: account.accountType === 'dedicated'
|
...account,
|
||||||
}))
|
platform: 'gemini',
|
||||||
|
isDedicated: account.accountType === 'dedicated'
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (geminiApiData.success) {
|
||||||
|
;(geminiApiData.data || []).forEach((account) => {
|
||||||
|
geminiAccounts.push({
|
||||||
|
...account,
|
||||||
|
platform: 'gemini-api',
|
||||||
|
isDedicated: account.accountType === 'dedicated'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
accounts.value.gemini = geminiAccounts
|
||||||
|
|
||||||
if (openaiData.success) {
|
if (openaiData.success) {
|
||||||
accounts.value.openai = (openaiData.data || []).map((account) => ({
|
accounts.value.openai = (openaiData.data || []).map((account) => ({
|
||||||
...account,
|
...account,
|
||||||
@@ -2501,6 +2521,19 @@ const getBoundAccountName = (accountId) => {
|
|||||||
return `${claudeAccount.name}`
|
return `${claudeAccount.name}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 处理 api: 前缀的 Gemini-API 账户
|
||||||
|
if (accountId.startsWith('api:')) {
|
||||||
|
const realAccountId = accountId.replace('api:', '')
|
||||||
|
const geminiApiAccount = accounts.value.gemini.find(
|
||||||
|
(acc) => acc.id === realAccountId && acc.platform === 'gemini-api'
|
||||||
|
)
|
||||||
|
if (geminiApiAccount) {
|
||||||
|
return `${geminiApiAccount.name}`
|
||||||
|
}
|
||||||
|
// 如果找不到,返回ID的前8位
|
||||||
|
return `${realAccountId.substring(0, 8)}`
|
||||||
|
}
|
||||||
|
|
||||||
// 从Gemini账户列表中查找
|
// 从Gemini账户列表中查找
|
||||||
const geminiAccount = accounts.value.gemini.find((acc) => acc.id === accountId)
|
const geminiAccount = accounts.value.gemini.find((acc) => acc.id === accountId)
|
||||||
if (geminiAccount) {
|
if (geminiAccount) {
|
||||||
@@ -2583,7 +2616,23 @@ const getGeminiBindingInfo = (key) => {
|
|||||||
if (key.geminiAccountId.startsWith('group:')) {
|
if (key.geminiAccountId.startsWith('group:')) {
|
||||||
return info
|
return info
|
||||||
}
|
}
|
||||||
// 检查账户是否存在
|
|
||||||
|
// 处理 api: 前缀的 Gemini-API 账户
|
||||||
|
if (key.geminiAccountId.startsWith('api:')) {
|
||||||
|
const realAccountId = key.geminiAccountId.replace('api:', '')
|
||||||
|
const account = accounts.value.gemini.find(
|
||||||
|
(acc) => acc.id === realAccountId && acc.platform === 'gemini-api'
|
||||||
|
)
|
||||||
|
if (!account) {
|
||||||
|
return `⚠️ ${info} (账户不存在)`
|
||||||
|
}
|
||||||
|
if (account.accountType === 'dedicated') {
|
||||||
|
return `🔒 API专属-${info}`
|
||||||
|
}
|
||||||
|
return `API-${info}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查 Gemini OAuth 账户是否存在
|
||||||
const account = accounts.value.gemini.find((acc) => acc.id === key.geminiAccountId)
|
const account = accounts.value.gemini.find((acc) => acc.id === key.geminiAccountId)
|
||||||
if (!account) {
|
if (!account) {
|
||||||
return `⚠️ ${info} (账户不存在)`
|
return `⚠️ ${info} (账户不存在)`
|
||||||
|
|||||||
Reference in New Issue
Block a user