-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode
More file actions
97 lines (70 loc) · 1.94 KB
/
Copy pathcode
File metadata and controls
97 lines (70 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import streamlit as st
from openai import OpenAI
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
# OpenAI API Key
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"
client = OpenAI(api_key=OPENAI_API_KEY)
st.title("📚 RAG Chatbot")
uploaded_file = st.file_uploader(
"Upload a PDF",
type=["pdf"]
)
if uploaded_file:
with open("temp.pdf", "wb") as f:
f.write(uploaded_file.read())
loader = PyPDFLoader("temp.pdf")
documents = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50
)
chunks = splitter.split_documents(documents)
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
vector_db = FAISS.from_documents(
chunks,
embeddings
)
st.success("PDF Indexed Successfully!")
question = st.text_input(
"Ask a Question"
)
if question:
docs = vector_db.similarity_search(
question,
k=3
)
context = "\n".join(
[doc.page_content for doc in docs]
)
prompt = f"""
You are a helpful assistant.
Use only the information below.
Context:
{context}
Question:
{question}
Answer:
"""
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": prompt
}
]
)
answer = response.choices[0].message.content
st.subheader("Answer")
st.write(answer)
st.subheader("Retrieved Chunks")
for i, doc in enumerate(docs):
st.write(f"Chunk {i+1}")
st.write(doc.page_content)
st.divider()