aiService.ts 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  1. import axios from 'axios'
  2. import type {
  3. Recipe,
  4. CuisineType,
  5. NutritionAnalysis,
  6. WinePairing,
  7. SauceRecipe,
  8. SaucePreference,
  9. CustomSauceRequest,
  10. FortuneResult,
  11. DailyFortuneParams,
  12. MoodFortuneParams,
  13. CoupleFortuneParams,
  14. NumberFortuneParams
  15. } from '@/types'
  16. import { getTextGenerationConfig } from '@/utils/apiConfig'
  17. // 创建动态axios实例
  18. const createAiClient = () => {
  19. const config = getTextGenerationConfig()
  20. return axios.create({
  21. baseURL: config.baseUrl,
  22. timeout: config.timeout,
  23. headers: {
  24. 'Content-Type': 'application/json',
  25. Authorization: `Bearer ${config.apiKey}`
  26. }
  27. })
  28. }
  29. /**
  30. * 调用AI接口生成菜谱
  31. * @param ingredients 食材列表
  32. * @param cuisine 菜系信息
  33. * @param customPrompt 自定义提示词(可选)
  34. * @returns Promise<Recipe>
  35. */
  36. export const generateRecipe = async (ingredients: string[], cuisine: CuisineType, customPrompt?: string): Promise<Recipe> => {
  37. try {
  38. const aiClient = createAiClient()
  39. const apiConfig = getTextGenerationConfig()
  40. // 构建提示词
  41. let prompt = `${cuisine.prompt}
  42. 用户提供的食材:${ingredients.join('、')}`
  43. // 如果有自定义要求,添加到提示词中
  44. if (customPrompt) {
  45. prompt += `
  46. 用户的特殊要求:${customPrompt}`
  47. }
  48. prompt += `
  49. 请按照以下JSON格式返回菜谱,不包含营养分析和酒水搭配:
  50. {
  51. "name": "菜品名称",
  52. "ingredients": ["食材1", "食材2"],
  53. "steps": [
  54. {
  55. "step": 1,
  56. "description": "步骤描述",
  57. "time": 5,
  58. "temperature": "中火"
  59. }
  60. ],
  61. "cookingTime": 30,
  62. "difficulty": "medium",
  63. "tips": ["技巧1", "技巧2"]
  64. }`
  65. // 调用AI接口
  66. const response = await aiClient.post('/chat/completions', {
  67. model: apiConfig.model,
  68. messages: [
  69. {
  70. role: 'system',
  71. content: '你是一位专业的厨师,请根据用户提供的食材和菜系要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。'
  72. },
  73. {
  74. role: 'user',
  75. content: prompt
  76. }
  77. ],
  78. temperature: apiConfig.temperature,
  79. stream: false
  80. })
  81. // 解析AI响应
  82. const aiResponse = response.data.choices[0].message.content
  83. // 清理响应内容,提取JSON部分
  84. let cleanResponse = aiResponse.trim()
  85. if (cleanResponse.startsWith('```json')) {
  86. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  87. } else if (cleanResponse.startsWith('```')) {
  88. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  89. }
  90. const recipeData = JSON.parse(cleanResponse)
  91. // 构建完整的Recipe对象
  92. const recipe: Recipe = {
  93. id: `recipe-${cuisine.id}-${Date.now()}`,
  94. name: recipeData.name || `${cuisine.name}推荐菜品`,
  95. cuisine: cuisine.name,
  96. ingredients: recipeData.ingredients || ingredients,
  97. steps: recipeData.steps || [
  98. { step: 1, description: '准备所有食材', time: 5 },
  99. { step: 2, description: '按照传统做法烹饪', time: 20 }
  100. ],
  101. cookingTime: recipeData.cookingTime || 25,
  102. difficulty: recipeData.difficulty || 'medium',
  103. tips: recipeData.tips || ['注意火候控制', '调味要适中'],
  104. nutritionAnalysis: undefined,
  105. winePairing: undefined
  106. }
  107. return recipe
  108. } catch (error) {
  109. console.error(`生成${cuisine.name}菜谱失败:`, error)
  110. // 检查是否是400错误或其他特定错误
  111. if (error && typeof error === 'object' && 'response' in error) {
  112. const axiosError = error as any
  113. if (axiosError.response?.status === 400) {
  114. throw new Error(`${cuisine.name}表示这个食材搭配太有挑战性了`)
  115. }
  116. }
  117. // 抛出友好的错误信息
  118. throw new Error(`${cuisine.name}暂时学不会这道菜`)
  119. }
  120. }
  121. /**
  122. * 生成一桌菜的菜单
  123. * @param config 一桌菜配置
  124. * @returns Promise<DishInfo[]>
  125. */
  126. export const generateTableMenu = async (config: {
  127. dishCount: number
  128. flexibleCount: boolean
  129. tastes: string[]
  130. cuisineStyle: string
  131. diningScene: string
  132. nutritionFocus: string
  133. customRequirement: string
  134. customDishes: string[]
  135. }): Promise<
  136. Array<{
  137. name: string
  138. description: string
  139. category: string
  140. tags: string[]
  141. }>
  142. > => {
  143. try {
  144. // 构建提示词
  145. const tasteText = config.tastes.length > 0 ? config.tastes.join('、') : '适中'
  146. const sceneMap = {
  147. family: '家庭聚餐',
  148. friends: '朋友聚会',
  149. romantic: '浪漫晚餐',
  150. business: '商务宴请',
  151. festival: '节日庆祝',
  152. casual: '日常用餐'
  153. }
  154. const nutritionMap = {
  155. balanced: '营养均衡',
  156. protein: '高蛋白',
  157. vegetarian: '素食为主',
  158. low_fat: '低脂健康',
  159. comfort: '滋补养生'
  160. }
  161. const styleMap = {
  162. mixed: '混合菜系',
  163. chinese: '中式为主',
  164. western: '西式为主',
  165. japanese: '日式为主'
  166. }
  167. const styleText = (styleMap as Record<string, string>)[config.cuisineStyle] || '混合菜系'
  168. const sceneText = (sceneMap as Record<string, string>)[config.diningScene] || '家庭聚餐'
  169. const nutritionText = (nutritionMap as Record<string, string>)[config.nutritionFocus] || '营养均衡'
  170. let prompt = `请为我设计一桌菜,要求如下:
  171. - ${config.flexibleCount ? `参考菜品数量:${config.dishCount}道菜(可以根据实际情况智能调整,重点是搭配合理)` : `菜品数量:${config.dishCount}道菜(请严格按照这个数量生成)`}
  172. - 口味偏好:${tasteText}
  173. - 菜系风格:${styleText}
  174. - 用餐场景:${sceneText}
  175. - 营养搭配:${nutritionText}`
  176. if (config.customDishes.length > 0) {
  177. prompt += `\n- ${config.flexibleCount ? '优先考虑的菜品' : '必须包含的菜品'}:${config.customDishes.join('、')}${
  178. config.flexibleCount ? '(可以作为参考,根据搭配需要决定是否全部包含)' : '(请确保这些菜品都包含在菜单中)'
  179. }`
  180. }
  181. if (config.customRequirement) {
  182. prompt += `\n- 特殊要求:${config.customRequirement}`
  183. }
  184. if (config.flexibleCount) {
  185. prompt += `
  186. 智能搭配原则:
  187. 1. 菜品数量可以灵活调整(建议在${Math.max(2, config.dishCount - 2)}-${config.dishCount + 2}道之间),重点是搭配合理、营养均衡
  188. 2. 每道菜应该有独特的特色,避免食材和口味重复过多
  189. 3. 如果指定的菜品较少或重复度高,可以适当减少总菜品数量,确保每道菜都有特色
  190. 4. 优先考虑菜品的多样性和营养搭配,而不是强制凑够指定数量
  191. 5. 合理搭配不同类型的菜品:主菜、素菜、汤品、凉菜、主食等
  192. 6. 避免出现重复搭配,每道菜都应该有独特价值`
  193. } else {
  194. prompt += `
  195. 固定数量原则:
  196. 1. 严格按照${config.dishCount}道菜的数量生成菜单
  197. 2. 确保菜品搭配合理,营养均衡
  198. 3. 每道菜都有独特特色,尽量避免食材重复
  199. 4. 合理分配不同类型的菜品:主菜、素菜、汤品、凉菜、主食等`
  200. }
  201. prompt += `
  202. 请按照以下JSON格式返回菜单:
  203. {
  204. "dishes": [
  205. {
  206. "name": "菜品名称",
  207. "description": "菜品简介和特色描述",
  208. "category": "主菜/素菜/汤品/凉菜/主食/甜品",
  209. "tags": ["标签1", "标签2", "标签3"]
  210. }
  211. ]
  212. }`
  213. const aiClient = createAiClient()
  214. const apiConfig = getTextGenerationConfig()
  215. const response = await aiClient.post('/chat/completions', {
  216. model: apiConfig.model,
  217. messages: [
  218. {
  219. role: 'system',
  220. content:
  221. '你是一位专业的菜单设计师,擅长根据不同场景和需求搭配合理的菜品组合。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答,包括菜名也要翻译成中文'
  222. },
  223. {
  224. role: 'user',
  225. content: prompt
  226. }
  227. ],
  228. temperature: 0.8,
  229. stream: false
  230. })
  231. // 解析AI响应
  232. const aiResponse = response.data.choices[0].message.content
  233. let cleanResponse = aiResponse.trim()
  234. if (cleanResponse.startsWith('```json')) {
  235. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  236. } else if (cleanResponse.startsWith('```')) {
  237. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  238. }
  239. const menuData = JSON.parse(cleanResponse)
  240. return menuData.dishes || []
  241. } catch (error) {
  242. console.error('生成一桌菜菜单失败:', error)
  243. throw new Error('大厨表示这个菜单搭配太有挑战性了,请稍后重试')
  244. }
  245. }
  246. /**
  247. * 为一桌菜中的单个菜品生成详细菜谱
  248. * @param dishName 菜品名称
  249. * @param dishDescription 菜品描述
  250. * @param category 菜品分类
  251. * @returns Promise<Recipe>
  252. */
  253. export const generateDishRecipe = async (dishName: string, dishDescription: string, category: string): Promise<Recipe> => {
  254. try {
  255. const prompt = `请为以下菜品生成详细的菜谱:
  256. 菜品名称:${dishName}
  257. 菜品描述:${dishDescription}
  258. 菜品分类:${category}
  259. 请按照以下JSON格式返回菜谱:
  260. {
  261. "name": "菜品名称",
  262. "ingredients": ["食材1", "食材2"],
  263. "steps": [
  264. {
  265. "step": 1,
  266. "description": "步骤描述",
  267. "time": 5,
  268. "temperature": "中火"
  269. }
  270. ],
  271. "cookingTime": 30,
  272. "difficulty": "easy/medium/hard",
  273. "tips": ["技巧1", "技巧2"]
  274. }`
  275. const aiClient = createAiClient()
  276. const apiConfig = getTextGenerationConfig()
  277. const response = await aiClient.post('/chat/completions', {
  278. model: apiConfig.model,
  279. messages: [
  280. {
  281. role: 'system',
  282. content: '你是一位专业的厨师,请根据菜品信息生成详细的制作菜谱。请严格按照JSON格式返回,不要包含任何其他文字。'
  283. },
  284. {
  285. role: 'user',
  286. content: prompt
  287. }
  288. ],
  289. temperature: apiConfig.temperature,
  290. stream: false
  291. })
  292. // 解析AI响应
  293. const aiResponse = response.data.choices[0].message.content
  294. let cleanResponse = aiResponse.trim()
  295. if (cleanResponse.startsWith('```json')) {
  296. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  297. } else if (cleanResponse.startsWith('```')) {
  298. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  299. }
  300. const recipeData = JSON.parse(cleanResponse)
  301. const recipe: Recipe = {
  302. id: `dish-recipe-${Date.now()}`,
  303. name: recipeData.name || dishName,
  304. cuisine: category,
  305. ingredients: recipeData.ingredients || ['主要食材', '调料'],
  306. steps: recipeData.steps || [
  307. { step: 1, description: '准备食材', time: 5 },
  308. { step: 2, description: '开始制作', time: 15 }
  309. ],
  310. cookingTime: recipeData.cookingTime || 20,
  311. difficulty: recipeData.difficulty || 'medium',
  312. tips: recipeData.tips || ['注意火候', '调味适中']
  313. }
  314. return recipe
  315. } catch (error) {
  316. console.error('生成菜品菜谱失败:', error)
  317. throw new Error('大厨表示这道菜太有挑战性了,请稍后重试')
  318. }
  319. }
  320. // 使用自定义提示词生成菜谱
  321. export const generateCustomRecipe = async (ingredients: string[], customPrompt: string): Promise<Recipe> => {
  322. try {
  323. const prompt = `你是一位专业的厨师,请根据用户提供的食材和特殊要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。
  324. 用户提供的食材:${ingredients.join('、')}
  325. 用户的特殊要求:${customPrompt}
  326. 请按照以下JSON格式返回菜谱,不包含营养分析和酒水搭配:
  327. {
  328. "name": "菜品名称",
  329. "ingredients": ["食材1", "食材2"],
  330. "steps": [
  331. {
  332. "step": 1,
  333. "description": "步骤描述",
  334. "time": 5,
  335. "temperature": "中火"
  336. }
  337. ],
  338. "cookingTime": 30,
  339. "difficulty": "medium",
  340. "tips": ["技巧1", "技巧2"]
  341. }`
  342. const aiClient = createAiClient()
  343. const apiConfig = getTextGenerationConfig()
  344. const response = await aiClient.post('/chat/completions', {
  345. model: apiConfig.model,
  346. messages: [
  347. {
  348. role: 'system',
  349. content: '你是一位专业的厨师,请根据用户提供的食材和特殊要求,生成详细的菜谱。请严格按照JSON格式返回,不要包含任何其他文字。'
  350. },
  351. {
  352. role: 'user',
  353. content: prompt
  354. }
  355. ],
  356. temperature: apiConfig.temperature,
  357. max_tokens: 2000,
  358. stream: false
  359. })
  360. const aiResponse = response.data.choices[0].message.content
  361. let cleanResponse = aiResponse.trim()
  362. if (cleanResponse.startsWith('```json')) {
  363. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  364. } else if (cleanResponse.startsWith('```')) {
  365. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  366. }
  367. const recipeData = JSON.parse(cleanResponse)
  368. const recipe: Recipe = {
  369. id: `recipe-custom-${Date.now()}`,
  370. name: recipeData.name || '自定义菜品',
  371. cuisine: '自定义',
  372. ingredients: recipeData.ingredients || ingredients,
  373. steps: recipeData.steps || [
  374. { step: 1, description: '准备所有食材', time: 5 },
  375. { step: 2, description: '按照要求烹饪', time: 20 }
  376. ],
  377. cookingTime: recipeData.cookingTime || 25,
  378. difficulty: recipeData.difficulty || 'medium',
  379. tips: recipeData.tips || ['根据个人口味调整', '注意火候控制'],
  380. nutritionAnalysis: undefined,
  381. winePairing: undefined
  382. }
  383. return recipe
  384. } catch (error) {
  385. console.error('生成自定义菜谱失败:', error)
  386. throw new Error('大厨表示这个自定义要求太有挑战性了,请稍后重试')
  387. }
  388. }
  389. // 流式生成多个菜系的菜谱
  390. export const generateMultipleRecipesStream = async (
  391. ingredients: string[],
  392. cuisines: CuisineType[],
  393. onRecipeGenerated: (recipe: Recipe, index: number, total: number) => void,
  394. onRecipeError?: (error: Error, index: number, cuisine: CuisineType, total: number) => void,
  395. customPrompt?: string
  396. ): Promise<void> => {
  397. const total = cuisines.length
  398. let completedCount = 0
  399. // 为了更好的用户体验,我们不并行生成,而是依次生成
  400. // 这样用户可以看到一个个菜谱依次完成的效果
  401. for (let index = 0; index < cuisines.length; index++) {
  402. const cuisine = cuisines[index]
  403. try {
  404. // 添加一些随机延迟,让生成过程更自然
  405. const delay = 1000 + Math.random() * 2000 // 1-3秒的随机延迟
  406. await new Promise(resolve => setTimeout(resolve, delay))
  407. const recipe = await generateRecipe(ingredients, cuisine, customPrompt)
  408. completedCount++
  409. onRecipeGenerated(recipe, index, total)
  410. } catch (error) {
  411. console.error(`生成${cuisine.name}菜谱失败:`, error)
  412. // 调用错误回调,让前端可以显示友好的错误信息
  413. if (onRecipeError) {
  414. const friendlyError = new Error(`${cuisine.name}不会这道菜,哈哈`)
  415. onRecipeError(friendlyError, index, cuisine, total)
  416. }
  417. // 即使某个菜系失败,也继续生成其他菜系
  418. continue
  419. }
  420. }
  421. if (completedCount === 0) {
  422. throw new Error('所有菜系生成都失败了,请稍后重试')
  423. }
  424. if (completedCount < total) {
  425. console.warn(`${total - completedCount}个菜系生成失败,但已成功生成${completedCount}个菜谱`)
  426. }
  427. }
  428. /**
  429. * 获取菜谱的营养分析
  430. * @param recipe 菜谱信息
  431. * @returns Promise<NutritionAnalysis>
  432. */
  433. export const getNutritionAnalysis = async (recipe: Recipe): Promise<NutritionAnalysis> => {
  434. try {
  435. const prompt = `请为以下菜谱生成详细的营养分析:
  436. 菜名:${recipe.name}
  437. 食材:${recipe.ingredients.join('、')}
  438. 烹饪方法:${recipe.steps.map(step => step.description).join(',')}
  439. 请按照以下JSON格式返回营养分析:
  440. {
  441. "nutrition": {
  442. "calories": 350,
  443. "protein": 25,
  444. "carbs": 45,
  445. "fat": 12,
  446. "fiber": 8,
  447. "sodium": 800,
  448. "sugar": 6,
  449. "vitaminC": 30,
  450. "calcium": 150,
  451. "iron": 3
  452. },
  453. "healthScore": 8,
  454. "balanceAdvice": ["建议搭配蔬菜沙拉增加维生素", "可适量减少盐分"],
  455. "dietaryTags": ["高蛋白", "低脂"],
  456. "servingSize": "1人份"
  457. }`
  458. const aiClient = createAiClient()
  459. const apiConfig = getTextGenerationConfig()
  460. const response = await aiClient.post('/chat/completions', {
  461. model: apiConfig.model,
  462. messages: [
  463. {
  464. role: 'system',
  465. content: '你是一位专业的营养师,请根据菜谱信息生成详细的营养分析。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答,包括菜名也要翻译成中文'
  466. },
  467. {
  468. role: 'user',
  469. content: prompt
  470. }
  471. ],
  472. temperature: 0.5, // 使用更低的temperature以获得更准确的分析
  473. stream: false
  474. })
  475. // 解析AI响应
  476. const aiResponse = response.data.choices[0].message.content
  477. let cleanResponse = aiResponse.trim()
  478. if (cleanResponse.startsWith('```json')) {
  479. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  480. } else if (cleanResponse.startsWith('```')) {
  481. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  482. }
  483. const nutritionData = JSON.parse(cleanResponse)
  484. return nutritionData
  485. } catch (error) {
  486. console.error('获取营养分析失败:', error)
  487. return generateFallbackNutrition(recipe.ingredients)
  488. }
  489. }
  490. /**
  491. * 获取菜谱的酒水搭配建议
  492. * @param recipe 菜谱信息
  493. * @returns Promise<WinePairing>
  494. */
  495. export const getWinePairing = async (recipe: Recipe): Promise<WinePairing> => {
  496. try {
  497. const prompt = `请为以下菜谱推荐合适的酒水搭配:
  498. 菜名:${recipe.name}
  499. 菜系:${recipe.cuisine}
  500. 食材:${recipe.ingredients.join('、')}
  501. 请按照以下JSON格式返回酒水搭配建议:
  502. {
  503. "name": "推荐酒水名称",
  504. "type": "red_wine",
  505. "reason": "搭配理由说明",
  506. "servingTemperature": "16-18°C",
  507. "glassType": "波尔多杯",
  508. "alcoholContent": "13.5%",
  509. "flavor": "风味描述",
  510. "origin": "产地"
  511. }`
  512. const aiClient = createAiClient()
  513. const apiConfig = getTextGenerationConfig()
  514. const response = await aiClient.post('/chat/completions', {
  515. model: apiConfig.model,
  516. messages: [
  517. {
  518. role: 'system',
  519. content: '你是一位专业的侍酒师,请根据菜谱信息推荐合适的酒水搭配。请严格按照JSON格式返回,不要包含任何其他文字。'
  520. },
  521. {
  522. role: 'user',
  523. content: prompt
  524. }
  525. ],
  526. temperature: 0.7,
  527. stream: false
  528. })
  529. // 解析AI响应
  530. const aiResponse = response.data.choices[0].message.content
  531. let cleanResponse = aiResponse.trim()
  532. if (cleanResponse.startsWith('```json')) {
  533. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  534. } else if (cleanResponse.startsWith('```')) {
  535. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  536. }
  537. const wineData = JSON.parse(cleanResponse)
  538. return wineData
  539. } catch (error) {
  540. console.error('获取酒水搭配失败:', error)
  541. return generateFallbackWinePairing({ id: 'custom', name: recipe.cuisine } as CuisineType, recipe.ingredients)
  542. }
  543. }
  544. // 生成后备营养分析数据
  545. const generateFallbackNutrition = (ingredients: string[]): NutritionAnalysis => {
  546. const baseCalories = ingredients.length * 50 + Math.floor(Math.random() * 100) + 200
  547. const hasVegetables = ingredients.some(ing => ['菜', '瓜', '豆', '萝卜', '白菜', '菠菜', '西红柿', '黄瓜', '茄子', '土豆'].some(veg => ing.includes(veg)))
  548. const hasMeat = ingredients.some(ing => ['肉', '鸡', '鱼', '虾', '蛋', '牛', '猪', '羊'].some(meat => ing.includes(meat)))
  549. const hasGrains = ingredients.some(ing => ['米', '面', '粉', '饭', '面条', '馒头'].some(grain => ing.includes(grain)))
  550. const dietaryTags: string[] = []
  551. if (hasVegetables && !hasMeat) dietaryTags.push('素食')
  552. if (hasMeat) dietaryTags.push('高蛋白')
  553. if (hasVegetables) dietaryTags.push('富含维生素')
  554. if (!hasGrains) dietaryTags.push('低碳水')
  555. if (baseCalories < 300) dietaryTags.push('低卡路里')
  556. const balanceAdvice: string[] = []
  557. if (!hasVegetables) balanceAdvice.push('建议搭配新鲜蔬菜增加维生素和膳食纤维')
  558. if (!hasMeat && !ingredients.some(ing => ['豆', '蛋', '奶'].some(protein => ing.includes(protein)))) {
  559. balanceAdvice.push('建议增加蛋白质来源,如豆类或蛋类')
  560. }
  561. if (hasGrains && hasMeat) balanceAdvice.push('营养搭配均衡,适合日常食用')
  562. if (ingredients.length > 5) balanceAdvice.push('食材丰富,营养全面')
  563. return {
  564. nutrition: {
  565. calories: baseCalories,
  566. protein: hasMeat ? 20 + Math.floor(Math.random() * 15) : 8 + Math.floor(Math.random() * 8),
  567. carbs: hasGrains ? 35 + Math.floor(Math.random() * 20) : 15 + Math.floor(Math.random() * 10),
  568. fat: hasMeat ? 12 + Math.floor(Math.random() * 8) : 5 + Math.floor(Math.random() * 5),
  569. fiber: hasVegetables ? 6 + Math.floor(Math.random() * 4) : 2 + Math.floor(Math.random() * 2),
  570. sodium: 600 + Math.floor(Math.random() * 400),
  571. sugar: 3 + Math.floor(Math.random() * 5),
  572. vitaminC: hasVegetables ? 20 + Math.floor(Math.random() * 30) : undefined,
  573. calcium: hasMeat || ingredients.some(ing => ['奶', '豆'].some(ca => ing.includes(ca))) ? 100 + Math.floor(Math.random() * 100) : undefined,
  574. iron: hasMeat ? 2 + Math.floor(Math.random() * 3) : undefined
  575. },
  576. healthScore: Math.floor(Math.random() * 3) + (hasVegetables ? 6 : 4) + (hasMeat ? 1 : 0),
  577. balanceAdvice: balanceAdvice.length > 0 ? balanceAdvice : ['营养搭配合理,可以放心享用'],
  578. dietaryTags: dietaryTags.length > 0 ? dietaryTags : ['家常菜'],
  579. servingSize: '1人份'
  580. }
  581. }
  582. // 生成后备酒水搭配数据
  583. const generateFallbackWinePairing = (cuisine: CuisineType, ingredients: string[]): WinePairing => {
  584. const hasSpicy = ingredients.some(ing => ['辣椒', '花椒', '胡椒', '姜', '蒜', '洋葱'].some(spice => ing.includes(spice)))
  585. const hasMeat = ingredients.some(ing => ['肉', '鸡', '鱼', '虾', '蛋', '牛', '猪', '羊'].some(meat => ing.includes(meat)))
  586. const hasSeafood = ingredients.some(ing => ['鱼', '虾', '蟹', '贝', '海带', '紫菜'].some(seafood => ing.includes(seafood)))
  587. const isLight = ingredients.some(ing => ['菜', '瓜', '豆腐', '蛋'].some(light => ing.includes(light)))
  588. const cuisineWineMap: Record<string, Partial<WinePairing>> = {
  589. 川菜大师: {
  590. name: '德国雷司令',
  591. type: 'white_wine',
  592. reason: '雷司令的甜度和酸度能很好地平衡川菜的麻辣,清洁口腔',
  593. servingTemperature: '8-10°C',
  594. glassType: '雷司令杯',
  595. alcoholContent: '11-12%',
  596. flavor: '清新果香,微甜带酸',
  597. origin: '德国莱茵河谷'
  598. },
  599. 粤菜大师: {
  600. name: '香槟',
  601. type: 'white_wine',
  602. reason: '香槟的气泡和酸度与粤菜的清淡鲜美完美搭配',
  603. servingTemperature: '6-8°C',
  604. glassType: '香槟杯',
  605. alcoholContent: '12%',
  606. flavor: '清爽气泡,柑橘香气',
  607. origin: '法国香槟区'
  608. },
  609. 日式料理大师: {
  610. name: '清酒',
  611. type: 'sake',
  612. reason: '清酒的清淡甘甜与日式料理的鲜美本味相得益彰',
  613. servingTemperature: '10-15°C',
  614. glassType: '清酒杯',
  615. alcoholContent: '15-16%',
  616. flavor: '清香甘甜,口感顺滑',
  617. origin: '日本'
  618. }
  619. }
  620. let winePairing = cuisineWineMap[cuisine.name] || {}
  621. if (!winePairing.name) {
  622. if (hasSpicy) {
  623. winePairing = {
  624. name: '德国雷司令',
  625. type: 'white_wine',
  626. reason: '甜白酒能很好地平衡辛辣食物,清洁口腔',
  627. servingTemperature: '8-10°C',
  628. glassType: '白酒杯',
  629. alcoholContent: '11-12%',
  630. flavor: '果香浓郁,微甜清新',
  631. origin: '德国'
  632. }
  633. } else if (hasSeafood) {
  634. winePairing = {
  635. name: '长相思白酒',
  636. type: 'white_wine',
  637. reason: '白酒的酸度和矿物质感与海鲜的鲜味完美搭配',
  638. servingTemperature: '8-10°C',
  639. glassType: '白酒杯',
  640. alcoholContent: '12-13%',
  641. flavor: '清新草本,柑橘香气',
  642. origin: '新西兰'
  643. }
  644. } else if (hasMeat && !isLight) {
  645. winePairing = {
  646. name: '赤霞珠红酒',
  647. type: 'red_wine',
  648. reason: '红酒的单宁与肉类的蛋白质结合,提升整体风味',
  649. servingTemperature: '16-18°C',
  650. glassType: '波尔多杯',
  651. alcoholContent: '13-14%',
  652. flavor: '浓郁果香,单宁丰富',
  653. origin: '法国波尔多'
  654. }
  655. } else {
  656. winePairing = {
  657. name: '绿茶',
  658. type: 'tea',
  659. reason: '绿茶的清香淡雅与清淡菜品相得益彰,有助消化',
  660. servingTemperature: '70-80°C',
  661. glassType: '茶杯',
  662. alcoholContent: '0%',
  663. flavor: '清香淡雅,回甘甜美',
  664. origin: '中国'
  665. }
  666. }
  667. }
  668. return {
  669. name: winePairing.name || '绿茶',
  670. type: winePairing.type || 'tea',
  671. reason: winePairing.reason || '经典搭配,有助消化',
  672. servingTemperature: winePairing.servingTemperature || '常温',
  673. glassType: winePairing.glassType,
  674. alcoholContent: winePairing.alcoholContent,
  675. flavor: winePairing.flavor || '清香怡人',
  676. origin: winePairing.origin
  677. }
  678. }
  679. /**
  680. * 测试AI服务连接
  681. * @returns Promise<boolean>
  682. */
  683. export const testAIConnection = async (): Promise<boolean> => {
  684. try {
  685. const aiClient = createAiClient()
  686. const apiConfig = getTextGenerationConfig()
  687. const response = await aiClient.post('/chat/completions', {
  688. model: apiConfig.model,
  689. messages: [
  690. {
  691. role: 'user',
  692. content: '你好'
  693. }
  694. ],
  695. max_tokens: 10
  696. })
  697. return response.status === 200
  698. } catch (error) {
  699. console.error('AI服务连接测试失败:', error)
  700. return false
  701. }
  702. }
  703. /**
  704. * 根据菜名生成详细菜谱
  705. * @param dishName 菜品名称
  706. * @returns Promise<Recipe>
  707. */
  708. export const generateDishRecipeByName = async (dishName: string): Promise<Recipe> => {
  709. try {
  710. const prompt = `请为"${dishName}"这道菜生成详细的制作教程。
  711. 要求:
  712. 1. 提供完整的食材清单(包括主料和调料)
  713. 2. 详细的制作步骤,每个步骤要包含具体的时间和火候
  714. 3. 实用的烹饪技巧和注意事项
  715. 4. 如果是地方菜,请说明其特色和来源
  716. 请按照以下JSON格式返回菜谱:
  717. {
  718. "name": "菜品名称",
  719. "ingredients": ["主料1 200g", "调料1 适量", "调料2 1勺"],
  720. "steps": [
  721. {
  722. "step": 1,
  723. "description": "详细的步骤描述,包含具体操作方法",
  724. "time": 5,
  725. "temperature": "中火/大火/小火"
  726. }
  727. ],
  728. "cookingTime": 30,
  729. "difficulty": "easy/medium/hard",
  730. "tips": ["实用技巧1", "注意事项2", "口感调节3"]
  731. }`
  732. const aiClient = createAiClient()
  733. const apiConfig = getTextGenerationConfig()
  734. const response = await aiClient.post('/chat/completions', {
  735. model: apiConfig.model,
  736. messages: [
  737. {
  738. role: 'system',
  739. content:
  740. '你是一位经验丰富的中华料理大师,精通各种菜系的制作方法。请根据用户提供的菜名,生成详细、实用的制作教程。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  741. },
  742. {
  743. role: 'user',
  744. content: prompt
  745. }
  746. ],
  747. temperature: 0.7,
  748. stream: false
  749. })
  750. // 解析AI响应
  751. const aiResponse = response.data.choices[0].message.content
  752. let cleanResponse = aiResponse.trim()
  753. if (cleanResponse.startsWith('```json')) {
  754. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  755. } else if (cleanResponse.startsWith('```')) {
  756. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  757. }
  758. const recipeData = JSON.parse(cleanResponse)
  759. // 构建完整的Recipe对象
  760. const recipe: Recipe = {
  761. id: `dish-search-${Date.now()}`,
  762. name: recipeData.name || dishName,
  763. cuisine: '传统菜谱',
  764. ingredients: recipeData.ingredients || ['主要食材', '调料'],
  765. steps: recipeData.steps || [
  766. { step: 1, description: '准备所有食材', time: 5 },
  767. { step: 2, description: '按照传统方法制作', time: 20 }
  768. ],
  769. cookingTime: recipeData.cookingTime || 25,
  770. difficulty: recipeData.difficulty || 'medium',
  771. tips: recipeData.tips || ['注意火候控制', '调味要适中'],
  772. nutritionAnalysis: undefined,
  773. winePairing: undefined
  774. }
  775. return recipe
  776. } catch (error) {
  777. console.error(`生成"${dishName}"菜谱失败:`, error)
  778. throw new Error(`大厨表示"${dishName}"这道菜太有挑战性了,请稍后重试`)
  779. }
  780. }
  781. /**
  782. * 根据酱料名称生成详细制作方法
  783. * @param sauceName 酱料名称
  784. * @returns Promise<SauceRecipe>
  785. */
  786. export const generateSauceRecipe = async (sauceName: string): Promise<SauceRecipe> => {
  787. try {
  788. const prompt = `请为"${sauceName}"这种酱料生成详细的制作教程。
  789. 要求:
  790. 1. 提供完整的食材清单(主料、辅料、调料)
  791. 2. 详细的制作步骤,包含具体操作方法、时间、温度控制
  792. 3. 实用的制作技巧和注意事项
  793. 4. 保存方法和保质期信息
  794. 5. 推荐的搭配菜品
  795. 6. 口味特点描述
  796. 请按照以下JSON格式返回酱料配方:
  797. {
  798. "name": "酱料名称",
  799. "category": "spicy/garlic/sweet/complex/regional/fusion",
  800. "ingredients": ["主料1 200g", "调料1 适量", "调料2 1勺"],
  801. "steps": [
  802. {
  803. "step": 1,
  804. "description": "详细的步骤描述",
  805. "time": 5,
  806. "temperature": "中火",
  807. "technique": "炒制"
  808. }
  809. ],
  810. "makingTime": 30,
  811. "difficulty": "easy/medium/hard",
  812. "tips": ["制作技巧1", "注意事项2"],
  813. "storage": {
  814. "method": "密封冷藏",
  815. "duration": "1个月",
  816. "temperature": "4°C"
  817. },
  818. "pairings": ["搭配菜品1", "搭配菜品2"],
  819. "tags": ["标签1", "标签2"],
  820. "spiceLevel": 3,
  821. "sweetLevel": 1,
  822. "saltLevel": 4,
  823. "sourLevel": 2,
  824. "description": "酱料特色描述"
  825. }`
  826. const aiClient = createAiClient()
  827. const apiConfig = getTextGenerationConfig()
  828. const response = await aiClient.post('/chat/completions', {
  829. model: apiConfig.model,
  830. messages: [
  831. {
  832. role: 'system',
  833. content:
  834. '你是一位专业的酱料制作大师,精通各种传统和创新酱料的制作方法。请根据用户提供的酱料名称,生成详细、实用的制作教程。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  835. },
  836. {
  837. role: 'user',
  838. content: prompt
  839. }
  840. ],
  841. temperature: 0.7,
  842. stream: false
  843. })
  844. const aiResponse = response.data.choices[0].message.content
  845. let cleanResponse = aiResponse.trim()
  846. if (cleanResponse.startsWith('```json')) {
  847. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  848. } else if (cleanResponse.startsWith('```')) {
  849. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  850. }
  851. const sauceData = JSON.parse(cleanResponse)
  852. const sauceRecipe: SauceRecipe = {
  853. id: `sauce-${Date.now()}`,
  854. name: sauceData.name || sauceName,
  855. category: sauceData.category || 'complex',
  856. ingredients: sauceData.ingredients || ['主要食材', '调料'],
  857. steps: sauceData.steps || [
  858. { step: 1, description: '准备所有食材', time: 5 },
  859. { step: 2, description: '按照传统方法制作', time: 20 }
  860. ],
  861. makingTime: sauceData.makingTime || 25,
  862. difficulty: sauceData.difficulty || 'medium',
  863. tips: sauceData.tips || ['注意火候控制', '调味要适中'],
  864. storage: sauceData.storage || {
  865. method: '密封保存',
  866. duration: '1周',
  867. temperature: '常温'
  868. },
  869. pairings: sauceData.pairings || ['面条', '蔬菜'],
  870. tags: sauceData.tags || ['家常', '经典'],
  871. spiceLevel: sauceData.spiceLevel || 2,
  872. sweetLevel: sauceData.sweetLevel || 2,
  873. saltLevel: sauceData.saltLevel || 3,
  874. sourLevel: sauceData.sourLevel || 2,
  875. description: sauceData.description || '经典酱料配方'
  876. }
  877. return sauceRecipe
  878. } catch (error) {
  879. console.error(`生成"${sauceName}"酱料配方失败:`, error)
  880. throw new Error(`酱料大师表示"${sauceName}"这个配方太有挑战性了,请稍后重试`)
  881. }
  882. }
  883. /**
  884. * 根据用户偏好推荐酱料
  885. * @param preferences 用户偏好配置
  886. * @returns Promise<string[]>
  887. */
  888. export const recommendSauces = async (preferences: SaucePreference): Promise<string[]> => {
  889. try {
  890. const useCaseMap = {
  891. noodles: '拌面',
  892. dipping: '蘸菜',
  893. cooking: '炒菜',
  894. bbq: '烧烤',
  895. hotpot: '火锅'
  896. }
  897. const useCaseText = preferences.useCase.map(uc => (useCaseMap as Record<string, string>)[uc] || uc).join('、')
  898. const ingredientsText = preferences.availableIngredients.length > 0 ? preferences.availableIngredients.join('、') : '无特殊要求'
  899. const prompt = `请根据以下用户偏好推荐合适的酱料:
  900. 用户偏好:
  901. - 辣度偏好:${preferences.spiceLevel}/5
  902. - 甜度偏好:${preferences.sweetLevel}/5
  903. - 咸度偏好:${preferences.saltLevel}/5
  904. - 酸度偏好:${preferences.sourLevel}/5
  905. - 使用场景:${useCaseText}
  906. - 现有食材:${ingredientsText}
  907. 请推荐5-8种最适合的酱料,按匹配度排序。
  908. 请按照以下JSON格式返回推荐结果:
  909. {
  910. "recommendations": [
  911. "酱料名称1",
  912. "酱料名称2",
  913. "酱料名称3"
  914. ]
  915. }`
  916. const aiClient = createAiClient()
  917. const apiConfig = getTextGenerationConfig()
  918. const response = await aiClient.post('/chat/completions', {
  919. model: apiConfig.model,
  920. messages: [
  921. {
  922. role: 'system',
  923. content: '你是一位专业的酱料推荐专家,能够根据用户的口味偏好和使用场景推荐最合适的酱料。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  924. },
  925. {
  926. role: 'user',
  927. content: prompt
  928. }
  929. ],
  930. temperature: 0.8,
  931. stream: false
  932. })
  933. const aiResponse = response.data.choices[0].message.content
  934. let cleanResponse = aiResponse.trim()
  935. if (cleanResponse.startsWith('```json')) {
  936. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  937. } else if (cleanResponse.startsWith('```')) {
  938. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  939. }
  940. const recommendationData = JSON.parse(cleanResponse)
  941. return recommendationData.recommendations || []
  942. } catch (error) {
  943. console.error('获取酱料推荐失败:', error)
  944. throw new Error('酱料大师暂时想不出好的推荐,请稍后重试')
  945. }
  946. }
  947. /**
  948. * 创建自定义酱料配方
  949. * @param request 自定义酱料创作请求
  950. * @returns Promise<SauceRecipe>
  951. */
  952. export const createCustomSauce = async (request: CustomSauceRequest): Promise<SauceRecipe> => {
  953. try {
  954. const baseTypeMap = {
  955. oil: '油性酱料',
  956. water: '水性酱料',
  957. paste: '膏状酱料',
  958. granular: '颗粒状酱料'
  959. }
  960. const flavorMap = {
  961. spicy: '辣味',
  962. sweet: '甜味',
  963. sour: '酸味',
  964. umami: '鲜味',
  965. aromatic: '香味'
  966. }
  967. const prompt = `请根据以下要求创作一个独特的酱料配方:
  968. 创作要求:
  969. - 基础类型:${baseTypeMap[request.baseType]}
  970. - 主要风味:${flavorMap[request.flavorDirection]}
  971. - 特殊食材:${request.specialIngredients.join('、')}
  972. - 期望口感:${request.expectedTexture}
  973. - 用途:${request.intendedUse}
  974. ${request.customRequirements ? `- 特殊要求:${request.customRequirements}` : ''}
  975. 请创作一个创新的酱料配方,要有独特性和实用性。
  976. 请按照以下JSON格式返回酱料配方:
  977. {
  978. "name": "创新酱料名称",
  979. "category": "fusion",
  980. "ingredients": ["主料1 200g", "调料1 适量"],
  981. "steps": [
  982. {
  983. "step": 1,
  984. "description": "详细步骤描述",
  985. "time": 5,
  986. "temperature": "中火",
  987. "technique": "制作技法"
  988. }
  989. ],
  990. "makingTime": 30,
  991. "difficulty": "medium",
  992. "tips": ["创作技巧1", "注意事项2"],
  993. "storage": {
  994. "method": "保存方法",
  995. "duration": "保质期",
  996. "temperature": "保存温度"
  997. },
  998. "pairings": ["搭配建议1", "搭配建议2"],
  999. "tags": ["创新", "自制"],
  1000. "spiceLevel": 3,
  1001. "sweetLevel": 2,
  1002. "saltLevel": 3,
  1003. "sourLevel": 2,
  1004. "description": "创新酱料特色描述"
  1005. }`
  1006. const aiClient = createAiClient()
  1007. const apiConfig = getTextGenerationConfig()
  1008. const response = await aiClient.post('/chat/completions', {
  1009. model: apiConfig.model,
  1010. messages: [
  1011. {
  1012. role: 'system',
  1013. content: '你是一位富有创意的酱料创作大师,擅长根据用户需求创作独特的酱料配方。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  1014. },
  1015. {
  1016. role: 'user',
  1017. content: prompt
  1018. }
  1019. ],
  1020. temperature: 0.9,
  1021. stream: false
  1022. })
  1023. const aiResponse = response.data.choices[0].message.content
  1024. let cleanResponse = aiResponse.trim()
  1025. if (cleanResponse.startsWith('```json')) {
  1026. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1027. } else if (cleanResponse.startsWith('```')) {
  1028. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1029. }
  1030. const sauceData = JSON.parse(cleanResponse)
  1031. const customSauce: SauceRecipe = {
  1032. id: `custom-sauce-${Date.now()}`,
  1033. name: sauceData.name || '自创酱料',
  1034. category: 'fusion',
  1035. ingredients: sauceData.ingredients || ['创新食材'],
  1036. steps: sauceData.steps || [
  1037. { step: 1, description: '准备创新食材', time: 5 },
  1038. { step: 2, description: '按照创意方法制作', time: 20 }
  1039. ],
  1040. makingTime: sauceData.makingTime || 25,
  1041. difficulty: sauceData.difficulty || 'medium',
  1042. tips: sauceData.tips || ['发挥创意', '调整口味'],
  1043. storage: sauceData.storage || {
  1044. method: '密封保存',
  1045. duration: '1周',
  1046. temperature: '冷藏'
  1047. },
  1048. pairings: sauceData.pairings || ['创意搭配'],
  1049. tags: sauceData.tags || ['创新', '自制'],
  1050. spiceLevel: sauceData.spiceLevel || 2,
  1051. sweetLevel: sauceData.sweetLevel || 2,
  1052. saltLevel: sauceData.saltLevel || 3,
  1053. sourLevel: sauceData.sourLevel || 2,
  1054. description: sauceData.description || '独特的自创酱料'
  1055. }
  1056. return customSauce
  1057. } catch (error) {
  1058. console.error('创建自定义酱料失败:', error)
  1059. throw new Error('酱料大师表示这个自定义配方太有挑战性了,请稍后重试')
  1060. }
  1061. }
  1062. /**
  1063. * 获取酱料搭配建议
  1064. * @param sauceName 酱料名称
  1065. * @returns Promise<string[]>
  1066. */
  1067. export const getSaucePairings = async (sauceName: string): Promise<string[]> => {
  1068. try {
  1069. const prompt = `请为"${sauceName}"这种酱料推荐最佳的搭配菜品和使用方法。
  1070. 要求:
  1071. 1. 推荐5-8种最适合的搭配菜品
  1072. 2. 说明具体的使用方法
  1073. 3. 考虑不同的烹饪场景
  1074. 请按照以下JSON格式返回搭配建议:
  1075. {
  1076. "pairings": [
  1077. "搭配菜品1 - 使用方法",
  1078. "搭配菜品2 - 使用方法",
  1079. "搭配菜品3 - 使用方法"
  1080. ]
  1081. }`
  1082. const aiClient = createAiClient()
  1083. const apiConfig = getTextGenerationConfig()
  1084. const response = await aiClient.post('/chat/completions', {
  1085. model: apiConfig.model,
  1086. messages: [
  1087. {
  1088. role: 'system',
  1089. content: '你是一位专业的美食搭配专家,精通各种酱料与菜品的最佳搭配方法。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  1090. },
  1091. {
  1092. role: 'user',
  1093. content: prompt
  1094. }
  1095. ],
  1096. temperature: 0.7,
  1097. stream: false
  1098. })
  1099. const aiResponse = response.data.choices[0].message.content
  1100. let cleanResponse = aiResponse.trim()
  1101. if (cleanResponse.startsWith('```json')) {
  1102. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1103. } else if (cleanResponse.startsWith('```')) {
  1104. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1105. }
  1106. const pairingData = JSON.parse(cleanResponse)
  1107. return pairingData.pairings || []
  1108. } catch (error) {
  1109. console.error('获取酱料搭配建议失败:', error)
  1110. return ['面条 - 拌面使用', '蔬菜 - 蘸食使用', '肉类 - 调味使用']
  1111. }
  1112. }
  1113. /**
  1114. * 生成今日运势菜
  1115. * @param params 运势参数
  1116. * @returns Promise<FortuneResult>
  1117. */
  1118. export const generateDailyFortune = async (params: DailyFortuneParams): Promise<FortuneResult> => {
  1119. try {
  1120. const prompt = `你是一位神秘的料理占卜师,请根据以下信息为用户推荐今日幸运菜:
  1121. 星座:${params.zodiac}
  1122. 生肖:${params.animal}
  1123. 日期:${params.date}
  1124. 请结合星座特性、生肖属性和今日能量,推荐一道能带来好运的菜品。
  1125. 请按照以下JSON格式返回占卜结果:
  1126. {
  1127. "dishName": "菜品名称",
  1128. "reason": "选择这道菜的占卜理由",
  1129. "luckyIndex": 8,
  1130. "description": "详细的占卜解析和菜品介绍",
  1131. "tips": ["烹饪技巧1", "幸运提示2"],
  1132. "difficulty": "medium",
  1133. "cookingTime": 30,
  1134. "mysticalMessage": "神秘的占卜师话语",
  1135. "ingredients": ["主要食材1", "主要食材2"],
  1136. "steps": ["制作步骤1", "制作步骤2"]
  1137. }`
  1138. const aiClient = createAiClient()
  1139. const apiConfig = getTextGenerationConfig()
  1140. const response = await aiClient.post('/chat/completions', {
  1141. model: apiConfig.model,
  1142. messages: [
  1143. {
  1144. role: 'system',
  1145. content:
  1146. '你是一位神秘而智慧的料理占卜师,精通星座学、生肖学和美食文化。你的话语充满神秘色彩,善于将占卜元素与美食完美结合。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  1147. },
  1148. {
  1149. role: 'user',
  1150. content: prompt
  1151. }
  1152. ],
  1153. temperature: 0.8,
  1154. stream: false
  1155. })
  1156. const aiResponse = response.data.choices[0].message.content
  1157. let cleanResponse = aiResponse.trim()
  1158. if (cleanResponse.startsWith('```json')) {
  1159. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1160. } else if (cleanResponse.startsWith('```')) {
  1161. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1162. }
  1163. const fortuneData = JSON.parse(cleanResponse)
  1164. const fortune: FortuneResult = {
  1165. id: `daily-fortune-${Date.now()}`,
  1166. type: 'daily',
  1167. date: params.date,
  1168. dishName: fortuneData.dishName || '幸运料理',
  1169. reason: fortuneData.reason || '星座与生肖的神秘指引',
  1170. luckyIndex: fortuneData.luckyIndex || Math.floor(Math.random() * 3) + 7,
  1171. description: fortuneData.description || '这道菜将为您带来今日好运',
  1172. tips: fortuneData.tips || ['用心制作', '保持好心情'],
  1173. difficulty: fortuneData.difficulty || 'medium',
  1174. cookingTime: fortuneData.cookingTime || 30,
  1175. mysticalMessage: fortuneData.mysticalMessage || '命运之轮正在转动,美味即将降临...',
  1176. ingredients: fortuneData.ingredients || [],
  1177. steps: fortuneData.steps || []
  1178. }
  1179. return fortune
  1180. } catch (error) {
  1181. console.error('生成今日运势菜失败:', error)
  1182. throw new Error('占卜师暂时无法感应到星象,请稍后重试')
  1183. }
  1184. }
  1185. /**
  1186. * 生成心情料理
  1187. * @param params 心情参数
  1188. * @returns Promise<FortuneResult>
  1189. */
  1190. export const generateMoodCooking = async (params: MoodFortuneParams): Promise<FortuneResult> => {
  1191. try {
  1192. const moodText = params.moods.join('、')
  1193. const intensityText = ['很轻微', '轻微', '一般', '强烈', '非常强烈'][params.intensity - 1]
  1194. const prompt = `你是一位擅长情感治愈的料理占卜师,请根据以下心情状态推荐治愈菜品:
  1195. 当前心情:${moodText}
  1196. 情绪强度:${intensityText}
  1197. 请推荐一道能够治愈这种心情的菜品,并给出温暖的情感分析。
  1198. 请按照以下JSON格式返回占卜结果:
  1199. {
  1200. "dishName": "菜品名称",
  1201. "reason": "这道菜如何治愈当前心情",
  1202. "luckyIndex": 7,
  1203. "description": "详细的情感分析和菜品治愈功效",
  1204. "tips": ["情感治愈建议1", "烹饪心得2"],
  1205. "difficulty": "easy",
  1206. "cookingTime": 25,
  1207. "mysticalMessage": "温暖治愈的话语",
  1208. "ingredients": ["治愈食材1", "治愈食材2"],
  1209. "steps": ["治愈步骤1", "治愈步骤2"]
  1210. }`
  1211. const aiClient = createAiClient()
  1212. const apiConfig = getTextGenerationConfig()
  1213. const response = await aiClient.post('/chat/completions', {
  1214. model: apiConfig.model,
  1215. messages: [
  1216. {
  1217. role: 'system',
  1218. content:
  1219. '你是一位温暖而智慧的情感治愈师,深谙美食与情感的关系。你善于通过菜品来抚慰人心,话语温暖治愈。请严格按照JSON���式返回,不要包含任何其他文字。请务必用中文回答。'
  1220. },
  1221. {
  1222. role: 'user',
  1223. content: prompt
  1224. }
  1225. ],
  1226. temperature: 0.7,
  1227. stream: false
  1228. })
  1229. const aiResponse = response.data.choices[0].message.content
  1230. let cleanResponse = aiResponse.trim()
  1231. if (cleanResponse.startsWith('```json')) {
  1232. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1233. } else if (cleanResponse.startsWith('```')) {
  1234. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1235. }
  1236. const fortuneData = JSON.parse(cleanResponse)
  1237. const fortune: FortuneResult = {
  1238. id: `mood-fortune-${Date.now()}`,
  1239. type: 'mood',
  1240. date: new Date().toISOString().split('T')[0],
  1241. dishName: fortuneData.dishName || '治愈料理',
  1242. reason: fortuneData.reason || '这道菜能温暖你的心',
  1243. luckyIndex: fortuneData.luckyIndex || Math.floor(Math.random() * 3) + 6,
  1244. description: fortuneData.description || '美食是最好的情感治愈师',
  1245. tips: fortuneData.tips || ['慢慢品味', '感受温暖'],
  1246. difficulty: fortuneData.difficulty || 'easy',
  1247. cookingTime: fortuneData.cookingTime || 25,
  1248. mysticalMessage: fortuneData.mysticalMessage || '让美食抚慰你的心灵,一切都会好起来的...',
  1249. ingredients: fortuneData.ingredients || [],
  1250. steps: fortuneData.steps || []
  1251. }
  1252. return fortune
  1253. } catch (error) {
  1254. console.error('生成心情料理失败:', error)
  1255. throw new Error('情感占卜师暂时感应不到你的心情,请稍后重试')
  1256. }
  1257. }
  1258. /**
  1259. * 生成缘分配菜
  1260. * @param params 双人参数
  1261. * @returns Promise<FortuneResult>
  1262. */
  1263. export const generateCoupleCooking = async (params: CoupleFortuneParams): Promise<FortuneResult> => {
  1264. try {
  1265. const prompt = `你是一位专门分析人际关系的料理占卜师,请分析两人的配菜缘分:
  1266. 第一人:
  1267. - 星座:${params.user1.zodiac}
  1268. - 生肖:${params.user1.animal}
  1269. - 性格:${params.user1.personality.join('、')}
  1270. 第二人:
  1271. - 星座:${params.user2.zodiac}
  1272. - 生肖:${params.user2.animal}
  1273. - 性格:${params.user2.personality.join('、')}
  1274. 请分析两人的配菜默契度,推荐适合合作制作的菜品。
  1275. 请按照以下JSON格式返回占卜结果:
  1276. {
  1277. "dishName": "适合合作的菜品名称",
  1278. "reason": "为什么这道菜适合你们一起做",
  1279. "luckyIndex": 8,
  1280. "description": "详细的缘分分析和配菜建议",
  1281. "tips": ["合作建议1", "默契提升技巧2"],
  1282. "difficulty": "medium",
  1283. "cookingTime": 40,
  1284. "mysticalMessage": "关于缘分和合作的神秘话语",
  1285. "ingredients": ["需要合作的食材1", "需要合作的食材2"],
  1286. "steps": ["合作步骤1", "合作步骤2"]
  1287. }`
  1288. const aiClient = createAiClient()
  1289. const apiConfig = getTextGenerationConfig()
  1290. const response = await aiClient.post('/chat/completions', {
  1291. model: apiConfig.model,
  1292. messages: [
  1293. {
  1294. role: 'system',
  1295. content:
  1296. '你是一位精通人际关系和美食文化的占卜师,善于分析人与人之间的默契和缘分。你的话语充满智慧和温暖。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  1297. },
  1298. {
  1299. role: 'user',
  1300. content: prompt
  1301. }
  1302. ],
  1303. temperature: 0.8,
  1304. stream: false
  1305. })
  1306. const aiResponse = response.data.choices[0].message.content
  1307. let cleanResponse = aiResponse.trim()
  1308. if (cleanResponse.startsWith('```json')) {
  1309. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1310. } else if (cleanResponse.startsWith('```')) {
  1311. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1312. }
  1313. const fortuneData = JSON.parse(cleanResponse)
  1314. const fortune: FortuneResult = {
  1315. id: `couple-fortune-${Date.now()}`,
  1316. type: 'couple',
  1317. date: new Date().toISOString().split('T')[0],
  1318. dishName: fortuneData.dishName || '缘分料理',
  1319. reason: fortuneData.reason || '你们的星座组合很适合这道菜',
  1320. luckyIndex: fortuneData.luckyIndex || Math.floor(Math.random() * 3) + 7,
  1321. description: fortuneData.description || '这道菜将增进你们的默契',
  1322. tips: fortuneData.tips || ['互相配合', '享受过程'],
  1323. difficulty: fortuneData.difficulty || 'medium',
  1324. cookingTime: fortuneData.cookingTime || 40,
  1325. mysticalMessage: fortuneData.mysticalMessage || '缘分天注定,美食见真情...',
  1326. ingredients: fortuneData.ingredients || [],
  1327. steps: fortuneData.steps || []
  1328. }
  1329. return fortune
  1330. } catch (error) {
  1331. console.error('生成缘分配菜失败:', error)
  1332. throw new Error('缘分占卜师暂时无法感应到你们的默契,请稍后重试')
  1333. }
  1334. }
  1335. /**
  1336. * 生成幸运数字菜
  1337. * @param params 数字参数
  1338. * @returns Promise<FortuneResult>
  1339. */
  1340. export const generateNumberFortune = async (params: NumberFortuneParams): Promise<FortuneResult> => {
  1341. try {
  1342. const numberSource = params.isRandom ? '随机生成' : '用户选择'
  1343. const prompt = `你是一位精通数字占卜的料理大师,请根据幸运数字推荐菜品:
  1344. 幸运数字:${params.number}
  1345. 数字来源:${numberSource}
  1346. 请解析这个数字的寓意,并推荐对应的幸运菜品。
  1347. 请按照以下JSON格式返回占卜结果:
  1348. {
  1349. "dishName": "与数字相关的菜品名称",
  1350. "reason": "数字寓意和选择理由",
  1351. "luckyIndex": 9,
  1352. "description": "数字占卜解析和菜品象征意义",
  1353. "tips": ["数字相关的幸运建议1", "制作要点2"],
  1354. "difficulty": "medium",
  1355. "cookingTime": 35,
  1356. "mysticalMessage": "关于数字和命运的神秘话语",
  1357. "ingredients": ["象征性食材1", "象征性食材2"],
  1358. "steps": ["制作步骤1", "制作步骤2"]
  1359. }`
  1360. const aiClient = createAiClient()
  1361. const apiConfig = getTextGenerationConfig()
  1362. const response = await aiClient.post('/chat/completions', {
  1363. model: apiConfig.model,
  1364. messages: [
  1365. {
  1366. role: 'system',
  1367. content:
  1368. '你是一位精通数字学和美食文化的神秘占卜师,善于解读数字的深层含义并与菜品联系。你的话语充满神秘和智慧。请严格按照JSON格式返回,不要包含任何其他文字。请务必用中文回答。'
  1369. },
  1370. {
  1371. role: 'user',
  1372. content: prompt
  1373. }
  1374. ],
  1375. temperature: 0.8,
  1376. stream: false
  1377. })
  1378. const aiResponse = response.data.choices[0].message.content
  1379. let cleanResponse = aiResponse.trim()
  1380. if (cleanResponse.startsWith('```json')) {
  1381. cleanResponse = cleanResponse.replace(/```json\s*/, '').replace(/```\s*$/, '')
  1382. } else if (cleanResponse.startsWith('```')) {
  1383. cleanResponse = cleanResponse.replace(/```\s*/, '').replace(/```\s*$/, '')
  1384. }
  1385. const fortuneData = JSON.parse(cleanResponse)
  1386. const fortune: FortuneResult = {
  1387. id: `number-fortune-${Date.now()}`,
  1388. type: 'number',
  1389. date: new Date().toISOString().split('T')[0],
  1390. dishName: fortuneData.dishName || '数字料理',
  1391. reason: fortuneData.reason || `数字${params.number}带来的神秘指引`,
  1392. luckyIndex: fortuneData.luckyIndex || Math.floor(Math.random() * 3) + 7,
  1393. description: fortuneData.description || '数字中蕴含着美食的秘密',
  1394. tips: fortuneData.tips || ['相信数字的力量', '用心制作'],
  1395. difficulty: fortuneData.difficulty || 'medium',
  1396. cookingTime: fortuneData.cookingTime || 35,
  1397. mysticalMessage: fortuneData.mysticalMessage || '数字是宇宙的语言,美食是心灵的慰藉...',
  1398. ingredients: fortuneData.ingredients || [],
  1399. steps: fortuneData.steps || []
  1400. }
  1401. return fortune
  1402. } catch (error) {
  1403. console.error('生成幸运数字菜失败:', error)
  1404. throw new Error('数字占卜师暂时无法解读这个数字,请稍后重试')
  1405. }
  1406. }
  1407. // 配置现在通过settings store管理,不再导出静态配置
  1408. /**
  1409. * 通用聊天(流式)
  1410. * @param messages 对话历史
  1411. * @param onDelta 每次增量文本回调
  1412. * @param onComplete 结束回调(携带完整文本)
  1413. * @param onError 错误回调
  1414. */
  1415. export const chatStream = async (
  1416. messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>,
  1417. onDelta: (deltaText: string) => void,
  1418. onComplete?: (fullText: string) => void,
  1419. onError?: (err: unknown) => void
  1420. ): Promise<void> => {
  1421. const config = getTextGenerationConfig()
  1422. const url = config.baseUrl.replace(/\/$/, '') + '/chat/completions'
  1423. const headers: Record<string, string> = {
  1424. 'Content-Type': 'application/json',
  1425. Authorization: `Bearer ${config.apiKey}`
  1426. }
  1427. const body = JSON.stringify({
  1428. model: config.model,
  1429. messages,
  1430. temperature: config.temperature,
  1431. stream: true
  1432. })
  1433. try {
  1434. const response = await fetch(url, {
  1435. method: 'POST',
  1436. headers,
  1437. body
  1438. })
  1439. if (!response.ok || !response.body) {
  1440. throw new Error(`请求失败: ${response.status}`)
  1441. }
  1442. const reader = response.body.getReader()
  1443. const decoder = new TextDecoder('utf-8')
  1444. let buffer = ''
  1445. let fullText = ''
  1446. while (true) {
  1447. const { value, done } = await reader.read()
  1448. if (done) break
  1449. buffer += decoder.decode(value, { stream: true })
  1450. // 以SSE事件为单位切分
  1451. const parts = buffer.split(/\n\n/)
  1452. buffer = parts.pop() || ''
  1453. for (const part of parts) {
  1454. const lines = part
  1455. .split('\n')
  1456. .map(l => l.trim())
  1457. .filter(Boolean)
  1458. for (const line of lines) {
  1459. if (!line.startsWith('data:')) continue
  1460. const data = line.slice(5).trim()
  1461. if (data === '[DONE]') {
  1462. if (onComplete) onComplete(fullText)
  1463. return
  1464. }
  1465. try {
  1466. const json = JSON.parse(data)
  1467. // 兼容OpenAI/同构流式规范
  1468. const delta = json.choices?.[0]?.delta?.content ?? json.choices?.[0]?.message?.content ?? ''
  1469. if (delta) {
  1470. fullText += delta
  1471. onDelta(delta)
  1472. }
  1473. } catch (e) {
  1474. // 非JSON行,忽略
  1475. continue
  1476. }
  1477. }
  1478. }
  1479. }
  1480. // 读流结束但未收到DONE
  1481. if (onComplete) onComplete(fullText)
  1482. } catch (err) {
  1483. if (onError) onError(err)
  1484. else console.error('chatStream error:', err)
  1485. throw err
  1486. }
  1487. }