VOOZH about

URL: https://thenewstack.io/how-to-build-a-qa-llm-application-with-langchain-and-gemini/

⇱ How to Build a Q&A LLM Application with LangChain and Gemini - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2024-03-21 05:00:46
How to Build a Q&A LLM Application with LangChain and Gemini
tutorial,
AI / Software Development

How to Build a Q&A LLM Application with LangChain and Gemini

We show you how to integrate LangChain with Google's Gemini LLM to build a Q&A application based on a PDF.
Mar 21st, 2024 5:00am by Janakiram MSV
👁 Featued image for: How to Build a Q&A LLM Application with LangChain and Gemini
Photo by Emily Morter on Unsplash.

In this tutorial, we will explore the integration of LangChain, a programming framework for using large language models (LLMs) in applications, with Google’s Gemini LLM to build a Q&A application based on a PDF.

Before going ahead with the tutorial, make sure you have an API key from Google AI Studio.

Step 1: Initializing the Environment

Create a Python virtual environment and install the required modules from the requirements.txt file.

python -m venv venv
source venv/bin/activate

Create the requirements.txt file with the below content:

pypdf2
chromadb
google.generativeai
langchain-google-genai
langchain
langchain_community
jupyter
pip install -r requirements.txt

Set an environment variable to access the API key implicitly from the code.

export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"

Launch Jupyter Notebook and get started with the code.

Step 2: Import Modules

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain.vectorstores import Chroma
import os

Step 3: Initialize the Models

This step loads the LLM with the Embeddings models responsible for converting text into lower-dimension vectors.

llm = ChatGoogleGenerativeAI(model="gemini-pro")
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")

Step 4: Load and Split the PDF

You can use any PDF of your choice. But for this tutorial, we will load the employee handbook of a fictitious company.

The code below loads the PDF and splits it into chunks of 250 characters, with an overlap of 50 characters between each chunk.

loader = PyPDFLoader("handbook.pdf")

text_splitter = CharacterTextSplitter(
 separator=".",
 chunk_size=250,
 chunk_overlap=50,
 length_function=len,
 is_separator_regex=False,
)

pages = loader.load_and_split(text_splitter)

Step 5: Initialize VectorDB and Configure Retriever

In the next step, we will convert each chunk of text into embeddings and store them in the Chroma vector database for retrieval. The parameter search_kwargs={"k": 5} defines the top matches to retrieve from a search.

vectordb=Chroma.from_documents(pages,embeddings)
retriever = vectordb.as_retriever(search_kwargs={"k": 5})

Step 6: Define the Retrieval Chain

In LangChain, each component is assembled together to form a logical chain. In this scenario, we have the prompt, the LLM, and the retriever as the key components. Let’s create a chain from them.

template = """
You are a helpful AI assistant.
Answer based on the context provided. 
context: {context}
input: {input}
answer:
"""
prompt = PromptTemplate.from_template(template)
combine_docs_chain = create_stuff_documents_chain(llm, prompt)
retrieval_chain = create_retrieval_chain(retriever, combine_docs_chain)

Step 7: Invoke the Chain

Now is the time to test if all the pieces of the puzzle are connected. We will invoke the chain and check the response.

response=retrieval_chain.invoke({"input":"How do I apply for personal leave?"})
print(response)

👁 Image

As we can see, the answer key has the expected response from the chain. Let’s print it out.

response["answer"]

👁 Image

Below is the complete code:

TRENDING STORIES
Janakiram MSV (Jani) is a practicing architect, research analyst, and advisor to Silicon Valley startups. He focuses on the convergence of modern infrastructure powered by cloud-native technology and machine intelligence driven by generative AI. Before becoming an entrepreneur, he spent...
Read more from Janakiram MSV
SHARE THIS STORY
TRENDING STORIES
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.