Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- chatbot_with_streamlit.py +46 -0
- requirements.txt +0 -0
chatbot_with_streamlit.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
|
3 |
+
from llama_index.llms import OpenAI
|
4 |
+
import openai
|
5 |
+
from llama_index import SimpleDirectoryReader
|
6 |
+
|
7 |
+
openai.api_key = st.secrets.openai_key
|
8 |
+
st.header("Chat with the Streamlit docs 💬 📚")
|
9 |
+
|
10 |
+
if "messages" not in st.session_state.keys(): # Initialize the chat message history
|
11 |
+
st.session_state.messages = [
|
12 |
+
{"role": "assistant", "content": "Ask me a question about Python!"}
|
13 |
+
]
|
14 |
+
|
15 |
+
@st.cache_resource(show_spinner=False)
|
16 |
+
def load_data():
|
17 |
+
with st.spinner(text="Loading and indexing the Streamlit docs – hang tight! This should take 1-2 minutes."):
|
18 |
+
reader = SimpleDirectoryReader(input_dir="./how-to-code-in-python.pdf", recursive=True)
|
19 |
+
docs = reader.load_data()
|
20 |
+
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."))
|
21 |
+
index = VectorStoreIndex.from_documents(docs, service_context=service_context)
|
22 |
+
return index
|
23 |
+
|
24 |
+
index = load_data()
|
25 |
+
|
26 |
+
|
27 |
+
chat_engine = index.as_chat_engine(chat_mode="condense_question", verbose=True)
|
28 |
+
|
29 |
+
if prompt := st.chat_input("Your question"): # Prompt for user input and save to chat history
|
30 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
31 |
+
|
32 |
+
for message in st.session_state.messages: # Display the prior chat messages
|
33 |
+
with st.chat_message(message["role"]):
|
34 |
+
st.write(message["content"])
|
35 |
+
|
36 |
+
|
37 |
+
# If last message is not from assistant, generate a new response
|
38 |
+
if st.session_state.messages[-1]["role"] != "assistant":
|
39 |
+
with st.chat_message("assistant"):
|
40 |
+
with st.spinner("Thinking..."):
|
41 |
+
response = chat_engine.chat(prompt)
|
42 |
+
st.write(response.response)
|
43 |
+
message = {"role": "assistant", "content": response.response}
|
44 |
+
st.session_state.messages.append(message) # Add response to message history
|
45 |
+
|
46 |
+
|
requirements.txt
ADDED
File without changes
|