acecalisto3 commited on
Commit
c5758aa
1 Parent(s): ee50d4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -360
app.py CHANGED
@@ -1,367 +1,222 @@
1
- from huggingface_hub import InferenceClient
2
- import gradio as gr
3
- import random
4
- import os
5
- import subprocess
6
- from typing import Dict, Tuple, List
7
- import dotenv
8
- import json
9
- from rich import print as rprint
10
- from rich.panel import Panel
11
- from rich.progress import track
12
- from rich.table import Table
13
- from rich.prompt import Prompt, Confirm
14
- from rich.markdown import Markdown
15
- from rich.traceback import install
16
- install() # Enable rich tracebacks for easier debugging
17
-
18
- from huggingface_hub import RepositoryInfo
19
-
20
- model_info = RepositoryInfo.fetch('huggingface/models/{}/{}'.format(" Meta-Llama-3.1-8B ", MODEL_NAME))
21
- client = InferenceClient(model_info, token=os.environ.get("HF_TOKEN"))
22
-
23
- # Chat Interface Parameters
24
- DEFAULT_TEMPERATURE = 0.9
25
- DEFAULT_MAX_NEW_TOKENS = 2048
26
- DEFAULT_TOP_P = 0.95
27
- DEFAULT_REPETITION_PENALTY = 1.2
28
-
29
- # Local Server
30
- LOCAL_HOST_PORT = 7860
31
-
32
- # --- Agent Roles ---
33
-
34
- agent_roles: Dict[str, Dict[str, bool]] = {
35
- "Web Developer": {"description": "A master of front-end and back-end web development.", "active": False},
36
- "Prompt Engineer": {"description": "An expert in crafting effective prompts for AI models.", "active": False},
37
- "Python Code Developer": {"description": "A skilled Python programmer who can write clean and efficient code.", "active": False},
38
- "Hugging Face Hub Expert": {"description": "A specialist in navigating and utilizing the Hugging Face Hub.", "active": False},
39
- "AI-Powered Code Assistant": {"description": "An AI assistant that can help with coding tasks and provide code snippets.", "active": False},
40
- }
41
-
42
- # --- Initial Prompt ---
43
-
44
- initial_prompt = """
45
- 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.
46
- Respond with complete program coding to client requests.
47
- Use your combined expertise to research information and explain it clearly.
48
- Don't answer solely based on what you already know. Always perform a search before providing a response.
49
- In special cases, like when the user specifies a page to read, there's no need to search.
50
- Read the provided page and answer the user's question accordingly.
51
- If you find limited information from search results, try these options:
52
- - Click on the links of the search results to access and read the content of each page.
53
- - Change your search query and perform a new search.
54
- Users are busy, so provide direct answers.
55
- BAD ANSWER EXAMPLE
56
- - Please refer to these pages.
57
- - You can write code referring to these pages.
58
- - The following page will be helpful.
59
- GOOD ANSWER EXAMPLE
60
- - This is the complete code: -- complete code here --
61
- - The answer to your question is -- answer here --
62
- List the URLs of the pages you referenced at the end of your answer for verification.
63
- 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.
64
- Search in English, especially for programming-related questions. ALWAYS SEARCH IN ENGLISH FOR THOSE.
65
- """
66
-
67
- # --- Custom CSS ---
68
-
69
- customCSS = """
70
- #component-7 {
71
- height: 1600px;
72
- flex-grow: 4;
73
- }
74
- .gradio-container {
75
- display: flex;
76
- flex-direction: column;
77
- height: 100vh;
78
- }
79
- .gradio-interface {
80
- flex-grow: 1;
81
- display: flex;
82
- flex-direction: column;
83
- }
84
- """
85
-
86
- # --- Functions ---
87
-
88
- # Function to toggle the active state of an agent
89
- def toggle_agent(agent_name: str) -> str:
90
- """Toggles the active state of an agent."""
91
- global agent_roles
92
- agent_roles[agent_name]["active"] = not agent_roles[agent_name]["active"]
93
- return f"{agent_name} is now {'active' if agent_roles[agent_name]['active'] else 'inactive'}"
94
-
95
- # Function to get the active agent cluster
96
- def get_active_agents() -> List[str]:
97
- """Returns a list of active agents."""
98
- return [agent for agent, is_active in agent_roles.items() if is_active]
99
-
100
- # Function to execute code
101
- def run_code(code: str) -> str:
102
- """Executes the provided code and returns the output."""
103
- try:
104
- output = subprocess.check_output(
105
- ['python', '-c', code],
106
- stderr=subprocess.STDOUT,
107
- universal_newlines=True,
108
- )
109
- return output
110
- except subprocess.CalledProcessError as e:
111
- return f"Error: {e.output}"
112
-
113
- # Function to format the prompt
114
- def format_prompt(message: str, history: list[Tuple[str, str]], agent_roles: list[str]) -> str:
115
- """Formats the prompt with the selected agent roles and conversation history."""
116
- prompt = initial_prompt # Use the global initial prompt
117
-
118
- for user_prompt, bot_response in history:
119
- prompt += f"[INST] {user_prompt} [/INST]"
120
- prompt += f" {bot_response}</s> "
121
-
122
- prompt += f"[INST] {message} [/INST]"
123
- return prompt
124
-
125
- # Function to generate a response
126
- def generate(prompt: str, history: list[Tuple[str, str]], agent_roles: list[str], temperature: float = DEFAULT_TEMPERATURE, max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS, top_p: float = DEFAULT_TOP_P, repetition_penalty: float = DEFAULT_REPETITION_PENALTY) -> str:
127
- """Generates a response using the selected agent roles and parameters."""
128
- temperature = float(temperature)
129
- if temperature < 1e-2:
130
- temperature = 1e-2
131
- top_p = float(top_p)
132
-
133
- generate_kwargs = dict(
134
- temperature=temperature,
135
- max_new_tokens=max_new_tokens,
136
- top_p=top_p,
137
- repetition_penalty=repetition_penalty,
138
- do_sample=True,
139
- seed=random.randint(0, 10**7),
140
- )
141
-
142
- formatted_prompt = format_prompt(prompt, history, agent_roles)
143
-
144
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
145
- output = ""
146
-
147
- for response in stream:
148
- output += response.token.text
149
- yield output
150
- return output
151
-
152
- # Function to handle user input and generate responses
153
- 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]:
154
- """Handles user input and generates responses."""
155
- if message.startswith("python"):
156
- # User entered code, execute it
157
- code = message[9:-3]
158
- output = run_code(code)
159
- return (message, output)
160
- else:
161
- # User entered a normal message, generate a response
162
- active_agents = get_active_agents()
163
- response = generate(message, history, active_agents, temperature, max_new_tokens, top_p, repetition_penalty)
164
- return (message, response)
165
-
166
- # Function to create a new web app instance
167
- def create_web_app(app_name: str, code: str) -> None:
168
- """Creates a new web app instance with the given name and code."""
169
- # Create a new directory for the app
170
- os.makedirs(app_name, exist_ok=True)
171
-
172
- # Create the app.py file
173
- with open(os.path.join(app_name, 'app.py'), 'w') as f:
174
- f.write(code)
175
-
176
- # Create the requirements.txt file
177
- with open(os.path.join(app_name, 'requirements.txt'), 'w') as f:
178
- f.write("gradio\nhuggingface_hub\nrich")
179
-
180
- # Print a success message
181
- print(f"Web app '{app_name}' created successfully!")
182
-
183
- # Function to handle the "Create Web App" button click
184
- def create_web_app_button_click(app_name: str, code: str) -> str:
185
- """Handles the "Create Web App" button click."""
186
- # Validate the app name
187
- if not app_name:
188
- return "Please enter a valid app name."
189
-
190
- # Create the web app instance
191
- create_web_app(app_name, code)
192
-
193
- # Return a success message
194
- return f"Web app '{app_name}' created successfully!"
195
-
196
- # Function to handle the "Deploy" button click
197
- def deploy_button_click(app_name: str, code: str) -> str:
198
- """Handles the "Deploy" button click."""
199
- # Validate the app name
200
- if not app_name:
201
- return "Please enter a valid app name."
202
-
203
- # Deploy the web app instance
204
- # ... (Implement deployment logic here)
205
-
206
- # Return a success message
207
- return f"Web app '{app_name}' deployed successfully!"
208
-
209
- # Function to handle the "Local Host" button click
210
- def local_host_button_click(app_name: str, code: str) -> str:
211
- """Handles the "Local Host" button click."""
212
- # Validate the app name
213
- if not app_name:
214
- return "Please enter a valid app name."
215
-
216
- # Start the local server
217
- os.chdir(app_name)
218
- subprocess.Popen(['gradio', 'run', 'app.py', '--share', '--server_port', str(LOCAL_HOST_PORT)])
219
-
220
- # Return a success message
221
- return f"Web app '{app_name}' running locally on port {LOCAL_HOST_PORT}!"
222
-
223
- # Function to handle the "Ship" button click
224
- def ship_button_click(app_name: str, code: str) -> str:
225
- """Handles the "Ship" button click."""
226
- # Validate the app name
227
- if not app_name:
228
- return "Please enter a valid app name."
229
-
230
- # Ship the web app instance
231
- # ... (Implement shipping logic here)
232
-
233
- # Return a success message
234
- return f"Web app '{app_name}' shipped successfully!"
235
-
236
- # --- Gradio Interface ---
237
-
238
- with gr.Blocks(css=customCSS, theme='ParityError/Interstellar') as demo:
239
- gr.Markdown(
240
- """
241
- # AI-Powered Code Generation and Web App Creation
242
- This application allows you to interact with an AI agent cluster to generate code and create web apps.
243
- """
244
- )
245
-
246
- # --- Agent Selection ---
247
- with gr.Row():
248
- gr.Markdown("## Select Your Agent Cluster")
249
- for agent_name, agent_data in agent_roles.items():
250
- button = gr.Button(agent_name, variant="secondary")
251
- textbox = gr.Textbox(agent_data["description"], interactive=False)
252
- button.click(toggle_agent, inputs=[button], outputs=[textbox])
253
-
254
- # --- Chat Interface ---
255
- with gr.Row():
256
- gr.Markdown("## Chat with the AI")
257
- chatbot = gr.Chatbot()
258
- chat_interface_input = gr.Textbox(label="Enter your message", placeholder="Ask me anything!")
259
-
260
- # Parameters
261
- with gr.Accordion("Advanced Parameters", open=False):
262
- temperature_slider = gr.Slider(
263
- label="Temperature",
264
- value=DEFAULT_TEMPERATURE,
265
- minimum=0.0,
266
- maximum=1.0,
267
- step=0.05,
268
- interactive=True,
269
- info="Higher values generate more diverse outputs",
270
- )
271
- max_new_tokens_slider = gr.Slider(
272
- label="Maximum New Tokens",
273
- value=DEFAULT_MAX_NEW_TOKENS,
274
- minimum=64,
275
- maximum=4096,
276
- step=64,
277
- interactive=True,
278
- info="The maximum number of new tokens",
279
- )
280
- top_p_slider = gr.Slider(
281
- label="Top-p (Nucleus Sampling)",
282
- value=DEFAULT_TOP_P,
283
- minimum=0.0,
284
- maximum=1,
285
- step=0.05,
286
- interactive=True,
287
- info="Higher values sample more low-probability tokens",
288
- )
289
- repetition_penalty_slider = gr.Slider(
290
- label="Repetition Penalty",
291
- value=DEFAULT_REPETITION_PENALTY,
292
- minimum=1.0,
293
- maximum=2.0,
294
- step=0.05,
295
- interactive=True,
296
- info="Penalize repeated tokens",
297
- )
298
-
299
- # Submit Button
300
- submit_button = gr.Button("Submit")
301
-
302
- # Chat Interface Logic
303
- submit_button.click(
304
- chat_interface,
305
- inputs=[
306
- chat_interface_input,
307
- chatbot,
308
- temperature_slider,
309
- max_new_tokens_slider,
310
- top_p_slider,
311
- repetition_penalty_slider,
312
- ],
313
- outputs=[
314
- chatbot,
315
- ],
316
  )
