Spaces:
Running
Running
Delete app.py
Browse files
app.py
DELETED
@@ -1,138 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import openai
|
3 |
-
import requests
|
4 |
-
import csv
|
5 |
-
|
6 |
-
|
7 |
-
prompt_templates = {"Default ChatGPT": ""}
|
8 |
-
|
9 |
-
def get_empty_state():
|
10 |
-
return {"total_tokens": 0, "messages": []}
|
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 |
-
|
48 |
-
system_prompt = []
|
49 |
-
if prompt_template:
|
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())
|
67 |
-
|
68 |
-
state['total_tokens'] += completion['usage']['total_tokens']
|
69 |
-
|
70 |
-
except Exception as e:
|
71 |
-
history.append(prompt_msg)
|
72 |
-
history.append({
|
73 |
-
"role": "system",
|
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 |
-
"""
|
95 |
-
|
96 |
-
with gr.Blocks(css=css) as demo:
|
97 |
-
|
98 |
-
state = gr.State(get_empty_state())
|
99 |
-
|
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():
|
108 |
-
with gr.Column():
|
109 |
-
chatbot = gr.Chatbot(elem_id="chatbox")
|
110 |
-
input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
|
111 |
-
btn_submit = gr.Button("Submit")
|
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')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|