前兩天已經準備好 Dify AI 應用,也建立了後端 API。
今天終於要讓 AI Recipe 網站開始使用 AI 產生食譜,而不是只從預先設定的資料中尋找料理。
一、前端呼叫自己的後端
在 script.js 中建立一個函式:
async function getAIRecipe(ingredients) {
const response = await fetch("/api/recipe", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ ingredients })
});
if (!response.ok) {
throw new Error("取得食譜失敗");
}
const data = await response.json();
return data.answer;
}
這裡的 fetch() 負責向後端傳送請求,async 和 await 則能讓程式等待 AI 回傳結果。
二、修改推薦功能
原本 Day 8 使用的是固定食譜資料,現在可以改成呼叫 AI:
async function recommendRecipe(ingredients) {
const answer = await getAIRecipe(
ingredients.join("、")
);
recipeResult.textContent = answer;
}
在按鈕事件中,整理完食材後呼叫:
recommendRecipe(ingredients);
三、測試 AI 推薦
例如輸入:
「雞蛋、番茄、洋蔥」
AI 就可以根據這些食材產生料理建議,而不是只能顯示我事先寫好的番茄炒蛋。
這代表網站已經開始具備真正的 AI 生成能力!
四、今天的成果
今天完成前端與後端的基本串接,讓使用者輸入的食材可以透過後端送到 Dify,再取得 AI 的回答。
不過,AI 回答的內容可能會因為每次提問而有所不同,因此下一篇要研究如何設計 Prompt,讓推薦結果更符合網站需求。