Building a Multi-Document Chatbot Using Mistral 7B, ChromaDB, and Langchain

November 29, 2023

Chatbots have come a long way from simple rule-based systems to sophisticated AI-powered conversational agents. Multi-document chatbots, in particular, have gained popularity for their ability to draw information from multiple sources, enabling them to provide more context-aware and informative responses. In this blog post, we'll delve into the process of creating a multi-document chatbot using advanced technologies such as Mistral 7B, ChromaDB, and Langchain.

The Rise of Multi-Document Chatbots

Multi-document chatbots have quickly become essential in the world of conversational AI. Unlike their predecessors, these advanced chatbots can access information from various sources and provide more context-aware responses. This evolution allows for a more engaging and informative user experience.

Understanding Mistral 7B

Mistral 7B is a state-of-the-art language model developed by Mistral, a startup that raised a whopping $113 Mn seed round to build foundational AI models and release them as open-source solutions. It possesses remarkable capabilities, including language understanding, text generation, and fine-tuning for specific tasks. To build a multi-document chatbot, you'll need to explore Mistral 7B's capabilities and understand how to set it up for your project.

Leveraging ChromaDB for Document Retrieval

ChromaDB is a powerful vector database for building AI pipelines and similarity search and document retrieval. By indexing and searching document embeddings efficiently, it plays a crucial role in enabling your chatbot to access and retrieve information from multiple sources. The integration of ChromaDB with Mistral 7B is key to creating a multi-document chatbot.

Implementing Langchain for Language Workflows

Langchain is a natural language processing framework that enhances the chatbot's ability to understand and process language inputs effectively. It pre-processes user queries, parses them, and prepares them for Mistral 7B. This step is fundamental to improving your chatbot's language understanding capabilities.

  • Retrieval in Langchain: In many applications involving Language Model (LLM) technology, there's often a need for user-specific data that isn't part of the model's training set. One way to accomplish this is through Retrieval Augmented Generation (RAG). In this process, external data is retrieved and then passed to the LLM when generating responses. Langchain offers a comprehensive set of tools for the Retrieval Augmented Generation applications, from simple to complex. This section of the tutorial covers everything related to the retrieval step, including data fetching, document loaders, transformers, text embeddings, vector stores, and retrievers.
  • Document Loaders: Langchain provides over 100 different document loaders to facilitate the retrieval of documents from various sources. It also offers integrations with other major providers in this space, such as AirByte and Unstructured. You can use Langchain to load documents of different types, including HTML, PDF, and code, from both private sources like S3 buckets and public websites.
  • Document Transformers: A crucial part of retrieval is fetching only the relevant portions of documents. Langchain streamlines this process by offering various transformation steps to prepare documents for retrieval. One of the primary tasks here involves splitting or chunking large documents into smaller, more manageable, segments. Langchain offers several algorithms for achieving this, as well as logic optimized for specific document types, such as code and markdown.
  • Text Embedding Models: Creating embeddings for documents is another key element of the retrieval process. Embeddings capture the semantic meaning of text, making it possible to quickly and efficiently find similar pieces of text. Langchain provides integrations with over 25 different embedding providers and methods, ranging from open-source solutions to proprietary APIs. This flexibility allows you to choose the one that best suits your specific needs. Langchain also offers a standardized interface for easy swapping between different models.
  • Vector Stores: With the emergence of embeddings, there's a growing need for databases that support the efficient storage and retrieval of these embeddings. Langchain caters to this need by offering integrations with over 50 different vector stores. These include open-source local options and cloud-hosted proprietary solutions, allowing you to select the one that aligns best with your requirements. Langchain maintains a standard interface to facilitate the seamless switching between different vector stores. 


