zabih1 commited on
Commit
2a5403f
·
verified ·
1 Parent(s): 1969b68

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +22 -0
  2. app.py +129 -0
  3. requirements.txt +9 -0
Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ # Create a user with non-root privileges
4
+ RUN useradd -m -u 1000 user
5
+ USER user
6
+
7
+ # Set environment variables
8
+ ENV HOME=/home/user \
9
+ PATH=/home/user/.local/bin:$PATH
10
+
11
+ # Set working directory
12
+ WORKDIR $HOME/app
13
+
14
+ # Copy application files and requirements
15
+ COPY --chown=user . $HOME/app
16
+ COPY ./requirements.txt $HOME/app/requirements.txt
17
+
18
+ # Install dependencies
19
+ RUN pip install -r requirements.txt
20
+
21
+ # Define the default command to run the app
22
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List
3
+
4
+ from langchain_openai import OpenAIEmbeddings
5
+ from langchain_chroma import Chroma
6
+ from langchain.chains import ConversationalRetrievalChain
7
+ from langchain_groq import ChatGroq
8
+
9
+ from langchain_community.document_loaders import PyPDFLoader
10
+ from langchain.memory import ChatMessageHistory, ConversationBufferMemory
11
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ from langchain_core.prompts import PromptTemplate
14
+ from langchain import hub
15
+
16
+ import chainlit as cl
17
+ from io import BytesIO
18
+
19
+ ##################################### Load the embeddings and model #####################################
20
+
21
+ groq_api_key = os.getenv("GROQ_API_KEY")
22
+ embeddings_api_key = os.getenv('GOOGLE_API_KEY')
23
+
24
+ embedding_model = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
25
+ llm = ChatGroq(model="mixtral-8x7b-32768", temperature=0)
26
+
27
+
28
+
29
+
30
+ ##################################### on_chat_start event handler #######################################
31
+
32
+ @cl.on_chat_start
33
+ async def on_chat_start():
34
+ files = None
35
+
36
+ while files is None:
37
+ files = await cl.AskFileMessage(
38
+ content="Please upload a text file to begin",
39
+ accept=["application/pdf"],
40
+ max_size_mb=20,
41
+ timeout=300
42
+ ).send()
43
+
44
+ file = files[0]
45
+ msg = cl.Message(content=f"Processing `{file.name}` ...")
46
+ await msg.send()
47
+
48
+ ##################################### Load the text from the file ####################################
49
+
50
+ pdf_loader = PyPDFLoader(file.path).load()
51
+
52
+ ##################################### Split the text into chunks #####################################
53
+
54
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
55
+ chunks = text_splitter.split_documents(pdf_loader)
56
+
57
+ ##################################### Chroma DB setup ################################################
58
+
59
+ docsearch = await cl.make_async(Chroma.from_documents)(
60
+ chunks, embedding_model
61
+ )
62
+
63
+ message_history = ChatMessageHistory()
64
+
65
+ memory = ConversationBufferMemory(
66
+ memory_key="chat_history",
67
+ output_key="answer",
68
+ chat_memory=message_history,
69
+ return_messages=True
70
+ )
71
+
72
+ ##################################### Chain setup ###################################################
73
+
74
+ # Define your custom prompt template
75
+ custom_prompt_template = """
76
+ Based on the provided context please answer . if you don't know the answer. just say i don't know.
77
+ {context}
78
+
79
+ Question: {question}
80
+ """
81
+ custom_prompt = PromptTemplate(
82
+ template=custom_prompt_template,
83
+ input_variables=["context", "question"],)
84
+
85
+ chain = ConversationalRetrievalChain.from_llm(
86
+ llm,
87
+ chain_type="stuff",
88
+ retriever=docsearch.as_retriever(),
89
+ memory=memory,
90
+ return_source_documents=True,
91
+ combine_docs_chain_kwargs={"prompt": custom_prompt}
92
+
93
+ )
94
+
95
+ msg.content = f"Processing `{file.name}` ... Done!✅ You can ask questions now!"
96
+ await msg.update()
97
+
98
+ cl.user_session.set("chain", chain)
99
+
100
+
101
+ ##################################### On message event handler ###########################################
102
+
103
+ @cl.on_message
104
+ async def main(message: cl.Message):
105
+ chain = cl.user_session.get("chain")
106
+ cb = cl.AsyncLangchainCallbackHandler()
107
+
108
+ res = await chain.acall(message.content, callbacks=[cb])
109
+ answer = res['answer']
110
+
111
+ source_documents = res["source_documents"] # type: List[Document]
112
+
113
+ text_elements = [] # type: List[cl.Text]
114
+
115
+ if source_documents:
116
+ for source_idx, source_doc in enumerate(source_documents):
117
+ source_name = f"source_{source_idx}"
118
+ # Create the text element referenced in the message
119
+ text_elements.append(
120
+ cl.Text(content=source_doc.page_content, name=source_name, display="side")
121
+ )
122
+ source_names = [text_el.name for text_el in text_elements]
123
+
124
+ if source_names:
125
+ answer += f"\nSources: {', '.join(source_names)}"
126
+ else:
127
+ answer += "\nNo sources found"
128
+
129
+ await cl.Message(content=answer, elements=text_elements).send()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ openai
3
+ chromadb
4
+ langchain-openai
5
+ langchain-chroma
6
+ langchain-google-genai
7
+ langchain-groq
8
+ chainlit
9
+ PyPDF2