Instillsoft Logo

December 01, 2025

Build Your First Gen AI App with React & LLMs: A Beginner's Guide

AI/ML
Image for the Generative AI blog post.

Generative AI has taken the world by storm, but what is it, really? If you're a student curious about AI, this guide is for you. We'll break down the basics of Generative AI and show you how to build your very first AI-powered application, step by step.

What is Generative AI?

Imagine an artist who can create brand-new paintings, not just copy existing ones. That's what Generative AI does with data. It's a type of artificial intelligence that can create new, original content—like text, images, or code—that has never existed before. The "brain" behind many of these text-based AI tools is a Large Language Model (LLM).

How Do These AI "Brains" (LLMs) Learn?

Think of training an LLM like teaching a student to become a world-class expert. It happens in a few stages:

  1. Reading the Entire Library (Pre-training): First, the model is given a gigantic library of text from the internet, books, and articles. Its only job is to read a sentence and guess the next word. By doing this billions of times, it learns grammar, facts, context, and even how to reason. It's not memorizing; it's learning patterns.

  2. Getting Coached by Experts (Fine-Tuning): After reading the library, the model is "fine-tuned." Humans create a high-quality dataset of questions and ideal answers. The model practices on these to learn how to be helpful and follow instructions, like a student learning from a teacher.

  3. Learning from Feedback (Reinforcement Learning): This is the final polish. Humans rank the AI's different answers to the same question from best to worst. This feedback is used to train another AI, called a "reward model," which learns what humans consider a "good" answer. The main LLM is then coached to get the highest score from this reward model, making it safer and more helpful.

This process creates a powerful model that can understand and generate human-like text for almost any task.

Let's Build an AI Story Generator! (From Scratch)

Theory is great, but let's build something! We'll create a simple web app where you can type in a topic, and an AI will write a short story about it. No prior experience with React or AI is needed—just follow these steps.

Prerequisites

Before you start, make sure you have Node.js installed on your computer. This is a JavaScript runtime that allows you to run web development tools.

Step 1: Create Your Next.js Project

First, open your computer's terminal (or command prompt). Navigate to where you want to create your project and run this command:

npx create-next-app@latest ai-story-app

This command will ask you a few questions. Choose the following options:

  • Would you like to use TypeScript? Yes
  • Would you like to use ESLint? Yes
  • Would you like to use Tailwind CSS? Yes
  • Would you like to use src/ directory? Yes
  • Would you like to use App Router? Yes
  • Would you like to customize the default import alias? No

After the setup is complete, navigate into your new project folder:

cd ai-story-app

Step 2: Install AI Packages

Next, we need to install Genkit, which is the AI toolkit we'll use to connect to Google's generative models.

npm install genkit @genkit-ai/google-genai zod dotenv
  • genkit: The core AI toolkit.
  • @genkit-ai/google-genai: The plugin to connect to Google's AI models (like Gemini).
  • zod: A tool for defining the structure of our data.
  • dotenv: A tool to manage secret API keys.

Step 3: Get Your API Key

To use the AI, you need an API key from Google AI Studio.

  1. Go to Google AI Studio.
  2. Click "Get API key" and create a new API key.
  3. In your project's root folder (ai-story-app), create a new file named .env.
  4. Inside .env, add the following line, pasting your key where indicated:
    GEMINI_API_KEY=YOUR_API_KEY_HERE
    

Step 4: Configure Genkit

Now, let's set up Genkit so our app knows how to use our API key. Create a new folder src/ai and inside it, create a file named genkit.ts.

File: src/ai/genkit.ts

import { genkit } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';

export const ai = genkit({
  plugins: [googleAI({ apiKey: process.env.GEMINI_API_KEY })],
  model: 'googleai/gemini-pro',
});

This file configures Genkit to use the Google AI plugin with your API key.

Step 5: Create the AI's "Brain" (The AI Flow)

This is the "backend" part of our app. It's the logic that tells the AI what to do. Create another file inside the src/ai folder.

File: src/ai/story-flow.ts

'use server'; // This tells Next.js to run this code on the server.

import { ai } from './genkit'; // Imports our configured AI tool.
import { z } from 'zod'; // A tool to define the shape of our data.

// 1. Define the input: What question will we ask the AI?
const StoryInputSchema = z.object({
  topic: z.string().describe("The topic for the story."),
});

// 2. Define the output: What answer do we want back from the AI?
const StoryOutputSchema = z.object({
  story: z.string().describe("The generated short story."),
});

