Build RAG Chatbot with Haystack, Haystack In-memory store, Mistral Pixtral, and OpenAI text-embedding-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:
- 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.
- Haystack in-memory store: a very simple, in-memory document store with no extra services or dependencies. It is great for experimenting with Haystack, and we do not recommend using it for production. If you want a much more scalable solution for your apps or even enterprise projects, we recommend using Zilliz Cloud, which is a fully managed vector database service built on the open-source Milvusand offers a free tier supporting up to 1 million vectors.)
- Mixtral: A high-performance, sparse mixture-of-experts (MoE) language model designed for efficient text generation and comprehension. Excelling in multilingual support and domain adaptability, it balances speed and accuracy, making it ideal for enterprise-scale applications, real-time chatbots, and resource-constrained environments requiring cost-effective AI solutions.
- OpenAI text-embedding-3-large: A state-of-the-art embedding model designed to convert text into high-dimensional vectors, capturing deep semantic relationships. Renowned for its accuracy, scalability, and ability to handle long contexts (up to 8192 tokens), it excels in semantic search, retrieval-augmented generation (RAG), recommendation systems, and multilingual NLP tasks requiring nuanced language understanding.
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 Pixtral
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='pixtral-12b-2409')
Step 3: Install and Set Up OpenAI text-embedding-3-large
Text documents often come with a set of metadata. If they are distinctive and semantically meaningful, you can embed them along with the text of the document to improve retrieval.
from haystack import Document
from haystack.components.embedders import OpenAIDocumentEmbedder
doc = Document(content="some text",meta={"title": "relevant title", "page number": 18})
document_embedder = OpenAIDocumentEmbedder(meta_fields_to_embed=["title"])
docs_w_embeddings = embedder.run(documents=[doc])["documents"]
Now let's install and set up the model.
from haystack import Document
from haystack.components.embedders import OpenAIDocumentEmbedder
from haystack.components.embedders import OpenAITextEmbedder
text_embedder = OpenAITextEmbedder(api_key=Secret.from_token("<your-api-key>"), model="text-embedding-3-large")
document_embedder = OpenAIDocumentEmbedder(api_key=Secret.from_token("<your-api-key>"), model="text-embedding-3-large")
Step 4: Install and Set Up Haystack In-memory store
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.retrievers import InMemoryEmbeddingRetriever
document_store = InMemoryDocumentStore()
retriever=InMemoryEmbeddingRetriever(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=InMemoryEmbeddingRetriever(document_store=document_store)
text_embedder = OpenAITextEmbedder(api_key=Secret.from_token("<your-api-key>"), model="text-embedding-3-large")
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.
Haystack in-memory store optimization tips
Haystack in-memory store is just a very simple, in-memory document store with no extra services or dependencies. We recommend that you just experiment it with RAG pipeline within your Haystack framework, and we do not recommend using it for production. If you want a much more scalable solution for your apps or even enterprise projects, we recommend using Zilliz Cloud, which is a fully managed vector database service built on the open-source Milvusand offers a free tier supporting up to 1 million vectors
Mistral Pixtral optimization tips
To optimize Mistral Pixtral in a RAG setup, fine-tune its prompt engineering by using clear, structured instructions to guide context integration. Limit retrieved documents to the most relevant chunks (e.g., 3-5) to reduce noise and improve response quality. Adjust temperature (0.2-0.5) for balanced creativity and precision. Use dynamic batching for parallel processing to accelerate inference. Implement quantization (e.g., 4-bit) to reduce memory usage without significant performance loss. Regularly evaluate retrieval alignment with domain-specific benchmarks to refine embedding and reranking strategies.
OpenAI text-embedding-3-large optimization tips
Optimize OpenAI text-embedding-3-large in RAG by adjusting the dimensions
parameter to balance accuracy and efficiency—lower values reduce latency and cost while retaining semantic relevance. Batch embedding requests to maximize throughput, preprocess text to remove noise (e.g., truncate to 8191 tokens, normalize whitespace), and cache frequent queries. Use cosine similarity for retrieval alignment, validate embeddings with domain-specific benchmarks, and fine-tune hybrid search strategies (e.g., combining sparse/dense vectors) to improve recall. Monitor API rate limits and leverage asynchronous calls for scalability.
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 magic of building a RAG system from scratch! You learned how to weave together four powerful tools—Haystack as your orchestration framework, Haystack’s In-memory Store for lightning-fast vector storage, Mistral Pixtral as your clever large language model (LLM), and OpenAI’s text-embedding-3-large to transform text into rich embeddings—into a seamless pipeline. The tutorial showed you how Haystack acts as the backbone, connecting your data to the LLM while the In-memory Store keeps vector searches snappy, even without heavy infrastructure. Mistral Pixtral’s ability to generate human-like answers and OpenAI’s embeddings (which capture context with surgical precision) turned raw data into a knowledge powerhouse. You even saw how to tweak chunk sizes, adjust retrieval thresholds, and balance cost vs. performance, ensuring your system isn’t just functional but efficient—and with the free RAG cost calculator, you’re now equipped to budget like a pro!
But this isn’t just about following steps—it’s about empowerment. You’ve seen firsthand how these tools unlock endless possibilities: chatbots that truly understand context, research assistants that dig deeper, or creative engines that spark new ideas. The optimizations you practiced aren’t just tweaks; they’re your toolkit for making RAG systems faster, cheaper, and smarter. Now, imagine what you can build next. Whether you’re refining your pipeline, experimenting with new models, or inventing entirely fresh use cases, the foundation is set. So go ahead—dive into the code, play with parameters, and let your creativity run wild. The world of AI is yours to shape, and with what you’ve learned today, you’re already unstoppable. Let’s build something amazing! 🚀
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 Pixtral
- Step 3: Install and Set Up OpenAI text-embedding-3-large
- Step 4: Install and Set Up Haystack In-memory store
- 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