Lianglan commited on
Commit
c120c4c
Β·
1 Parent(s): 0e64bca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -29
app.py CHANGED
@@ -1,10 +1,8 @@
1
  import gradio as gr
2
- import os
3
  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
 
@@ -13,28 +11,37 @@ def get_empty_state():
13
 
14
  def download_prompt_templates():
15
  url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/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
 
@@ -43,9 +50,17 @@ def submit_message(user_token, prompt, prompt_template, temperature, max_tokens,
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())
@@ -59,21 +74,21 @@ def submit_message(user_token, prompt, prompt_template, temperature, max_tokens,
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
  """
@@ -85,9 +100,8 @@ with gr.Blocks(css=css) as demo:
85
 
86
  with gr.Column(elem_id="col-container"):
87
  gr.Markdown("""## OpenAI ChatGPT Demo
88
- Using the ofiicial API (gpt-3.5-turbo model)<br>
89
- Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).<br>
90
- Current limit is 3000 tokens per conversation.""",
91
  elem_id="header")
92
 
93
  with gr.Row():
@@ -98,26 +112,27 @@ with gr.Blocks(css=css) as demo:
98
  total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
99
  btn_clear_conversation = gr.Button("πŸ”ƒ Start New Conversation")
100
  with gr.Column():
 
 
101
  prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
102
  prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
103
- gr.Markdown("Enter your own OpenAI API Key to remove the 3000 token limit. You can get it [here](https://platform.openai.com/account/api-keys).", elem_id="label")
104
- user_token = gr.Textbox(placeholder="OpenAI API Key", type="password", show_label=False)
105
  with gr.Accordion("Advanced parameters", open=False):
106
- temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, interactive=True, label="Temperature (higher = more creative/chaotic)")
107
- max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, interactive=True, label="Max tokens per response")
 
108
 
109
- gr.HTML('''<br><br><br><center><a href="https://huggingface.co/spaces/anzorq/chatgpt-demo?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>You can duplicate this Space.<br>
110
- Don't forget to set your own <a href="https://platform.openai.com/account/api-keys">OpenAI API Key</a> environment variable in Settings.<br>
111
  <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.chatgpt_api_demo_hf" alt="visitors"></p></center>''')
112
 
113
- btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
114
- input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
115
  btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
116
  prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
117
  user_token.change(on_token_change, inputs=[user_token], outputs=[])
118
 
119
 
120
- demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template])
121
 
122
 
123
- demo.launch(debug=True, height='800px')
 
 
1
  import gradio as gr
 
2
  import openai
3
  import requests
4
+ import csv
5
 
 
6
 
7
  prompt_templates = {"Default ChatGPT": ""}
8
 
 
11
 
12
  def download_prompt_templates():
13
  url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
14
+ try:
15
+ response = requests.get(url)
16
+ reader = csv.reader(response.text.splitlines())
17
+ next(reader) # skip the header row
18
+ for row in reader:
19
+ if len(row) >= 2:
20
+ act = row[0].strip('"')
21
+ prompt = row[1].strip('"')
22
+ prompt_templates[act] = prompt
23
+
24
+ except requests.exceptions.RequestException as e:
25
+ print(f"An error occurred while downloading prompt templates: {e}")
26
+ return
27
 
28
  choices = list(prompt_templates.keys())
29
+ choices = choices[:1] + sorted(choices[1:])
30
  return gr.update(value=choices[0], choices=choices)
31
 
32
  def on_token_change(user_token):
33
+ openai.api_key = user_token
34
 
35
  def on_prompt_template_change(prompt_template):
36
  if not isinstance(prompt_template, str): return
37
  return prompt_templates[prompt_template]
38
 
39
+ def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, context_length, state):
40
 
41
  history = state['messages']
42
 
43
  if not prompt:
44
+ return gr.update(value=''), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']}", state
45
 
46
  prompt_template = prompt_templates[prompt_template]
47
 
 
50
  system_prompt = [{ "role": "system", "content": prompt_template }]
51
 
52
  prompt_msg = { "role": "user", "content": prompt }
53
+
54
+ if not user_token:
55
+ history.append(prompt_msg)
56
+ history.append({
57
+ "role": "system",
58
+ "content": "Error: OpenAI API Key is not set."
59
+ })
60
+ return '', [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: 0", state
61
 
62
  try:
63
+ completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history[-context_length*2:] + [prompt_msg], temperature=temperature, max_tokens=max_tokens)
64
 
65
  history.append(prompt_msg)
66
  history.append(completion.choices[0].message.to_dict())
 
74
  "content": f"Error: {e}"
75
  })
76
 
77
+ total_tokens_used_msg = f"Total tokens used: {state['total_tokens']}"
78
  chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)]
 
79
 
80
+ return '', chat_messages, total_tokens_used_msg, state
81
 
82
  def clear_conversation():
83
  return gr.update(value=None, visible=True), None, "", get_empty_state()
84
 
85
+
86
  css = """
87
  #col-container {max-width: 80%; margin-left: auto; margin-right: auto;}
88
  #chatbox {min-height: 400px;}
89
  #header {text-align: center;}
90
  #prompt_template_preview {padding: 1em; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;}
91
+ #total_tokens_str {text-align: right; font-size: 0.8em; color: #666;}
92
  #label {font-size: 0.8em; padding: 0.5em; margin: 0;}
93
  .message { font-size: 1.2em; }
94
  """
 
100
 
101
  with gr.Column(elem_id="col-container"):
102
  gr.Markdown("""## OpenAI ChatGPT Demo
103
+ Using the ofiicial API (gpt-3.5-turbo model)
104
+ Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).""",
 
105
  elem_id="header")
106
 
107
  with gr.Row():
 
112
  total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
113
  btn_clear_conversation = gr.Button("πŸ”ƒ Start New Conversation")
114
  with gr.Column():
115
+ gr.Markdown("Enter your OpenAI API Key. You can get one [here](https://platform.openai.com/account/api-keys).", elem_id="label")
116
+ user_token = gr.Textbox(value='', placeholder="OpenAI API Key", type="password", show_label=False)
117
  prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
118
  prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
 
 
119
  with gr.Accordion("Advanced parameters", open=False):
120
+ temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, label="Temperature", info="Higher = more creative/chaotic")
121
+ max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, label="Max tokens per response")
122
+ context_length = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Context length", info="Number of previous messages to send to the chatbot. Be careful with high values, it can blow up the token budget quickly.")
123
 
124
+ gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:<a href="https://huggingface.co/spaces/anzorq/chatgpt-demo?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
 
125
  <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.chatgpt_api_demo_hf" alt="visitors"></p></center>''')
126
 
127
+ btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state])
128
+ input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state])
129
  btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
130
  prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
131
  user_token.change(on_token_change, inputs=[user_token], outputs=[])
132
 
133
 
134
+ demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template], queur=False)
135
 
136
 
137
+ demo.queue(concurrency_count=10)
138
+ demo.launch(height='800px')