// 3. Create the prompt: These are the instructions for the AI.
const storyPrompt = ai.definePrompt({
  name: 'storyPrompt',
  input: { schema: StoryInputSchema },
  output: { schema: StoryOutputSchema },
  prompt: `Write a short, engaging story about {{{topic}}}. The story should have a clear beginning, middle, and end.`,
});

// 4. Create the flow: This wraps our prompt into a function we can call from our webpage.
export async function generateStory(input: { topic: string }) {
  const { output } = await storyPrompt(input);
  return output!; // Run the prompt and return the final output.
}

Step 6: Build the User Interface (The React Component)

This is the "frontend"—the webpage the user interacts with. Go to src/app/page.tsx and replace its content with the following code.

File: src/app/page.tsx

'use client'; // This tells Next.js that this code runs in the user's browser.

import { useState } from 'react';
import { generateStory } from '@/ai/story-flow'; // Import our AI function.

export default function StoryWriterPage() {
  const [topic, setTopic] = useState('');
  const [story, setStory] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleGenerate = async () => {
    if (!topic) return;

    setIsLoading(true);
    setStory('');

    try {
      const result = await generateStory({ topic });
      setStory(result.story);
    } catch (error) {
      setStory('Sorry, something went wrong. Please try again.');
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container max-w-2xl mx-auto py-12 px-4">
      <h1 className="text-3xl font-bold mb-4">AI Story Generator</h1>
      <p className="mb-6 text-gray-600">Enter a topic, and our AI will write a short story for you!</p>
      
      <div className="space-y-4">
        <input
          type="text"
          value={topic}
          onChange={(e) => setTopic(e.target.value)}
          placeholder="e.g., 'a brave knight' or 'a cat who travels to space'"
          className="w-full p-3 border rounded-lg"
        />
        <button
          onClick={handleGenerate}
          disabled={isLoading}
          className="w-full px-4 py-3 bg-blue-600 text-white font-semibold rounded-lg disabled:bg-gray-400 hover:bg-blue-700 transition-colors"
        >
          {isLoading ? 'Generating...' : 'Generate Story'}
        </button>
      </div>

      {story && (
        <div className="mt-8 p-6 border rounded-lg bg-gray-50">
          <h2 className="text-xl font-semibold mb-2">Your Story:</h2>
          <p className="whitespace-pre-wrap leading-relaxed">{story}</p>
        </div>
      )}
    </div>
  );
}

Step 7: Run Your App!

You're all set! Go back to your terminal and run the development server:

npm run dev

Now, open your web browser and go to http://localhost:3000. You should see your AI Story Generator! Type a topic, click the button, and watch the AI work its magic.

The Future is Generative

Congratulations! You've just built a complete AI application from scratch. This same pattern can be used for anything from drafting emails to debugging code. By understanding these fundamentals, you're on your way to building the next generation of intelligent apps.

Ready to Innovate?

Whether you're planning a new project or looking to upgrade your team's skills, we're here to help.

Contact us via email, connect on WhatsApp at +91 9110245113, or book a free consultation to discuss your training or project needs.

Explore More Courses by Gaurab K.

Continue your learning journey with these popular programs.

AI & Machine Learning
Agentic AI Foundations

Turn AWS services like Amazon Q and Bedrock Agents into the building blocks of autonomous AI.

AI & Machine Learning
Generative AI Mastery

Master generative AI on AWS, including use cases, prompt engineering, responsible AI, and security. Hands-on labs included—no prior experience needed!

Mobile & Web Development
Full-Stack with Python & Django

Learn to build powerful and secure web applications with Python's leading framework, Django, for rapid development.

Mobile & Web Development
MERN Full-Stack Development

Build end-to-end web applications using the popular MERN stack (MongoDB, Express.js, React, Node.js).

Mobile & Web Development
Full-Stack with Java, Angular & Gen AI

Become a complete full-stack developer using Java with Spring Boot, Angular, and integrating modern Cloud and Gen AI services.

Cloud Computing
GCP - Associate Cloud Engineer

Learn to deploy applications, monitor operations, and manage enterprise solutions on Google Cloud Platform.

Explore Our Training Programs

Profile of Gaurab K.

Gaurab K.

Lead Trainer

AI & Machine Learning Training

Ready for the AI revolution? Our courses are designed to give you a competitive edge for top roles.

Profile of Gaurab K.

Gaurab K.

Lead Trainer

Mobile & Web Development Training

Go full-stack. Our bootcamps cover everything you need to become a top-tier developer.