Upload app.py
Browse files
app.py
CHANGED
|
@@ -9,9 +9,11 @@
|
|
| 9 |
myfont=FontProperties(fname='/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/SimHei.ttf')
|
| 10 |
sns.set_style('whitegrid',{'font.sans-serif':['simhei','Arial']})
|
| 11 |
|
|
|
|
| 12 |
'''
|
| 13 |
-
# TODO:
|
| 14 |
|
|
|
|
| 15 |
from codeinterpreterapi import CodeInterpreterSession, File
|
| 16 |
import streamlit as st
|
| 17 |
from codeinterpreterapi import CodeInterpreterSession
|
|
@@ -20,7 +22,6 @@ import os
|
|
| 20 |
import matplotlib.pyplot as plt
|
| 21 |
import xlrd
|
| 22 |
import pandas as pd
|
| 23 |
-
# from io import StringIO
|
| 24 |
# import csv
|
| 25 |
import tempfile
|
| 26 |
from tempfile import NamedTemporaryFile
|
|
@@ -29,55 +30,66 @@ from pathlib import Path
|
|
| 29 |
from matplotlib.font_manager import FontProperties
|
| 30 |
import seaborn as sns
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
# #* 如果碰到接口问题,可以启用如下设置。
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
|
| 43 |
# layout settings.
|
| 44 |
st.title("个人大语言模型商业智能中心")
|
| 45 |
st.subheader("Artificial Intelligence Backend Center for Individuals")
|
| 46 |
-
# col1, col2 = st.columns(spec=[1, 2])
|
| 47 |
-
# radio_1 = col1.radio(label='ChatGPT版本', options=[
|
| 48 |
-
# 'GPT-3.5', 'GPT-4.0'], horizontal=True, label_visibility='visible')
|
| 49 |
-
# radio_2 = col2.radio(label='模式选择', options=[
|
| 50 |
-
# '核心模式', '联网模式', '数据模式'], horizontal=True, label_visibility='visible')
|
| 51 |
-
|
| 52 |
-
uploaded_file = st.file_uploader(
|
| 53 |
-
"选择一个文件", type=(["csv", "xlsx", "xls"]))
|
| 54 |
-
|
| 55 |
-
if uploaded_file is not None:
|
| 56 |
-
filename=uploaded_file.name
|
| 57 |
-
# st.write(filename) ## print out the whole file name to validate.
|
| 58 |
-
try:
|
| 59 |
-
if '.csv' in filename:
|
| 60 |
-
csv_file = pd.read_csv(uploaded_file)
|
| 61 |
-
st.write(csv_file[:3]) # 这里只是显示文件,后面需要定位文件所在的绝对路径。
|
| 62 |
-
else:
|
| 63 |
-
xls_file = pd.read_excel(uploaded_file)
|
| 64 |
-
st.write(xls_file[:3])
|
| 65 |
-
except Exception as e:
|
| 66 |
-
st.write(e)
|
| 67 |
-
|
| 68 |
-
uploaded_file_name = "File_provided"
|
| 69 |
-
temp_dir = tempfile.TemporaryDirectory()
|
| 70 |
-
# ! working.
|
| 71 |
-
uploaded_file_path = pathlib.Path(temp_dir.name) / uploaded_file_name
|
| 72 |
-
with open(uploaded_file_path, 'wb') as output_temporary_file:
|
| 73 |
-
# output_temporary_file.write(uploaded_file.read())
|
| 74 |
-
# ! 必须用这种格式读入内容,然后才可以写入temporary文件夹中。
|
| 75 |
-
output_temporary_file.write(uploaded_file.getvalue())
|
| 76 |
-
st.write(uploaded_file_path) # * 可以查看文件是否真实存在,然后是否可以
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def search(query):
|
| 82 |
# Construct a request
|
| 83 |
# mkt = 'en-EN'
|
|
@@ -87,7 +99,8 @@ def search(query):
|
|
| 87 |
|
| 88 |
# Call the API
|
| 89 |
try:
|
| 90 |
-
response = requests.get(bing_search_endpoint,
|
|
|
|
| 91 |
response.raise_for_status()
|
| 92 |
json = response.json()
|
| 93 |
return json["webPages"]["value"]
|
|
@@ -99,18 +112,12 @@ def search(query):
|
|
| 99 |
# openai.api_key = st.secrets["OPENAI_API_KEY"]
|
| 100 |
|
| 101 |
# async def main():
|
| 102 |
-
async def
|
| 103 |
-
|
| 104 |
-
radio_1 = col1.radio(label='ChatGPT版本', options=[
|
| 105 |
-
'GPT-3.5', 'GPT-4.0'], horizontal=True, label_visibility='visible')
|
| 106 |
-
radio_2 = col2.radio(label='模式选择', options=[
|
| 107 |
-
'核心模式', '联网模式', '数据模式'], horizontal=True, label_visibility='visible')
|
| 108 |
-
|
| 109 |
-
## Set a default model
|
| 110 |
if "openai_model" not in st.session_state:
|
| 111 |
st.session_state["openai_model"] = "gpt-3.5-turbo-16k"
|
| 112 |
-
|
| 113 |
if radio_1 == 'GPT-3.5':
|
|
|
|
| 114 |
print('radio_1: GPT-3.5 starts!')
|
| 115 |
st.session_state["openai_model"] = "gpt-3.5-turbo-16k"
|
| 116 |
else:
|
|
@@ -127,7 +134,12 @@ async def main():
|
|
| 127 |
st.markdown(message["content"])
|
| 128 |
|
| 129 |
# Display assistant response in chat message container
|
| 130 |
-
if prompt := st.chat_input("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 132 |
with st.chat_message("user"):
|
| 133 |
st.markdown(prompt)
|
|
@@ -136,79 +148,81 @@ async def main():
|
|
| 136 |
message_placeholder = st.empty()
|
| 137 |
full_response = ""
|
| 138 |
|
| 139 |
-
if radio_2 == '数据分析模式':
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
elif radio_2 == '联网模式':
|
| 204 |
# print('联网模式入口,prompt:', prompt)
|
| 205 |
input_message = prompt
|
| 206 |
internet_search_result = search(input_message)
|
| 207 |
-
search_prompt = [
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
st.session_state.messages.append(
|
|
|
|
| 212 |
|
| 213 |
for response in openai.ChatCompletion.create(
|
| 214 |
model=st.session_state["openai_model"],
|
|
@@ -218,34 +232,134 @@ async def main():
|
|
| 218 |
],
|
| 219 |
stream=True,
|
| 220 |
):
|
| 221 |
-
full_response += response.choices[0].delta.get(
|
|
|
|
| 222 |
message_placeholder.markdown(full_response + "▌")
|
| 223 |
message_placeholder.markdown(full_response)
|
| 224 |
st.session_state.messages.append(
|
| 225 |
{"role": "assistant", "content": full_response})
|
| 226 |
|
| 227 |
-
|
| 228 |
print('GPT only starts!!!')
|
| 229 |
-
print('
|
| 230 |
-
# st.session_state.messages.append({"role": "system", "content": 'You are a helpful AI assistant: ChatGPT.'})
|
| 231 |
-
|
| 232 |
for response in openai.ChatCompletion.create(
|
| 233 |
model=st.session_state["openai_model"],
|
| 234 |
-
messages=[
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
],
|
|
|
|
| 238 |
stream=True,
|
| 239 |
):
|
| 240 |
-
|
| 241 |
-
|
| 242 |
message_placeholder.markdown(full_response + "▌")
|
|
|
|
| 243 |
message_placeholder.markdown(full_response)
|
| 244 |
st.session_state.messages.append(
|
| 245 |
{"role": "assistant", "content": full_response})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
if __name__ == "__main__":
|
| 249 |
import asyncio
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
myfont=FontProperties(fname='/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/SimHei.ttf')
|
| 10 |
sns.set_style('whitegrid',{'font.sans-serif':['simhei','Arial']})
|
| 11 |
|
| 12 |
+
|
| 13 |
'''
|
| 14 |
+
# TODO:solve the data analysi model issue.
|
| 15 |
|
| 16 |
+
import requests
|
| 17 |
from codeinterpreterapi import CodeInterpreterSession, File
|
| 18 |
import streamlit as st
|
| 19 |
from codeinterpreterapi import CodeInterpreterSession
|
|
|
|
| 22 |
import matplotlib.pyplot as plt
|
| 23 |
import xlrd
|
| 24 |
import pandas as pd
|
|
|
|
| 25 |
# import csv
|
| 26 |
import tempfile
|
| 27 |
from tempfile import NamedTemporaryFile
|
|
|
|
| 30 |
from matplotlib.font_manager import FontProperties
|
| 31 |
import seaborn as sns
|
| 32 |
|
| 33 |
+
os.environ["OPENAI_API_KEY"] = "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"
|
| 34 |
+
openai.api_key = "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"
|
| 35 |
+
# os.environ["OPENAI_API_KEY"] = "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" ## Carrie
|
| 36 |
+
# openai.api_key = "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" ## Carrie
|
| 37 |
+
# os.environ["VERBOSE"] = "True" # 可以看到具体的错误?
|
| 38 |
|
| 39 |
# #* 如果碰到接口问题,可以启用如下设置。
|
| 40 |
+
openai.proxy = {
|
| 41 |
+
"http": "http://127.0.0.1:7890",
|
| 42 |
+
"https": "http://127.0.0.1:7890"
|
| 43 |
+
}
|
| 44 |
|
| 45 |
# layout settings.
|
| 46 |
st.title("个人大语言模型商业智能中心")
|
| 47 |
st.subheader("Artificial Intelligence Backend Center for Individuals")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# tab1, tab2 = st.tabs(["传统模式", "数据模型"])
|
| 50 |
+
|
| 51 |
+
# with tab1:
|
| 52 |
+
col1, col2 = st.columns(spec=[1, 2])
|
| 53 |
+
radio_1 = col1.radio(label='ChatGPT版本', options=[
|
| 54 |
+
'GPT-3.5', 'GPT-4.0'], horizontal=True, label_visibility='visible')
|
| 55 |
+
radio_2 = col2.radio(label='模式选择', options=[
|
| 56 |
+
'核心模式', '联网模式', '数据模式'], horizontal=True, label_visibility='visible')
|
| 57 |
+
|
| 58 |
+
# with tab2:
|
| 59 |
+
def upload_file(uploaded_file):
|
| 60 |
+
# uploaded_file = st.file_uploader(
|
| 61 |
+
# "选择一个文件", type=(["csv", "xlsx", "xls"]))
|
| 62 |
+
if uploaded_file is not None:
|
| 63 |
+
filename = uploaded_file.name
|
| 64 |
+
st.write(filename) ## print out the whole file name to validate.
|
| 65 |
+
try:
|
| 66 |
+
if '.csv' in filename:
|
| 67 |
+
csv_file = pd.read_csv(uploaded_file)
|
| 68 |
+
st.write(csv_file[:3]) # 这里只是显示文件,后面需要定位文件所在的绝对路径。
|
| 69 |
+
else:
|
| 70 |
+
xls_file = pd.read_excel(uploaded_file)
|
| 71 |
+
st.write(xls_file[:3])
|
| 72 |
+
except Exception as e:
|
| 73 |
+
st.write(e)
|
| 74 |
+
|
| 75 |
+
uploaded_file_name = "File_provided"
|
| 76 |
+
temp_dir = tempfile.TemporaryDirectory()
|
| 77 |
+
# ! working.
|
| 78 |
+
uploaded_file_path = pathlib.Path(temp_dir.name) / uploaded_file_name
|
| 79 |
+
with open(uploaded_file_path, 'wb') as output_temporary_file:
|
| 80 |
+
# output_temporary_file.write(uploaded_file.read())
|
| 81 |
+
# ! 必须用这种格式读入内容,然后才可以写入temporary文件夹中。
|
| 82 |
+
output_temporary_file.write(uploaded_file.getvalue())
|
| 83 |
+
st.write(uploaded_file_path) # * 可以查看文件是否真实存在,���后是否可以
|
| 84 |
+
output_temporary_file.close()
|
| 85 |
+
|
| 86 |
+
return uploaded_file_path
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
bing_search_api_key = '1fbcda1fb09547efbcdae7cb83a367b5'
|
| 90 |
+
bing_search_endpoint = 'https://api.bing.microsoft.com/v7.0/search'
|
| 91 |
+
|
| 92 |
+
|
| 93 |
def search(query):
|
| 94 |
# Construct a request
|
| 95 |
# mkt = 'en-EN'
|
|
|
|
| 99 |
|
| 100 |
# Call the API
|
| 101 |
try:
|
| 102 |
+
response = requests.get(bing_search_endpoint,
|
| 103 |
+
headers=headers, params=params)
|
| 104 |
response.raise_for_status()
|
| 105 |
json = response.json()
|
| 106 |
return json["webPages"]["value"]
|
|
|
|
| 112 |
# openai.api_key = st.secrets["OPENAI_API_KEY"]
|
| 113 |
|
| 114 |
# async def main():
|
| 115 |
+
async def text_mode():
|
| 116 |
+
# Set a default model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
if "openai_model" not in st.session_state:
|
| 118 |
st.session_state["openai_model"] = "gpt-3.5-turbo-16k"
|
|
|
|
| 119 |
if radio_1 == 'GPT-3.5':
|
| 120 |
+
# print('----------'*5)
|
| 121 |
print('radio_1: GPT-3.5 starts!')
|
| 122 |
st.session_state["openai_model"] = "gpt-3.5-turbo-16k"
|
| 123 |
else:
|
|
|
|
| 134 |
st.markdown(message["content"])
|
| 135 |
|
| 136 |
# Display assistant response in chat message container
|
| 137 |
+
# if prompt := st.chat_input("Say something"):
|
| 138 |
+
prompt = st.chat_input("Say something")
|
| 139 |
+
print('prompt now:', prompt)
|
| 140 |
+
print('----------'*5)
|
| 141 |
+
# if prompt:
|
| 142 |
+
if prompt:
|
| 143 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 144 |
with st.chat_message("user"):
|
| 145 |
st.markdown(prompt)
|
|
|
|
| 148 |
message_placeholder = st.empty()
|
| 149 |
full_response = ""
|
| 150 |
|
| 151 |
+
# if radio_2 == '数据分析模式':
|
| 152 |
+
# print('数据分析模式启动!')
|
| 153 |
+
# with st.chat_message("assistant"):
|
| 154 |
+
# # message_placeholder = st.empty()
|
| 155 |
+
# # full_response = ""
|
| 156 |
+
# async with CodeInterpreterSession() as session:
|
| 157 |
+
# # user_request = "对于文件中的'SepalLengthCm’数据给我一个'直方图',提供图表,并给出分析结果"
|
| 158 |
+
# #! 可以用设定dpi=300来输出高质量的图表。(注:图的解析度dpi设定为300)
|
| 159 |
+
# environ_settings = """【背景要求】如果我没有告诉你任何定制化的要求,那么请你按照以下的默认要求来回答:
|
| 160 |
+
# -------------------------------------------------------------------------
|
| 161 |
+
# 1. 你需要用提问的语言来回答(如:中文提问你就用中文来回答,英文提问你就用英文来回答)。
|
| 162 |
+
# 2. 如果要求你输出图表,那么图的解析度dpi需要设定为300。图尽量使用seaborn库。seaborn库的参数设定:sns.set(rc={'axes.facecolor':'#FFF9ED','figure.facecolor':'#FFF9ED'}, palette='dark'。
|
| 163 |
+
# 3. 如果需要显示中文,那么设置如下:
|
| 164 |
+
# 3.1 首先,你需要安装中文字体:
|
| 165 |
+
# myfont=FontProperties(fname='/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/SimHei.ttf')
|
| 166 |
+
# 3.2 然后,你需要设定在matplotlib(plt)和seaborn(sns)中设定:
|
| 167 |
+
# sns.set_style({'font.sans-serif':['Arial','SimHei']})
|
| 168 |
+
# plt.rcParams['font.sans-serif'] = ['SimHei']
|
| 169 |
+
# plt.rcParams['font.family']='sans-serif'
|
| 170 |
+
# plt.title(fontsize = 18)
|
| 171 |
+
# -------------------------------------------------------------------------
|
| 172 |
+
# """ # seaborn中的palette参数可以设定图表的颜色,选项包括:deep, muted, pastel, bright, dark, colorblind,Spectral。更多参数可以参考:https://seaborn.pydata.org/generated/seaborn.color_palette.html。
|
| 173 |
+
|
| 174 |
+
# uploaded_file_path = upload_file()
|
| 175 |
+
|
| 176 |
+
# user_request = environ_settings + "\n\n" + \
|
| 177 |
+
# "你需要完成以下任务:\n\n" + prompt + \
|
| 178 |
+
# f"注:文件位置在{uploaded_file_path}"
|
| 179 |
+
# print('user_request: \n', user_request)
|
| 180 |
+
|
| 181 |
+
# # 加载上传的文件,主要路径在上面代码中。
|
| 182 |
+
# files = [File.from_path(str(uploaded_file_path))]
|
| 183 |
+
|
| 184 |
+
# with st.status('thinking...', expanded=True, state='running') as status:
|
| 185 |
+
# # generate the response
|
| 186 |
+
# response = await session.generate_response(
|
| 187 |
+
# user_request, files=files
|
| 188 |
+
# )
|
| 189 |
+
|
| 190 |
+
# # output to the user
|
| 191 |
+
# print("AI: ", response.content)
|
| 192 |
+
# full_response = response.content
|
| 193 |
+
# ### full_response = "this is full response"
|
| 194 |
+
|
| 195 |
+
# # for file in response.files:
|
| 196 |
+
# for i, file in enumerate(response.files):
|
| 197 |
+
# # await file.asave(f"/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/output{i}.png") ##working.
|
| 198 |
+
# # st.image(file.get_image()) #! working.
|
| 199 |
+
# # * 注意这里的设定,可以提高图片的精细程度。
|
| 200 |
+
# st.image(file.get_image(), width=None,
|
| 201 |
+
# output_format='PNG')
|
| 202 |
+
|
| 203 |
+
# # message_placeholder.markdown(full_response + "▌") ## orignal code.
|
| 204 |
+
# # message_placeholder.markdown(full_response) ## orignal code.
|
| 205 |
+
# st.write(full_response)
|
| 206 |
+
# status.update(label='complete', state='complete')
|
| 207 |
+
# # st.session_state.messages.append(
|
| 208 |
+
# # {"role": "assistant", "content": full_response})
|
| 209 |
+
|
| 210 |
+
# await session.astop() # ! 确认需要关闭。
|
| 211 |
+
# # st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 212 |
+
|
| 213 |
+
if radio_2 == '联网模式':
|
|
|
|
|
|
|
| 214 |
# print('联网模式入口,prompt:', prompt)
|
| 215 |
input_message = prompt
|
| 216 |
internet_search_result = search(input_message)
|
| 217 |
+
search_prompt = [
|
| 218 |
+
f"Source:\nTitle: {result['name']}\nURL: {result['url']}\nContent: {result['snippet']}" for result in internet_search_result]
|
| 219 |
+
prompt = "基于如下的互联网公开信息, 回答问题:\n\n" + \
|
| 220 |
+
"\n\n".join(search_prompt[:3]) + "\n\n问题: " + input_message + \
|
| 221 |
+
"你需要注意的是回答问题时必须用提问的语言(如英文或者中文)来提示:'答案基于互联网公开信息。'" + "\n\n答案: " # 限制了只有3个搜索结果。
|
| 222 |
+
# prompt = "Use these sources to answer the question:\n\n" + "\n\n".join(search_prompt[0:3]) + "\n\nQuestion: " + input_message + "(注意:回答问题时请提示'以下答案基于互联网公开信息。')\n\n" + "\n\nAnswer: "
|
| 223 |
|
| 224 |
+
st.session_state.messages.append(
|
| 225 |
+
{"role": "user", "content": prompt})
|
| 226 |
|
| 227 |
for response in openai.ChatCompletion.create(
|
| 228 |
model=st.session_state["openai_model"],
|
|
|
|
| 232 |
],
|
| 233 |
stream=True,
|
| 234 |
):
|
| 235 |
+
full_response += response.choices[0].delta.get(
|
| 236 |
+
"content", "")
|
| 237 |
message_placeholder.markdown(full_response + "▌")
|
| 238 |
message_placeholder.markdown(full_response)
|
| 239 |
st.session_state.messages.append(
|
| 240 |
{"role": "assistant", "content": full_response})
|
| 241 |
|
| 242 |
+
if radio_2 == '核心模式':
|
| 243 |
print('GPT only starts!!!')
|
| 244 |
+
print('messages:', st.session_state['messages'])
|
|
|
|
|
|
|
| 245 |
for response in openai.ChatCompletion.create(
|
| 246 |
model=st.session_state["openai_model"],
|
| 247 |
+
# messages=[
|
| 248 |
+
# {"role": m["role"], "content": m["content"]}
|
| 249 |
+
# for m in st.session_state.messages
|
| 250 |
+
# ],
|
| 251 |
+
messages=[{'role': 'system', 'content': 'you are ChatGPT'}, {'role': 'user', 'content': prompt}],
|
| 252 |
stream=True,
|
| 253 |
):
|
| 254 |
+
full_response += response.choices[0].delta.get(
|
| 255 |
+
"content", "")
|
| 256 |
message_placeholder.markdown(full_response + "▌")
|
| 257 |
+
print('session completed!')
|
| 258 |
message_placeholder.markdown(full_response)
|
| 259 |
st.session_state.messages.append(
|
| 260 |
{"role": "assistant", "content": full_response})
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
async def data_mode(uploaded_file_path):
|
| 264 |
+
print('数据分析模式启动!')
|
| 265 |
+
|
| 266 |
+
## TODO: validate the existence of uploaded file.
|
| 267 |
+
st.write(uploaded_file_path)
|
| 268 |
+
tmp1 = pd.read_csv(str(uploaded_file_path))
|
| 269 |
+
st.write(tmp1[:5])
|
| 270 |
+
|
| 271 |
+
# Initialize chat history
|
| 272 |
+
if "messages" not in st.session_state:
|
| 273 |
+
st.session_state.messages = []
|
| 274 |
+
|
| 275 |
+
# Display chat messages from history on app rerun
|
| 276 |
+
for message in st.session_state.messages:
|
| 277 |
+
with st.chat_message(message["role"]):
|
| 278 |
+
st.markdown(message["content"])
|
| 279 |
+
|
| 280 |
+
# Display assistant response in chat message container
|
| 281 |
+
# if prompt := st.chat_input("Say something"):
|
| 282 |
+
prompt = st.chat_input("Say something")
|
| 283 |
+
print('prompt now:', prompt)
|
| 284 |
+
print('----------'*5)
|
| 285 |
+
# if prompt:
|
| 286 |
+
if prompt:
|
| 287 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 288 |
+
with st.chat_message("user"):
|
| 289 |
+
st.markdown(prompt)
|
| 290 |
+
|
| 291 |
+
with st.chat_message("assistant"):
|
| 292 |
+
async with CodeInterpreterSession() as session:
|
| 293 |
+
# user_request = "对于文件中的'SepalLengthCm’数据给我一个'直方图',提供图表,并给出分析结果"
|
| 294 |
+
#! 可以用设定dpi=300来输出高质量的图表。(注:图的解析度dpi设定为300)
|
| 295 |
+
environ_settings = """【背景要求】如果我没有告诉你任何定制化的要求,那么请你按照以下的默认要求来回答:
|
| 296 |
+
-------------------------------------------------------------------------
|
| 297 |
+
1. 你需要用提问的语言来回答(如:中文提问你就用中文来回答,英文提问你就用英文来回答)。
|
| 298 |
+
2. 如果要求你输出图表,那么图的解析度dpi需要设定为300。图尽量使用seaborn库。seaborn库的参数设定:sns.set(rc={'axes.facecolor':'#FFF9ED','figure.facecolor':'#FFF9ED'}, palette='dark'。
|
| 299 |
+
3. 如果需要显示中文,那么设置如下:
|
| 300 |
+
3.1 首先,你需要安装中文字体:
|
| 301 |
+
myfont=FontProperties(fname='/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/SimHei.ttf')
|
| 302 |
+
3.2 然后,你需要设定在matplotlib(plt)和seaborn(sns)中设定:
|
| 303 |
+
sns.set_style({'font.sans-serif':['Arial','SimHei']})
|
| 304 |
+
plt.rcParams['font.sans-serif'] = ['SimHei']
|
| 305 |
+
plt.rcParams['font.family']='sans-serif'
|
| 306 |
+
plt.title(fontsize = 18)
|
| 307 |
+
-------------------------------------------------------------------------
|
| 308 |
+
""" # seaborn中的palette参数可以设定图表的颜色,选项包括:deep, muted, pastel, bright, dark, colorblind,Spectral。更多参数可以参考:https://seaborn.pydata.org/generated/seaborn.color_palette.html。
|
| 309 |
+
|
| 310 |
+
# uploaded_file_path = upload_file()
|
| 311 |
|
| 312 |
+
user_request = environ_settings + "\n\n" + \
|
| 313 |
+
"你需要完成以下任务:\n\n" + prompt + "\n\n" \
|
| 314 |
+
f"注:文件位置在{uploaded_file_path}"
|
| 315 |
+
print('user_request: \n', user_request)
|
| 316 |
+
|
| 317 |
+
# 加载上传的文件,主要路径在上面代码中。
|
| 318 |
+
files = [File.from_path(str(uploaded_file_path))]
|
| 319 |
+
|
| 320 |
+
with st.status('thinking...', expanded=True, state='running') as status:
|
| 321 |
+
# generate the response
|
| 322 |
+
response = await session.generate_response(
|
| 323 |
+
user_request, files=files
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# output to the user
|
| 327 |
+
print("AI: ", response.content)
|
| 328 |
+
full_response = response.content
|
| 329 |
+
### full_response = "this is full response"
|
| 330 |
+
|
| 331 |
+
# for file in response.files:
|
| 332 |
+
for i, file in enumerate(response.files):
|
| 333 |
+
# await file.asave(f"/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/output{i}.png") ##working.
|
| 334 |
+
# st.image(file.get_image()) #! working.
|
| 335 |
+
# * 注意这里的设定,可以提高图片的精细程度。
|
| 336 |
+
st.image(file.get_image(), width=None,
|
| 337 |
+
output_format='PNG')
|
| 338 |
+
|
| 339 |
+
# message_placeholder.markdown(full_response + "▌") ## orignal code.
|
| 340 |
+
# message_placeholder.markdown(full_response) ## orignal code.
|
| 341 |
+
st.write(full_response)
|
| 342 |
+
status.update(label='complete', state='complete')
|
| 343 |
+
# st.session_state.messages.append(
|
| 344 |
+
# {"role": "assistant", "content": full_response})
|
| 345 |
+
|
| 346 |
+
await session.astop() # ! 确认需要关闭。
|
| 347 |
+
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 348 |
|
| 349 |
if __name__ == "__main__":
|
| 350 |
import asyncio
|
| 351 |
+
if radio_2 != "数据模式":
|
| 352 |
+
# * 也可以用命令执行这个python文件。’streamlit run frontend/app.py‘
|
| 353 |
+
asyncio.run(text_mode())
|
| 354 |
+
# upload_file()
|
| 355 |
+
elif radio_2 == "数据模式":
|
| 356 |
+
uploaded_file = st.file_uploader(
|
| 357 |
+
"选择一个文件", type=(["csv", "xlsx", "xls"]))
|
| 358 |
+
## 默认状态下没有上传文件,None,会报错。需要判断。
|
| 359 |
+
if uploaded_file is not None:
|
| 360 |
+
uploaded_file_path = upload_file(uploaded_file)
|
| 361 |
+
asyncio.run(data_mode(uploaded_file_path))
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
|