flnxi-Wu/app/api/ai-chat/route.ts
WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +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
})
}