Skip to main content

RAG Chatbot

Learn how to build a chatbot that uses retrieval-augmented generation (RAG) to answer questions based on a custom knowledge base.

What is RAG?

RAG (Retrieval Augmented Generation) enhances AI responses by fetching relevant information and providing it as context to the language model. This allows the model to answer questions about information it wasn’t trained on, such as proprietary data or recent events.

How It Works

  1. Chunking: Break source material into smaller pieces
  2. Embedding: Convert text chunks into vector representations
  3. Storage: Store embeddings in a vector database
  4. Retrieval: When a user asks a question, embed the query and find similar chunks
  5. Generation: Pass relevant chunks to the LLM as context

Prerequisites

  • Node.js 18+
  • A Vercel AI Gateway API key
  • PostgreSQL with pgvector extension

Setup

Clone the starter repository:

Database Setup

Create a .env file:
Add your database URL and AI Gateway API key:
Run migrations:

Implementation

Create Embeddings Schema

Define a table to store text chunks and their embeddings:

Generate Embeddings

Create a function to chunk and embed text:

Store Resources with Embeddings

Create a server action to save content and generate embeddings:

Retrieve Similar Content

Implement semantic search using cosine similarity:

Create the Chat Interface

Build a route handler that uses tools for adding and retrieving information:

Frontend with useChat

Create a chat interface using the useChat hook:

Running the Application

Visit http://localhost:3000 and try:
  1. Tell the chatbot information: “My favorite food is pizza”
  2. Ask questions: “What is my favorite food?”
The chatbot will store information in its knowledge base and retrieve it when needed.

Key Concepts

  • Embeddings: Vector representations of text that capture semantic meaning
  • Vector Database: Stores embeddings and enables similarity search
  • Cosine Similarity: Measures how similar two embeddings are
  • Chunking: Breaking text into smaller pieces for better embedding quality
  • Tools: Enable the agent to add and retrieve information dynamically

Next Steps

  • Experiment with different chunking strategies
  • Try different embedding models
  • Implement more advanced retrieval techniques
  • Add user-specific knowledge bases

Resources