-
Notifications
You must be signed in to change notification settings - Fork 37
/
langchain_groq_rag.py
71 lines (53 loc) · 2.41 KB
/
langchain_groq_rag.py
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
import os
import streamlit as st
from langchain_groq import ChatGroq
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate
from langchain.chains import create_retrieval_chain
import time
from dotenv import load_dotenv
load_dotenv() #
groq_api_key = os.environ['GROQ_API_KEY']
if "vector" not in st.session_state:
st.session_state.embeddings = OllamaEmbeddings()
st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html")
st.session_state.docs = st.session_state.loader.load()
st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
st.session_state.documents = st.session_state.text_splitter.split_documents( st.session_state.docs)
st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings)
st.title("Chat with Docs - Groq Edition :) ")
llm = ChatGroq(
groq_api_key=groq_api_key,
model_name='mixtral-8x7b-32768'
)
prompt = ChatPromptTemplate.from_template("""
Answer the following question based only on the provided context.
Think step by step before providing a detailed answer.
I will tip you $200 if the user finds the answer helpful.
<context>
{context}
</context>
Question: {input}""")
document_chain = create_stuff_documents_chain(llm, prompt)
retriever = st.session_state.vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)
prompt = st.text_input("Input your prompt here")
# If the user hits enter
if prompt:
# Then pass the prompt to the LLM
start = time.process_time()
response = retrieval_chain.invoke({"input": prompt})
print(f"Response time: {time.process_time() - start}")
st.write(response["answer"])
# With a streamlit expander
with st.expander("Document Similarity Search"):
# Find the relevant chunks
for i, doc in enumerate(response["context"]):
# print(doc)
# st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
st.write(doc.page_content)
st.write("--------------------------------")