Build RAG Chatbot with LangChain, pgvector, Mistral AI Mistral 7B, and Nomic Embed Text V2

Introduction to RAG

Retrieval-Augmented Generation (RAG) is a game-changer for GenAI applications, especially in conversational AI. It combines the power of pre-trained large language models (LLMs) like OpenAI’s GPT with external knowledge sources stored in vector databases such as Milvus and Zilliz Cloud, allowing for more accurate, contextually relevant, and up-to-date response generation. A RAG pipeline usually consists of four basic components: a vector database, an embedding model, an LLM, and a framework.

Key Components We'll Use for This RAG Chatbot

This tutorial shows you how to build a simple RAG chatbot in Python using the following components:

  • LangChain: An open-source framework that helps you orchestrate the interaction between LLMs, vector stores, embedding models, etc, making it easier to integrate a RAG pipeline.
  • Pgvector: an open-source extension for PostgreSQL that enables efficient storage and querying of high-dimensional vector data, essential for machine learning and AI applications. Designed to handle embeddings, it supports fast approximate nearest neighbor (ANN) searches using algorithms like HNSW and IVFFlat. Since it is just a vector search add-on to traditional search rather than a purpose-built vector database, it lacks scalability and availability and many other advanced features required by enterprise-level applications. Therefore, if you prefer a much more scalable solution or hate to manage your own infrastructure, we recommend using Zilliz Cloud, which is a fully managed vector database service built on the open-source Milvus and offers a free tier supporting up to 1 million vectors.)
  • Mistral AI's Mistral 7B: A highly efficient and powerful language model with 7 billion parameters. It is designed to offer robust performance for a wide range of natural language processing tasks, delivering high-quality responses while maintaining a balance between speed and computational resource usage. Its architecture is optimized for both flexibility and scalability in AI applications.
  • Nomic Embed Text V2: An open-source, multilingual text embedding model using a Mixture-of-Experts (MoE) architecture for efficient processing. Trained on 1.6 billion text pairs, it excels in retrieval tasks, supports flexible embedding dimensions, and optimizes storage and compute costs. Its training data and code are fully open-sourced for transparency.

By the end of this tutorial, you’ll have a functional chatbot capable of answering questions based on a custom knowledge base.

Note: Since we may use proprietary models in our tutorials, make sure you have the required API key beforehand.

Step 1: Install and Set Up LangChain

%pip install --quiet --upgrade langchain-text-splitters langchain-community langgraph

Step 2: Install and Set Up Mistral AI Mistral 7B

pip install -qU "langchain[mistralai]"
import getpass
import os

