JunchuanYu commited on
Commit
4ec9ef9
1 Parent(s): 1a898c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -97
app.py CHANGED
@@ -4,128 +4,128 @@ import openai
4
  import requests
5
  import json
6
 
7
- # openai.api_key = os.environ.get("OPENAI_API_KEY")
8
 
9
- # prompt_templates = {"Default ChatGPT": ""}
10
 
11
- # def get_empty_state():
12
- # return {"total_tokens": 0, "messages": []}
13
 
14
- # def download_prompt_templates():
15
- # url = "https://raw.githubusercontent.com/JunchuanYu/Sydney/main/prompts.csv"
16
- # response = requests.get(url)
17
 
18
- # for line in response.text.splitlines()[1:]:
19
- # act, prompt = line.split('","')
20
- # prompt_templates[act.replace('"', '')] = prompt.replace('"', '')
21
 
22
- # choices = list(prompt_templates.keys())
23
- # return gr.update(value=choices[0], choices=choices)
24
 
25
- # def on_token_change(user_token):
26
- # openai.api_key = user_token or os.environ.get("OPENAI_API_KEY")
27
 
28
- # def on_prompt_template_change(prompt_template):
29
- # if not isinstance(prompt_template, str): return
30
- # return prompt_templates[prompt_template]
31
 
32
- # def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, state):
33
 
34
- # history = state['messages']
35
 
36
- # if not prompt:
37
- # return gr.update(value='', visible=state['total_tokens'] < 1_000), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']} / 3000", state
38
 
39
- # prompt_template = prompt_templates[prompt_template]
40
 
41
- # system_prompt = []
42
- # if prompt_template:
43
- # system_prompt = [{ "role": "system", "content": prompt_template }]
44
 
45
- # prompt_msg = { "role": "user", "content": prompt }
46
 
47
- # try:
48
- # completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history + [prompt_msg], temperature=temperature, max_tokens=max_tokens)
49
 
50
- # history.append(prompt_msg)
51
- # history.append(completion.choices[0].message.to_dict())
52
 
53
- # state['total_tokens'] += completion['usage']['total_tokens']
54
 
55
- # except Exception as e:
56
- # history.append(prompt_msg)
57
- # history.append({
58
- # "role": "system",
59
- # "content": f"Error: {e}"
60
- # })
61
-
62
- # total_tokens_used_msg = f"Total tokens used: {state['total_tokens']} / 3000" if not user_token else ""
63
- # chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)]
64
- # input_visibility = user_token or state['total_tokens'] < 3000
65
-
66
- # return gr.update(value='', visible=input_visibility), chat_messages, total_tokens_used_msg, state
67
-
68
- # def clear_conversation():
69
- # return gr.update(value=None, visible=True), None, "", get_empty_state()
70
-
71
- # css = """
72
- # #col-container {max-width: 80%; margin-left: auto; margin-right: auto;}
73
- # #chatbox {min-height: 400px;}
74
- # #header {text-align: center;}
75
- # #prompt_template_preview {padding: 1em; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;}
76
- # #total_tokens_str {text-align: right; font-size: 0.8em; color: #666; height: 1em;}
77
- # #label {font-size: 0.8em; padding: 0.5em; margin: 0;}
78
- # .message { font-size: 1.2em; }
79
- # """
80
-
81
- # with gr.Blocks(css=css) as demo:
82
  with gr.Blocks() as demo:
83
 
84
  gr.Markdown("""# <p align="center">Sydney-AI <p> <b>""")
