chenpei d0dc94e36d feat: 将弹幕功能替换为AI聊天助手
新功能:
- 创建AI聊天助手组件(AIChatWidget)
- 支持文字+图片多模态对话
- 集成Gemini AI API
- 支持图片编辑和内容生成
- 实时对话历史管理
- 优雅的UI设计,支持黑夜模式

技术实现:
- 后端API代理Gemini API(/api/ai-chat)
- 支持最多5张图片上传
- 流式响应处理
- 对话历史管理
- Base64图片处理

配置:
- 在.env中添加Gemini API配置
- GEMINI_API_KEY
- GEMINI_API_BASE_URL
- GEMINI_MODEL

替换原弹幕功能,提供更强大的AI助手体验!
2025-10-27 17:45:37 +08:00

117 lines
3.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json(
{ error: '未授权' },
{ status: 401 }
)
}
const { messages, model } = await req.json()
const apiKey = process.env.GEMINI_API_KEY
const apiBaseUrl = process.env.GEMINI_API_BASE_URL || 'https://generativelanguage.googleapis.com/v1beta'
const modelName = model || process.env.GEMINI_MODEL || 'gemini-2.0-flash-exp'
if (!apiKey) {
return NextResponse.json(
{ error: 'Gemini API未配置' },
{ status: 500 }
)
}
// 构建Gemini API请求
const geminiMessages = messages.map((msg: any) => {
if (typeof msg.content === 'string') {
return {
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }]
}
} else if (Array.isArray(msg.content)) {
const parts = msg.content.map((part: any) => {
if (part.type === 'text') {
return { text: part.text }
} else if (part.type === 'image_url') {
// 提取base64图片数据
const base64Match = part.image_url.url.match(/data:image\/([^;]+);base64,(.+)/)
if (base64Match) {
return {
inlineData: {
mimeType: `image/${base64Match[1]}`,
data: base64Match[2]
}
}
}
}
return null
}).filter(Boolean)
return {
role: msg.role === 'assistant' ? 'model' : 'user',
parts
}
}
return null
}).filter(Boolean)
// 调用Gemini API
const response = await fetch(
`${apiBaseUrl}/models/${modelName}:generateContent?key=${apiKey}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: geminiMessages,
generationConfig: {
temperature: 1,
topK: 40,
topP: 0.95,
maxOutputTokens: 8192,
},
}),
}
)
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
console.error('Gemini API error:', errorData)
return NextResponse.json(
{ error: errorData.error?.message || '调用Gemini API失败' },
{ status: response.status }
)
}
const data = await response.json()
return NextResponse.json(data)
} catch (error) {
console.error('AI chat error:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : '处理失败' },
{ status: 500 }
)
}
}
// GET endpoint to check API configuration
export async function GET() {
const apiKey = process.env.GEMINI_API_KEY
const apiBaseUrl = process.env.GEMINI_API_BASE_URL || 'https://generativelanguage.googleapis.com/v1beta'
const model = process.env.GEMINI_MODEL || 'gemini-2.0-flash-exp'
return NextResponse.json({
configured: !!apiKey,
apiBaseUrl,
model
})
}