if not os.environ.get("MISTRAL_API_KEY"):
  os.environ["MISTRAL_API_KEY"] = getpass.getpass("Enter API key for Mistral AI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("open-mistral-7b", model_provider="mistralai")

Step 3: Install and Set Up Nomic Embed Text V2

pip install -qU langchain-nomic
import getpass
import os

if not os.environ.get("NOMIC_API_KEY"):
  os.environ["NOMIC_API_KEY"] = getpass.getpass("Enter API key for Nomic: ")

from langchain_nomic import NomicEmbeddings

embeddings = NomicEmbeddings(model="nomic-ai/nomic-embed-text-v2-moe")

Step 4: Install and Set Up pgvector

pip install -qU langchain-postgres
from langchain_postgres import PGVector

vector_store = PGVector(
    embeddings=embeddings,
    collection_name="my_docs",
    connection="postgresql+psycopg://...",
)

Step 5: Build a RAG Chatbot

Now that you’ve set up all components, let’s start to build a simple chatbot. We’ll use the Milvus introduction doc as a private knowledge base. You can replace it with your own dataset to customize your RAG chatbot.

import bs4
from langchain import hub
from langchain_community.document_loaders import WebBaseLoader
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langgraph.graph import START, StateGraph
from typing_extensions import List, TypedDict

# Load and chunk contents of the blog
loader = WebBaseLoader(
    web_paths=("https://milvus.io/docs/overview.md",),
    bs_kwargs=dict(
        parse_only=bs4.SoupStrainer(
            class_=("doc-style doc-post-content")
        )
    ),
)

docs = loader.load()

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
all_splits = text_splitter.split_documents(docs)

# Index chunks
_ = vector_store.add_documents(documents=all_splits)

# Define prompt for question-answering
prompt = hub.pull("rlm/rag-prompt")


# Define state for application
class State(TypedDict):
    question: str
    context: List[Document]
    answer: str


# Define application steps
def retrieve(state: State):
    retrieved_docs = vector_store.similarity_search(state["question"])
    return {"context": retrieved_docs}


def generate(state: State):
    docs_content = "\n\n".join(doc.page_content for doc in state["context"])
    messages = prompt.invoke({"question": state["question"], "context": docs_content})
    response = llm.invoke(messages)
    return {"answer": response.content}


# Compile application and test
graph_builder = StateGraph(State).add_sequence([retrieve, generate])
graph_builder.add_edge(START, "retrieve")
graph = graph_builder.compile()

Test the Chatbot

Yeah! You've built your own chatbot. Let's ask the chatbot a question.

response = graph.invoke({"question": "What data types does Milvus support?"})
print(response["answer"])

Example Output

Milvus supports various data types including sparse vectors, binary vectors, JSON, and arrays. Additionally, it handles common numerical and character types, making it versatile for different data modeling needs. This allows users to manage unstructured or multi-modal data efficiently.

Optimization Tips

As you build your RAG system, optimization is key to ensuring peak performance and efficiency. While setting up the components is an essential first step, fine-tuning each one will help you create a solution that works even better and scales seamlessly. In this section, we’ll share some practical tips for optimizing all these components, giving you the edge to build smarter, faster, and more responsive RAG applications.

LangChain optimization tips

To optimize LangChain, focus on minimizing redundant operations in your workflow by structuring your chains and agents efficiently. Use caching to avoid repeated computations, speeding up your system, and experiment with modular design to ensure that components like models or databases can be easily swapped out. This will provide both flexibility and efficiency, allowing you to quickly scale your system without unnecessary delays or complications.

pgvector optimization tips

To optimize pgvector in a Retrieval-Augmented Generation (RAG) setup, consider indexing your vectors using GiST or IVFFlat to significantly speed up search queries and improve retrieval performance. Make sure to leverage parallelization for query execution, allowing multiple queries to be processed simultaneously, especially for large datasets. Optimize memory usage by tuning the vector storage size and using compressed embeddings where possible. To further enhance query speed, implement pre-filtering techniques to narrow down search space before querying. Regularly rebuild indexes to ensure they are up to date with any new data. Fine-tune vectorization models to reduce dimensionality without sacrificing accuracy, thus improving both storage efficiency and retrieval times. Finally, manage resource allocation carefully, utilizing horizontal scaling for larger datasets and offloading intensive operations to dedicated processing units to maintain responsiveness during high-traffic periods.

Mistral AI Mistral 7B optimization tips

Mistral 7B is a dense transformer-based model optimized for efficiency, making it a strong choice for RAG applications with constrained resources. Improve retrieval by using high-quality embeddings and reranking strategies to ensure only the most relevant documents are included in the context window. Optimize token usage by structuring input prompts concisely, eliminating redundant details while preserving key information. Use temperature (0.1–0.3) for consistent factual accuracy and adjust sampling techniques based on the required response diversity. Deploy Mistral 7B in a scalable infrastructure by leveraging quantization techniques (such as 4-bit or 8-bit precision) to improve inference speed without significantly impacting accuracy. Implement batch processing for handling multiple queries efficiently, reducing overall computational load. When working in real-time applications, consider response caching to minimize redundant API calls.

Nomic Embed Text V2 optimization tips

Nomic Embed Text V2 is a versatile embedding model suited for general-purpose text search tasks in RAG systems. Optimize efficiency by preprocessing input data to remove irrelevant noise and focus on the most meaningful content, which can help reduce computational overhead. For faster retrieval, employ approximate nearest neighbor (ANN) search algorithms like HNSW or FAISS to speed up the search process while maintaining accuracy. Consider implementing vector quantization techniques to reduce storage space without significantly affecting retrieval quality. Utilize batching to process multiple texts in parallel and minimize API latency. If working with large datasets, regularly update embeddings to reflect the most recent information, ensuring that your retrieval system remains relevant and effective.

By implementing these tips across your components, you'll be able to enhance the performance and functionality of your RAG system, ensuring it’s optimized for both speed and accuracy. Keep testing, iterating, and refining your setup to stay ahead in the ever-evolving world of AI development.

RAG Cost Calculator: A Free Tool to Calculate Your Cost in Seconds

Estimating the cost of a Retrieval-Augmented Generation (RAG) pipeline involves analyzing expenses across vector storage, compute resources, and API usage. Key cost drivers include vector database queries, embedding generation, and LLM inference.

RAG Cost Calculator is a free tool that quickly estimates the cost of building a RAG pipeline, including chunking, embedding, vector storage/search, and LLM generation. It also helps you identify cost-saving opportunities and achieve up to 10x cost reduction on vector databases with the serverless option.

Calculate your RAG cost now.

Calculate your RAG cost Calculate your RAG cost

What Have You Learned?

By diving into this tutorial, you’ve unlocked the power of combining cutting-edge tools to build a robust RAG system from the ground up! You learned how LangChain acts as the glue, orchestrating workflows between your data, models, and applications with flexibility. By integrating pgvector as your vector database, you now understand how to store and retrieve embeddings efficiently, turning unstructured data into searchable knowledge. The Mistral AI Mistral 7B model showcased its prowess in generating human-like, context-aware responses, while Nomic Embed Text V2 transformed your text into rich embeddings, capturing semantic nuances for precise retrieval. Together, these tools form a seamless pipeline: ingest data, embed it, store it for fast lookup, and generate answers that feel natural and informed. Plus, you picked up pro tips like optimizing chunk sizes for embeddings and filtering metadata in pgvector to balance speed and accuracy—small tweaks that make a big difference in performance. And let’s not forget the handy free RAG cost calculator shared in the tutorial, helping you estimate expenses and scale smartly!

Now that you’ve seen the magic of RAG in action, it’s time to run with it! You’ve got the blueprint to create applications that answer questions, summarize content, or even power chatbots with depth and precision. Experiment with fine-tuning Mistral 7B for niche domains, tweak pgvector’s indexing strategies, or swap in different embedding models to see how they impact results. The tools are yours, and the possibilities are endless. Remember, every iteration brings you closer to building something truly transformative. So fire up your IDE, play with the code, and let your creativity flow—your next RAG-powered innovation is just a few lines of code away. Happy building, and here’s to the incredible things you’ll create! 🚀

Further Resources

🌟 In addition to this RAG tutorial, unleash your full potential with these incredible resources to level up your RAG skills.

We'd Love to Hear What You Think!

We’d love to hear your thoughts! 🌟 Leave your questions or comments below or join our vibrant Milvus Discord community to share your experiences, ask questions, or connect with thousands of AI enthusiasts. Your journey matters to us!

If you like this tutorial, show your support by giving our Milvus GitHub repo a star ⭐—it means the world to us and inspires us to keep creating! 💖

keepReading