85
- # state = gr.State(get_empty_state())
86
-
87
-
88
- # with gr.Column(elem_id="col-container"):
89
- # gr.Markdown("""
90
- # # # Sydney-AI <b>
91
- # # <p align="left"> This app is an intelligent online chat app developed based on the newly released OpenAI API "gpt-3.5-turbo". The app's operating costs are sponsored by "45度科研人". Currently, the tokens is limited to 3000. If you want to remove this restriction, you can input your own OpenAI API key.<p>
92
- # # <p align="left"> The default model role of the app is the original assistant of ChatGPT, but you can also choose from the provided roles. <p>
93
- # # <p align="left"> Two adjustable parameters are provided to optimize the model: temperature, where a larger value leads to more creative replies, and max tokens, where a larger value allows the model to reply with more content. <p>
94
- # # APP link: https://junchuanyu-sydney-ai.hf.space""",elem_id="header")
95
-
96
- # with gr.Row():
97
- # with gr.Column():
98
- # chatbot = gr.Chatbot(elem_id="chatbox").style(color_map=("blue", "green"))
99
- # input_message = gr.Textbox(show_label=False, placeholder="Enter text and press submit", visible=True).style(container=False)
100
- # btn_submit = gr.Button("Submit")
101
- # total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
102
- # btn_clear_conversation = gr.Button("Restart Conversation")
103
- # with gr.Column():
104
- # gr.Markdown("Enter your own OpenAI API Key to remove the 3000 token limit. You can get it follow this instruction [here](https://blog.pangao.vip/%E8%B6%85%E8%AF%A6%E7%BB%86%E6%B3%A8%E5%86%8COpenAI%E6%8E%A5%E5%8F%A3%E8%B4%A6%E5%8F%B7%E7%9A%84%E6%95%99%E7%A8%8B/).", elem_id="label")
105
- # user_token = gr.Textbox(placeholder="OpenAI API Key", type="password", show_label=False)
106
- # prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
107
- # prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
108
- # with gr.Accordion("Advanced parameters", open=False):
109
- # temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, interactive=True, label="Temperature (higher = more creative/chaotic)")
110
- # max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, interactive=True, label="Max tokens per response")
111
- # # gr.Markdown("![](https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png)",elem_id="header")
112
 
113
- gr.Markdown("""
114
- <div align=center>Sydney-AI正在升级改版,优化输出显示和promp问题,新版近期上线,请关注[45度科研人]公众号信息!</div>
115
- <div align=center><img width = '200' height ='200' src ="https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png"/></div>""", elem_id="header")
116
 
117
- # gr.Markdown("""
118
- # you can follow the WeChat public account [45度科研人] and leave me a message!
119
- # <div align=center><img width = '200' height ='200' src ="https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png"/></div>""", elem_id="header")
120
 
121
- # btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
122
- # input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
123
- # btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
124
- # prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
125
- # user_token.change(on_token_change, inputs=[user_token], outputs=[])
126
 
127
 
128
- # demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template])
129
 
130
 
131
  demo.launch(debug=False)
 
4
  import requests
5
  import json
6
 
7
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
8
 
9
+ prompt_templates = {"Default ChatGPT": ""}
10
 
11
+ def get_empty_state():
12
+ return {"total_tokens": 0, "messages": []}
13
 
14
+ def download_prompt_templates():
15
+ url = "https://raw.githubusercontent.com/JunchuanYu/Sydney/main/prompts.csv"
16
+ response = requests.get(url)
17
 
18
+ for line in response.text.splitlines()[1:]:
19
+ act, prompt = line.split('","')
20
+ prompt_templates[act.replace('"', '')] = prompt.replace('"', '')
21
 
22
+ choices = list(prompt_templates.keys())
23
+ return gr.update(value=choices[0], choices=choices)
24
 
25
+ def on_token_change(user_token):
26
+ openai.api_key = user_token or os.environ.get("OPENAI_API_KEY")
27
 
28
+ def on_prompt_template_change(prompt_template):
29
+ if not isinstance(prompt_template, str): return
30
+ return prompt_templates[prompt_template]
31
 
32
+ def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, state):
33
 
34
+ history = state['messages']
35
 
36
+ if not prompt:
37
+ return gr.update(value='', visible=state['total_tokens'] < 1_000), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']} / 3000", state
38
 
39
+ prompt_template = prompt_templates[prompt_template]
40
 
41
+ system_prompt = []
42
+ if prompt_template:
43
+ system_prompt = [{ "role": "system", "content": prompt_template }]
44
 
45
+ prompt_msg = { "role": "user", "content": prompt }
46
 
47
+ try:
48
+ completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history + [prompt_msg], temperature=temperature, max_tokens=max_tokens)
49
 
50
+ history.append(prompt_msg)
51
+ history.append(completion.choices[0].message.to_dict())
52
 
53
+ state['total_tokens'] += completion['usage']['total_tokens']
54
 
