Build RAG Chatbot with Llamaindex, HNSWlib, DeepSeek R1, and voyage-3-large
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:
- Llamaindex: a data framework that connects large language models (LLMs) with various data sources, enabling efficient retrieval-augmented generation (RAG). It helps structure, index, and query private or external data, optimizing LLM applications for search, chatbots, and analytics.
- HNSWlib: a high-performance C++ and Python library for approximate nearest neighbor (ANN) search using the Hierarchical Navigable Small World (HNSW) algorithm. It provides fast, scalable, and efficient similarity search in high-dimensional spaces, making it ideal for vector databases and AI applications.
- DeepSeek R1: DeepSeek R1 is an open-weight large language model (LLM) designed for high-performance natural language processing, featuring a 128K context window for long-document understanding. It excels in reasoning, coding, and text generation, making it ideal for research, commercial applications, and AI-driven workflows requiring extended context retention and adaptability.
- Voyage-3-Large: This model is designed for generative tasks, offering enhanced creativity and contextual understanding. With robust training on diverse datasets, it excels in producing coherent narratives and dialogue, making it ideal for applications in storytelling, content creation, and interactive experiences where imaginative output is essential.
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 Llamaindex
pip install llama-index
Step 2: Install and Set Up DeepSeek R1
%pip install llama-index-llms-deepseek
from llama_index.llms.deepseek import DeepSeek
# you can also set DEEPSEEK_API_KEY in your environment variables
llm = DeepSeek(model="deepseek-reasoner", api_key="you_api_key")
# You might also want to set deepseek as your default llm
# from llama_index.core import Settings
# Settings.llm = llm
Step 3: Install and Set Up voyage-3-large
%pip install llama-index-embeddings-voyageai
from llama_index.embeddings.voyageai import VoyageEmbedding
embed_model = VoyageEmbedding(
voyage_api_key="",
model_name="voyage-3-large",
)
Step 4: Install and Set Up HNSWlib
%pip install llama-index-vector-stores-hnswlib
from llama_index.vector_stores.hnswlib import HnswlibVectorStore
from llama_index.core import (
VectorStoreIndex,
StorageContext,
SimpleDirectoryReader,
)
vector_store = HnswlibVectorStore.from_params(
space="ip",
dimension=embed_model._model.get_sentence_embedding_dimension(),
max_elements=1000,
)
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 requests
from llama_index.core import SimpleDirectoryReader
# load documents
url = 'https://raw.githubusercontent.com/milvus-io/milvus-docs/refs/heads/v2.5.x/site/en/about/overview.md'
example_file = 'example_file.md' # You can replace it with your own file paths.
response = requests.get(url)
with open(example_file, 'wb') as f:
f.write(response.content)
documents = SimpleDirectoryReader(
input_files=[example_file]
).load_data()
print("Document ID:", documents[0].doc_id)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context, embed_model=embed_model
)
query_engine = index.as_query_engine(llm=llm)
res = query_engine.query("What is Milvus?") # You can replace it with your own question.
print(res)
Example output
Milvus is a high-performance, highly scalable vector database designed to operate efficiently across various environments, from personal laptops to large-scale distributed systems. It is available as both open-source software and a cloud service. Milvus excels in managing unstructured data by converting it into numerical vectors through embeddings, which facilitates fast and scalable searches and analytics. The database supports a wide range of data types and offers robust data modeling capabilities, allowing users to organize their data effectively. Additionally, Milvus provides multiple deployment options, including a lightweight version for quick prototyping and a distributed version for handling massive data scales.
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.
LlamaIndex optimization tips
To optimize LlamaIndex for a Retrieval-Augmented Generation (RAG) setup, structure your data efficiently using hierarchical indices like tree-based or keyword-table indices for faster retrieval. Use embeddings that align with your use case to improve search relevance. Fine-tune chunk sizes to balance context length and retrieval precision. Enable caching for frequently accessed queries to enhance performance. Optimize metadata filtering to reduce unnecessary search space and improve speed. If using vector databases, ensure indexing strategies align with your query patterns. Implement async processing to handle large-scale document ingestion efficiently. Regularly monitor query performance and adjust indexing parameters as needed for optimal results.
HNSWlib optimization tips
To optimize HNSWlib for a Retrieval-Augmented Generation (RAG) setup, fine-tune the M parameter (number of connections per node) to balance accuracy and memory usage—higher values improve recall but increase indexing time. Adjust ef_construction
(search depth during indexing) to enhance retrieval quality. During queries, set ef_search
dynamically based on latency vs. accuracy trade-offs. Use multi-threading for faster indexing and querying. Ensure vectors are properly normalized for consistent similarity comparisons. If working with large datasets, periodically rebuild the index to maintain efficiency. Store the index on disk and load it efficiently for persistence in production environments. Monitor query performance and tweak parameters to achieve optimal speed-recall balance.
DeepSeek R1 optimization tips
To optimize DeepSeek R1 in a RAG setup, ensure that retrieval delivers high-quality, semantically relevant documents by fine-tuning your embedding model and search strategies. Use hybrid retrieval (vector + keyword search) to improve accuracy, especially for complex queries. Keep document chunks concise but rich in context to avoid exceeding token limits. Leverage caching to reduce redundant queries and enhance response speed. Experiment with prompt templates to maximize the model’s reasoning and comprehension capabilities. Monitor API latency and adjust query batching to improve efficiency. Fine-tune temperature settings to maintain consistency in generated responses.
voyage-3-large optimization tips
voyage-3-large provides enhanced reasoning capabilities, making it ideal for complex RAG tasks requiring deep contextual understanding. Optimize retrieval by implementing a multi-step ranking system that prioritizes highly relevant documents while filtering out lower-quality information. Use structured prompts with clearly delineated context and user queries to improve comprehension. Adjust temperature (0.1–0.3) and fine-tune top-k and top-p settings to maintain accuracy and prevent excessive variability. Take advantage of parallelized inference and request batching to improve processing efficiency. Leverage caching for high-frequency queries to reduce costs and latency. In multi-model setups, deploy voyage-3-large for intricate reasoning tasks while using smaller models for less complex queries to balance cost and performance effectively.
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
What Have You Learned?
Congratulations on completing this tutorial! You’ve delved into the dynamic world of Retrieval-Augmented Generation (RAG) systems, and what an exciting journey it’s been! By integrating LlamaIndex, HNSWlib, the DeepSeek R1 vector database, and the voyage-3-large LLM, you've learned how to construct a robust pipeline that combines efficient data retrieval with powerful language generation. Each of these components plays a crucial role: LlamaIndex enables you to efficiently manage and query your datasets, HNSWlib brings speed and accuracy to vector searches, while the DeepSeek R1 provides an outstanding foundation for embedding your data. And let’s not forget the voyage-3-large LLM, which transforms those embeddings into insightful, contextually aware responses!
Throughout this tutorial, you’ve also discovered key optimization tips to enhance your RAG system. Utilizing a free RAG cost calculator, you've gained valuable insights into managing your resources more efficiently. Now that you’ve grasped how these components fit together, the possibilities for creating your own innovative RAG applications are endless! Don’t stop here—embrace the knowledge you’ve gained, start building and optimizing your unique RAG systems, and let your creativity shine! The future is bright for you and your projects, so go ahead and make your mark on the world of AI!
Further Resources
🌟 In addition to this RAG tutorial, unleash your full potential with these incredible resources to level up your RAG skills.
- How to Build a Multimodal RAG | Documentation
- How to Enhance the Performance of Your RAG Pipeline
- Graph RAG with Milvus | Documentation
- How to Evaluate RAG Applications - Zilliz Learn
- Generative AI Resource Hub | Zilliz
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! 💖
- Introduction to RAG
- Key Components We'll Use for This RAG Chatbot
- Step 1: Install and Set Up Llamaindex
- Step 2: Install and Set Up DeepSeek R1
- Step 3: Install and Set Up voyage-3-large
- Step 4: Install and Set Up HNSWlib
- Step 5: Build a RAG Chatbot
- Optimization Tips
- RAG Cost Calculator: A Free Tool to Calculate Your Cost in Seconds
- What Have You Learned?
- Further Resources
- We'd Love to Hear What You Think!
Content
Vector Database at Scale
Zilliz Cloud is a fully-managed vector database built for scale, perfect for your RAG apps.
Try Zilliz Cloud for Free