generated from streamlit/document-qa-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
53 lines (44 loc) · 1.81 KB
/
streamlit_app.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
import streamlit as st
from openai import OpenAI
# Show title and description.
st.title("📄 Document question answering")
st.write(
"Upload a document below and ask a question about it – GPT will answer! "
"To use this app, you need to provide an OpenAI API key, which you can get [here](https://platform.openai.com/account/api-keys). "
)
# Ask user for their OpenAI API key via `st.text_input`.
# Alternatively, you can store the API key in `./.streamlit/secrets.toml` and access it
# via `st.secrets`, see https://docs.streamlit.io/develop/concepts/connections/secrets-management
openai_api_key = st.text_input("OpenAI API Key", type="password")
if not openai_api_key:
st.info("Please add your OpenAI API key to continue.", icon="🗝️")
else:
# Create an OpenAI client.
client = OpenAI(api_key=openai_api_key)
# Let the user upload a file via `st.file_uploader`.
uploaded_file = st.file_uploader(
"Upload a document (.txt or .md)", type=("txt", "md")
)
# Ask the user for a question via `st.text_area`.
question = st.text_area(
"Now ask a question about the document!",
placeholder="Can you give me a short summary?",
disabled=not uploaded_file,
)
if uploaded_file and question:
# Process the uploaded file and question.
document = uploaded_file.read().decode()
messages = [
{
"role": "user",
"content": f"Here's a document: {document} \n\n---\n\n {question}",
}
]
# Generate an answer using the OpenAI API.
stream = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
stream=True,
)
# Stream the response to the app using `st.write_stream`.
st.write_stream(stream)