upload Ai
This commit is contained in:
+110
@@ -0,0 +1,110 @@
|
||||
const Router = require('koa-router');
|
||||
const fetch = require('node-fetch');
|
||||
|
||||
const router = new Router();
|
||||
|
||||
// NVIDIA API 配置
|
||||
const NVIDIA_API_KEY = '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';
|
||||
const NVIDIA_API_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
|
||||
|
||||
// 生成商品信息的 API
|
||||
router.post('/generate-product', async (ctx) => {
|
||||
try {
|
||||
const { imageUrl, keywords } = ctx.request.body;
|
||||
|
||||
if (!imageUrl && !keywords) {
|
||||
ctx.status = 400;
|
||||
ctx.body = {
|
||||
code: 400,
|
||||
message: '请提供商品图片或关键词'
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建提示词
|
||||
let prompt = '你是一个专业的便利店商品管理助手。';
|
||||
|
||||
if (imageUrl) {
|
||||
prompt += `\n请分析这张商品图片:${imageUrl}`;
|
||||
}
|
||||
|
||||
if (keywords) {
|
||||
prompt += `\n关键词:${keywords}`;
|
||||
}
|
||||
|
||||
prompt += `
|
||||
请生成商品的详细信息,返回JSON格式,不要包含其他内容:
|
||||
{
|
||||
"name": "商品名称(简洁明了,2-10字)",
|
||||
"category": "商品分类(请从以下选择:饮料,零食,日用品,食品,烟酒,其他)",
|
||||
"description": "商品详细描述(50-100字,突出产品特点)",
|
||||
"suggestedPrice": 建议售价(数字)
|
||||
}`;
|
||||
|
||||
// 调用 NVIDIA API
|
||||
const response = await fetch(NVIDIA_API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${NVIDIA_API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'deepseek-ai/deepseek-v4-pro',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt
|
||||
}
|
||||
],
|
||||
temperature: 0.7,
|
||||
max_tokens: 500
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('NVIDIA API Error:', response.status, errorText);
|
||||
throw new Error(`API 调用失败: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const aiResponse = data.choices[0].message.content;
|
||||
|
||||
// 解析 JSON 响应
|
||||
let productInfo;
|
||||
try {
|
||||
// 清理响应文本,只保留 JSON 部分
|
||||
const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
|
||||
if (jsonMatch) {
|
||||
productInfo = JSON.parse(jsonMatch[0]);
|
||||
} else {
|
||||
throw new Error('无法解析 AI 响应');
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error('JSON 解析失败:', aiResponse);
|
||||
// 如果解析失败,提供默认值
|
||||
productInfo = {
|
||||
name: keywords || '新商品',
|
||||
category: '其他',
|
||||
description: '商品描述',
|
||||
suggestedPrice: 0
|
||||
};
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 200,
|
||||
message: '生成成功',
|
||||
data: productInfo
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('生成商品信息失败:', error);
|
||||
ctx.status = 500;
|
||||
ctx.body = {
|
||||
code: 500,
|
||||
message: error.message || '生成失败,请稍后重试'
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user