Xây dựng Chatbot trên dữ liệu CSV của bạn với LangChain và OpenAI
Trò chuyện với các tệp CSV của bạn bằng chatbot bộ nhớ | Được tạo bằng Langchain và OpenAI

Trong bài viết này, chúng ta sẽ xem cách xây dựng một chatbot đơn giản với bộ nhớ có thể trả lời các câu hỏi của bạn về dữ liệu CSV của riêng bạn.
Chào mọi người! Trong vài tuần qua, tôi đã thử nghiệm tiềm năng hấp dẫn của các mô hình ngôn ngữ lớn để tạo ra mọi thứ và đã đến lúc chia sẻ những gì tôi đã học được!
Chúng tôi sẽ sử dụng LangChain để liên kết gpt-3.5
với dữ liệu của chúng tôi và Streamlit để tạo giao diện người dùng cho chatbot của chúng tôi.
Không giống như ChatGPT cung cấp ngữ cảnh hạn chế trên dữ liệu của chúng tôi (chúng tôi chỉ có thể cung cấp tối đa 4096 mã thông báo), chatbot của chúng tôi sẽ có thể xử lý dữ liệu CSV và quản lý cơ sở dữ liệu lớn nhờ sử dụng các nhúng và kho lưu trữ véc tơ.

Mật mã
Bây giờ chúng ta hãy thực tế! Chúng tôi sẽ phát triển chatbot của mình trên dữ liệu CSV với rất ít cú pháp Python.
Tuyên bố miễn trừ trách nhiệm : Mã này là phiên bản đơn giản hóa của chatbot mà tôi đã tạo, nó không được tối ưu hóa để giảm chi phí API OpenAI, để có một chatbot được tối ưu hóa và hiệu quả hơn, vui lòng xem dự án GitHub của tôi: yvann-hub/Robby-chatbot hoặc chỉ thử nghiệm ứng dụng tại Robby-chatbot.com .
- Đầu tiên, chúng ta sẽ cài đặt các thư viện cần thiết:
pip install streamlit streamlit_chat langchain openai faiss-cpu tiktoken
import streamlit as st
from streamlit_chat import message
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationalRetrievalChain
from langchain.document_loaders.csv_loader import CSVLoader
from langchain.vectorstores import FAISS
import tempfile
fishfry-locations.csv
user_api_key = st.sidebar.text_input(
label="#### Your OpenAI API key ",
placeholder="Paste your openAI API key, sk-",
type="password")
uploaded_file = st.sidebar.file_uploader("upload", type="csv")
if uploaded_file :
#use tempfile because CSVLoader only accepts a file_path
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8", csv_args={
'delimiter': ','})
data = loader.load()
st.write(data)
0:"Document(page_content='venue_name: McGinnis Sisters\nvenue_type: Market\nvenue_address: 4311 Northern Pike, Monroeville, PA\nwebsite: http://www.mcginnis-sisters.com/\nmenu_url: \nmenu_text: \nphone: 412-858-7000\nemail: \nalcohol: \nlunch: True', metadata={'source': 'C:\\Users\\UTILIS~1\\AppData\\Local\\Temp\\tmp6_24nxby', 'row': 0})"
1:"Document(page_content='venue_name: Holy Cross (Reilly Center)\nvenue_type: Church\nvenue_address: 7100 West Ridge Road, Fairview PA\nwebsite: \nmenu_url: \nmenu_text: Fried pollack, fried shrimp, or combo. Adult $10, Child $5. Includes baked potato, homemade coleslaw, roll, butter, dessert, and beverage. Mac and cheese $5.\nphone: 814-474-2605\nemail: \nalcohol: \nlunch: ', metadata={'source': 'C:\\Users\\UTILIS~1\\AppData\\Local\\Temp\\tmp6_24nxby', 'row': 1})"
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(data, embeddings)
vectorstore
để tìm thông tin liên quan từ tài liệu của chúng tôi.chain = ConversationalRetrievalChain.from_llm(
llm = ChatOpenAI(temperature=0.0,model_name='gpt-3.5-turbo'),
retriever=vectorstore.as_retriever())
st.session_state[‘history’]
lưu trữ lịch sử hội thoại của người dùng khi họ truy cập trang Streamlit.def conversational_chat(query):
result = chain({"question": query,
"chat_history": st.session_state['history']})
st.session_state['history'].append((query, result["answer"]))
return result["answer"]
[‘generated’]
tương ứng với phản hồi của chatbot.[‘past’]
tương ứng với các tin nhắn được cung cấp bởi người dùng.- Vùng chứa không cần thiết nhưng giúp cải thiện giao diện người dùng bằng cách đặt khu vực câu hỏi của người dùng bên dưới tin nhắn trò chuyện.
if 'history' not in st.session_state:
st.session_state['history'] = []
if 'generated' not in st.session_state:
st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " "]
if 'past' not in st.session_state:
st.session_state['past'] = ["Hey ! "]
#container for the chat history
response_container = st.container()
#container for the user's text input
container = st.container()
conversational_chat
chức năng của chúng tôi với câu hỏi của người dùng làm đối số.with container:
with st.form(key='my_form', clear_on_submit=True):
user_input = st.text_input("Query:", placeholder="Talk about your csv data here (:", key='input')
submit_button = st.form_submit_button(label='Send')
if submit_button and user_input:
output = conversational_chat(user_input)
st.session_state['past'].append(user_input)
st.session_state['generated'].append(output)
if st.session_state['generated']:
with response_container:
for i in range(len(st.session_state['generated'])):
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
streamlit run name_of_your_chatbot.py #run with the name of your file
The result after launch the last command
Bạn cũng có thể tìm thấy toàn bộ dự án trên GitHub của tôi .