Peggy Fan commited on
Commit
3d61243
β€’
1 Parent(s): 05b0694

starter files

Browse files
Files changed (2) hide show
  1. app.py +49 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from langchain.llms import OpenAI
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import Chroma
7
+ from langchain.chains import RetrievalQA
8
+
9
+ openai_api_key = os.environ["openai+api_key"]
10
+
11
+ def generate_response(uploaded_file, openai_api_key, query_text):
12
+ # Load document if file is uploaded
13
+ if uploaded_file is not None:
14
+ documents = [uploaded_file.read().decode()]
15
+ # Split documents into chunks
16
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
17
+ texts = text_splitter.create_documents(documents)
18
+ # Select embeddings
19
+ embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
20
+ # Create a vectorstore from documents
21
+ db = Chroma.from_documents(texts, embeddings)
22
+ # Create retriever interface
23
+ retriever = db.as_retriever()
24
+ # Create QA chain
25
+ qa = RetrievalQA.from_chain_type(llm=OpenAI(openai_api_key=openai_api_key), chain_type='stuff', retriever=retriever)
26
+ return qa.run(query_text)
27
+
28
+ # Page title
29
+ st.set_page_config(page_title='πŸ¦œπŸ”— Ask the Doc App')
30
+ st.title('πŸ¦œπŸ”— Ask the Doc App')
31
+
32
+ # File upload
33
+ uploaded_file = st.file_uploader('Upload an article', type='txt')
34
+ # Query text
35
+ query_text = st.text_input('Enter your question:', placeholder = 'Please provide a short summary.', disabled=not uploaded_file)
36
+
37
+ # Form input and query
38
+ result = []
39
+ with st.form('myform', clear_on_submit=True):
40
+ # openai_api_key = st.text_input('OpenAI API Key', type='password', disabled=not (uploaded_file and query_text))
41
+ submitted = st.form_submit_button('Submit', disabled=not(uploaded_file and query_text))
42
+ if submitted and openai_api_key.startswith('sk-'):
43
+ with st.spinner('Calculating...'):
44
+ response = generate_response(uploaded_file, openai_api_key, query_text)
45
+ result.append(response)
46
+ del openai_api_key
47
+
48
+ if len(result):
49
+ st.info(response)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ langchain
3
+ openai
4
+ chromadb
5
+ tiktoken