Peter Yang commited on
Commit
13881b0
Β·
1 Parent(s): 0955ea8

chatbot using openai

Browse files
Files changed (1) hide show
  1. pages/16_πŸ“ˆ_ChatBot.py +64 -81
pages/16_πŸ“ˆ_ChatBot.py CHANGED
@@ -1,83 +1,66 @@
1
  import streamlit as st
2
- import pandas as pd
3
- import io
4
- import base64
5
-
6
-
7
- # st.set_page_config(layout="wide")
8
-
9
- # Function for the CSV Visualization App
10
- def app():
11
-
12
- hide_streamlit_style = """
13
- <style>
14
- #MainMenu {visibility: hidden;}
15
- footer {visibility: hidden;}
16
- </style>
17
- """
18
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
19
-
20
- st.title("CSV Data Cleaning Tool")
21
-
22
- st.markdown("Upload one or multiple CSV files to preprocess and clean your files quickly and stress free.")
23
-
24
- uploaded_files = st.file_uploader("Choose CSV files", type="csv", accept_multiple_files=True)
25
-
26
- dataframes = []
27
-
28
- if uploaded_files:
29
- for file in uploaded_files:
30
- file.seek(0)
31
- df = pd.read_csv(file)
32
- dataframes.append(df)
33
-
34
- if len(dataframes) > 1:
35
- merge = st.checkbox("Merge uploaded CSV files")
36
-
37
- if merge:
38
- # Merge options
39
- keep_first_header_only = st.selectbox("Keep only the header (first row) of the first file", ["Yes", "No"])
40
- remove_duplicate_rows = st.selectbox("Remove duplicate rows", ["No", "Yes"])
41
- remove_empty_rows = st.selectbox("Remove empty rows", ["Yes", "No"])
42
- end_line = st.selectbox("End line", ["\\n", "\\r\\n"])
43
-
44
- try:
45
- if keep_first_header_only == "Yes":
46
- for i, df in enumerate(dataframes[1:]):
47
- df.columns = dataframes[0].columns.intersection(df.columns)
48
- dataframes[i+1] = df
49
-
50
- merged_df = pd.concat(dataframes, ignore_index=True, join='outer')
51
-
52
- if remove_duplicate_rows == "Yes":
53
- merged_df.drop_duplicates(inplace=True)
54
-
55
- if remove_empty_rows == "Yes":
56
- merged_df.dropna(how="all", inplace=True)
57
-
58
- dataframes = [merged_df]
59
-
60
- except ValueError as e:
61
- st.error("Please make sure columns match in all files. If you don't want them to match, select 'No' in the first option.")
62
- st.stop()
63
-
64
- # Show or hide DataFrames
65
- show_dataframes = st.checkbox("Show DataFrames", value=True)
66
-
67
- if show_dataframes:
68
- for i, df in enumerate(dataframes):
69
- st.write(f"DataFrame {i + 1}")
70
- st.dataframe(df)
71
-
72
- if st.button("Download cleaned data"):
73
- for i, df in enumerate(dataframes):
74
- csv = df.to_csv(index=False)
75
- b64 = base64.b64encode(csv.encode()).decode()
76
- href = f'<a href="data:file/csv;base64,{b64}" download="cleaned_data_{i + 1}.csv">Download cleaned_data_{i + 1}.csv</a>'
77
- st.markdown(href, unsafe_allow_html=True)
78
  else:
79
- st.warning("Please upload CSV file(s).")
80
- st.stop()
81
- app()
82
-
83
-
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ import json
4
+
5
+ st.title("OpenAI Chatbot Interface")
6
+ st.write("Interact with OpenAI's GPT-3 models in real-time using your OpenAI API. Choose from a selection of their best models, set the temperature and max tokens, and start a conversation. Delete the conversation at any time to start fresh.")
7
+
8
+ if "history" not in st.session_state:
9
+ st.session_state.history = []
10
+
11
+ st.sidebar.markdown("## Configuration")
12
+ KEY = st.sidebar.text_input("Enter Your OpenAI API Key", placeholder="API Key", value="")
13
+ models = ['text-davinci-003', 'text-curie-001', 'text-babbage-001', 'text-ada-001']
14
+ model = st.sidebar.selectbox("Select a model", models, index=0)
15
+
16
+ temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.7)
17
+ max_tokens = st.sidebar.slider("Max Tokens", 0, 4000, 1786)
18
+
19
+ if st.sidebar.button("Delete Conversation"):
20
+ st.session_state.history = []
21
+ st.sidebar.markdown("## GPT-3")
22
+ st.sidebar.markdown("OpenAI's GPT-3 models can understand and generate natural language. They offer four main models with different levels of power suitable for different tasks. Davinci is the most capable model, and Ada is the fastest.")
23
+ st.sidebar.markdown("text-davinci-003 | 4,000 max tokens")
24
+ st.sidebar.markdown("text-curie-001 | 2,048 max tokens")
25
+ st.sidebar.markdown("text-babbage-001 | 2,048 max tokens")
26
+ st.sidebar.markdown("text-ada-001 | 2,048 max tokens")
27
+
28
+ def generate_answer(prompt):
29
+ API_KEY = KEY
30
+ API_URL = "https://api.openai.com/v1/completions"
31
+ headers = {
32
+ 'Content-Type': 'application/json',
33
+ 'Authorization': 'Bearer ' + API_KEY
34
+ }
35
+ previous_messages = [chat['message'] for chat in st.session_state.history if not chat['is_user']]
36
+ previous_messages_text = '\n'.join(previous_messages)
37
+ full_prompt = previous_messages_text + '\n' + prompt if previous_messages_text else prompt
38
+ data = {
39
+ "model": model,
40
+ "prompt": full_prompt,
41
+ "temperature": temperature,
42
+ "max_tokens": max_tokens
43
+ }
44
+ if not API_KEY:
45
+ st.warning("Please input your API key")
46
+ return
47
+ response = requests.post(API_URL, headers=headers, data=json.dumps(data))
48
+ result = response.json()
49
+ if 'choices' in result:
50
+ message_bot = result['choices'][0]['text'].strip()
51
+ st.session_state.history.append({"message": prompt, "is_user": True})
52
+ st.session_state.history.append({"message": message_bot, "is_user": False})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  else:
54
+ st.error("An error occurred while processing the API response. If using a model other than text-davinci-003, then lower the Max Tokens.")
55
+
56
+ prompt = st.text_input("Prompt", placeholder="Prompt Here", value="")
57
+ if st.button("Submit"):
58
+ generate_answer(prompt)
59
+ with st.spinner("Waiting for the response from the bot..."):
60
+ for chat in st.session_state.history:
61
+ if chat['is_user']:
62
+ st.markdown("<img src='https://i.ibb.co/zVSbGvb/585e4beacb11b227491c3399.png' width='50' height='50' style='float:right;'>", unsafe_allow_html=True)
63
+ st.markdown(f"<div style='float:right; padding:10px; background-color: #2E2E2E; border-radius:10px; margin:10px;'>{chat['message']}</div>", unsafe_allow_html=True)
64
+ else:
65
+ st.markdown("<img src='https://i.ibb.co/LZFvDND/5841c0bda6515b1e0ad75a9e-1.png' width='50' height='50' style='float:left;'>", unsafe_allow_html=True)
66
+ st.markdown(f"<div style='float:left; padding:10px; background-color: #2E2E2E; border-radius:10px; margin:10px;'>{chat['message']}</div>", unsafe_allow_html=True)