abidlabs HF staff commited on
Commit
e23ea2d
1 Parent(s): 77cee2e

Upload 2 files

Browse files
Files changed (2) hide show
  1. app_template.py +74 -0
  2. maker.py +226 -0
app_template.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import requests
4
+
5
+ zephyr_7b_beta = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta/"
6
+
7
+ HF_TOKEN = os.getenv("HF_TOKEN")
8
+ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
9
+
10
+ def build_input_prompt(message, chatbot, system_prompt):
11
+ """
12
+ Constructs the input prompt string from the chatbot interactions and the current message.
13
+ """
14
+ input_prompt = "<|system|>\n" + system_prompt + "</s>\n<|user|>\n"
15
+ for interaction in chatbot:
16
+ input_prompt = input_prompt + str(interaction[0]) + "</s>\n<|assistant|>\n" + str(interaction[1]) + "\n</s>\n<|user|>\n"
17
+
18
+ input_prompt = input_prompt + str(message) + "</s>\n<|assistant|>"
19
+ return input_prompt
20
+
21
+
22
+ def post_request_beta(payload):
23
+ """
24
+ Sends a POST request to the predefined Zephyr-7b-Beta URL and returns the JSON response.
25
+ """
26
+ response = requests.post(zephyr_7b_beta, headers=HEADERS, json=payload)
27
+ response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
28
+ return response.json()
29
+
30
+
31
+ def predict_beta(message, chatbot=[], system_prompt=""):
32
+ input_prompt = build_input_prompt(message, chatbot, system_prompt)
33
+ data = {
34
+ "inputs": input_prompt
35
+ }
36
+
37
+ try:
38
+ response_data = post_request_beta(data)
39
+ json_obj = response_data[0]
40
+
41
+ if 'generated_text' in json_obj and len(json_obj['generated_text']) > 0:
42
+ bot_message = json_obj['generated_text']
43
+ return bot_message
44
+ elif 'error' in json_obj:
45
+ raise gr.Error(json_obj['error'] + ' Please refresh and try again with smaller input prompt')
46
+ else:
47
+ warning_msg = f"Unexpected response: {json_obj}"
48
+ raise gr.Error(warning_msg)
49
+ except requests.HTTPError as e:
50
+ error_msg = f"Request failed with status code {e.response.status_code}"
51
+ raise gr.Error(error_msg)
52
+ except json.JSONDecodeError as e:
53
+ error_msg = f"Failed to decode response as JSON: {str(e)}"
54
+ raise gr.Error(error_msg)
55
+
56
+ def test_preview_chatbot(message, history):
57
+ response = predict_beta(message, history, SYSTEM_PROMPT)
58
+ text_start = response.rfind("<|assistant|>", ) + len("<|assistant|>")
59
+ response = response[text_start:]
60
+ return response
61
+
62
+
63
+ welcome_preview_message = f"""
64
+ Welcome to **{TITLE}**! Say something like:
65
+
66
+ "{EXAMPLE_INPUT}"
67
+ """
68
+
69
+ chatbot_preview = gr.Chatbot(layout="panel", value=[(None, welcome_preview_message)])
70
+ textbox_preview = gr.Textbox(scale=7, container=False, value=EXAMPLE_INPUT)
71
+
72
+ demo = gr.ChatInterface(test_preview_chatbot, chatbot=chatbot_preview, textbox=textbox_preview)
73
+
74
+ demo.launch()
maker.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import huggingface_hub
5
+ from huggingface_hub import HfApi
6
+
7
+ HF_TOKEN = "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"
8
+ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
9
+
10
+ zephyr_7b_beta = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta/"
11
+
12
+
13
+ welcome_message = """
14
+ Hi! I'll help you **build a GPT**. You can say something like, "make a bot that gives advice on how to grow your startup."
15
+
16
+ What would you like to make?
17
+ """
18
+
19
+ welcome_preview_message = """
20
+ Welcome to **{}**! Say something like:
21
+
22
+ "{}"
23
+ """
24
+
25
+ # sample_response = """
26
+ # Certainly! Here we go:
27
+
28
+ # Title: Recipe Recommender
29
+ # System Prompt: Utilize your language model abilities to suggest delicious recipes based on user preferences such as ingredients, cuisine type, cooking time, etc. Ensure accuracy and variety while maintaining a conversational style with the user.
30
+ # Example User Input: Vegetarian dinner ideas under 30 minutes
31
+ # """
32
+
33
+ zephyr_system_prompt = """
34
+ You are an AI whose job it is to help users create their own chatbots. In particular, you need to respond succintly in a friendly tone, write a system prompt for an LLM, a catchy title for the chatbot, and a very short example user input. Make sure each part is included.
35
+
36
+ For example, if a user says, "make a bot that gives advice on how to grow your startup", first do a friendly response, then add the title, system prompt, and example user input. Immediately STOP after the example input. It should be EXACTLY in this format:
37
+
38
+ Sure, I'd be happy to help you build a bot! I'm generating a title, system prompt, and an example input. How do they sound? Feel free to give me feedback!
39
+ Title: Startup Coach
40
+ System prompt: Your job as an LLM is to provide good startup advice. Do not provide extraneous comments on other topics. Be succinct but useful.
41
+ Example input: Risks of setting up a non-profit board
42
+
43
+ Here's another example. If a user types, "Make a chatbot that roasts tech ceos", respond:
44
+ Sure, I'd be happy to help you build a bot! I'm generating a title, system prompt, and an example input. How do they sound? Feel free to give me feedback!
45
+ Title: Tech Roaster
46
+ System prompt: As an LLM, your primary function is to deliver hilarious and biting critiques of technology CEOs. Keep it witty and entertaining, but also make sure your jokes aren't too mean-spirited or factually incorrect.
47
+ Example input: Elon Musk
48
+ """
49
+
50
+ def build_input_prompt(message, chatbot, system_prompt):
51
+ """
52
+ Constructs the input prompt string from the chatbot interactions and the current message.
53
+ """
54
+ input_prompt = "<|system|>\n" + system_prompt + "</s>\n<|user|>\n"
55
+ for interaction in chatbot:
56
+ input_prompt = input_prompt + str(interaction[0]) + "</s>\n<|assistant|>\n" + str(interaction[1]) + "\n</s>\n<|user|>\n"
57
+
58
+ input_prompt = input_prompt + str(message) + "</s>\n<|assistant|>"
59
+ return input_prompt
60
+
61
+
62
+ def post_request_beta(payload):
63
+ """
64
+ Sends a POST request to the predefined Zephyr-7b-Beta URL and returns the JSON response.
65
+ """
66
+ response = requests.post(zephyr_7b_beta, headers=HEADERS, json=payload)
67
+ response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
68
+ return response.json()
69
+
70
+
71
+ def predict_beta(message, chatbot=[], system_prompt=zephyr_system_prompt):
72
+ input_prompt = build_input_prompt(message, chatbot, system_prompt)
73
+ data = {
74
+ "inputs": input_prompt
75
+ }
76
+
77
+ try:
78
+ response_data = post_request_beta(data)
79
+ json_obj = response_data[0]
80
+
81
+ if 'generated_text' in json_obj and len(json_obj['generated_text']) > 0:
82
+ bot_message = json_obj['generated_text']
83
+ return bot_message
84
+ elif 'error' in json_obj:
85
+ raise gr.Error(json_obj['error'] + ' Please refresh and try again with smaller input prompt')
86
+ else:
87
+ warning_msg = f"Unexpected response: {json_obj}"
88
+ raise gr.Error(warning_msg)
89
+ except requests.HTTPError as e:
90
+ error_msg = f"Request failed with status code {e.response.status_code}"
91
+ raise gr.Error(error_msg)
92
+ except json.JSONDecodeError as e:
93
+ error_msg = f"Failed to decode response as JSON: {str(e)}"
94
+ raise gr.Error(error_msg)
95
+
96
+
97
+ def extract_title_prompt_example(text, title, system_prompt, example_input):
98
+ try:
99
+ # Finding the indices of the key terms
100
+ text_start = text.rfind("<|assistant|>", ) + len("<|assistant|>")
101
+ text = text[text_start:]
102
+ except ValueError:
103
+ pass
104
+ try:
105
+ title_start = text.lower().rfind("title:") + len("title:")
106
+ prompt_start = text.lower().rfind("system prompt:")
107
+ title = text[title_start:prompt_start].strip()
108
+ except ValueError:
109
+ pass
110
+ try:
111
+ prompt_start = text.lower().rfind("system prompt:") + len("system prompt:")
112
+ example_start = text.lower().rfind("example input:")
113
+ system_prompt = text[prompt_start:example_start].strip()
114
+ except ValueError:
115
+ pass
116
+ try:
117
+ example_start = text.lower().rfind("example input:") + len("example input:")
118
+ example_input = text[example_start:].strip()
119
+ example_input = example_input[:example_input.index("\n")]
120
+ except ValueError:
121
+ pass
122
+ return text, title, system_prompt, example_input
123
+
124
+ def make_open_gpt(message, history, current_title, current_system_prompt, current_example_input):
125
+ response = predict_beta(message, history, zephyr_system_prompt)
126
+ response, title, system_prompt, example_input = extract_title_prompt_example(response, current_title, current_system_prompt, current_example_input)
127
+ return "", history + [(message, response)], title, system_prompt, example_input, [(None, welcome_preview_message.format(title, example_input))], example_input, gr.Column(visible=True), gr.Group(visible=True)
128
+
129
+ def set_title_example(title, example):
130
+ return [(None, welcome_preview_message.format(title, example))], example, gr.Column(visible=True), gr.Group(visible=True)
131
+
132
+ chatbot_preview = gr.Chatbot(layout="panel")
133
+ textbox_preview = gr.Textbox(scale=7, container=False)
134
+
135
+ def test_preview_chatbot(message, history, system_prompt):
136
+ response = predict_beta(message, history, system_prompt)
137
+ text_start = response.rfind("<|assistant|>", ) + len("<|assistant|>")
138
+ response = response[text_start:]
139
+ return response
140
+
141
+
142
+
143
+ constants = """
144
+ SYSTEM_PROMPT = "{}"
145
+ TITLE = "{}"
146
+ EXAMPLE_INPUT = "{}"
147
+ """
148
+
149
+
150
+ def publish(textbox_system_prompt, textbox_title, textbox_example, textbox_token):
151
+ source_file = 'app_template.py'
152
+ destination_file = 'app.py'
153
+ constants_formatted = constants.format(textbox_system_prompt, textbox_title, textbox_example)
154
+ with open(source_file, 'r') as file:
155
+ original_content = file.read()
156
+ with open(destination_file, 'w') as file:
157
+ file.write(constants_formatted + original_content)
158
+
159
+ api = HfApi(token=textbox_token)
160
+ new_space = api.create_repo(
161
+ repo_id=f"open-gpt-{textbox_title.lower().replace(' ', '-')}",
162
+ repo_type="space",
163
+ exist_ok=True,
164
+ private=False,
165
+ space_sdk="gradio",
166
+ token=textbox_token,
167
+ )
168
+ api.upload_file(
169
+ repo_id=new_space.repo_id,
170
+ path_or_fileobj='app.py',
171
+ path_in_repo='app.py',
172
+ token=textbox_token,
173
+ repo_type="space",
174
+ )
175
+ api.upload_file(
176
+ repo_id=new_space.repo_id,
177
+ path_or_fileobj='README.md',
178
+ path_in_repo='README.md',
179
+ token=textbox_token,
180
+ repo_type="space",
181
+ )
182
+ huggingface_hub.add_space_secret(
183
+ new_space.repo_id, "HF_TOKEN", textbox_token, token=textbox_token
184
+ )
185
+
186
+ return gr.Markdown(f"Published to https://huggingface.co/spaces/{new_space.repo_id} ✅", visible=True), gr.Button("Publish", interactive=True)
187
+
188
+
189
+ css = """
190
+ #preview-tab-button{
191
+ font-weight: bold;
192
+ }
193
+ """
194
+
195
+ with gr.Blocks(css=css) as demo:
196
+ gr.Markdown("🥧 **GPT Baker** lets you create your own **open-source GPTs**. Start chatting to automatically below to automatically bake your GPT (or you can manually configure the recipe in the second tab). You can build and test them for free, but will need a [HF Pro account](https://huggingface.co/subscribe/pro) to publish them on Spaces (as Open GPTs are powered by the Zephyr 7B beta model using the HF Inference API). You will **not be charged** for usage of your Open GPT as the HF Inference API Pro membership does not charge per-query. Find your token here: https://huggingface.co/settings/tokens")
197
+ with gr.Row():
198
+ with gr.Column(scale=3):
199
+ with gr.Tab("Create"):
200
+ chatbot_maker = gr.Chatbot([(None, welcome_message)], layout="panel", elem_id="chatbot-maker")
201
+ with gr.Group():
202
+ with gr.Row():
203
+ textbox_maker = gr.Textbox(placeholder="Make a bot that roasts tech CEOs", scale=7, container=False, autofocus=True)
204
+ submit_btn = gr.Button("Bake 👩‍🍳", variant="secondary")
205
+ with gr.Tab("Configure Recipe"):
206
+ textbox_title = gr.Textbox("GPT Preview", label="Title")
207
+ textbox_system_prompt = gr.Textbox(label="System prompt", lines=6)
208
+ textbox_example = gr.Textbox(label="Placeholder example", lines=2)
209
+ with gr.Tab("Files"):
210
+ gr.Markdown("RAG coming soon!")
211
+ with gr.Column(visible=False, scale=5) as preview_column:
212
+ with gr.Tab("🪄 Preview of your Open GPT", elem_id="preview-tab") as preview_tab:
213
+ gr.ChatInterface(test_preview_chatbot, chatbot=chatbot_preview, textbox=textbox_preview, autofocus=False, submit_btn="Test", additional_inputs=[textbox_system_prompt])
214
+ with gr.Group(visible=False) as publish_row:
215
+ with gr.Row():
216
+ textbox_token = gr.Textbox(show_label=False, placeholder="Ready to publish to Spaces? Enter your HF token here", scale=7)
217
+ publish_btn = gr.Button("Publish", variant="primary")
218
+
219
+ published_status = gr.Markdown(visible=False)
220
+
221
+ gr.on([submit_btn.click, textbox_maker.submit], make_open_gpt, [textbox_maker, chatbot_maker, textbox_title, textbox_system_prompt, textbox_example], [textbox_maker, chatbot_maker, textbox_title, textbox_system_prompt, textbox_example, chatbot_preview, textbox_preview, preview_column, publish_row])
222
+ gr.on([textbox_title.blur, textbox_example.blur], set_title_example, [textbox_title, textbox_example], [chatbot_preview, textbox_preview, preview_column, publish_row])
223
+
224
+ publish_btn.click(lambda : gr.Button("Publishing...", interactive=False), None, publish_btn).then(publish, [textbox_system_prompt, textbox_title, textbox_example, textbox_token], [published_status, publish_btn])
225
+
226
+ demo.launch()