acecalisto3 commited on
Commit
130e96a
·
verified ·
1 Parent(s): 25aca21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -106
app.py CHANGED
@@ -3,9 +3,6 @@ import gradio as gr
3
  import random
4
  import os
5
  import subprocess
6
- import threading
7
- import time
8
- import shutil
9
  from typing import Dict, Tuple, List
10
  import json
11
  from rich import print as rprint
@@ -43,28 +40,27 @@ agent_roles: Dict[str, Dict[str, bool]] = {
43
 
44
  # --- Initial Prompt ---
45
 
46
- selected_agent = list(agent_roles.keys())[0]
47
- initial_prompt = f"""
48
- You are an expert {selected_agent} who responds with complete program coding to client requests.
49
- Using available tools, please explain the researched information.
50
- Please don't answer based solely on what you already know. Always perform a search before providing a response.
51
- In special cases, such as when the user specifies a page to read, there's no need to search.
52
- Please read the provided page and answer the user's question accordingly.
53
- If you find that there's not much information just by looking at the search results page, consider these two options and try them out:
54
- - Try clicking on the links of the search results to access and read the content of each page.
55
  - Change your search query and perform a new search.
56
- Users are extremely busy and not as free as you are.
57
- Therefore, to save the user's effort, please provide direct answers.
58
  BAD ANSWER EXAMPLE
59
  - Please refer to these pages.
60
- - You can write code referring these pages.
61
- - Following page will be helpful.
62
  GOOD ANSWER EXAMPLE
63
  - This is the complete code: -- complete code here --
64
- - The answer of you question is -- answer here --
65
- Please make sure to list the URLs of the pages you referenced at the end of your answer. (This will allow users to verify your response.)
66
- Please make sure to answer in the language used by the user. If the user asks in Japanese, please answer in Japanese. If the user asks in Spanish, please answer in Spanish.
67
- But, you can go ahead and search in English, especially for programming-related questions. PLEASE MAKE SURE TO ALWAYS SEARCH IN ENGLISH FOR THOSE.
68
  """
69
 
70
  # --- Custom CSS ---
@@ -74,6 +70,16 @@ customCSS = """
74
  height: 1600px;
75
  flex-grow: 4;
76
  }
 
 
 
 
 
 
 
 
 
 
77
  """
78
 
79
  # --- Functions ---
@@ -86,9 +92,9 @@ def toggle_agent(agent_name: str) -> str:
86
  return f"{agent_name} is now {'active' if agent_roles[agent_name]['active'] else 'inactive'}"
87
 
88
  # Function to get the active agent cluster
89
- def get_agent_cluster() -> Dict[str, bool]:
90
- """Returns a dictionary of active agents."""
91
- return {agent: agent_roles[agent]["active"] for agent in agent_roles}
92
 
93
  # Function to execute code
94
  def run_code(code: str) -> str:
@@ -106,29 +112,7 @@ def run_code(code: str) -> str:
106
  # Function to format the prompt
107
  def format_prompt(message: str, history: list[Tuple[str, str]], agent_roles: list[str]) -> str:
108
  """Formats the prompt with the selected agent roles and conversation history."""
109
- prompt = f"""
110
- You are an expert agent cluster, consisting of {', '.join(agent_roles)}.
111
- Respond with complete program coding to client requests.
112
- Using available tools, please explain the researched information.
113
- Please don't answer based solely on what you already know. Always perform a search before providing a response.
114
- In special cases, such as when the user specifies a page to read, there's no need to search.
115
- Please read the provided page and answer the user's question accordingly.
116
- If you find that there's not much information just by looking at the search results page, consider these two options and try them out:
117
- - Try clicking on the links of the search results to access and read the content of each page.
118
- - Change your search query and perform a new search.
119
- Users are extremely busy and not as free as you are.
120
- Therefore, to save the user's effort, please provide direct answers.
121
- BAD ANSWER EXAMPLE
122
- - Please refer to these pages.
123
- - You can write code referring these pages.
124
- - Following page will be helpful.
125
- GOOD ANSWER EXAMPLE
126
- - This is the complete code: -- complete code here --
127
- - The answer of you question is -- answer here --
128
- Please make sure to list the URLs of the pages you referenced at the end of your answer. (This will allow users to verify your response.)
129
- Please make sure to answer in the language used by the user. If the user asks in Japanese, please answer in Japanese. If the user asks in Spanish, please answer in Spanish.
130
- But, you can go ahead and search in English, especially for programming-related questions. PLEASE MAKE SURE TO ALWAYS SEARCH IN ENGLISH FOR THOSE.
131
- """
132
 
133
  for user_prompt, bot_response in history:
134
  prompt += f"[INST] {user_prompt} [/INST]"
@@ -165,7 +149,7 @@ def generate(prompt: str, history: list[Tuple[str, str]], agent_roles: list[str]
165
  return output
166
 
167
  # Function to handle user input and generate responses
168
- def chat_interface(message: str, history: list[Tuple[str, str]], agent_cluster: Dict[str, bool], temperature: float, max_new_tokens: int, top_p: float, repetition_penalty: float) -> Tuple[str, str]:
169
  """Handles user input and generates responses."""
170
  if message.startswith("python"):
171
  # User entered code, execute it
@@ -174,7 +158,7 @@ def chat_interface(message: str, history: list[Tuple[str, str]], agent_cluster:
174
  return (message, output)
175
  else:
176
  # User entered a normal message, generate a response
177
- active_agents = [agent for agent, is_active in agent_cluster.items() if is_active]
178
  response = generate(message, history, active_agents, temperature, max_new_tokens, top_p, repetition_penalty)
179
  return (message, response)
180
 
@@ -190,17 +174,14 @@ def create_web_app(app_name: str, code: str) -> None:
190
 
191
  # Create the requirements.txt file
192
  with open(os.path.join(app_name, 'requirements.txt'), 'w') as f:
193
- f.write("gradio\nhuggingface_hub")
194
 
195
  # Print a success message
196
  print(f"Web app '{app_name}' created successfully!")
197
 
198
  # Function to handle the "Create Web App" button click
199
- def create_web_app_button_click(code: str) -> str:
200
  """Handles the "Create Web App" button click."""
201
- # Get the app name from the user
202
- app_name = gr.Textbox.get().strip()
203
-
204
  # Validate the app name
205
  if not app_name:
206
  return "Please enter a valid app name."
@@ -214,9 +195,6 @@ def create_web_app_button_click(code: str) -> str:
214
  # Function to handle the "Deploy" button click
215
  def deploy_button_click(app_name: str, code: str) -> str:
216
  """Handles the "Deploy" button click."""
217
- # Get the app name from the user
218
- app_name = gr.Textbox.get().strip()
219
-
220
  # Validate the app name
221
  if not app_name:
222
  return "Please enter a valid app name."
@@ -230,9 +208,6 @@ def deploy_button_click(app_name: str, code: str) -> str:
230
  # Function to handle the "Local Host" button click
231
  def local_host_button_click(app_name: str, code: str) -> str:
232
  """Handles the "Local Host" button click."""
233
- # Get the app name from the user
234
- app_name = gr.Textbox.get().strip()
235
-
236
  # Validate the app name
237
  if not app_name:
238
  return "Please enter a valid app name."
@@ -247,9 +222,6 @@ def local_host_button_click(app_name: str, code: str) -> str:
247
  # Function to handle the "Ship" button click
248
  def ship_button_click(app_name: str, code: str) -> str:
249
  """Handles the "Ship" button click."""
250
- # Get the app name from the user
251
- app_name = gr.Textbox.get().strip()
252
-
253
  # Validate the app name
254
  if not app_name:
255
  return "Please enter a valid app name."
@@ -262,9 +234,17 @@ def ship_button_click(app_name: str, code: str) -> str:
262
 
263
  # --- Gradio Interface ---
264
 
265
- with gr.Blocks(theme='ParityError/Interstellar') as demo:
 
 
 
 
 
 
 
266
  # --- Agent Selection ---
267
  with gr.Row():
 
268
  for agent_name, agent_data in agent_roles.items():
269
  button = gr.Button(agent_name, variant="secondary")
270
  textbox = gr.Textbox(agent_data["description"], interactive=False)
@@ -272,47 +252,48 @@ with gr.Blocks(theme='ParityError/Interstellar') as demo:
272
 
273
  # --- Chat Interface ---
274
  with gr.Row():
 
275
  chatbot = gr.Chatbot()
276
  chat_interface_input = gr.Textbox(label="Enter your message", placeholder="Ask me anything!")
277
- chat_interface_output = gr.Textbox(label="Response", interactive=False)
278
 
279
  # Parameters
280
- temperature_slider = gr.Slider(
281
- label="Temperature",
282
- value=DEFAULT_TEMPERATURE,
283
- minimum=0.0,
284
- maximum=1.0,
285
- step=0.05,
286
- interactive=True,
287
- info="Higher values generate more diverse outputs",
288
- )
289
- max_new_tokens_slider = gr.Slider(
290
- label="Maximum New Tokens",
291
- value=DEFAULT_MAX_NEW_TOKENS,
292
- minimum=64,
293
- maximum=4096,
294
- step=64,
295
- interactive=True,
296
- info="The maximum number of new tokens",
297
- )
298
- top_p_slider = gr.Slider(
299
- label="Top-p (Nucleus Sampling)",
300
- value=DEFAULT_TOP_P,
301
- minimum=0.0,
302
- maximum=1,
303
- step=0.05,
304
- interactive=True,
305
- info="Higher values sample more low-probability tokens",
306
- )
307
- repetition_penalty_slider = gr.Slider(
308
- label="Repetition Penalty",
309
- value=DEFAULT_REPETITION_PENALTY,
310
- minimum=1.0,
311
- maximum=2.0,
312
- step=0.05,
313
- interactive=True,
314
- info="Penalize repeated tokens",
315
- )
 
316
 
317
  # Submit Button
318
  submit_button = gr.Button("Submit")
@@ -323,7 +304,6 @@ with gr.Blocks(theme='ParityError/Interstellar') as demo:
323
  inputs=[
324
  chat_interface_input,
325
  chatbot,
326
- get_agent_cluster,
327
  temperature_slider,
328
  max_new_tokens_slider,
329
  top_p_slider,
@@ -331,12 +311,12 @@ with gr.Blocks(theme='ParityError/Interstellar') as demo:
331
  ],
332
  outputs=[
333
  chatbot,
334
- chat_interface_output,
335
  ],
336
  )
337
 
338
  # --- Web App Creation ---
339
  with gr.Row():
 
340
  app_name_input = gr.Textbox(label="App Name", placeholder="Enter your app name")
341
  code_output = gr.Textbox(label="Code", interactive=False)
342
  create_web_app_button = gr.Button("Create Web App")
@@ -347,7 +327,7 @@ with gr.Blocks(theme='ParityError/Interstellar') as demo:
347
  # Web App Creation Logic
348
  create_web_app_button.click(
349
  create_web_app_button_click,
350
- inputs=[code_output],
351
  outputs=[gr.Textbox(label="Status", interactive=False)],
352
  )
353
 
@@ -373,9 +353,9 @@ with gr.Blocks(theme='ParityError/Interstellar') as demo:
373
  )
374
 
375
  # --- Connect Chat Output to Code Output ---
376
- chat_interface_output.change(
377
- lambda x: x,
378
- inputs=[chat_interface_output],
379
  outputs=[code_output],
380
  )
381
 
 
3
  import random
4
  import os
5
  import subprocess
 
 
 
6
  from typing import Dict, Tuple, List
7
  import json
8
  from rich import print as rprint
 
40
 
41
  # --- Initial Prompt ---
42
 
43
+ initial_prompt = """
44
+ You are an expert agent cluster, consisting of a Web Developer, a Prompt Engineer, a Python Code Developer, a Hugging Face Hub Expert, and an AI-Powered Code Assistant.
45
+ Respond with complete program coding to client requests.
46
+ Use your combined expertise to research information and explain it clearly.
47
+ Don't answer solely based on what you already know. Always perform a search before providing a response.
48
+ In special cases, like when the user specifies a page to read, there's no need to search.
49
+ Read the provided page and answer the user's question accordingly.
50
+ If you find limited information from search results, try these options:
51
+ - Click on the links of the search results to access and read the content of each page.
52
  - Change your search query and perform a new search.
53
+ Users are busy, so provide direct answers.
 
54
  BAD ANSWER EXAMPLE
55
  - Please refer to these pages.
56
+ - You can write code referring to these pages.
57
+ - The following page will be helpful.
58
  GOOD ANSWER EXAMPLE
59
  - This is the complete code: -- complete code here --
60
+ - The answer to your question is -- answer here --
61
+ List the URLs of the pages you referenced at the end of your answer for verification.
62
+ Answer in the language used by the user. If the user asks in Japanese, answer in Japanese. If the user asks in Spanish, answer in Spanish.
63
+ Search in English, especially for programming-related questions. ALWAYS SEARCH IN ENGLISH FOR THOSE.
64
  """
65
 
66
  # --- Custom CSS ---
 
70
  height: 1600px;
71
  flex-grow: 4;
72
  }
