💻
RAG and LLM Bootcamp
  • Welcome to the Bootcamp
    • Course Structure
    • Course Syllabus and Timelines
    • Know your Educators
    • Action Items and Prerequisites
    • Kick-Off Session for the Bootcamp
  • Basics of LLMs
    • What is Generative AI?
    • What is a Large Language Model?
    • Advantages and Applications of LLMs
    • Bonus Resource: Multimodal LLMs and Google Gemini
  • Word Vectors, Simplified
    • What is a Word Vector?
    • Word Vector Relationships
    • Role of Context in LLMs
    • Transforming Vectors into LLM Responses
    • Bonus: Overview of the Transformer Architecture
      • Attention Mechanism
      • Multi-Head Attention and Transformer Architecture
      • Vision Transformers (ViTs)
    • Bonus: Future of LLMs? | By Transformer Co-inventor
    • Graded Quiz 1
  • Prompt Engineering and Token Limits
    • What is Prompt Engineering
    • Prompt Engineering and In-context Learning
    • For Starters: Best Practices
    • Navigating Token Limits
    • Hallucinations in LLMs
    • Prompt Engineering Excercise (Ungraded)
      • Story for the Excercise: The eSports Enigma
      • Your Task fror the Module
  • RAG and LLM Architecture
    • What is Retrieval Augmented Generation (RAG)?
    • Primer to RAG: Pre-trained and Fine-Tuned LLMs
    • In-context Learning
    • High-level LLM Architecture Components for In-context Learning
    • Diving Deeper: LLM Architecture Components
    • Basic RAG Architecture with Key Components
    • RAG versus Fine-Tuning and Prompt Engineering
    • Versatility and Efficiency in RAG
    • Key Benefits of using RAG in an Enterprise/Production Setup
    • Hands-on Demo: Performing Similarity Search in Vectors (Bonus Module)
    • Using kNN and LSH to Enhance Similarity Search (Bonus Module)
    • Bonus Video: Implementing End-to-End RAG | 1-Hour Session
    • Graded Quiz 2
  • Hands-on Development
    • Prerequisites (Must)
    • Docker Basics
    • Your Hands-on RAG Journey
    • 1 – First RAG Pipeline
      • Building with Open AI
      • How it Works
      • Using Open AI Alternatives
      • RAG with Open Source and Running "Examples"
    • 2 – Amazon Discounts App
      • How the Project Works
      • Building the App
    • 3 – Private RAG with Mistral, Ollama and Pathway
      • Building a Private RAG project
      • (Bonus) Adaptive RAG Overview
    • 4 – Realtime RAG with LlamaIndex/Langchain and Pathway
      • Understand the Basics
      • Implementation with LlamaIndex and Langchain
  • Final Project + Giveaways
    • Prizes and Giveaways
    • Suggested Tracks for Ideation
    • Sample Projects and Additional Resources
    • Submit Project for Review
Powered by GitBook
On this page
  • Introduction
  • Prerequisites
  • Step-by-Step Process
  • Conclusion
  1. Hands-on Development
  2. 1 – First RAG Pipeline

Using Open AI Alternatives

PreviousHow it WorksNextRAG with Open Source and Running "Examples"

Last updated 10 months ago

In this module, we’ll cover how to build a RAG project using alternate APIs by Gemini, Replicate, and 300+ LLMs apart from OpenAI.

Here you'll use Google Gemini Pro for chat completions/generation and Sentence Transformer for embeddings.

If you've already built a pipeline using OpenAI, you can jump to .

Introduction

We’ll walk you through setting up a RAG project using Gemini Pro and Pathway.

Key Features:

  • Create an in-memory persistent vector store with real-time document indexing using Pathway that can easily work with documents in your Google Drive, Microsoft 365 SharePoint, Databases, Local directory, etc.

  • Connect an LLM model of choice () to your knowledge base.

  • Get quality, accurate, and precise responses to your questions.

  • Ask questions about folders, files, or all your documents easily, with the help of filtering options.

  • Get an executive outlook for a question on different files to easily access available knowledge in your documents.

Prerequisites

Before we begin, ensure you have the following requirements we shared earlier:

  • Docker Desktop: This tool allows you to run applications in isolated containers. Download Docker Desktop. (Note: Your antivirus software might block the installation, so temporarily disable it if needed.)

  • If you’re using VS Code, consider installing the Docker extension to manage containers directly from the editor.

Step-by-Step Process

Step 1: Verify Docker Installation

First, let’s verify that Docker is properly installed and open in your system. Open your terminal (Command Prompt on Windows) and run:

docker --version

You should see the Docker version information if it's installed correctly.

Step 2: Clone the LLM App Templates Repository

Next, clone the llm-app repository from GitHub. This repository contains all the files you’ll need.

git clone https://github.com/pathwaycom/llm-app.git

If you get an error because you have previously cloned an older version of the llm-app repository, ensure you're in the correct repository directory and update it using:

git pull

This will update your local repository with the latest changes from the remote repository.

Step 3: Navigate to the Project Directory

Change to the directory where the relevant example of your current project is located.

cd examples/pipelines/demo-question-answering

Step 4: Create a .env File and Put Your Gemini API Key

If you've already built a pipeline with Open AI, this is where things get slightly different. Configure your key in a .env file by providing it as follows:

GEMINI_API_KEY=*******

Replace ******* with your actual Gemini API key. Save the file as .env in the demo-question-answering folder.

Step 5: Update requirements.txt File

Add the following dependencies to the requirements.txt file that enable us to use Pathway LiteLLM wrapper, Google's APIs, and Sentence Transformers (a.k.a. SBERT) for embeddings:

pathway[all]>=0.11.0
python-dotenv==1.0.1
mpmath==1.3.0
litellm>=1.35
Google-generativeai
Sentence-transformers

