ai-pdf-chatbot-langchain README

The project's README from github.com/mayooear/ai-pdf-chatbot-langchain. As one markdown file: README.md.

AI PDF Chatbot & Agent Powered by LangChain and LangGraph

This monorepo is a customizable template example of an AI chatbot agent that "ingests" PDF documents, stores embeddings in a vector database (Supabase), and then answers user queries using OpenAI (or another LLM provider) utilising LangChain and LangGraph as orchestration frameworks.

This template is also an accompanying example to the book Learning LangChain (O'Reilly): Building AI and LLM applications with LangChain and LangGraph.

[!IMPORTANT] This project is not actively maintained and is kept here for reference. Please do not expect responses to new issues or pull requests.

Here's what the Chatbot UI looks like:

Screenshot 2025-02-20 at 05 39 55

Table of Contents

  1. Features
  2. Architecture Overview
  3. Prerequisites
  4. Installation
  5. Environment Variables
  6. Local Development
  7. Usage
  8. Production Build & Deployment
  9. Customizing the Agent
  10. Troubleshooting
  11. Next Steps

Features


Architecture Overview

┌─────────────────────┐    1. Upload PDFs    ┌───────────────────────────┐
│Frontend (Next.js)   │ ────────────────────> │Backend (LangGraph)       │
│ - React UI w/ chat  │                      │ - Ingestion Graph         │
│ - Upload .pdf files │ <────────────────────┤   + Vector embedding via  │
└─────────────────────┘    2. Confirmation   │     SupabaseVectorStore   │
(storing embeddings in DB)

┌─────────────────────┐    3. Ask questions  ┌───────────────────────────┐
│Frontend (Next.js)   │ ────────────────────> │Backend (LangGraph)       │
│ - Chat + SSE stream │                      │ - Retrieval Graph         │
│ - Display sources   │ <────────────────────┤   + Chat model (OpenAI)   │
└─────────────────────┘ 4. Streamed answers  └───────────────────────────┘

The system consists of:


Prerequisites

  1. Node.js v18+ (we recommend Node v20).
  2. Yarn (or npm, but this monorepo is pre-configured with Yarn).
  3. Supabase project (if you plan to store embeddings in Supabase; see Setting up Supabase).
  4. OpenAI API Key (or another LLM provider’s key, supported by LangChain).
  5. LangChain API Key (free and optional, but highly recommended for debugging and tracing your LangChain and LangGraph applications). Learn more here

Installation

  1. Clone the repository:

    git clone https://github.com/mayooear/ai-pdf-chatbot-langchain.git
    cd ai-pdf-chatbot-langchain
    
  2. Install dependencies (from the monorepo root):

yarn install

3.	Configure environment variables in both backend and frontend. See .`env.example` files for details.

Environment Variables

The project relies on environment variables to configure keys and endpoints. Each sub-project (backend and frontend) has its own .env.example. Copy these to .env and fill in your details.

Frontend Variables

Create a .env file in frontend:

cp frontend/.env.example frontend/.env

    NEXT_PUBLIC_LANGGRAPH_API_URL=http://localhost:2024
    LANGCHAIN_API_KEY=your-langsmith-api-key-here # Optional: LangSmith API key
    LANGGRAPH_INGESTION_ASSISTANT_ID=ingestion_graph
    LANGGRAPH_RETRIEVAL_ASSISTANT_ID=retrieval_graph

    LANGCHAIN_TRACING_V2=true # Optional: Enable LangSmith tracing

    LANGCHAIN_PROJECT="pdf-chatbot" # Optional: LangSmith project name

Backend Variables

Create a .env file in backend:

cp backend/.env.example backend/.env

    OPENAI_API_KEY=your-openai-api-key-here
    SUPABASE_URL=your-supabase-url-here
    SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key-here

    LANGCHAIN_TRACING_V2=true # Optional: Enable LangSmith tracing

    LANGCHAIN_PROJECT="pdf-chatbot" # Optional: LangSmith project name

Explanation of Environment Variables:

Local Development

This monorepo uses Turborepo to manage both backend and frontend projects. You can run them separately for development.

Running the Backend

  1. Navigate to backend:
cd backend
  1. Install dependencies (already done if you ran yarn install at the root).

  2. Start LangGraph in dev mode:

yarn langgraph:dev

This will launch a local LangGraph server on port 2024 by default. It should redirect you to a UI for interacting with the LangGraph server. Langgraph studio guide

Running the Frontend

  1. Navigate to frontend:
cd frontend
  1. Start the Next.js development server:
yarn dev

This will start a local Next.js development server (by default on port 3000).

Access the UI in your browser at http://localhost:3000.

Usage

Once both services are running:

  1. Use langgraph studio UI to interact with the LangGraph server and ensure the workflow is working as expected.

  2. Navigate to http://localhost:3000 to use the chatbot UI.

  3. Upload a small PDF document via the file upload button at the bottom of the page. This will trigger the ingestion graph to extract the text and store the embeddings in Supabase via the frontend app/api/ingest route.

  4. After the ingestion is complete, ask questions in the chat input.

  5. The chatbot will trigger the retrieval graph via the app/api/chat route to retrieve the most relevant documents from the vector database and use the relevant PDF context (if needed) to answer.

Uploading/Ingesting PDFs

Click on the paperclip icon in the chat input area.

Select one or more PDF files to upload ensuring a total of max 5, each under 10MB (you can change these threshold values in the app/api/ingest route).

The backend processes the PDFs, extracts text, and stores embeddings in Supabase (or your chosen vector store).

Asking Questions

Viewing Chat History

Deploying the Backend

To deploy your LangGraph agent to a cloud service, you can either use LangGraph's cloud as per this guide or self-host it as per this guide.

Deploying the Frontend

The frontend can be deployed to any hosting that supports Next.js (Vercel, Netlify, etc.).

Make sure to set relevant environment variables in your deployment environment. In particular, ensure NEXT_PUBLIC_LANGGRAPH_API_URL is pointing to your deployed backend URL.

Customizing the Agent

You can customize the agent on the backend and frontend.

Backend

Frontend

Troubleshooting

  1. .env Not Loaded

    • Make sure you copied .env.example to .env in both backend and frontend.
    • Check your environment variables are correct and restart the dev server.
  2. Supabase Vector Store

    • Ensure you have configured your Supabase instance with the documents table and match_documents function. Check the official LangChain docs on Supabase integration.
  3. OpenAI Errors

    • Double-check your OPENAI_API_KEY. Make sure you have enough credits/quota.
  4. LangGraph Not Running

    • If yarn langgraph:dev fails, confirm your Node version is >= 18 and that you have all dependencies installed.
  5. Network Errors

    • Frontend must point to the correct NEXT_PUBLIC_LANGGRAPH_API_URL. By default, it is http://localhost:2024.

Next Steps

If you'd like to contribute to this project, feel free to open a pull request. Ensure it is well documented and includes tests in the test files.

If you'd like to learn more about building AI chatbots and agents with LangChain and LangGraph, check out the book Learning LangChain (O'Reilly).

