122 lines
3.4 KiB
TypeScript

// AI聊天API - 使用Gemini API
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
// POST - 发送消息到AI
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json(
{ error: '未授权' },
{ status: 401 }
);
}
const { messages, model } = await request.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格式
const geminiMessages = messages.map((msg: any) => {
// 文本消息
if (typeof msg.content === 'string') {
return {
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }],
};
}
// 多模态消息(文本+图片)
if (Array.isArray(msg.content)) {
const parts = msg.content.map((part: any) => {
if (part.type === 'text') {
return { text: part.text };
}
if (part.type === 'image_url') {
// 解析base64图片
const match = part.image_url.url.match(/data:image\/([^;]+);base64,(.+)/);
if (match) {
return {
inlineData: {
mimeType: `image/${match[1]}`,
data: match[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 - 获取AI配置状态
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,
});
}