Nikhil-Murade commited on
Commit
fcf101b
·
verified ·
1 Parent(s): be5055f

app.py, requirements.txt added

Browse files
Files changed (2) hide show
  1. app.py +50 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Import necessary libraries
2
+ ## Llamaindex library recently updated
3
+ import streamlit as st
4
+ import openai
5
+
6
+ from llama_index.core import VectorStoreIndex, ServiceContext, Document
7
+ from llama_index.llms.openai import OpenAI
8
+ from llama_index.core import SimpleDirectoryReader
9
+
10
+
11
+ openai.api_key = os.getenv("OPENAI_API_KEY")
12
+ st.header("Chat with the Streamlit docs💬 📚")
13
+
14
+ if "messages" not in st.session_state.keys(): # Initialize the chat message history
15
+ st.session_state.messages = [
16
+ {"role": "assistant", "content": "Ask me a question"}
17
+ ]
18
+
19
+
20
+ @st.cache_resource(show_spinner=False)
21
+ def load_data():
22
+ with st.spinner(text="Loading and indexing the Streamlit docs – hang tight! This should take 1-2 minutes."):
23
+ reader = SimpleDirectoryReader(input_files=["Self-Management.pdf"], recursive=True)
24
+ docs = reader.load_data()
25
+ service_context = ServiceContext.from_defaults(llm=OpenAI(model="gpt-3.5-turbo", temperature=0.5, system_prompt="You are an expert on the Streamlit Python library and your job is to answer technical questions. Assume that all questions are related to the Streamlit Python library. Keep your answers technical and based on facts – do not hallucinate features."))
26
+ index = VectorStoreIndex.from_documents(docs, service_context=service_context)
27
+ return index
28
+
29
+ index = load_data()
30
+
31
+
32
+ chat_engine = index.as_chat_engine(chat_mode="condense_question", verbose=True)
33
+
34
+
35
+ if prompt := st.chat_input("Your question"): # Prompt for user input and save to chat history
36
+ st.session_state.messages.append({"role": "user", "content": prompt})
37
+
38
+ for message in st.session_state.messages: # Display the prior chat messages
39
+ with st.chat_message(message["role"]):
40
+ st.write(message["content"])
41
+
42
+ # If last message is not from assistant, generate a new response
43
+ if st.session_state.messages[-1]["role"] != "assistant":
44
+ with st.chat_message("assistant"):
45
+ with st.spinner("Thinking..."):
46
+ response = chat_engine.chat(prompt)
47
+ st.write(response.response)
48
+ message = {"role": "assistant", "content": response.response}
49
+ st.session_state.messages.append(message) # Add response to message history
50
+
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ streamlit
2
+ openai
3
+ llama-index