We'll create a website where you can:
chicken, rice, tomatoes
)node -v
Open your terminal and run:
npm create vite@latest recipe-bot -- --template svelte
cd recipe-bot
npm install
Add the OpenAI package:
npm install openai
Create a .env
file:
VITE_OPENAI_KEY=your-copied-key-here
src/
āāā lib/
ā āāā RecipeGenerator.svelte
āāā App.svelte
āāā main.js
Create src/lib/RecipeGenerator.svelte
:
<script>
let ingredients = "";
let mealType = "dinner";
let isLoading = false;
let error = null;
let recipe = null;
async function generateRecipe() {
if (!ingredients.trim()) {
error = "Please enter some ingredients!";
return;
}
isLoading = true;
error = null;
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${import.meta.env.VITE_OPENAI_KEY}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{
role: "user",
content: `Create a ${mealType} recipe using: ${ingredients}`
}]
})
});
const data = await response.json();
recipe = data.choices[0].message.content;
} catch (err) {
error = "Failed to generate recipe";
} finally {
isLoading = false;
}
}
</script>
<div class="generator">
<h2>š³ What's in your kitchen?</h2>
{#if error}
<div class="error">ā ļø {error}</div>
{/if}
<textarea
bind:value={ingredients}
placeholder="e.g. chicken, rice, tomatoes..."
rows="3"
/>
<select bind:value={mealType}>
<option value="breakfast">Breakfast</option>
<option value="lunch">Lunch</option>
<option value="dinner">Dinner</option>
</select>
<button on:click={generateRecipe}>
{#if isLoading}ā³{:else}āØ{/if}
Create Recipe
</button>
{#if recipe}
<div class="recipe">
<h3>Your Recipe:</h3>
<pre>{recipe}</pre>
</div>
{/if}
</div>
<style>
.generator {
max-width: 600px;
margin: 0 auto;
padding: 2rem;
}
textarea, select, button {
width: 100%;
padding: 0.5rem;
margin-bottom: 1rem;
}
.error { color: red; }
.recipe { margin-top: 2rem; }
</style>
Update src/App.svelte
:
<script>
import RecipeGenerator from './lib/RecipeGenerator.svelte';
</script>
<main>
<RecipeGenerator />
</main>
<style>
main {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
</style>
Start the development server:
npm run dev
Then open http://localhost:5173
Part | Explanation |
---|---|
ingredients |
Stores what you type in the box |
mealType |
Remembers your meal selection |
generateRecipe() |
Calls OpenAI to create recipes |
{#if} blocks |
Show/hide parts of the interface |
Problem: API not working
Fix:
.env
file has correct keyProblem: Page not updating
Fix:
npm run dev