73
+ .gradio-container {
74
+ display: flex;
75
+ flex-direction: column;
76
+ height: 100vh;
77
+ }
78
+ .gradio-interface {
79
+ flex-grow: 1;
80
+ display: flex;
81
+ flex-direction: column;
82
+ }
83
  """
84
 
85
  # --- Functions ---
 
92
  return f"{agent_name} is now {'active' if agent_roles[agent_name]['active'] else 'inactive'}"
93
 
94
  # Function to get the active agent cluster
95
+ def get_active_agents() -> List[str]:
96
+ """Returns a list of active agents."""
97
+ return [agent for agent, is_active in agent_roles.items() if is_active]
98
 
99
  # Function to execute code
100
  def run_code(code: str) -> str:
 
112
  # Function to format the prompt
113
  def format_prompt(message: str, history: list[Tuple[str, str]], agent_roles: list[str]) -> str:
114
  """Formats the prompt with the selected agent roles and conversation history."""
115
+ prompt = initial_prompt # Use the global initial prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  for user_prompt, bot_response in history:
118
  prompt += f"[INST] {user_prompt} [/INST]"
 
149
  return output
150
 
151
  # Function to handle user input and generate responses
152
+ def chat_interface(message: str, history: list[Tuple[str, str]], temperature: float, max_new_tokens: int, top_p: float, repetition_penalty: float) -> Tuple[str, str]:
153
  """Handles user input and generates responses."""
154
  if message.startswith("python"):
155
  # User entered code, execute it
 
158
  return (message, output)
159
  else:
160
  # User entered a normal message, generate a response
161
+ active_agents = get_active_agents()
162
  response = generate(message, history, active_agents, temperature, max_new_tokens, top_p, repetition_penalty)
163
  return (message, response)
164
 
 
174
 
175
  # Create the requirements.txt file
176
  with open(os.path.join(app_name, 'requirements.txt'), 'w') as f:
177
+ f.write("gradio\nhuggingface_hub\nrich")
178
 
179
  # Print a success message
180
  print(f"Web app '{app_name}' created successfully!")
181
 
182
  # Function to handle the "Create Web App" button click
183
+ def create_web_app_button_click(app_name: str, code: str) -> str:
184
  """Handles the "Create Web App" button click."""
 
 
 
185
  # Validate the app name
186
  if not app_name:
187
  return "Please enter a valid app name."
 
195
  # Function to handle the "Deploy" button click
196
  def deploy_button_click(app_name: str, code: str) -> str:
197
  """Handles the "Deploy" button click."""
 
 
 
198
  # Validate the app name
199
  if not app_name:
200
  return "Please enter a valid app name."
 
208
  # Function to handle the "Local Host" button click
209
  def local_host_button_click(app_name: str, code: str) -> str:
210
  """Handles the "Local Host" button click."""
 
 
 
211
  # Validate the app name
212
  if not app_name:
213
  return "Please enter a valid app name."
 
222
  # Function to handle the "Ship" button click
223
  def ship_button_click(app_name: str, code: str) -> str:
224
  """Handles the "Ship" button click."""
 
 
 
225
  # Validate the app name
226
  if not app_name:
227
  return "Please enter a valid app name."
 
234
 
235
  # --- Gradio Interface ---
236
 
237
+ with gr.Blocks(css=customCSS, theme='ParityError/Interstellar') as demo:
238
+ gr.Markdown(
239
+ """
240
+ # AI-Powered Code Generation and Web App Creation
241
+ This application allows you to interact with an AI agent cluster to generate code and create web apps.
242
+ """
243
+ )
244
+
245
  # --- Agent Selection ---
246
  with gr.Row():
247
+ gr.Markdown("## Select Your Agent Cluster")
248
  for agent_name, agent_data in agent_roles.items():
249
  button = gr.Button(agent_name, variant="secondary")
250
  textbox = gr.Textbox(agent_data["description"], interactive=False)
 
252
 
253
  # --- Chat Interface ---
254
  with gr.Row():
255
+ gr.Markdown("## Chat with the AI")
256
  chatbot = gr.Chatbot()
257
  chat_interface_input = gr.Textbox(label="Enter your message", placeholder="Ask me anything!")
 
258
 
259
  # Parameters
260
+ with gr.Accordion("Advanced Parameters", open=False):
261
+ temperature_slider = gr.Slider(
262
+ label="Temperature",
263
+ value=DEFAULT_TEMPERATURE,
264
+ minimum=0.0,
265
+ maximum=1.0,
266
+ step=0.05,
267
+ interactive=True,
268
+ info="Higher values generate more diverse outputs",
269
+ )
270
+ max_new_tokens_slider = gr.Slider(
271
+ label="Maximum New Tokens",
272
+ value=DEFAULT_MAX_NEW_TOKENS,
273
+ minimum=64,
274
+ maximum=4096,
275
+ step=64,
276
+ interactive=True,
277
+ info="The maximum number of new tokens",
278
+ )
279
+ top_p_slider = gr.Slider(
280
+ label="Top-p (Nucleus Sampling)",
281
+ value=DEFAULT_TOP_P,
282
+ minimum=0.0,
283
+ maximum=1,
284
+ step=0.05,
285
+ interactive=True,
286
+ info="Higher values sample more low-probability tokens",
287
+ )
288
+ repetition_penalty_slider = gr.Slider(
289
+ label="Repetition Penalty",
290
+ value=DEFAULT_REPETITION_PENALTY,
291
+ minimum=1.0,
292
+ maximum=2.0,
293
+ step=0.05,
294
+ interactive=True,
295
+ info="Penalize repeated tokens",
296
+ )
297
 
298
  # Submit Button
299
  submit_button = gr.Button("Submit")
 
304
  inputs=[
305
  chat_interface_input,
306
  chatbot,
 
307
  temperature_slider,
308
  max_new_tokens_slider,
309
  top_p_slider,
 
311
  ],
312
  outputs=[
313
  chatbot,
 
314
  ],
315
  )
316
 
317
  # --- Web App Creation ---
318
  with gr.Row():
319
+ gr.Markdown("## Create Your Web App")
320
  app_name_input = gr.Textbox(label="App Name", placeholder="Enter your app name")
321
  code_output = gr.Textbox(label="Code", interactive=False)
322
  create_web_app_button = gr.Button("Create Web App")
 
327
  # Web App Creation Logic
328
  create_web_app_button.click(
329
  create_web_app_button_click,
330
+ inputs=[app_name_input, code_output],
331
  outputs=[gr.Textbox(label="Status", interactive=False)],
332
  )
333
 
 
353
  )
354
 
355
  # --- Connect Chat Output to Code Output ---
356
+ chatbot.change(
357
+ lambda x: x[-1][1] if x else "",
358
+ inputs=[chatbot],
359
  outputs=[code_output],
360
  )
361