svelte-beginners-toolkit Svelte Themes

Svelte Beginners Toolkit

A beginner-friendly guide to Svelte using AI-powered learning

šŸ³ Beginner's Guide to Building an AI Recipe Bot

Table of Contents


What We're Building

We'll create a website where you can:

  • Type ingredients you have (like chicken, rice, tomatoes)
  • Select a meal type (breakfast, lunch, or dinner)
  • Get a custom AI-generated recipe
  • See the recipe displayed on your screen


Setup Instructions

Install Node.js

  1. Download from nodejs.org
  2. Run the installer (use default settings)
  3. Verify installation:
node -v

Install VS Code


Get OpenAI API Key

  1. Sign up at openai.com
  2. Go to API keys
  3. Click "Create new secret key"
  4. Copy this key (we'll use it later)

Create Your Project

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

Build the Recipe Generator

File Structure

src/
ā”œā”€ā”€ lib/
│   └── RecipeGenerator.svelte
ā”œā”€ā”€ App.svelte
└── main.js

RecipeGenerator.svelte

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>

App.svelte

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>

Run Your Project

Start the development server:

npm run dev

Then open http://localhost:5173


Understanding the Code

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

Troubleshooting

Problem: API not working
Fix:

  • Check .env file has correct key
  • Verify OpenAI account has credits

Problem: Page not updating
Fix:

  • Restart server with npm run dev
  • Check browser console (F12) for errors

Next Steps

  • Add more customization (servings, dietary restrictions, etc.)
  • Style with Tailwind CSS or Bootstrap
  • Deploy to Vercel or Netlify

Top categories

Loading Svelte Themes