Once your data is stored in the database, you'll need to retrieve it effectively. Langchain supports a variety of retrieval algorithms, adding significant value to the process. It includes basic methods for a quick start, such as a simple semantic search. However, Langchain also goes the extra mile by providing a collection of advanced algorithms to enhance retrieval performance. These include:

  • Parent Document Retriever: This feature allows you to create multiple embeddings per parent document, making it possible to look up smaller document chunks while retaining larger contextual information.
  • Self-Query Retriever: User questions often contain references that require more than semantic matching; they may involve metadata filters. Self-query retrieval allows you to parse out the semantic elements of a query from other metadata filters, making responses more context-aware.
  • Ensemble Retriever: Sometimes, you may want to retrieve documents from multiple sources or employ various retrieval algorithms. The ensemble retriever feature enables you to do this effortlessly.

Incorporating retrieval into your chatbot's architecture is vital for making it a true multi-document chatbot. The powerful combination of Mistral 7B, ChromaDB, and Langchain, with its advanced retrieval capabilities, opens up new possibilities for enhancing user interactions and providing informative responses.

Building the Multi-Document Chatbot

With a solid foundation in Mistral 7B, ChromaDB, and Langchain, you can now begin building your multi-document chatbot. This entails data preprocessing, model fine-tuning, and deployment strategies to ensure that your chatbot can provide accurate and informative responses.


If you require extra GPU resources for the tutorials ahead, you can explore the offerings on E2E CLOUD. We provide a diverse selection of GPUs.

To get one, head over to MyAccount, and sign up. Then launch a GPU node as is shown in the screenshot below:

Make sure you add your ssh keys during launch, or through the security tab after launching. 

Once you have launched a node, you can use VSCode Remote Explorer to ssh into the node and use it as a local development environment. 

Running Langchain and RAG for Text Generation and Retrieval

In this tutorial, we'll walk you through using Langchain and the Retrieval-Augmented Generation (RAG) model to perform text generation and information retrieval tasks. Langchain is a framework for orchestrating various Natural Language Processing (NLP) models and components, and RAG is a model that combines text generation and retrieval for more contextually relevant responses.

Running with Langchain

Setting Up the Environment

!pip install -q -U bitsandbytes
!pip install -q -U git+
!pip install -q -U git+
!pip install -q -U git+
!pip install -q -U einops
!pip install -q -U safetensors
!pip install -q -U torch
!pip install -q -U xformers
!pip install -q -U langchain
!pip install -q -U ctransformers[cuda]
!pip install chromadb
!pip install sentence-transformers

Authenticating with Hugging Face

To authenticate with Hugging Face, you'll need an access token. Here's how to get it:

  1. Go to your Hugging Face account.
  2. Navigate to ‘Settings’ and click on ‘Access Tokens’.
  3. Create a new token or copy an existing one.

(Link to Huggingface)

!pip install huggingface_hub

from huggingface_hub import notebook_login
  • We begin by defining the model we want to use. In this case, it's ‘mistralai/Mistral-7B-Instruct-v0.1.’
  • We create an instance of the model for text generation and set various parameters for its behavior.

