anything-vs-anything/src/app/api/compare/route.ts

97 lines
3.5 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const { item1, item2, description1, description2, language } = await request.json();
if (!item1 || !item2) {
return NextResponse.json(
{ error: 'Both items are required' },
{ status: 400 }
);
}
// 根据传入的语言参数判断,默认为英文
const isChinese = language === 'zh-CN';
console.log(`isChinese? [${isChinese}]`)
const prompt = isChinese ?
`请详细比较 ${item1}${item2},用中文表格格式展示。${description1 ? `\n\n${item1} 的补充信息:${description1}` : ''
}${description2 ? `\n${item2} 的补充信息:${description2}` : ''
}
请提供全面的中文对比分析,严格按照以下要求:
## 输出要求:
1. **主要内容使用中文表达**
2. **专业术语、品牌名称、技术名词可保持原文**
3. **描述性文字和解释说明必须使用中文**
4. **表格标题使用中文**
## 表格结构:
- 创建多个对比维度的行(根据对比事物选取最关键的特征作为维度)
- 每个对比项目都用清晰、客观的中文描述
- 专业术语可保持原文,但需要中文解释说明
- 包含详细的相似性和差异性分析
- 确保对比内容平衡且信息丰富
- 使用标准 markdown 表格格式
## 表格格式:
表格必须包含三列:
- 第一列:对比维度(中文)
- 第二列:${item1}(中文描述,术语可保持原文)
- 第三列:${item2}(中文描述,术语可保持原文)
请开始进行中文对比分析:` :
`Compare ${item1} and ${item2} in a detailed table format. ${description1 ? `Additional context for ${item1}: ${description1}` : ''
} ${description2 ? `Additional context for ${item2}: ${description2}` : ''
}
Please provide a comprehensive comparison in a markdown table format with the following structure:
- Create rows for different comparison aspects (features, pros, cons, price range, best use cases, etc.)
- Use clear, objective language
- Include both similarities and differences
- Make the comparison balanced and informative
- Format the response as a proper markdown table
The table should have three columns: Aspect, ${item1}, ${item2}`;
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
'Content-Type': 'application/json',
'HTTP-Referer': process.env.NEXT_PUBLIC_SITE_URL || 'https://anything-vs-anything.com',
'X-Title': 'Anything vs Anything',
},
body: JSON.stringify({
model: isChinese && process.env.OPENROUTER_CHINESE_MODEL
? process.env.OPENROUTER_CHINESE_MODEL
: process.env.OPENROUTER_MODEL || 'anthropic/claude-3.5-sonnet',
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 2000,
}),
});
if (!response.ok) {
throw new Error(`OpenRouter API error: ${response.status}`);
}
const data = await response.json();
const comparison = data.choices[0]?.message?.content || 'No comparison generated';
return NextResponse.json({ comparison });
} catch (error) {
console.error('Error calling OpenRouter API:', error);
return NextResponse.json(
{ error: 'Failed to generate comparison' },
{ status: 500 }
);
}
}