Build an AI Agent in a Next.js app using Web AI Framework

4 min read

Cover Image for Build an AI Agent in a Next.js app using Web AI Framework

AI agents have taken the internet by storm. It is an autonomous software that uses LLMs to handle more than just text generation—it interacts with digital environments, makes decisions, and performs tasks based on its language understanding.

AI agents enhance LLMs by adding new capabilities while leaning on them for reasoning and decision-making.

In this guide, let’s create an AI agent in a Next.js app using the first web AI framework called BaseAI.

Prerequisites

1- Install Next.js

First, you need to install Next.js in your project directory.

npx create-next-app@latest nextjs-baseai-app

Also, setup tailwind in your Next.js app.

2- Install BaseAI

Next, you need to install BaseAI in your project directory.

npx baseai@latest init

3- Create a Summary AI Agent Pipe

Create a new pipe using the pipe command. Use summary as the pipe name and for system prompt use You are a helpful AI assistant. Make everything Less wordy..

npx baseai@latest pipe

It creates a pipe at baseai/pipes/summary.ts in your current directory.

4- Set Environment Variables

Use following command to create a .env file in your project directory.

cp .env.baseai.example .env

Set the OPENAI_API_KEY in the .env file.

5- Add API Route Handler

Create a new API route handler app/api/langbase/pipes/run/route.ts to use the pipe.

import {Pipe} from '@baseai/core';
import {NextRequest} from 'next/server';

import pipeSummary from '../../../../../baseai/pipes/summary';

export async function POST(req: NextRequest) {

const runOptions = await req.json();

// 1. Initiate the Pipe.

const pipe = new Pipe(pipeSummary());

// 2. Run the pipe

const result = await pipe.run(runOptions);

// 3. Return the response stringified.

return new Response(JSON.stringify(result));

}

6- Add React Component

Add following to your Next.js app to run the pipe.

  • Pipe run page at app/pipe-run/page.tsx

  • Pipe run component at components/pipe-run.tsx — This component will run the pipe.

  • UI Button component at components/ui/button.tsx

  • UI Input component at components/ui/input.tsx

Install the required dependencies.

npm install @radix-ui/react-slot class-variance-authority clsx tailwind-merge

Here’s the code:

import PipeRunExample from '@/components/pipe-run';

export default function Page() {
    return (
        <div className="w-full max-w-md">

            <h1 className="text-2xl font-light text-gray-800 mb-1 text-center">
                ⌘ Langbase AI Agent Pipe: Run
            </h1>

            <p className="text-muted-foreground text-base font-light mb-20 text-center">
                Run a pipe to generate a text completion
            </p>

            <PipeRunExample />
        </div>
    );
}

Refer to Next.js with BaseAI codebase for more details.

7- Add Environment Variables

To be able to run and later deploy your Next.js app, you need to add your Langbase and LLM provider keys. Add the following environment variables to your .env file at the root of your app.

# !! SERVER SIDE ONLY !!
# Keep all your API keys secret — use only on the server side.

# TODO: ADD: Both in your production and local env files.
# Langbase API key for your User or Org account.
# How to get this API key https://langbase.com/docs/api-reference/api-keys
LANGBASE_API_KEY=

# TODO: ADD: LOCAL ONLY. Add only to local env files.
# Following keys are needed for local pipe runs. Add the providers you are using.
# For Langbase, please add the keys in your LLM keysets on Langbase Studio.
# Read more: Langbase LLM Keysets https://langbase.com/docs/features/keysets
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
COHERE_API_KEY=
FIREWORKS_API_KEY=
GOOGLE_API_KEY=
GROQ_API_KEY=
MISTRAL_API_KEY=
PERPLEXITY_API_KEY=
TOGETHER_API_KEY=

LANGBASE_API_KEY is the user or org API key that you authenticated with. You can obtain your User/Org API Key from the Langbase dashboard.

8- Run the Next.js BaseAI App

Run BaseAI dev server and start the Next.js app.

# Terminal 1
npx baseai@latest dev # Start BaseAI dev server

# Terminal 2
npm run dev # Start Next.js app

Open http://localhost:3000/pipe-run to see the pipe run page.

Write a prompt message and click on the Ask AI button to generate the completion. The AI response will be displayed below the button. This all happens locally on your machine.

9- Deploy BaseAI Project on Langbase

To deploy the project on Langbase, you need to authenticate with your Langbase account.

npx baseai@latest auth

After authentication, you can deploy the project using the following command. When you deploy, you need to add keys for providers like OpenAI, Google, etc., in Langbase Keysets.

npx baseai@latest deploy

This will deploy your project on Langbase and you can access it as a serverless highly scalable API. Check the BaseAI deploy documentation for more details.

Resources

  • Complete guide here.