import torch
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(

Langchain Setup

  • We import Langchain components.
  • We create a Langchain pipeline using the model for text generation.

pipeline = pipeline(

from langchain import HuggingFacePipeline
from langchain import PromptTemplate, LLMChain
llm = HuggingFacePipeline(pipeline=pipeline)

model_id = "mistralai/Mistral-7B-Instruct-v0.1"

from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
model_4bit = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto",quantization_config=quantization_config, )
tokenizer = AutoTokenizer.from_pretrained(model_id)

Generating Text

  • We define a template for generating responses that include context and a question.
  • We provide a specific question and context for the model to generate a response.
  • The response variable now contains the generated response.

template = """[INST] You are a helpful, respectful and honest assistant. Answer exactly in few words from the context
Answer the question below from the context below:
{question} [/INST] 
question_p = """What is the date for the announcement"""
context_p = """ On August 10, it was announced that its subsidiary, JSW Neo Energy, has agreed to acquire a portfolio encompassing 1753 megawatts of renewable energy generation capacity from Mytrah Energy India Pvt Ltd for Rs 10,530 crore."""
prompt = PromptTemplate(template=template, input_variables=["question","context"])
llm_chain = LLMChain(prompt=prompt, llm=llm)
response ={"question":question_p,"context":context_p})

Retrieval Augmented Generation (RAG)

Setting Up RAG

  • We start by importing the necessary modules for RAG set-up.

import chromadb
from chromadb.config import Settings
from langchain.llms import HuggingFacePipeline
from langchain.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.vectorstores import Chroma

Providing Document Context

  • We furnish an example document context, which, in this instance, is a news article.

mna_news = """On August 10, JSW Energy announced that its subsidiary, JSW Neo Energy, has reached an agreement to acquire a portfolio comprising 1753 megawatts of renewable energy generation capacity from Mytrah Energy India Pvt Ltd for Rs 10,530 crore. The JSW Group, led by Sajjan Jindal, had previously signed an exclusivity agreement with Mytrah Energy, based in Hyderabad, to purchase the company's wind and solar assets.
This marks the largest acquisition by JSW Energy since its inception, encompassing 17 special-purpose vehicles and one ancillary SPV. The completion of the transaction is contingent on the approval of the Competition Commission of India (CCI) and other customary approval standards for a transaction of this magnitude, as stated in the company's release.
Upon completion of the acquisition, JSW Energy's operational generation capacity will surge by over 35 per cent, rising from 4,784 MW to 6,537 MW. The company also revealed ongoing wind and hydro projects with a capacity of about 2,500 MW, expected to be commissioned in phases over the next 18-24 months. This addition elevates JSW Energy's platform capacity to 9.1 GW, with the share of renewables increasing to 65 per cent, according to a stock exchange filing. Furthermore, the company anticipates that this move will contribute to achieving its renewable-led capacity growth target of 10 GW by FY25, surpassing the set timelines. """

Setting Up RAG Components

  • We configure various components, such as text splitting and embeddings.
  • We create a vector store using the provided documents and embeddings.
  • We configure the retrieval component, and retriever, and set up the RetrievalQA.

from langchain.schema.document import Document
documents = [Document(page_content=mna_news, metadata={"source": "local"})]
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=20)
all_splits = text_splitter.split_documents(documents)
model_name = "sentence-transformers/all-mpnet-base-v2"
model_kwargs = {"device": "cuda"}
embeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs)

chromadb = Chroma.from_documents(documents=all_splits, embedding=embeddings, persist_directory="chroma_db")

chromadb = Chroma.from_documents(documents=all_splits, embedding=embeddings, persist_directory="chroma_db")

retriever = chromadb.as_retriever()

retrieverQA = RetrievalQA.from_chain_type(

Def run_rag(retrieverQA , text_query ):
    print(f"Text Query: {text_query }\n")
    result = )
    print("\nResult: ", result)

Running a Query

text_query =""" What company is both buyer and seller here? """
run_rag(retrieverQA, text_query )

Real-World Applications

Multi-document chatbots, such as this, have a wide range of real-world applications. They can be used in customer support, research, content curation, and more. Some of the applications are as follows:

  • Customer Support
  • Legal Assistance
  • Healthcare Information Retrieval
  • E-learning Support
  • Making Email listings


The development of multi-document chatbots is an exciting frontier in the field of AI-powered conversational agents. By combining Mistral 7B's language understanding, ChromaDB’s document retrieval, and Langchain's language processing, developers can create chatbots that provide comprehensive, context-aware responses to user queries. This blog post serves as a starting point for anyone interested in building multi-document chatbots using these advanced technologies, opening up new possibilities for human-machine interaction. With the right tools and techniques, you can create chatbots that are more informative and engaging than ever before.


Langchain documentation:

Mistral 7B research paper:

News article:


Latest Blogs
This is a decorative image for: A Complete Guide To Customer Acquisition For Startups
October 18, 2022

A Complete Guide To Customer Acquisition For Startups

Any business is enlivened by its customers. Therefore, a strategy to constantly bring in new clients is an ongoing requirement. In this regard, having a proper customer acquisition strategy can be of great importance.

So, if you are just starting your business, or planning to expand it, read on to learn more about this concept.

The problem with customer acquisition

As an organization, when working in a diverse and competitive market like India, you need to have a well-defined customer acquisition strategy to attain success. However, this is where most startups struggle. Now, you may have a great product or service, but if you are not in the right place targeting the right demographic, you are not likely to get the results you want.

To resolve this, typically, companies invest, but if that is not channelized properly, it will be futile.

So, the best way out of this dilemma is to have a clear customer acquisition strategy in place.

How can you create the ideal customer acquisition strategy for your business?

  • Define what your goals are

You need to define your goals so that you can meet the revenue expectations you have for the current fiscal year. You need to find a value for the metrics –

  • MRR – Monthly recurring revenue, which tells you all the income that can be generated from all your income channels.
  • CLV – Customer lifetime value tells you how much a customer is willing to spend on your business during your mutual relationship duration.  
  • CAC – Customer acquisition costs, which tells how much your organization needs to spend to acquire customers constantly.
  • Churn rate – It tells you the rate at which customers stop doing business.

All these metrics tell you how well you will be able to grow your business and revenue.

  • Identify your ideal customers

You need to understand who your current customers are and who your target customers are. Once you are aware of your customer base, you can focus your energies in that direction and get the maximum sale of your products or services. You can also understand what your customers require through various analytics and markers and address them to leverage your products/services towards them.

  • Choose your channels for customer acquisition

How will you acquire customers who will eventually tell at what scale and at what rate you need to expand your business? You could market and sell your products on social media channels like Instagram, Facebook and YouTube, or invest in paid marketing like Google Ads. You need to develop a unique strategy for each of these channels. 

  • Communicate with your customers

If you know exactly what your customers have in mind, then you will be able to develop your customer strategy with a clear perspective in mind. You can do it through surveys or customer opinion forms, email contact forms, blog posts and social media posts. After that, you just need to measure the analytics, clearly understand the insights, and improve your strategy accordingly.

Combining these strategies with your long-term business plan will bring results. However, there will be challenges on the way, where you need to adapt as per the requirements to make the most of it. At the same time, introducing new technologies like AI and ML can also solve such issues easily. To learn more about the use of AI and ML and how they are transforming businesses, keep referring to the blog section of E2E Networks.

Reference Links

This is a decorative image for: Constructing 3D objects through Deep Learning
October 18, 2022

Image-based 3D Object Reconstruction State-of-the-Art and trends in the Deep Learning Era

3D reconstruction is one of the most complex issues of deep learning systems. There have been multiple types of research in this field, and almost everything has been tried on it — computer vision, computer graphics and machine learning, but to no avail. However, that has resulted in CNN or convolutional neural networks foraying into this field, which has yielded some success.

The Main Objective of the 3D Object Reconstruction

Developing this deep learning technology aims to infer the shape of 3D objects from 2D images. So, to conduct the experiment, you need the following:

  • Highly calibrated cameras that take a photograph of the image from various angles.
  • Large training datasets can predict the geometry of the object whose 3D image reconstruction needs to be done. These datasets can be collected from a database of images, or they can be collected and sampled from a video.

By using the apparatus and datasets, you will be able to proceed with the 3D reconstruction from 2D datasets.

State-of-the-art Technology Used by the Datasets for the Reconstruction of 3D Objects

The technology used for this purpose needs to stick to the following parameters:

  • Input

Training with the help of one or multiple RGB images, where the segmentation of the 3D ground truth needs to be done. It could be one image, multiple images or even a video stream.

The testing will also be done on the same parameters, which will also help to create a uniform, cluttered background, or both.

  • Output

The volumetric output will be done in both high and low resolution, and the surface output will be generated through parameterisation, template deformation and point cloud. Moreover, the direct and intermediate outputs will be calculated this way.

  • Network architecture used

The architecture used in training is 3D-VAE-GAN, which has an encoder and a decoder, with TL-Net and conditional GAN. At the same time, the testing architecture is 3D-VAE, which has an encoder and a decoder.

  • Training used

The degree of supervision used in 2D vs 3D supervision, weak supervision along with loss functions have to be included in this system. The training procedure is adversarial training with joint 2D and 3D embeddings. Also, the network architecture is extremely important for the speed and processing quality of the output images.

  • Practical applications and use cases

Volumetric representations and surface representations can do the reconstruction. Powerful computer systems need to be used for reconstruction.

Given below are some of the places where 3D Object Reconstruction Deep Learning Systems are used:

  • 3D reconstruction technology can be used in the Police Department for drawing the faces of criminals whose images have been procured from a crime site where their faces are not completely revealed.
  • It can be used for re-modelling ruins at ancient architectural sites. The rubble or the debris stubs of structures can be used to recreate the entire building structure and get an idea of how it looked in the past.
  • They can be used in plastic surgery where the organs, face, limbs or any other portion of the body has been damaged and needs to be rebuilt.
  • It can be used in airport security, where concealed shapes can be used for guessing whether a person is armed or is carrying explosives or not.
  • It can also help in completing DNA sequences.

So, if you are planning to implement this technology, then you can rent the required infrastructure from E2E Networks and avoid investing in it. And if you plan to learn more about such topics, then keep a tab on the blog section of the website

Reference Links

This is a decorative image for: Comprehensive Guide to Deep Q-Learning for Data Science Enthusiasts
October 18, 2022

A Comprehensive Guide To Deep Q-Learning For Data Science Enthusiasts

For all data science enthusiasts who would love to dig deep, we have composed a write-up about Q-Learning specifically for you all. Deep Q-Learning and Reinforcement learning (RL) are extremely popular these days. These two data science methodologies use Python libraries like TensorFlow 2 and openAI’s Gym environment.

So, read on to know more.

What is Deep Q-Learning?

Deep Q-Learning utilizes the principles of Q-learning, but instead of using the Q-table, it uses the neural network. The algorithm of deep Q-Learning uses the states as input and the optimal Q-value of every action possible as the output. The agent gathers and stores all the previous experiences in the memory of the trained tuple in the following order:

State> Next state> Action> Reward

The neural network training stability increases using a random batch of previous data by using the experience replay. Experience replay also means the previous experiences stocking, and the target network uses it for training and calculation of the Q-network and the predicted Q-Value. This neural network uses openAI Gym, which is provided by taxi-v3 environments.

Now, any understanding of Deep Q-Learning   is incomplete without talking about Reinforcement Learning.

What is Reinforcement Learning?

Reinforcement is a subsection of ML. This part of ML is related to the action in which an environmental agent participates in a reward-based system and uses Reinforcement Learning to maximize the rewards. Reinforcement Learning is a different technique from unsupervised learning or supervised learning because it does not require a supervised input/output pair. The number of corrections is also less, so it is a highly efficient technique.

Now, the understanding of reinforcement learning is incomplete without knowing about Markov Decision Process (MDP). MDP is involved with each state that has been presented in the results of the environment, derived from the state previously there. The information which composes both states is gathered and transferred to the decision process. The task of the chosen agent is to maximize the awards. The MDP optimizes the actions and helps construct the optimal policy.

For developing the MDP, you need to follow the Q-Learning Algorithm, which is an extremely important part of data science and machine learning.

What is Q-Learning Algorithm?

The process of Q-Learning is important for understanding the data from scratch. It involves defining the parameters, choosing the actions from the current state and also choosing the actions from the previous state and then developing a Q-table for maximizing the results or output rewards.

The 4 steps that are involved in Q-Learning:

  1. Initializing parameters – The RL (reinforcement learning) model learns the set of actions that the agent requires in the state, environment and time.
  2. Identifying current state – The model stores the prior records for optimal action definition for maximizing the results. For acting in the present state, the state needs to be identified and perform an action combination for it.
  3. Choosing the optimal action set and gaining the relevant experience – A Q-table is generated from the data with a set of specific states and actions, and the weight of this data is calculated for updating the Q-Table to the following step.
  4. Updating Q-table rewards and next state determination – After the relevant experience is gained and agents start getting environmental records. The reward amplitude helps to present the subsequent step.  

In case the Q-table size is huge, then the generation of the model is a time-consuming process. This situation requires Deep Q-learning.

Hopefully, this write-up has provided an outline of Deep Q-Learning and its related concepts. If you wish to learn more about such topics, then keep a tab on the blog section of the E2E Networks website.

Reference Links

This is a decorative image for: GAUDI: A Neural Architect for Immersive 3D Scene Generation
October 13, 2022

GAUDI: A Neural Architect for Immersive 3D Scene Generation

The evolution of artificial intelligence in the past decade has been staggering, and now the focus is shifting towards AI and ML systems to understand and generate 3D spaces. As a result, there has been extensive research on manipulating 3D generative models. In this regard, Apple’s AI and ML scientists have developed GAUDI, a method specifically for this job.

An introduction to GAUDI

The GAUDI 3D immersive technique founders named it after the famous architect Antoni Gaudi. This AI model takes the help of a camera pose decoder, which enables it to guess the possible camera angles of a scene. Hence, the decoder then makes it possible to predict the 3D canvas from almost every angle.

What does GAUDI do?

GAUDI can perform multiple functions –

  • The extensions of these generative models have a tremendous effect on ML and computer vision. Pragmatically, such models are highly useful. They are applied in model-based reinforcement learning and planning world models, SLAM is s, or 3D content creation.
  • Generative modelling for 3D objects has been used for generating scenes using graf, pigan, and gsn, which incorporate a GAN (Generative Adversarial Network). The generator codes radiance fields exclusively. Using the 3D space in the scene along with the camera pose generates the 3D image from that point. This point has a density scalar and RGB value for that specific point in 3D space. This can be done from a 2D camera view. It does this by imposing 3D datasets on those 2D shots. It isolates various objects and scenes and combines them to render a new scene altogether.
  • GAUDI also removes GANs pathologies like mode collapse and improved GAN.
  • GAUDI also uses this to train data on a canonical coordinate system. You can compare it by looking at the trajectory of the scenes.

How is GAUDI applied to the content?

The steps of application for GAUDI have been given below:

  • Each trajectory is created, which consists of a sequence of posed images (These images are from a 3D scene) encoded into a latent representation. This representation which has a radiance field or what we refer to as the 3D scene and the camera path is created in a disentangled way. The results are interpreted as free parameters. The problem is optimized by and formulation of a reconstruction objective.
  • This simple training process is then scaled to trajectories, thousands of them creating a large number of views. The model samples the radiance fields totally from the previous distribution that the model has learned.
  • The scenes are thus synthesized by interpolation within the hidden space.
  • The scaling of 3D scenes generates many scenes that contain thousands of images. During training, there is no issue related to canonical orientation or mode collapse.
  • A novel de-noising optimization technique is used to find hidden representations that collaborate in modelling the camera poses and the radiance field to create multiple datasets with state-of-the-art performance in generating 3D scenes by building a setup that uses images and text.

To conclude, GAUDI has more capabilities and can also be used for sampling various images and video datasets. Furthermore, this will make a foray into AR (augmented reality) and VR (virtual reality). With GAUDI in hand, the sky is only the limit in the field of media creation. So, if you enjoy reading about the latest development in the field of AI and ML, then keep a tab on the blog section of the E2E Networks website.

Reference Links

Build on the most powerful infrastructure cloud

A vector illustration of a tech city using latest cloud technologies & infrastructure