Build RAG Chatbot with Haystack, OpenSearch, NVIDIA Llama 3 70B Instruct, and HuggingFace all-mpnet-base-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:
- Haystack: An open-source Python framework designed for building production-ready NLP applications, particularly question answering and semantic search systems. Haystack excels at retrieving information from large document collections through its modular architecture that combines retrieval and reader components. Ideal for developers creating search applications, chatbots, and knowledge management systems that require efficient document processing and accurate information extraction from unstructured text.
- OpenSearch: An open-source search and analytics suite derived from Elasticsearch. It offers robust full-text search and real-time analytics, with vector search available as an add-on for similarity-based queries, extending its capabilities to handle high-dimensional data. Since it is just a vector search add-on 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.)
- NVIDIA Llama 3 70B Instruct: A high-performance AI model optimized by NVIDIA for complex instruction-following tasks, combining Meta's Llama 3 70B architecture with NVIDIA’s hardware-accelerated efficiency. Strengths include rapid inference, scalability on GPUs, and nuanced context understanding. Ideal for enterprise-grade chatbots, technical support automation, and data-driven decision-making in resource-intensive environments.
- HuggingFace all-mpnet-base-v2: A versatile sentence-transformers model optimized for generating high-quality semantic embeddings. Leveraging MPNet's masked and permuted pretraining, it excels in capturing nuanced text semantics, offering robust performance in multilingual and domain-specific tasks. Ideal for semantic search, text clustering, similarity comparison, and information retrieval due to its efficiency and accuracy.
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 Haystack
import os
import requests
from haystack import Pipeline
from haystack.components.converters import MarkdownToDocument
from haystack.components.preprocessors import DocumentSplitter
from haystack.components.writers import DocumentWriter
Step 2: Install and Set Up NVIDIA Llama 3 70B Instruct
To start using models self-hosted with NVIDIA, we need to install the nvidia-haystack
package first.
pip install nvidia-haystack
To use LLMs with NVIDIA, you need to specify the correct api_url
and your API key. You can get your API key directly from the catalog website. You also need to get an NVIDIA API key to build this pipeline. Here, we will use the NVIDIA_API_KEY
environment variable by default. Otherwise, you can pass an API key at initialization with api_key
, as in the following example.
from haystack.utils.auth import Secret
from haystack_integrations.components.generators.nvidia import NvidiaGenerator
generator = NvidiaGenerator(
model="meta/llama3-70b-instruct",
api_url="https://integrate.api.nvidia.com/v1",
api_key=Secret.from_token("<your-api-key>"),
model_arguments={
"temperature": 0.2,
"top_p": 0.7,
"max_tokens": 1024,
},
)
generator.warm_up()
Step 3: Install and Set Up HuggingFace all-mpnet-base-v2
Haystack'sHuggingFaceAPITextEmbedder
can be used to embed strings with different Hugging Face APIs:
The component uses a HF_API_TOKEN
environment variable by default. Otherwise, you can pass a Hugging Face API token at initialization with token
– see code examples below. The token is needed:
- If you use the Serverless Inference API, or
- If you use Inference Endpoints.
Here, in this tutorial, we'll use the Free Serverless Inference API. Let's install and set up the model.
To use this API, you need a free Hugging Face token. The Embedder expects the model
in api_params
.
from haystack.components.embedders import HuggingFaceAPITextEmbedder
from haystack.utils import Secret
from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder
from haystack.dataclasses import Document
text_embedder = HuggingFaceAPITextEmbedder(api_type="serverless_inference_api",
api_params={"model": "sentence-transformers/all-mpnet-base-v2"},
token=Secret.from_token("<your-api-key>"))
document_embedder = HuggingFaceAPIDocumentEmbedder(api_type="serverless_inference_api",
api_params={"model": "sentence-transformers/all-mpnet-base-v2"},
token=Secret.from_token("<your-api-key>"))
Step 4: Install and Set Up OpenSearch
If you have Docker set up, we recommend pulling the Docker image and running it.
docker pull opensearchproject/opensearch:2.11.0
docker run -p 9200:9200 -p 9600:9600 -e "discovery.type=single-node" -e "ES_JAVA_OPTS=-Xms1024m -Xmx1024m" opensearchproject/opensearch:2.11.0
Once you have a running OpenSearch instance, install the opensearch-haystack
integration:
pip install opensearch-haystack
from haystack_integrations.components.retrievers.opensearch import OpenSearchEmbeddingRetriever
from haystack_integrations.document_stores.opensearch import OpenSearchDocumentStore
document_store = OpenSearchDocumentStore(hosts="http://localhost:9200", use_ssl=True,
verify_certs=False, http_auth=("admin", "admin"))
retriever = OpenSearchEmbeddingRetriever(document_store=document_store)
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 your own dataset to customize your RAG chatbot.
url = 'https://raw.githubusercontent.com/milvus-io/milvus-docs/refs/heads/v2.5.x/site/en/about/overview.md'
example_file = 'example_file.md'
response = requests.get(url)
with open(example_file, 'wb') as f:
f.write(response.content)
file_paths = [example_file] # You can replace it with your own file paths.
indexing_pipeline = Pipeline()
indexing_pipeline.add_component("converter", MarkdownToDocument())
indexing_pipeline.add_component("splitter", DocumentSplitter(split_by="sentence", split_length=2))
indexing_pipeline.add_component("embedder", document_embedder)
indexing_pipeline.add_component("writer", DocumentWriter(document_store))
indexing_pipeline.connect("converter", "splitter")
indexing_pipeline.connect("splitter", "embedder")
indexing_pipeline.connect("embedder", "writer")
indexing_pipeline.run({"converter": {"sources": file_paths}})
# print("Number of documents:", document_store.count_documents())
question = "What is Milvus?" # You can replace it with your own question.
retrieval_pipeline = Pipeline()
retrieval_pipeline.add_component("embedder", text_embedder)
retrieval_pipeline.add_component("retriever", retriever)
retrieval_pipeline.connect("embedder", "retriever")
retrieval_results = retrieval_pipeline.run({"embedder": {"text": question}})
# for doc in retrieval_results["retriever"]["documents"]:
# print(doc.content)
# print("-" * 10)
from haystack.utils import Secret
from haystack.components.builders import PromptBuilder
retriever = OpenSearchEmbeddingRetriever(document_store=document_store)
text_embedder = HuggingFaceAPITextEmbedder(api_type="serverless_inference_api",
api_params={"model": "sentence-transformers/all-mpnet-base-v2"},
token=Secret.from_token("<your-api-key>"))
prompt_template = """Answer the following query based on the provided context. If the context does
not include an answer, reply with 'I don't know'.\n
Query: {{query}}
Documents:
{% for doc in documents %}
{{ doc.content }}
{% endfor %}
Answer:
"""
rag_pipeline = Pipeline()
rag_pipeline.add_component("text_embedder", text_embedder)
rag_pipeline.add_component("retriever", retriever)
rag_pipeline.add_component("prompt_builder", PromptBuilder(template=prompt_template))
rag_pipeline.add_component("generator", generator)
rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
rag_pipeline.connect("retriever.documents", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "generator")
results = rag_pipeline.run({"text_embedder": {"text": question}, "prompt_builder": {"query": question},})
print('RAG answer:\n', results["generator"]["replies"][0])
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.
Haystack optimization tips
To optimize Haystack in a RAG setup, ensure you use an efficient retriever like FAISS or Milvus for scalable and fast similarity searches. Fine-tune your document store settings, such as indexing strategies and storage backends, to balance speed and accuracy. Use batch processing for embedding generation to reduce latency and optimize API calls. Leverage Haystack's pipeline caching to avoid redundant computations, especially for frequently queried documents. Tune your reader model by selecting a lightweight yet accurate transformer-based model like DistilBERT to speed up response times. Implement query rewriting or filtering techniques to enhance retrieval quality, ensuring the most relevant documents are retrieved for generation. Finally, monitor system performance with Haystack’s built-in evaluation tools to iteratively refine your setup based on real-world query performance.
OpenSearch optimization tips
To optimize OpenSearch in a Retrieval-Augmented Generation (RAG) setup, fine-tune indexing by enabling efficient mappings and reducing unnecessary stored fields. Use HNSW for vector search to speed up similarity queries while balancing recall and latency with appropriate ef_search
and ef_construction
values. Leverage shard and replica settings to distribute load effectively, and enable caching for frequent queries. Optimize text-based retrieval with BM25 tuning and custom analyzers for better relevance. Regularly monitor cluster health, index size, and query performance using OpenSearch Dashboards and adjust configurations accordingly.
NVIDIA Llama 3 70B Instruct optimization tips
Optimize inference speed by leveraging model quantization (e.g., 16-bit or 8-bit) to reduce memory usage without significant accuracy loss. Use NVIDIA’s TensorRT-LLM for kernel fusion and efficient GPU utilization, and enable dynamic batching to process multiple queries concurrently. Fine-tune retrieval relevance thresholds to balance precision and recall, minimizing unnecessary context. Cache frequent retrieval results and precompute embeddings. Profile memory usage to avoid bottlenecks, and employ mixed-precision training if fine-tuning. Regularly update drivers and libraries (e.g., CUDA, PyTorch) to leverage hardware acceleration and software optimizations.
HuggingFace all-mpnet-base-v2 optimization tips
To optimize the all-mpnet-base-v2 model in a RAG setup, preprocess input text by removing noise, truncating to the 384-token limit, and splitting documents into contextually coherent chunks. Use cosine similarity for retrieval, as the model is fine-tuned for this metric. Batch embedding generation improves throughput, while leveraging GPU acceleration reduces latency. Fine-tune the model on domain-specific data for better relevance. Index embeddings with FAISS or HNSW for efficient nearest-neighbor searches, and experiment with chunk overlap to balance context retention and redundancy.
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?
By diving into this tutorial, you’ve unlocked the power of building a RAG system from the ground up! You’ve seen how Haystack acts as the glue that seamlessly connects all components, orchestrating the flow of data from retrieval to generation. You learned to leverage OpenSearch as your vector database, storing and querying embeddings at lightning speed to fetch the most relevant context for your queries. Then came NVIDIA Llama 3 70B Instruct, the powerhouse LLM that transforms retrieved information into coherent, human-like responses, showcasing its knack for understanding nuance and delivering precise answers. And let’s not forget the HuggingFace all-mpnet-base-v2 embedding model, which turned raw text into rich, meaningful vectors, ensuring your system understands the semantic depth of every word. Together, these tools form a dynamic pipeline that bridges the gap between static data and intelligent, context-aware interactions—proving that cutting-edge AI is within your reach!
But this tutorial didn’t stop at the basics. You also picked up pro tips for optimizing your RAG system, like fine-tuning retrieval thresholds and balancing speed with accuracy. And that free RAG cost calculator? It’s your new secret weapon for estimating expenses and scaling your projects wisely. Imagine what’s next: refining your pipeline for niche use cases, experimenting with hybrid search strategies, or even integrating multimodal data. The possibilities are endless, and you’re now equipped to tackle them all. So grab your code editor, fire up OpenSearch, and let Llama 3’s creativity loose—your next breakthrough RAG application is just a few keystrokes away. Build boldly, optimize fearlessly, and remember: every line of code you write brings the future of AI a little closer to reality. Let’s make it happen! 🚀
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 Haystack
- Step 2: Install and Set Up NVIDIA Llama 3 70B Instruct
- Step 3: Install and Set Up HuggingFace all-mpnet-base-v2
- Step 4: Install and Set Up OpenSearch
- 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