ILyaz03 anzorq commited on
Commit
1e2f609
0 Parent(s):

Duplicate from anzorq/chatgpt-demo

Browse files

Co-authored-by: AQ <[email protected]>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +138 -0
  4. requirements.txt +1 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Chatgpt Demo
3
+ emoji: 🐠
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.20.1
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: anzorq/chatgpt-demo
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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')
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ openai==0.27.0