Build RAG Chatbot with Haystack, Milvus, Mistral Nemo, and AmazonBedrock cohere embed-multilingual-v3
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.
- Milvus: An open-source vector database optimized to store, index, and search large-scale vector embeddings efficiently, perfect for use cases like RAG, semantic search, and recommender systems. If you hate to manage your own infrastructure, we recommend using Zilliz Cloud, which is a fully managed vector database service built on Milvus and offers a free tier supporting up to 1 million vectors.
- Mistral Nemo: A high-efficiency multilingual AI model optimized for natural language understanding and generation. It excels in low-latency conversational applications, offering robust performance across languages with minimal computational resources. Ideal for real-time chatbots, customer service automation, and scalable multilingual NLP tasks requiring accuracy and speed.
- AmazonBedrock Cohere Embed-Multilingual-v3: A multilingual text embedding model hosted on Amazon Bedrock designed to generate high-dimensional vector representations (1024 dimensions) for text in over 100 languages. It excels at semantic understanding, cross-lingual retrieval, and scalability, making it ideal for multilingual search, content recommendation, clustering, and retrieval-augmented generation (RAG) systems requiring broad language support and semantic 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 Mistral Nemo
To use Mistral models, you need first to get a Mistral API key. You can write this key in:
- The
api_key
init parameter using Secret API - The
MISTRAL_API_KEY
environment variable (recommended)
Now, after you get the API key, let's install the Install the mistral-haystack
package.
pip install mistral-haystack
from haystack_integrations.components.generators.mistral import MistralChatGenerator
from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
generator = MistralChatGenerator(api_key=Secret.from_env_var("MISTRAL_API_KEY"), streaming_callback=print_streaming_chunk, model='open-mistral-nemo')
Step 3: Install and Set Up AmazonBedrock cohere embed-multilingual-v3
Amazon Bedrock is a fully managed service that makes high-performing foundation models from leading AI startups and Amazon available through a unified API.
To use embedding models on Amazon Bedrock for text and document embedding together with Haystack, you need to initialize an AmazonBedrockTextEmbedder
and AmazonBedrockDocumentEmbedder
with the model name, the AWS credentials (aws_access_key_id
, aws_secret_access_key
, and aws_region_name
) should be set as environment variables, be configured as described above or passed as Secret arguments. Note, make sure the region you set supports Amazon Bedrock.
Now, let's start installing and setting up models with Amazon Bedrock.
pip install amazon-bedrock-haystack
import os
from haystack_integrations.components.embedders.amazon_bedrock import AmazonBedrockTextEmbedder
from haystack_integrations.components.embedders.amazon_bedrock import AmazonBedrockDocumentEmbedder
from haystack.dataclasses import Document
os.environ["AWS_ACCESS_KEY_ID"] = "..."
os.environ["AWS_SECRET_ACCESS_KEY"] = "..."
os.environ["AWS_DEFAULT_REGION"] = "us-east-1" # just an example
text_embedder = AmazonBedrockTextEmbedder(model="cohere.embed-multilingual-v3",
input_type="search_query"
document_embedder = AmazonBedrockDocumentEmbedder(model="cohere.embed-multilingual-v3",
input_type="search_document"
Step 4: Install and Set Up Milvus
pip install --upgrade pymilvus milvus-haystack
from milvus_haystack import MilvusDocumentStore
from milvus_haystack.milvus_embedding_retriever import MilvusEmbeddingRetriever
document_store = MilvusDocumentStore(connection_args={"uri": "./milvus.db"}, drop_old=True,)
retriever = MilvusEmbeddingRetriever(document_store=document_store, top_k=3)
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 = MilvusEmbeddingRetriever(document_store=document_store, top_k=3)
text_embedder = AmazonBedrockTextEmbedder(model="cohere.embed-multilingual-v3",
input_type="search_query"
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.
Milvus optimization tips
Milvus serves as a highly efficient vector database, critical for retrieval tasks in a RAG system. To optimize its performance, ensure that indexes are properly built to balance speed and accuracy; consider utilizing HNSW (Hierarchical Navigable Small World) for efficient nearest neighbor search where response time is crucial. Partitioning data based on usage patterns can enhance query performance and reduce load times, enabling better scalability. Regularly monitor and adjust cache settings based on query frequency to avoid latency during data retrieval. Employ batch processing for vector insertions, which can minimize database lock contention and enhance overall throughput. Additionally, fine-tune the model parameters by experimenting with the dimensionality of the vectors; higher dimensions can improve retrieval accuracy but may increase search time, necessitating a balance tailored to your specific use case and hardware infrastructure.
Mistral Nemo optimization tips
To optimize Mistral Nemo in a RAG setup, focus on improving retrieval quality by fine-tuning embeddings for domain-specific data, chunking documents into 256-512 token segments for balanced context, and using metadata filtering to reduce noise. Adjust the top-k retrieval count dynamically based on query complexity. For generation, enable model quantization (e.g., 4-bit) to speed up inference and trim response length via max_token limits. Use caching for frequent queries and profile latency to identify bottlenecks. Regularly validate outputs against ground-truth datasets to refine accuracy.
AmazonBedrock cohere embed-multilingual-v3 optimization tips
Optimize input preprocessing by normalizing text (lowercasing, removing special characters) and splitting documents into chunks aligned with the model’s 512-token limit. Use batch processing for bulk embeddings to reduce latency and costs. Filter irrelevant content before embedding to improve retrieval quality. For multilingual queries, ensure language-specific stopword removal and consider hybrid retrieval combining semantic and keyword search. Regularly validate embedding quality via cosine similarity checks and align vector dimensions with your database (e.g., PCA for dimensionality reduction). Cache frequent queries and update embeddings periodically to reflect data changes.
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 combining cutting-edge tools to build a sophisticated RAG system from the ground up! You learned how Haystack acts as the backbone, seamlessly orchestrating workflows between your data pipeline, vector database, and language model. Milvus stepped in as your high-performance vector database, handling dense embeddings from Cohere’s embed-multilingual-v3 model with ease, enabling lightning-fast semantic search across multilingual datasets. Then, Mistral Nemo (hosted via Amazon Bedrock) became your creative brain, generating natural, context-rich responses by synthesizing retrieved information. Together, these tools transformed raw data into a dynamic knowledge engine—indexing, retrieving, and generating answers in real-time! You also explored optimization tricks like chunking strategies, metadata filtering, and hybrid search setups to fine-tune accuracy and speed. And let’s not forget the free RAG cost calculator you discovered, a game-changer for balancing performance and budget as you scale!
Now, you’re equipped to build smarter, faster, and more inclusive AI applications. Imagine creating chatbots that understand multiple languages, or search engines that grasp intent, not just keywords—this tutorial showed you the blueprint. The world of RAG is yours to explore: experiment with different models, tweak retrieval parameters, or integrate domain-specific data. Remember, every iteration brings you closer to a system that feels almost magical. So go ahead—fire up your code editor, spin up those cloud resources, and start crafting solutions that amaze. The future of intelligent applications is in your hands, and you’ve got the tools to shape it. Let’s build something extraordinary! 🚀
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 Mistral Nemo
- Step 3: Install and Set Up AmazonBedrock cohere embed-multilingual-v3
- Step 4: Install and Set Up Milvus
- 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