feat: 支持Gemini-Api接入

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

View File

@@ -4366,6 +4366,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
'openai',
'openai-responses',
'gemini',
'gemini-api',
'droid'
]
if (!allowedPlatforms.includes(platform)) {
@@ -4378,6 +4379,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
const accountTypeMap = {
openai: 'openai',
'openai-responses': 'openai-responses',
'gemini-api': 'gemini-api',
droid: 'droid'
}
@@ -4387,6 +4389,7 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
openai: 'gpt-4o-mini-2024-07-18',
'openai-responses': 'gpt-4o-mini-2024-07-18',
gemini: 'gemini-1.5-flash',
'gemini-api': 'gemini-2.0-flash',
droid: 'unknown'
}
@@ -4411,6 +4414,11 @@ router.get('/accounts/:accountId/usage-history', authenticateAdmin, async (req,
case 'gemini':
accountData = await geminiAccountService.getAccount(accountId)
break
case 'gemini-api': {
const geminiApiAccountService = require('../services/geminiApiAccountService')
accountData = await geminiApiAccountService.getAccount(accountId)
break
}
case 'droid':
accountData = await droidAccountService.getAccount(accountId)
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

View File

@@ -3,6 +3,7 @@ const router = express.Router()
const logger = require('../utils/logger')
const { authenticateApiKey } = require('../middleware/auth')
const geminiAccountService = require('../services/geminiAccountService')
const geminiApiAccountService = require('../services/geminiApiAccountService')
const { sendGeminiRequest, getAvailableModels } = require('../services/geminiRelayService')
const crypto = require('crypto')
const sessionHelper = require('../utils/sessionHelper')
@@ -10,6 +11,8 @@ const unifiedGeminiScheduler = require('../services/unifiedGeminiScheduler')
const apiKeyService = require('../services/apiKeyService')
const { updateRateLimitCounters } = require('../utils/rateLimitHelper')
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
// 生成会话哈希
@@ -77,6 +80,9 @@ async function applyRateLimitTracking(req, usageSummary, model, context = '') {
router.post('/messages', authenticateApiKey, async (req, res) => {
const startTime = Date.now()
let abortController = null
let accountId
let accountType
let sessionHash
try {
const apiKeyData = req.apiKey
@@ -111,18 +117,17 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
}
// 生成会话哈希用于粘性会话
const sessionHash = generateSessionHash(req)
sessionHash = generateSessionHash(req)
// 使用统一调度选择可用的 Gemini 账户(传递请求的模型)
let accountId
try {
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
apiKeyData,
sessionHash,
model // 传递请求的模型进行过滤
model, // 传递请求的模型进行过滤
{ allowApiAccounts: true } // 允许调度 API 账户
)
const { accountId: selectedAccountId } = schedulerResult
accountId = selectedAccountId
;({ accountId, accountType } = schedulerResult)
} catch (error) {
logger.error('Failed to select Gemini account:', error)
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)
if (!account) {
return res.status(503).json({
error: {
message: 'Selected account not found',
type: 'service_unavailable'
}
})
let account
if (isApiAccount) {
account = await geminiApiAccountService.getAccount(accountId)
if (!account) {
return res.status(503).json({
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()
@@ -160,20 +182,126 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
}
})
// 发送请求到 Gemini
const 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
})
let geminiResponse
if (isApiAccount) {
// API 账户:直接调用 Google Gemini API
// 转换 OpenAI 格式的 messages 为 Gemini 格式的 contents
const contents = messages.map((msg) => ({
role: msg.role === 'assistant' ? 'model' : msg.role,
parts: [{ text: msg.content }]
}))
const requestBody = {
contents,
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) {
// 设置流式响应头
@@ -182,15 +310,90 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
res.setHeader('Connection', 'keep-alive')
res.setHeader('X-Accel-Buffering', 'no')
// 流式传输响应
for await (const chunk of geminiResponse) {
if (abortController.signal.aborted) {
break
if (isApiAccount) {
// API 账户:处理 SSE 流并记录使用统计
let totalUsage = {
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 {
// 非流式响应
res.json(geminiResponse)
@@ -202,14 +405,24 @@ router.post('/messages', authenticateApiKey, async (req, res) => {
logger.error('Gemini request error:', error)
// 处理速率限制
if (error.status === 429) {
if (req.apiKey && req.account) {
await geminiAccountService.setAccountRateLimited(req.account.id, true)
const errorStatus = error.response?.status || error.status
if (errorStatus === 429 && accountId) {
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 = {
error: error.error || {
message: error.message || 'Internal server error',
@@ -700,13 +913,38 @@ async function handleGenerateContent(req, res) {
})
}
// 使用统一调度选择账号
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
// 使用统一调度选择账号v1internal 不允许 API 账户)
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
req.apiKey,
sessionHash,
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)
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 version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
@@ -854,13 +1092,38 @@ async function handleStreamGenerateContent(req, res) {
})
}
// 使用统一调度选择账号
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
// 使用统一调度选择账号v1internal 不允许 API 账户)
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
req.apiKey,
sessionHash,
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)
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 version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'

View File

@@ -3,9 +3,12 @@ const router = express.Router()
const { authenticateApiKey } = require('../middleware/auth')
const logger = require('../utils/logger')
const geminiAccountService = require('../services/geminiAccountService')
const geminiApiAccountService = require('../services/geminiApiAccountService')
const unifiedGeminiScheduler = require('../services/unifiedGeminiScheduler')
const apiKeyService = require('../services/apiKeyService')
const sessionHelper = require('../utils/sessionHelper')
const axios = require('axios')
const ProxyHelper = require('../utils/proxyHelper')
// 导入 geminiRoutes 中导出的处理函数
const { handleLoadCodeAssist, handleOnboardUser, handleCountTokens } = require('./geminiRoutes')
@@ -136,6 +139,8 @@ async function normalizeAxiosStreamError(error) {
async function handleStandardGenerateContent(req, res) {
let account = null
let sessionHash = null
let accountId = null // 提升到外部作用域
let isApiAccount = false // 提升到外部作用域
try {
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,
sessionHash,
model
model,
{ allowApiAccounts: true } // 允许调度 API 账户
)
account = await geminiAccountService.getAccount(accountId)
const { accessToken, refreshToken } = account
;({ accountId } = schedulerResult)
const { accountType } = schedulerResult
// 判断账户类型:根据 accountType 判断,而非 accountId 前缀
isApiAccount = accountType === 'gemini-api' // 赋值而不是声明
const actualAccountId = accountId // accountId 已经是实际 ID无需处理前缀
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
logger.info(`Standard Gemini API generateContent request (${version})`, {
model,
projectId: account.projectId,
apiKeyId: req.apiKey?.id || 'unknown'
})
if (isApiAccount) {
// Gemini API 账户:使用 API Key 直接请求
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
@@ -235,63 +268,106 @@ async function handleStandardGenerateContent(req, res) {
}
}
const client = await geminiAccountService.getOauthClient(accessToken, refreshToken, proxyConfig)
let response
// 项目ID优先级账户配置的项目ID > 临时项目ID > 尝试获取
let effectiveProjectId = account.projectId || account.tempProjectId || null
if (isApiAccount) {
// Gemini API 账户:直接使用 API Key 请求
// baseUrl 填写域名,如 https://generativelanguage.googleapis.com版本固定为 v1beta
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:generateContent?key=${account.apiKey}`
// 如果没有任何项目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(accountId, effectiveProjectId)
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
// 构建 Axios 配置
const axiosConfig = {
method: 'POST',
url: apiUrl,
data: actualRequestData,
headers: {
'Content-Type': 'application/json'
}
} 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'
// 添加代理配置
if (proxyConfig) {
const proxyHelper = new ProxyHelper()
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
}
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`
// 调用内部 APIcloudcode-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`
// 调用内部 APIcloudcode-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) {
try {
@@ -303,7 +379,7 @@ async function handleStandardGenerateContent(req, res) {
0, // cacheCreateTokens
0, // cacheReadTokens
model,
account.id
accountId // 账户 ID
)
logger.info(
`📊 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) {
logger.warn(`⚠️ Gemini account ${account.id} rate limited (Standard API), marking as limited`)
if (error.response?.status === 429 && accountId) {
logger.warn(`⚠️ Gemini account ${accountId} rate limited (Standard API), marking as limited`)
try {
await unifiedGeminiScheduler.markAccountRateLimited(account.id, 'gemini', sessionHash)
const rateLimitAccountType = isApiAccount ? 'gemini-api' : 'gemini'
await unifiedGeminiScheduler.markAccountRateLimited(
accountId, // 账户 ID
rateLimitAccountType,
sessionHash
)
} catch (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 account = null
let sessionHash = null
let accountId = null // 提升到外部作用域
let isApiAccount = false // 提升到外部作用域
try {
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,
sessionHash,
model
model,
{ allowApiAccounts: true } // 允许调度 API 账户
)
account = await geminiAccountService.getAccount(accountId)
const { accessToken, refreshToken } = account
;({ accountId } = schedulerResult)
const { accountType } = schedulerResult
// 判断账户类型:根据 accountType 判断,而非 accountId 前缀
isApiAccount = accountType === 'gemini-api' // 赋值而不是声明
const actualAccountId = accountId // accountId 已经是实际 ID无需处理前缀
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
logger.info(`Standard Gemini API streamGenerateContent request (${version})`, {
model,
projectId: account.projectId,
apiKeyId: req.apiKey?.id || 'unknown'
})
if (isApiAccount) {
// Gemini API 账户:使用 API Key 直接请求
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()
@@ -460,64 +577,109 @@ async function handleStandardStreamGenerateContent(req, res) {
}
}
const client = await geminiAccountService.getOauthClient(accessToken, refreshToken, proxyConfig)
let streamResponse
// 项目ID优先级账户配置的项目ID > 临时项目ID > 尝试获取
let effectiveProjectId = account.projectId || account.tempProjectId || null
if (isApiAccount) {
// Gemini API 账户:直接使用 API Key 请求流式接口
// baseUrl 填写域名,版本固定为 v1beta
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:streamGenerateContent?key=${account.apiKey}&alt=sse`
// 如果没有任何项目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(accountId, effectiveProjectId)
logger.info(`📋 Fetched and cached temporary projectId: ${effectiveProjectId}`)
}
} catch (loadError) {
logger.warn('Failed to fetch projectId from loadCodeAssist:', loadError.message)
// 构建 Axios 配置
const axiosConfig = {
method: 'POST',
url: apiUrl,
data: actualRequestData,
headers: {
'Content-Type': 'application/json'
},
responseType: 'stream',
signal: abortController.signal
}
}
// 如果还是没有项目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'
// 添加代理配置
if (proxyConfig) {
const proxyHelper = new ProxyHelper()
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
}
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`
// 调用内部 APIcloudcode-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`
// 调用内部 APIcloudcode-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 响应头
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
@@ -672,7 +834,7 @@ async function handleStandardStreamGenerateContent(req, res) {
0, // cacheCreateTokens
0, // cacheReadTokens
model,
account.id
accountId // 使用原始 accountId含前缀
)
.then(() => {
logger.info(
@@ -743,12 +905,17 @@ async function handleStandardStreamGenerateContent(req, res) {
})
// 处理速率限制
if (error.response?.status === 429) {
if (error.response?.status === 429 && accountId) {
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 {
await unifiedGeminiScheduler.markAccountRateLimited(account.id, 'gemini', sessionHash)
const rateLimitAccountType = isApiAccount ? 'gemini-api' : 'gemini'
await unifiedGeminiScheduler.markAccountRateLimited(
accountId, // 账户 ID
rateLimitAccountType,
sessionHash
)
} catch (limitError) {
logger.warn('Failed to mark account as rate limited in scheduler:', limitError)
}