55
+ except Exception as e:
56
+ history.append(prompt_msg)
57
+ history.append({
58
+ "role": "system",
59
+ "content": f"Error: {e}"
60
+ })
61
+
62
+ total_tokens_used_msg = f"Total tokens used: {state['total_tokens']} / 3000" if not user_token else ""
63
+ chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)]
64
+ input_visibility = user_token or state['total_tokens'] < 3000
65
+
66
+ return gr.update(value='', visible=input_visibility), chat_messages, total_tokens_used_msg, state
67
+
68
+ def clear_conversation():
69
+ return gr.update(value=None, visible=True), None, "", get_empty_state()
70
+
71
+ css = """
72
+ #col-container {max-width: 80%; margin-left: auto; margin-right: auto;}
73
+ #chatbox {min-height: 400px;}
74
+ #header {text-align: center;}
75
+ #prompt_template_preview {padding: 1em; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;}
76
+ #total_tokens_str {text-align: right; font-size: 0.8em; color: #666; height: 1em;}
77
+ #label {font-size: 0.8em; padding: 0.5em; margin: 0;}
78
+ .message { font-size: 1.2em; }
79
+ """
80
+
81
+ with gr.Blocks(css=css) as demo:
82
  with gr.Blocks() as demo:
83
 
84
  gr.Markdown("""# <p align="center">Sydney-AI <p> <b>""")
85
+ state = gr.State(get_empty_state())
86
+
87
+
88
+ with gr.Column(elem_id="col-container"):
89
+ gr.Markdown("""
90
+ # # Sydney-AI <b>
91
+ # <p align="left"> This app is an intelligent online chat app developed based on the newly released OpenAI API "gpt-3.5-turbo". The app's operating costs are sponsored by "45度科研人". Currently, the tokens is limited to 3000. If you want to remove this restriction, you can input your own OpenAI API key.<p>
92
+ # <p align="left"> The default model role of the app is the original assistant of ChatGPT, but you can also choose from the provided roles. <p>
93
+ # <p align="left"> Two adjustable parameters are provided to optimize the model: temperature, where a larger value leads to more creative replies, and max tokens, where a larger value allows the model to reply with more content. <p>
94
+ # APP link: https://junchuanyu-sydney-ai.hf.space""",elem_id="header")
95
+
96
+ with gr.Row():
97
+ with gr.Column():
98
+ chatbot = gr.Chatbot(elem_id="chatbox").style(color_map=("blue", "green"))
99
+ input_message = gr.Textbox(show_label=False, placeholder="Enter text and press submit", visible=True).style(container=False)
100
+ btn_submit = gr.Button("Submit")
101
+ total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
102
+ btn_clear_conversation = gr.Button("Restart Conversation")
103
+ with gr.Column():
104
+ gr.Markdown("Enter your own OpenAI API Key to remove the 3000 token limit. You can get it follow this instruction [here](https://blog.pangao.vip/%E8%B6%85%E8%AF%A6%E7%BB%86%E6%B3%A8%E5%86%8COpenAI%E6%8E%A5%E5%8F%A3%E8%B4%A6%E5%8F%B7%E7%9A%84%E6%95%99%E7%A8%8B/).", elem_id="label")
105
+ user_token = gr.Textbox(placeholder="OpenAI API Key", type="password", show_label=False)
106
+ prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
107
+ prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
108
+ with gr.Accordion("Advanced parameters", open=False):
109
+ temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, interactive=True, label="Temperature (higher = more creative/chaotic)")
110
+ max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, interactive=True, label="Max tokens per response")
111
+ # gr.Markdown("![](https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png)",elem_id="header")
112
 
113
+ # gr.Markdown("""
114
+ # <div align=center>Sydney-AI正在升级改版,优化输出显示和promp问题,新版近期上线,请关注[45度科研人]公众号信息!</div>
115
+ # <div align=center><img width = '200' height ='200' src ="https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png"/></div>""", elem_id="header")
116
 
117
+ gr.Markdown("""
118
+ you can follow the WeChat public account [45度科研人] and leave me a message!
119
+ <div align=center><img width = '200' height ='200' src ="https://dunazo.oss-cn-beijing.aliyuncs.com/blog/wechat-simple.png"/></div>""", elem_id="header")
120
 
121
+ btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
122
+ input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
123
+ btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
124
+ prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
125
+ user_token.change(on_token_change, inputs=[user_token], outputs=[])
126
 
127
 
128
+ demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template])
129
 
130
 
131
  demo.launch(debug=False)