anzorq commited on
Commit
02c16f4
1 Parent(s): 4740dd6
Files changed (2) hide show
  1. app.py +95 -40
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,64 +1,119 @@
1
  import gradio as gr
2
  import os
 
3
  import requests
4
  import json
5
 
6
- api_key = os.environ.get("OPENAI_API_KEY")
7
 
8
- def openai_chat(prompt, history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  if not prompt:
11
- return gr.update(value='', visible=len(history) < 10), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], history
12
-
13
- url = "https://api.openai.com/v1/chat/completions"
14
- headers = {
15
- "Content-Type": "application/json",
16
- "Authorization": f"Bearer {api_key}"
17
- }
18
- prompt_msg = {
19
- "role": "user",
20
- "content": prompt
21
- }
22
 
23
- data = {
24
- "model": "gpt-3.5-turbo",
25
- "messages": history + [prompt_msg]
26
- }
27
 
28
- response = requests.post(url, headers=headers, json=data)
29
- json_data = json.loads(response.text)
 
30
 
31
- response = json_data["choices"][0]["message"]
 
 
 
32
 
33
- history.append(prompt_msg)
34
- history.append(response)
 
 
 
 
 
 
 
 
 
35
 
36
- return gr.update(value='', visible=len(history) < 10), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], history
 
 
37
 
38
- def start_new_conversation(history):
39
- history = []
40
- return gr.update(value=None, visible=True), gr.update(value=[]), history
 
41
 
42
  css = """
43
- #col-container {max-width: 50%; margin-left: auto; margin-right: auto;}
44
  #chatbox {min-height: 400px;}
45
  #header {text-align: center;}
 
 
 
46
  """
47
 
48
  with gr.Blocks(css=css) as demo:
49
- history = gr.State([])
 
 
50
 
51
  with gr.Column(elem_id="col-container"):
52
- gr.Markdown("""## OpenAI Chatbot Demo
53
- Using the ofiicial API and GPT-3.5 Turbo model.
54
- Current limit is 5 messages per conversation.""",
 
55
  elem_id="header")
56
- chatbot = gr.Chatbot(elem_id="chatbox")
57
- input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
58
- btn_start_new_conversation = gr.Button("Start a new conversation")
59
-
60
- input_message.submit(openai_chat, [input_message, history], [input_message, chatbot, history])
61
- btn_start_new_conversation.click(start_new_conversation, [history], [input_message, chatbot, history])
62
-
63
- if __name__ == "__main__":
64
- demo.launch(debug=True, height='800px')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ def get_empty_state():
12
+ return {"total_tokens": 0, "messages": []}
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
 
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
  """
79
 
80
  with gr.Blocks(css=css) as demo:
81
+
82
+ state = gr.State(get_empty_state())
83
+
84
 
85
  with gr.Column(elem_id="col-container"):
86
+ gr.Markdown("""## OpenAI ChatGPT Demo
87
+ Using the ofiicial API (gpt-3.5-turbo model)<br>
88
+ Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).<br>
89
+ Current limit is 3000 tokens per conversation.""",
90
  elem_id="header")
91
+
92
+ with gr.Row():
93
+ with gr.Column():
94
+ chatbot = gr.Chatbot(elem_id="chatbox")
95
+ input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
96
+ total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
97
+ btn_clear_conversation = gr.Button("🔃 Start New Conversation")
98
+ with gr.Column():
99
+ prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
100
+ prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
101
+ 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")
102
+ user_token = gr.Textbox(placeholder="OpenAI API Key", type="password", show_label=False)
103
+ with gr.Accordion("Advanced parameters", open=False):
104
+ temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, interactive=True, label="Temperature (higher = more creative/chaotic)")
105
+ max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, interactive=True, label="Max tokens per response")
106
+
107
+ 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>
108
+ Don't forget to set your own <a href="https://platform.openai.com/account/api-keys">OpenAI API Key</a> environment variable in Settings.</center>''')
109
+
110
+ input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
111
+ btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
112
+ prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
113
+ user_token.change(on_token_change, inputs=[user_token], outputs=[])
114
+
115
+
116
+ demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template])
117
+
118
+
119
+ demo.launch(debug=True, height='800px')
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ openai