import axios from 'axios' import type { Recipe, CuisineType, NutritionAnalysis, WinePairing } from '@/types' // AI服务配置 - 从环境变量读取 const AI_CONFIG = { // baseURL: 'https://api.deepseek.com/v1/', // apiKey: import.meta.env.VITE_TEXT_GENERATION_API_KEY, // model: 'deepseek-chat', // temperature: 0.7, // timeout: 300000 baseURL: 'https://open.bigmodel.cn/api/paas/v4/', apiKey: import.meta.env.VITE_IMAGE_GENERATION_API_KEY, model: 'glm-4-flash-250414', temperature: 0.7, timeout: 300000 } // 创建axios实例 const aiClient = axios.create({ baseURL: AI_CONFIG.baseURL, timeout: AI_CONFIG.timeout, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${AI_CONFIG.apiKey}` } }) /** * 调用AI接口生成菜谱 * @param ingredients 食材列表 * @param cuisine 菜系信息 * @param customPrompt 自定义提示词(可选) * @returns Promise */ export const generateRecipe = async (ingredients: string[], cuisine: CuisineType, customPrompt?: string): Promise => { try { // 构建提示词 let prompt = `${cuisine.prompt} 用户提供的食材:${ingredients.join('、')}` // 如果有自定义要求,添加到提示词中 if (customPrompt) { prompt += ` 用户的特殊要求:${customPrompt}` } prompt += ` 请按照以下JSON格式返回菜谱,不包含营养分析和酒水搭配: { "name": "菜品名称", "ingredients": ["食材1", "食材2"], "steps": [ { "step": 1, "description": "步骤描述", "time": 5, "temperature": "中火" } ], "cookingTime": 30, "difficulty": "medium", "tips": ["技巧1", "技巧2"] }` // 调用智谱AI接口 const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的厨师,请根据用户提供的食材和菜系要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。' }, { role: 'user', content: prompt } ], temperature: AI_CONFIG.temperature, stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content // 清理响应内容,提取JSON部分 let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const recipeData = JSON.parse(cleanResponse) // 构建完整的Recipe对象 const recipe: Recipe = { id: `recipe-${cuisine.id}-${Date.now()}`, name: recipeData.name || `${cuisine.name}推荐菜品`, cuisine: cuisine.name, ingredients: recipeData.ingredients || ingredients, steps: recipeData.steps || [ { step: 1, description: '准备所有食材', time: 5 }, { step: 2, description: '按照传统做法烹饪', time: 20 } ], cookingTime: recipeData.cookingTime || 25, difficulty: recipeData.difficulty || 'medium', tips: recipeData.tips || ['注意火候控制', '调味要适中'], nutritionAnalysis: undefined, winePairing: undefined } return recipe } catch (error) { console.error(`生成${cuisine.name}菜谱失败:`, error) // 抛出错误,让上层处理 throw new Error(`AI生成${cuisine.name}菜谱失败,请稍后重试`) } } /** * 生成一桌菜的菜单 * @param config 一桌菜配置 * @returns Promise */ export const generateTableMenu = async (config: { dishCount: number flexibleCount: boolean tastes: string[] cuisineStyle: string diningScene: string nutritionFocus: string customRequirement: string customDishes: string[] }): Promise< Array<{ name: string description: string category: string tags: string[] }> > => { try { // 构建提示词 const tasteText = config.tastes.length > 0 ? config.tastes.join('、') : '适中' const sceneMap = { family: '家庭聚餐', friends: '朋友聚会', romantic: '浪漫晚餐', business: '商务宴请', festival: '节日庆祝', casual: '日常用餐' } const nutritionMap = { balanced: '营养均衡', protein: '高蛋白', vegetarian: '素食为主', low_fat: '低脂健康', comfort: '滋补养生' } const styleMap = { mixed: '混合菜系', chinese: '中式为主', western: '西式为主', japanese: '日式为主' } let prompt = `请为我设计一桌菜,要求如下: - ${config.flexibleCount ? `参考菜品数量:${config.dishCount}道菜(可以根据实际情况智能调整,重点是搭配合理)` : `菜品数量:${config.dishCount}道菜(请严格按照这个数量生成)`} - 口味偏好:${tasteText} - 菜系风格:${styleMap[config.cuisineStyle] || '混合菜系'} - 用餐场景:${sceneMap[config.diningScene] || '家庭聚餐'} - 营养搭配:${nutritionMap[config.nutritionFocus] || '营养均衡'}` if (config.customDishes.length > 0) { prompt += `\n- ${config.flexibleCount ? '优先考虑的菜品' : '必须包含的菜品'}:${config.customDishes.join('、')}${ config.flexibleCount ? '(可以作为参考,根据搭配需要决定是否全部包含)' : '(请确保这些菜品都包含在菜单中)' }` } if (config.customRequirement) { prompt += `\n- 特殊要求:${config.customRequirement}` } if (config.flexibleCount) { prompt += ` 智能搭配原则: 1. 菜品数量可以灵活调整(建议在${Math.max(2, config.dishCount - 2)}-${config.dishCount + 2}道之间),重点是搭配合理、营养均衡 2. 每道菜应该有独特的特色,避免食材和口味重复过多 3. 如果指定的菜品较少或重复度高,可以适当减少总菜品数量,确保每道菜都有特色 4. 优先考虑菜品的多样性和营养搭配,而不是强制凑够指定数量 5. 合理搭配不同类型的菜品:主菜、素菜、汤品、凉菜、主食等 6. 避免出现重复搭配,每道菜都应该有独特价值` } else { prompt += ` 固定数量原则: 1. 严格按照${config.dishCount}道菜的数量生成菜单 2. 确保菜品搭配合理,营养均衡 3. 每道菜都有独特特色,尽量避免食材重复 4. 合理分配不同类型的菜品:主菜、素菜、汤品、凉菜、主食等` } prompt += ` 请按照以下JSON格式返回菜单: { "dishes": [ { "name": "菜品名称", "description": "菜品简介和特色描述", "category": "主菜/素菜/汤品/凉菜/主食/甜品", "tags": ["标签1", "标签2", "标签3"] } ] }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的菜单设计师,擅长根据不同场景和需求搭配合理的菜品组合。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答,包括菜名也要翻译成中文' }, { role: 'user', content: prompt } ], temperature: 0.8, stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const menuData = JSON.parse(cleanResponse) return menuData.dishes || [] } catch (error) { console.error('生成一桌菜菜单失败:', error) throw new Error('AI生成菜单失败,请稍后重试') } } /** * 为一桌菜中的单个菜品生成详细菜谱 * @param dishName 菜品名称 * @param dishDescription 菜品描述 * @param category 菜品分类 * @returns Promise */ export const generateDishRecipe = async (dishName: string, dishDescription: string, category: string): Promise => { try { const prompt = `请为以下菜品生成详细的菜谱: 菜品名称:${dishName} 菜品描述:${dishDescription} 菜品分类:${category} 请按照以下JSON格式返回菜谱: { "name": "菜品名称", "ingredients": ["食材1", "食材2"], "steps": [ { "step": 1, "description": "步骤描述", "time": 5, "temperature": "中火" } ], "cookingTime": 30, "difficulty": "easy/medium/hard", "tips": ["技巧1", "技巧2"] }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的厨师,请根据菜品信息生成详细的制作菜谱。请严格按照JSON格式返回,不要包含任何其他文字。' }, { role: 'user', content: prompt } ], temperature: 0.7, stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const recipeData = JSON.parse(cleanResponse) const recipe: Recipe = { id: `dish-recipe-${Date.now()}`, name: recipeData.name || dishName, cuisine: category, ingredients: recipeData.ingredients || ['主要食材', '调料'], steps: recipeData.steps || [ { step: 1, description: '准备食材', time: 5 }, { step: 2, description: '开始制作', time: 15 } ], cookingTime: recipeData.cookingTime || 20, difficulty: recipeData.difficulty || 'medium', tips: recipeData.tips || ['注意火候', '调味适中'] } return recipe } catch (error) { console.error('生成菜品菜谱失败:', error) throw new Error('AI生成菜谱失败,请稍后重试') } } // 使用自定义提示词生成菜谱 export const generateCustomRecipe = async (ingredients: string[], customPrompt: string): Promise => { try { const prompt = `你是一位专业的厨师,请根据用户提供的食材和特殊要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。 用户提供的食材:${ingredients.join('、')} 用户的特殊要求:${customPrompt} 请按照以下JSON格式返回菜谱,不包含营养分析和酒水搭配: { "name": "菜品名称", "ingredients": ["食材1", "食材2"], "steps": [ { "step": 1, "description": "步骤描述", "time": 5, "temperature": "中火" } ], "cookingTime": 30, "difficulty": "medium", "tips": ["技巧1", "技巧2"] }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的厨师,请根据用户提供的食材和特殊要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。' }, { role: 'user', content: prompt } ], temperature: AI_CONFIG.temperature, max_tokens: 2000, stream: false }) const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const recipeData = JSON.parse(cleanResponse) const recipe: Recipe = { id: `recipe-custom-${Date.now()}`, name: recipeData.name || '自定义菜品', cuisine: '自定义', ingredients: recipeData.ingredients || ingredients, steps: recipeData.steps || [ { step: 1, description: '准备所有食材', time: 5 }, { step: 2, description: '按照要求烹饪', time: 20 } ], cookingTime: recipeData.cookingTime || 25, difficulty: recipeData.difficulty || 'medium', tips: recipeData.tips || ['根据个人口味调整', '注意火候控制'], nutritionAnalysis: undefined, winePairing: undefined } return recipe } catch (error) { console.error('生成自定义菜谱失败:', error) throw new Error('AI生成自定义菜谱失败,请稍后重试') } } // 流式生成多个菜系的菜谱 export const generateMultipleRecipesStream = async ( ingredients: string[], cuisines: CuisineType[], onRecipeGenerated: (recipe: Recipe, index: number, total: number) => void, customPrompt?: string ): Promise => { const total = cuisines.length let completedCount = 0 // 为了更好的用户体验,我们不并行生成,而是依次生成 // 这样用户可以看到一个个菜谱依次完成的效果 for (let index = 0; index < cuisines.length; index++) { const cuisine = cuisines[index] try { // 添加一些随机延迟,让生成过程更自然 const delay = 1000 + Math.random() * 2000 // 1-3秒的随机延迟 await new Promise(resolve => setTimeout(resolve, delay)) const recipe = await generateRecipe(ingredients, cuisine, customPrompt) completedCount++ onRecipeGenerated(recipe, index, total) } catch (error) { console.error(`生成${cuisine.name}菜谱失败:`, error) // 即使某个菜系失败,也继续生成其他菜系 continue } } if (completedCount === 0) { throw new Error('所有菜系生成都失败了,请稍后重试') } if (completedCount < total) { console.warn(`${total - completedCount}个菜系生成失败,但已成功生成${completedCount}个菜谱`) } } /** * 获取菜谱的营养分析 * @param recipe 菜谱信息 * @returns Promise */ export const getNutritionAnalysis = async (recipe: Recipe): Promise => { try { const prompt = `请为以下菜谱生成详细的营养分析: 菜名:${recipe.name} 食材:${recipe.ingredients.join('、')} 烹饪方法:${recipe.steps.map(step => step.description).join(',')} 请按照以下JSON格式返回营养分析: { "nutrition": { "calories": 350, "protein": 25, "carbs": 45, "fat": 12, "fiber": 8, "sodium": 800, "sugar": 6, "vitaminC": 30, "calcium": 150, "iron": 3 }, "healthScore": 8, "balanceAdvice": ["建议搭配蔬菜沙拉增加维生素", "可适量减少盐分"], "dietaryTags": ["高蛋白", "低脂"], "servingSize": "1人份" }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的营养师,请根据菜谱信息生成详细的营养分析。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答,包括菜名也要翻译成中文' }, { role: 'user', content: prompt } ], temperature: 0.5, // 使用更低的temperature以获得更准确的分析 stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const nutritionData = JSON.parse(cleanResponse) return nutritionData } catch (error) { console.error('获取营养分析失败:', error) return generateFallbackNutrition(recipe.ingredients) } } /** * 获取菜谱的酒水搭配建议 * @param recipe 菜谱信息 * @returns Promise */ export const getWinePairing = async (recipe: Recipe): Promise => { try { const prompt = `请为以下菜谱推荐合适的酒水搭配: 菜名:${recipe.name} 菜系:${recipe.cuisine} 食材:${recipe.ingredients.join('、')} 请按照以下JSON格式返回酒水搭配建议: { "name": "推荐酒水名称", "type": "red_wine", "reason": "搭配理由说明", "servingTemperature": "16-18°C", "glassType": "波尔多杯", "alcoholContent": "13.5%", "flavor": "风味描述", "origin": "产地" }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位专业的侍酒师,请根据菜谱信息推荐合适的酒水搭配。请严格按照JSON格式返回,不要包含任何其他文字。' }, { role: 'user', content: prompt } ], temperature: 0.7, stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const wineData = JSON.parse(cleanResponse) return wineData } catch (error) { console.error('获取酒水搭配失败:', error) return generateFallbackWinePairing({ id: 'custom', name: recipe.cuisine } as CuisineType, recipe.ingredients) } } // 生成后备营养分析数据 const generateFallbackNutrition = (ingredients: string[]): NutritionAnalysis => { const baseCalories = ingredients.length * 50 + Math.floor(Math.random() * 100) + 200 const hasVegetables = ingredients.some(ing => ['菜', '瓜', '豆', '萝卜', '白菜', '菠菜', '西红柿', '黄瓜', '茄子', '土豆'].some(veg => ing.includes(veg))) const hasMeat = ingredients.some(ing => ['肉', '鸡', '鱼', '虾', '蛋', '牛', '猪', '羊'].some(meat => ing.includes(meat))) const hasGrains = ingredients.some(ing => ['米', '面', '粉', '饭', '面条', '馒头'].some(grain => ing.includes(grain))) const dietaryTags: string[] = [] if (hasVegetables && !hasMeat) dietaryTags.push('素食') if (hasMeat) dietaryTags.push('高蛋白') if (hasVegetables) dietaryTags.push('富含维生素') if (!hasGrains) dietaryTags.push('低碳水') if (baseCalories < 300) dietaryTags.push('低卡路里') const balanceAdvice: string[] = [] if (!hasVegetables) balanceAdvice.push('建议搭配新鲜蔬菜增加维生素和膳食纤维') if (!hasMeat && !ingredients.some(ing => ['豆', '蛋', '奶'].some(protein => ing.includes(protein)))) { balanceAdvice.push('建议增加蛋白质来源,如豆类或蛋类') } if (hasGrains && hasMeat) balanceAdvice.push('营养搭配均衡,适合日常食用') if (ingredients.length > 5) balanceAdvice.push('食材丰富,营养全面') return { nutrition: { calories: baseCalories, protein: hasMeat ? 20 + Math.floor(Math.random() * 15) : 8 + Math.floor(Math.random() * 8), carbs: hasGrains ? 35 + Math.floor(Math.random() * 20) : 15 + Math.floor(Math.random() * 10), fat: hasMeat ? 12 + Math.floor(Math.random() * 8) : 5 + Math.floor(Math.random() * 5), fiber: hasVegetables ? 6 + Math.floor(Math.random() * 4) : 2 + Math.floor(Math.random() * 2), sodium: 600 + Math.floor(Math.random() * 400), sugar: 3 + Math.floor(Math.random() * 5), vitaminC: hasVegetables ? 20 + Math.floor(Math.random() * 30) : undefined, calcium: hasMeat || ingredients.some(ing => ['奶', '豆'].some(ca => ing.includes(ca))) ? 100 + Math.floor(Math.random() * 100) : undefined, iron: hasMeat ? 2 + Math.floor(Math.random() * 3) : undefined }, healthScore: Math.floor(Math.random() * 3) + (hasVegetables ? 6 : 4) + (hasMeat ? 1 : 0), balanceAdvice: balanceAdvice.length > 0 ? balanceAdvice : ['营养搭配合理,可以放心享用'], dietaryTags: dietaryTags.length > 0 ? dietaryTags : ['家常菜'], servingSize: '1人份' } } // 生成后备酒水搭配数据 const generateFallbackWinePairing = (cuisine: CuisineType, ingredients: string[]): WinePairing => { const hasSpicy = ingredients.some(ing => ['辣椒', '花椒', '胡椒', '姜', '蒜', '洋葱'].some(spice => ing.includes(spice))) const hasMeat = ingredients.some(ing => ['肉', '鸡', '鱼', '虾', '蛋', '牛', '猪', '羊'].some(meat => ing.includes(meat))) const hasSeafood = ingredients.some(ing => ['鱼', '虾', '蟹', '贝', '海带', '紫菜'].some(seafood => ing.includes(seafood))) const isLight = ingredients.some(ing => ['菜', '瓜', '豆腐', '蛋'].some(light => ing.includes(light))) const cuisineWineMap: Record> = { 川菜大师: { name: '德国雷司令', type: 'white_wine', reason: '雷司令的甜度和酸度能很好地平衡川菜的麻辣,清洁口腔', servingTemperature: '8-10°C', glassType: '雷司令杯', alcoholContent: '11-12%', flavor: '清新果香,微甜带酸', origin: '德国莱茵河谷' }, 粤菜大师: { name: '香槟', type: 'white_wine', reason: '香槟的气泡和酸度与粤菜的清淡鲜美完美搭配', servingTemperature: '6-8°C', glassType: '香槟杯', alcoholContent: '12%', flavor: '清爽气泡,柑橘香气', origin: '法国香槟区' }, 日式料理大师: { name: '清酒', type: 'sake', reason: '清酒的清淡甘甜与日式料理的鲜美本味相得益彰', servingTemperature: '10-15°C', glassType: '清酒杯', alcoholContent: '15-16%', flavor: '清香甘甜,口感顺滑', origin: '日本' } } let winePairing = cuisineWineMap[cuisine.name] || {} if (!winePairing.name) { if (hasSpicy) { winePairing = { name: '德国雷司令', type: 'white_wine', reason: '甜白酒能很好地平衡辛辣食物,清洁口腔', servingTemperature: '8-10°C', glassType: '白酒杯', alcoholContent: '11-12%', flavor: '果香浓郁,微甜清新', origin: '德国' } } else if (hasSeafood) { winePairing = { name: '长相思白酒', type: 'white_wine', reason: '白酒的酸度和矿物质感与海鲜的鲜味完美搭配', servingTemperature: '8-10°C', glassType: '白酒杯', alcoholContent: '12-13%', flavor: '清新草本,柑橘香气', origin: '新西兰' } } else if (hasMeat && !isLight) { winePairing = { name: '赤霞珠红酒', type: 'red_wine', reason: '红酒的单宁与肉类的蛋白质结合,提升整体风味', servingTemperature: '16-18°C', glassType: '波尔多杯', alcoholContent: '13-14%', flavor: '浓郁果香,单宁丰富', origin: '法国波尔多' } } else { winePairing = { name: '绿茶', type: 'tea', reason: '绿茶的清香淡雅与清淡菜品相得益彰,有助消化', servingTemperature: '70-80°C', glassType: '茶杯', alcoholContent: '0%', flavor: '清香淡雅,回甘甜美', origin: '中国' } } } return { name: winePairing.name || '绿茶', type: winePairing.type || 'tea', reason: winePairing.reason || '经典搭配,有助消化', servingTemperature: winePairing.servingTemperature || '常温', glassType: winePairing.glassType, alcoholContent: winePairing.alcoholContent, flavor: winePairing.flavor || '清香怡人', origin: winePairing.origin } } /** * 测试AI服务连接 * @returns Promise */ export const testAIConnection = async (): Promise => { try { const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'user', content: '你好' } ], max_tokens: 10 }) return response.status === 200 } catch (error) { console.error('AI服务连接测试失败:', error) return false } } /** * 根据菜名生成详细菜谱 * @param dishName 菜品名称 * @returns Promise */ export const generateDishRecipeByName = async (dishName: string): Promise => { try { const prompt = `请为"${dishName}"这道菜生成详细的制作教程。 要求: 1. 提供完整的食材清单(包括主料和调料) 2. 详细的制作步骤,每个步骤要包含具体的时间和火候 3. 实用的烹饪技巧和注意事项 4. 如果是地方菜,请说明其特色和来源 请按照以下JSON格式返回菜谱: { "name": "菜品名称", "ingredients": ["主料1 200g", "调料1 适量", "调料2 1勺"], "steps": [ { "step": 1, "description": "详细的步骤描述,包含具体操作方法", "time": 5, "temperature": "中火/大火/小火" } ], "cookingTime": 30, "difficulty": "easy/medium/hard", "tips": ["实用技巧1", "注意事项2", "口感调节3"] }` const response = await aiClient.post('/chat/completions', { model: AI_CONFIG.model, messages: [ { role: 'system', content: '你是一位经验丰富的中华料理大师,精通各种菜系的制作方法。请根据用户提供的菜名,生成详细、实用的制作教程。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。' }, { role: 'user', content: prompt } ], temperature: 0.7, stream: false }) // 解析AI响应 const aiResponse = response.data.choices[0].message.content let cleanResponse = aiResponse.trim() if (cleanResponse.startsWith('```json')) { cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '') } else if (cleanResponse.startsWith('```')) { cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '') } const recipeData = JSON.parse(cleanResponse) // 构建完整的Recipe对象 const recipe: Recipe = { id: `dish-search-${Date.now()}`, name: recipeData.name || dishName, cuisine: '传统菜谱', ingredients: recipeData.ingredients || ['主要食材', '调料'], steps: recipeData.steps || [ { step: 1, description: '准备所有食材', time: 5 }, { step: 2, description: '按照传统方法制作', time: 20 } ], cookingTime: recipeData.cookingTime || 25, difficulty: recipeData.difficulty || 'medium', tips: recipeData.tips || ['注意火候控制', '调味要适中'], nutritionAnalysis: undefined, winePairing: undefined } return recipe } catch (error) { console.error(`生成"${dishName}"菜谱失败:`, error) throw new Error(`AI生成"${dishName}"菜谱失败,请稍后重试`) } } // 导出配置更新函数,供外部使用 export { AI_CONFIG }