ai-pdf-chatbot-langchain (mayooear/ai-pdf-chatbot-langchain)

Searching Database…

Что это такое?Это шаблонный проект для ИИ-агента-чатбота, который загружает PDF-документы, сохраняет их эмбеддинги в векторной базе данных (Supabase) и отвечает на вопросы пользователя о них с помощью LLM, например OpenAI, с оркестрацией через LangChain и LangGraph.
Это готовый продукт или шаблон, на котором я буду строить?Это настраиваемый шаблон монорепозитория с бэкендом на Node.js/TypeScript и LangGraph и фронтендом на Next.js/React. Это отправная точка, которую нужно адаптировать, а не готовое приложение.
Как мне запустить это локально?Клонируйте репозиторий, выполните 'yarn install' в корне, скопируйте файлы .env.example из папок frontend и backend в .env и заполните их, затем запустите dev-сервер LangGraph в папке backend и dev-сервер Next.js в папке frontend (по умолчанию порты 2024 и 3000).
Какие аккаунты или ключи нужны перед стартом?Нужны Node.js v18+ (рекомендуется v20) с Yarn, проект Supabase с таблицей documents и функцией match_documents для векторного поиска, а также ключ API OpenAI (или ключ другого провайдера LLM). Ключ API LangChain/LangSmith необязателен, но рекомендуется для трассировки.
Этот проект ещё поддерживается?Нет, проект заархивирован и явно помечен как неподдерживаемый, он сохранён только для справки. Также история чата не сохраняется между сессиями в демо-интерфейсе, сохраняются только загруженные документы.
Для кого это предназначено?Для разработчиков, которым нужна эталонная реализация чатботов по PDF в стиле RAG на LangChain/LangGraph, и для читателей книги 'Learning LangChain' (O'Reilly), которые ищут сопровождающий её пример кода.
Как на самом деле работают загрузка PDF и ответы?Вы загружаете до 5 PDF-файлов (максимум по 10 МБ каждый) через интерфейс чата. Это запускает граф загрузки, который извлекает текст и сохраняет эмбеддинги в Supabase. Когда вы задаёте вопрос, запускается граф поиска: он находит наиболее релевантные фрагменты и выводит ответ по частям, со ссылками 'View Sources'.
Могу ли я заменить векторное хранилище или провайдера LLM?Да. В backend файлы src/shared/configuration.ts и src/shared/retrieval.ts позволяют изменить векторное хранилище по умолчанию, значение k и фильтры, а также добавить новые функции-ретриверы. В frontend файл constants/graphConfigs.ts определяет модель и ретривер, которые отправляются в графы.
Можно ли развернуть это в продакшн?Да. Бэкенд на LangGraph можно развернуть в облаке LangGraph или на собственном сервере, а фронтенд на Next.js можно развернуть на любом хостинге, совместимом с Next.js, например Vercel или Netlify.
Creator
mayooear
Size
6.6 MB
Stars
16.6K
Updated
CommitMar 27
Age
3y
Commits · 90 Days