317
 
318
- # --- Web App Creation ---
319
- with gr.Row():
320
- gr.Markdown("## Create Your Web App")
321
- app_name_input = gr.Textbox(label="App Name", placeholder="Enter your app name")
322
- code_output = gr.Textbox(label="Code", interactive=False)
323
- create_web_app_button = gr.Button("Create Web App")
324
- deploy_button = gr.Button("Deploy")
325
- local_host_button = gr.Button("Local Host")
326
- ship_button = gr.Button("Ship")
327
-
328
- # Web App Creation Logic
329
- create_web_app_button.click(
330
- create_web_app_button_click,
331
- inputs=[app_name_input, code_output],
332
- outputs=[gr.Textbox(label="Status", interactive=False)],
333
- )
334
-
335
- # Deploy the web app
336
- deploy_button.click(
337
- deploy_button_click,
338
- inputs=[app_name_input, code_output],
339
- outputs=[gr.Textbox(label="Status", interactive=False)],
340
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
 
342
- # Local host the web app
343
- local_host_button.click(
344
- local_host_button_click,
345
- inputs=[app_name_input, code_output],
346
- outputs=[gr.Textbox(label="Status", interactive=False)],
347
- )
348
 
349
- # Ship the web app
350
- ship_button.click(
351
- ship_button_click,
352
- inputs=[app_name_input, code_output],
353
- outputs=[gr.Textbox(label="Status", interactive=False)],
354
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
- # --- Connect Chat Output to Code Output ---
357
- chatbot.change(
358
- lambda x: x[-1][1] if x else "",
359
- inputs=[chatbot],
360
- outputs=[code_output],
361
- )
362
 
363
- # --- Initialize Hugging Face Client ---
364
- client = InferenceClient(repo_id="MODEL_NAME", token=os.environ.get("HF_TOKEN"))
 
365
 
366
- # --- Launch Gradio ---
367
- demo.queue().launch(debug=True)
 
1
+ import asyncio
2
+ import logging
3
+ from typing import Dict, Any
4
+ from functools import partial
5
+
6
+ from flask import Flask, request, jsonify
7
+ from langchain import PromptTemplate, LLMChain
8
+ from langchain.llms import OpenAI
9
+ from langchain.chains import ConversationChain
10
+ from langchain.memory import ConversationBufferMemory
11
+ from langchain.vectorstores import Chroma
12
+ from langchain.embeddings import OpenAIEmbeddings
13
+ from langchain.document_loaders import TextLoader
14
+
15
+ logging.basicConfig(level=logging.INFO)
16
+
17
+ # Define core component classes
18
+ class Task:
19
+ def __init__(self, task_name: str, input_data: Any, agent_name: str):
20
+ self.task_name = task_name
21
+ self.input_data = input_data
22
+ self.agent_name = agent_name
23
+
24
+ class ModelManager:
25
+ def __init__(self):
26
+ self.model = None
27
+
28
+ async def start(self):
29
+ logging.info("Starting model.")
30
+ await asyncio.sleep(1) # Simulate loading time
31
+
32
+ async def stop(self):
33
+ logging.info("Unloading model.")
34
+
35
+ class CodeArchitect:
36
+ def __init__(self, model_manager: ModelManager, model=None):
37
+ self.model_manager = model_manager
38
+ self.generator = model if model else pipeline("text-generation", model="gpt2")
39
+
40
+ async def start(self):
41
+ await self.model_manager.start()
42
+
43
+ async def stop(self):
44
+ await self.model_manager.stop()
45
+
46
+ async def generate_code(self, text_input: str) -> str:
47
+ response = self.generator(text_input, max_length=5000, num_return_sequences=1)[0]['generated_text']
48
+ return response
49
+
50
+ class UIUXWizard:
51
+ def __init__(self, model_manager: ModelManager, vector_store=None):
52
+ self.model_manager = model_manager
53
+ self.vector_store = vector_store
54
+ self.conversation_chain = ConversationChain(
55
+ llm=OpenAI(temperature=0.7),
56
+ memory=ConversationBufferMemory(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  )
58
 
59
+ async def start(self):
60
+ await self.model_manager.start()
61
+
62
+ async def stop(self):
63
+ await self.model_manager.stop()
64
+
65
+ def get_memory_response(self, query):
66
+ if self.vector_store is None:
67
+ return "No memory available."
68
+ else:
69
+ results = self.vector_store.similarity_search(query, k=3)
70
+ return "\n".join(results)
71
+
72
+ def get_conversation_response(self, query):
73
+ return self.conversation_chain.run(query)
74
+
75
+ # Define VersionControl class
76
+ class VersionControl:
77
+ def __init__(self, system_name: str):
78
+ self.system_name = system_name
79
+
80
+ async def start(self):
81
+ logging.info(f"Starting version control system: {self.system_name}")
82
+ await asyncio.sleep(1) # Simulate initialization time
83
+
84
+ async def stop(self):
85
+ logging.info(f"Stopping version control system: {self.system_name}")
86
+
87
+ # Define Documentation class
88
+ class Documentation:
89
+ def __init__(self, system_name: str):
90
+ self.system_name = system_name
91
+
92
+ async def start(self):
93
+ logging.info(f"Starting documentation system: {self.system_name}")
94
+ await asyncio.sleep(1) # Simulate initialization time
95
+
96
+ async def stop(self):
97
+ logging.info(f"Stopping documentation system: {self.system_name}")
98
+
99
+ class BuildAutomation:
100
+ def __init__(self, system_name: str):
101
+ self.system_name = system_name
102
+
103
+ async def start(self):
104
+ logging.info(f"Starting build automation system: {self.system_name}")
105
+ await asyncio.sleep(1) # Simulate initialization time
106
+
107
+ async def stop(self):
108
+ logging.info(f"Stopping build automation system: {self.system_name}")
109
+
110
+ # Define EliteDeveloperCluster class
111
+ class EliteDeveloperCluster:
112
+ def __init__(self, config: Dict[str, Any], model):
113
+ self.config = config
114
+ self.model_manager = ModelManager()
115
+ self.code_architect = CodeArchitect(self.model_manager, model)
116
+ self.uiux_wizard = UIUXWizard(self.model_manager)
117
+ self.version_control = VersionControl(config["version_control_system"])
118
+ self.documentation = Documentation(config["documentation_system"])
119
+ self.build_automation = BuildAutomation(config["build_automation_system"])
120
+ self.task_queue = asyncio.Queue()
121
+
122
+ async def start(self):
123
+ await self.code_architect.start()
124
+ await self.uiux_wizard.start()
125
+ await self.version_control.start()
126
+ await self.documentation.start()
127
+ await self.build_automation.start()
128
+
129
+ async def stop(self):
130
+ await self.code_architect.stop()
131
+ await self.uiux_wizard.stop()
132
+ await self.version_control.stop()
133
+ await self.documentation.stop()
134
+ await self.build_automation.stop()
135
+
136
+ async def process_task(self, task: Task):
137
+ if task.task_name == "generate_code":
138
+ response = await self.code_architect.generate_code(task.input_data)
139
+ return response
140
+ elif task.task_name == "get_memory_response":
141
+ response = self.uiux_wizard.get_memory_response(task.input_data)
142
+ return response
143
+ elif task.task_name == "get_conversation_response":
144
+ response = self.uiux_wizard.get_conversation_response(task.input_data)
145
+ return response
146
+ else:
147
+ return f"Unknown task: {task.task_name}"
148
+
149
+ async def process_tasks(self):
150
+ while True:
151
+ task = await self.task_queue.get()
152
+ response = await self.process_task(task)
153
+ logging.info(f"Processed task: {task.task_name} for agent: {task.agent_name}")
154
+ self.task_queue.task_done()
155
+ yield response
156
+
157
+ def route_request(self, query: str) -> str:
158
+ # TODO: Implement logic to determine the appropriate agent based on query
159
+ # For now, assume all requests are for the UIUXWizard
160
+ return self.uiux_wizard.get_conversation_response(query)
161
+
162
+ # Flask App for handling agent requests
163
+ app = Flask(__name__)
164
+
165
+ @app.route('/agent', methods=['POST'])
166
+ def agent_request():
167
+ data = request.get_json()
168
+ if data.get('input_value'):
169
+ # Process request from any agent (Agent 2, Agent 3, etc.)
170
+ task = Task(f"Process request from {data.get('agent_name', 'unknown agent')}", data.get('input_value'), data.get('agent_name', 'unknown agent'))
171
+ cluster.task_queue.put_nowait(task)
172
+ return jsonify({'response': 'Received input: from an agent, task added to queue.'})
173
+ else:
174
+ return jsonify({'response': 'Invalid input'})
175
 
176
+ # Chat Interface
177
+ def get_response(query: str) -> str:
178
+ return cluster.route_request(query)
 
 
 
179
 
180
+ def response_streaming(text: str):
181
+ try:
182
+ for char in text:
183
+ yield char
184
+ except Exception as e:
185
+ logging.error(f"Error in response streaming: {e}")
186
+ yield "Error occurred while streaming the response."
187
+
188
+ class ChatApp:
189
+ def __init__(self, cluster: EliteDeveloperCluster):
190
+ self.cluster = cluster
191
+
192
+ async def start(self):
193
+ await self.cluster.start()
194
+
195
+ async def stop(self):
196
+ await self.cluster.stop()
197
+
198
+ async def handle_request(self, query: str) -> str:
199
+ response = await self.cluster.process_tasks()
200
+ return response
201
+
202
+ # Configuration
203
+ config = {
204
+ "version_control_system": "Git",
205
+ "testing_framework": "PyTest",
206
+ "documentation_system": "Sphinx",
207
+ "build_automation_system": "Jenkins",
208
+ "redis_host": "localhost",
209
+ "redis_port": 6379,
210
+ "max_workers": 4,
211
+ }
212
 
213
+ if __name__ == "__main__":
214
+ # Initialize the cluster
215
+ cluster = EliteDeveloperCluster(config, model=None)
 
 
 
216
 
217
+ # Start the cluster and task processing loop
218
+ asyncio.run(cluster.start())
219
+ asyncio.run(cluster.process_tasks())
220
 
221
+ # Run Flask app
222
+ app.run(debug=True)