Step 6: Update app.py Code

Replace the existing app.py code with the following:

import logging
import sys
import os
import click
import pathway as pw
import yaml
from dotenv import load_dotenv

from pathway.udfs import DiskCache, ExponentialBackoffRetryStrategy
from pathway.xpacks.llm import embedders, llms, parsers, splitters
from pathway.xpacks.llm.question_answering import BaseRAGQuestionAnswerer
from pathway.xpacks.llm.vector_store import VectorStoreServer

# To use advanced features with Pathway Scale, get your free license key from
# https://pathway.com/features and paste it below.
# To use Pathway Community, comment out the line below.
pw.set_license_key("demo-license-key-with-telemetry")

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(name)s %(levelname)s %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

load_dotenv()

def data_sources(source_configs) -> list[pw.Table]:
    sources = []
    for source_config in source_configs:
        if source_config["kind"] == "local":
            source = pw.io.fs.read(
                **source_config["config"],
                format="binary",
                with_metadata=True,
            )
            sources.append(source)
        elif source_config["kind"] == "gdrive":
            source = pw.io.gdrive.read(
                **source_config["config"],
                with_metadata=True,
            )
            sources.append(source)
        elif source_config["kind"] == "sharepoint":
            try:
                import pathway.xpacks.connectors.sharepoint as io_sp

                source = io_sp.read(**source_config["config"], with_metadata=True)
                sources.append(source)
            except ImportError:
                print(
                    "The Pathway Sharepoint connector is part of the commercial offering, "
                    "please contact us for a commercial license."
                )
                sys.exit(1)

    return sources

@click.command()
@click.option("--config_file", default="config.yaml", help="Config file to be used.")
def run(config_file: str = "config.yaml"):
    with open(config_file) as config_f:
        configuration = yaml.safe_load(config_f)

    LLM_MODEL = configuration["llm_config"]["model"]

    embedding_model = "avsolatorio/GIST-small-Embedding-v0"

    embedder = embedders.SentenceTransformerEmbedder(
        embedding_model,
        call_kwargs={"show_progress_bar": False}
    )

    chat = llms.LiteLLMChat(
        model=LLM_MODEL,
        retry_strategy=ExponentialBackoffRetryStrategy(max_retries=6),
        cache_strategy=DiskCache(),
    )

    host_config = configuration["host_config"]
    host, port = host_config["host"], host_config["port"]

    doc_store = VectorStoreServer(
        *data_sources(configuration["sources"]),
        embedder=embedder,
        splitter=splitters.TokenCountSplitter(max_tokens=400),
        parser=parsers.ParseUnstructured(),
    )

    rag_app = BaseRAGQuestionAnswerer(llm=chat, indexer=doc_store)

    rag_app.build_server(host=host, port=port)

    rag_app.run_server(with_cache=True, terminate_on_error=False)

if __name__ == "__main__":
    run()

Key Changes:

  • Embedding Model Selection: Chose avsolatorio/GIST-small-Embedding-v0 for embedding chunked texts. This model is compact and performed well in tests. Other options include mixedbread-ai/mxbai-embed-large-v1and avsolatorio/GIST-Embedding-v0.

  • LLM Initialization: Integrated the Gemini Pro model by updating the configuration and initialization script to use LLM_MODEL instead of GPT_MODEL.

Step 7: Update config.yaml File

Update the model specification in the config.yaml file to use Gemini Pro and keep rest of the items as is:

llm_config:
  model: "gemini/gemini-pro"

Step 8: Build the Docker Image

Build the Docker image. This step might take a few minutes depending on your machine. Ensure you have enough space (approximately 8 GB).

docker build -t raggem .

Step 9: Run the Docker Container

Run the Docker container, mounting the data folder and exposing port 8000. For Windows:

docker run -v "${PWD}/data:/app/data" -p 8000:8000 raggem

For Linux/Mac:

docker run -v "$(pwd)/data:/app/data" -p 8000:8000 --env-file .env raggem

Handling Port Conflicts: If port 8000 is already in use, specify a different port. For example, to use port 8080:

For Windows:

docker run -v "${PWD}/data:/app/data" -p 8080:8000 raggem

For Linux/Mac:

docker run -v "$(pwd)/data:/app/data" -p 8080:8000 --env-file .env raggem

Step 10: Check the List of Files

To see the list of files in the data folder, use the curl command. While doing this ensure that you'll need to update the port here as well if you changed it in the previous step while managing port conflicts:

curl -X 'POST' 'http://localhost:8000/v1/pw_list_documents' -H 'accept: */*' -H 'Content-Type: application/json'

This will return the list of files that are ingested as an external data source for your RAG project.

Step 11: Run the RAG Service

Start the RAG service by asking a simple question. For example:

curl -X 'POST' 'http://0.0.0.0:8000/v1/pw_ai_answer' -H 'accept: */*' -H 'Content-Type: application/json' -d '{
  "prompt": "What are the terms and conditions"
}'

The response should be something like:

code"The terms and conditions are: Rights Granted, Use of Titles, Warranties and Representations, Indemnification, Disclaimers, Limitation of Liability, Governing Law, Dispute Resolution, Term, Termination, Entire Agreement, Assignment, Waiver, Severability, Notices, Counterparts and Construction."

Conclusion

This will help you set up a powerful RAG pipeline with Gemini Pro.

If you get stuck, you should explore the Pathway documentation here and try to find the issue yourself once. It will also help you understand the code better, and many of your queries can actually be figured out via LLMs as well.

If still needed, you are very welcomed to ask it in the Discord channel for this bootcamp or also post your query on . It is generally a great practice to post your queries in the most relevant open source communities.

😄
LiteLLM's Discord
https://docs.litellm.ai/docs/providers
Step 4