September 11, 2024
How to Chat with Your Excel Data Using Langchain and OpenAI API
Imagine being able to ask questions directly to your Excel data, as if you’re having a conversation with a financial analyst.

By Vikash Singh
5 min read
No more filtering columns, manually creating pivot tables, or scrolling through endless rows to find insights! What if you could simply ask, "What were the total sales in Q1?" and get an answer right away?
Sounds futuristic, right?
Well, the future is here — and it's powered by OpenAI and Langchain.
In this guide, I'll show you exactly how you can chat with your Excel files, turning dry data into dynamic conversations.
If you're ready to take your data analysis skills to the next level and explore a fun, practical use case of AI, keep reading.
Let's dive in!
Step 1: Install Required Libraries
First, you'll need to install the required libraries. You can do this using pip!
!pip install openai langchain pandas!pip install openai langchain pandasThis will install the following libraries:
- OpenAI API: To interact with the GPT-3/4 models.
- Langchain: A framework to handle language models.
- Pandas: To handle Excel files.
Step 2: Set Up OpenAI API Key
You will need to get an OpenAI API key from the OpenAI website. Once you have the key, store it in an environment variable or directly use it in the script.
import os
import openai
import pandas as pd
# Set your OpenAI API key
openai_api_key = "your_openai_api_key_hereimport os
import openai
import pandas as pd
# Set your OpenAI API key
openai_api_key = "your_openai_api_key_hereStep 3: Read the Excel File Using Pandas
Next, you need to read the Excel file and convert it into a format that can be processed by the language model. Pandas provides a convenient way to read Excel files.
We'll be using a dummy excel file here, but you can replace it with any of your organization's or personal excel files too.
import pandas as pd
# Read Excel file
df = pd.read_excel("sample_excel.xlsx")
# Display the first few rows of the DataFrame
print(df.head())import pandas as pd
# Read Excel file
df = pd.read_excel("sample_excel.xlsx")
# Display the first few rows of the DataFrame
print(df.head())Output:
This is a simple dataset, and you can create it, if you want to follow along in your excel.
Step 4: Convert DataFrame to Text
Since OpenAI GPT models work with text, we need to convert the Excel content (stored in the DataFrame) into a readable string format that we can send to the API. This is done with the code below:
# Convert DataFrame to text (string format)
excel_data = df.to_string(index=False)
# Preview the data as text
print(excel_data)
# Convert DataFrame to text (string format)
excel_data = df.to_string(index=False)
# Preview the data as text
print(excel_data)Output:
Step 5: Set Up Langchain to Chat with the Excel File
Now, let's get to the fun part — actually setting up Langchain so you can start chatting with your Excel file!
So, what exactly is Langchain, and why do we need it?
In simple terms, Langchain is a fantastic framework that makes it super easy to use large language models (like OpenAI's GPT) with different data sources.
Langchain does the heavy lifting of connecting your data to the AI.
What does that mean for you?
It means you can focus on asking questions and getting answers without worrying about the technical nitty-gritty of processing your Excel data.
Langchain will handle the backend magic for us.
We'll use it to interact with the text content of your Excel file. But first things first, ensure you import the necessary components, and then initialize the OpenAI model.
from langchain import OpenAI, LLMChain, PromptTemplate
# Initialize OpenAI model
llm = OpenAI(openai_api_key=openai_api_key)from langchain import OpenAI, LLMChain, PromptTemplate
# Initialize OpenAI model
llm = OpenAI(openai_api_key=openai_api_key)Next, define a simple prompt template for the chatbot. The will be used to guide the language model when interacting with your Excel data.
# Define a prompt template to ask questions about the Excel data
template = """
You are given the following data extracted from an Excel file:
{excel_data}
Answer the following question:
{question}
"""
# Define a prompt template to ask questions about the Excel data
template = """
You are given the following data extracted from an Excel file:
{excel_data}
Answer the following question:
{question}
"""Setting Up the Prompt and Chain
Th next step is to set up the prompt and the chain, which is done in the following lines of code.
# Set up the prompt and chain
prompt = PromptTemplate(input_variables=["excel_data", "question"], template=template)
chain = LLMChain(llm=llm, prompt=prompt)
# Set up the prompt and chain
prompt = PromptTemplate(input_variables=["excel_data", "question"], template=template)
chain = LLMChain(llm=llm, prompt=prompt)The prompt is essentially the message or instruction we give to the AI model. Think of it as how we ask a question or give context to the model so that it knows what to do. In this case, the prompt is made up of two parts:
- Excel data: The text version of your Excel file.
- Question: Whatever you want to ask about the data.
Once we have a prompt ready, the LLMChain comes into play. You can think of the chain as the bridge that connects our prompt with the AI model (in this case, GPT). It tells the AI, "Here's what you need to work with (the data and question), now give me a smart response."
In summary, the prompt provides the data and question to the AI, and the chain makes sure the AI can process that information and give us useful answers. Together, they form the heart of our chatbot!
Step 6: Build the Chatbot Function
Now, let's build a chatbot function that allows you to ask questions about the Excel file.
def chat_with_excel(excel_data, question):
# Run the chain with the provided question
response = chain.run(excel_data=excel_data, question=question)
return responsedef chat_with_excel(excel_data, question):
# Run the chain with the provided question
response = chain.run(excel_data=excel_data, question=question)
return responseStep 7: Test the Chatbot
Now that everything is set up, you can interact with your Excel file by asking questions!
# Test the chatbot with a question
question = "What is the average revenue?"
response = chat_with_excel(excel_data, question)
# Print the response
print(response)# Test the chatbot with a question
question = "What is the average revenue?"
response = chat_with_excel(excel_data, question)
# Print the response
print(response)Output:
The average revenue is calculated by adding all the revenue values and dividing by the total number of values. In this case, there are 6 revenue values.
Average Revenue = (25000 + 30000 + 20000 + 28000 + 32000 + 21000) / 6 = 26500
Therefore, the average revenue is $26,500.The average revenue is calculated by adding all the revenue values and dividing by the total number of values. In this case, there are 6 revenue values.
Average Revenue = (25000 + 30000 + 20000 + 28000 + 32000 + 21000) / 6 = 26500
Therefore, the average revenue is $26,500.We can see that the LLM has succesfully given the resul along with the steps.
This is getting interesting, isn't it?
Let's ask one more question.
# Test the chatbot with another question
question = "Give me five-number summary for Revenue and Profit"
response = chat_with_excel(excel_data, question)
# Print the response
print(response)# Test the chatbot with another question
question = "Give me five-number summary for Revenue and Profit"
response = chat_with_excel(excel_data, question)
# Print the response
print(response)Output:
Revenue:
Min: 20000
Q1: 25000
Median: 28000
Q3: 32000
Max: 32000
Profit:
Min: 3000
Q1: 5000
Median: 6000
Q3: 8000
Max: 8000Revenue:
Min: 20000
Q1: 25000
Median: 28000
Q3: 32000
Max: 32000
Profit:
Min: 3000
Q1: 5000
Median: 6000
Q3: 8000
Max: 8000Great, the LLM chatbot is indeed interacting with the excel file and giving us the answers.
You can further enhance the functionality by adding logic to preprocess or clean the Excel data before sending it to the model or create a loop that allows multiple questions to be asked in sequence.
Conclusion
By following these steps, you have created a simple chatbot that can interact with your Excel file using the OpenAI API and Langchain framework.
You are ready to get started with your own excel files and be the financial wizard who knows all the answers. This can be extended further to handle more complex tasks depending on your needs.
Feel free to modify the chatbot to suit your specific data requirements!
Hope you enjoyed the guide and learned something from it. If you're interested in generative AI, you might like the following blogs too:
- Getting started with LLMs in Hugging Face
- Getting started in LLMs with OpenAI
- The What, Why, and How of Generative AI
I also write on statistics, data science and machine learning, you can view these stories on the stories page.
Connect with me on LinkedIn.
Happy Learning!