acecalisto3 commited on
Commit
54ce177
·
verified ·
1 Parent(s): 2ea07e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +252 -619
app.py CHANGED
@@ -1,647 +1,280 @@
1
- import subprocess
2
  import os
3
- from io import StringIO
4
- import sys
5
- import black
6
- import streamlit as st
7
- from pylint import lint
8
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
9
- from transformers import pipeline as transformers_pipeline
10
- from huggingface_hub import hf_hub_url, cached_download
11
  import json
12
  import time
13
- import shutil
14
- import gradio as gr
15
 
16
- # --- Global State ---
17
- if 'chat_history' not in st.session_state:
18
- st.session_state['chat_history'] = []
19
- if 'workspace_projects' not in st.session_state:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  st.session_state.workspace_projects = {}
21
- if 'available_agents' not in st.session_state:
22
- st.session_state.available_agents = []
23
- if 'available_clusters' not in st.session_state:
24
- st.session_state.available_clusters = []
25
- if 'current_project' not in st.session_state:
 
 
26
  st.session_state.current_project = None
27
- if 'current_agent' not in st.session_state:
28
  st.session_state.current_agent = None
29
- if 'current_cluster' not in st.session_state:
30
  st.session_state.current_cluster = None
31
- if 'hf_token' not in st.session_state:
32
  st.session_state.hf_token = None
33
- if 'repo_name' not in st.session_state:
34
  st.session_state.repo_name = None
35
- if 'selected_model' not in st.session_state:
36
  st.session_state.selected_model = None
37
- if 'selected_code_model' not in st.session_state:
38
  st.session_state.selected_code_model = None
39
- if 'selected_chat_model' not in st.session_state:
40
  st.session_state.selected_chat_model = None
41
 
42
- # --- Agent Class ---
43
- class AIAgent:
44
- def __init__(self, name, description, skills, persona_prompt=None):
45
- self.name = name
46
- self.description = description
47
- self.skills = skills
48
- self.persona_prompt = persona_prompt
49
-
50
- def create_agent_prompt(self):
51
- skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
52
- agent_prompt = f"""
53
- I am an AI agent named {self.name}, designed to assist developers with their projects.
54
- My expertise lies in the following areas:
55
-
56
- {skills_str}
57
-
58
- {self.persona_prompt if self.persona_prompt else ''}
59
-
60
- I am here to help you build, deploy, and improve your applications.
61
- Feel free to ask me any questions or present me with any challenges you encounter.
62
- I will do my best to provide helpful and insightful responses.
63
- """
64
- return agent_prompt
65
-
66
- def autonomous_build(self, chat_history, workspace_projects):
67
- """
68
- Autonomous build logic that continues based on the state of chat history and workspace projects.
69
- """
70
- # Example logic: Generate a summary of chat history and workspace state
71
- summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
72
- summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
73
-
74
- # Example: Generate the next logical step in the project
75
- next_step = "Based on the current state, the next logical step is to implement the main application logic."
76
-
77
- return summary, next_step
78
-
79
- # --- Agent Management ---
80
- def save_agent_to_file(agent):
81
- """Saves the agent's prompt to a file."""
82
- if not os.path.exists("agents"):
83
- os.makedirs("agents")
84
- file_path = os.path.join("agents", f"{agent.name}.txt")
85
- with open(file_path, "w") as file:
86
- file.write(agent.create_agent_prompt())
87
- st.session_state.available_agents.append(agent.name)
88
-
89
- def load_agent_prompt(agent_name):
90
- """Loads an agent prompt from a file."""
91
- file_path = os.path.join("agents", f"{agent_name}.txt")
92
- if os.path.exists(file_path):
93
- with open(file_path, "r") as file:
94
- agent_prompt = file.read()
95
- return agent_prompt
96
- else:
97
- return None
98
-
99
- def create_agent_from_text(name, text, persona_prompt=None):
100
- skills = text.split('\n')
101
- agent = AIAgent(name, "AI agent created from text input.", skills, persona_prompt)
102
- save_agent_to_file(agent)
103
- return agent.create_agent_prompt()
104
-
105
- # --- Cluster Management ---
106
- def create_agent_cluster(cluster_name, agent_names):
107
- """Creates a cluster of agents."""
108
- if not os.path.exists("clusters"):
109
- os.makedirs("clusters")
110
- cluster_path = os.path.join("clusters", f"{cluster_name}.json")
111
- with open(cluster_path, "w") as file:
112
- json.dump({"agents": agent_names}, file)
113
- st.session_state.available_clusters.append(cluster_name)
114
-
115
- def load_agent_cluster(cluster_name):
116
- """Loads an agent cluster from a file."""
117
- cluster_path = os.path.join("clusters", f"{cluster_name}.json")
118
- if os.path.exists(cluster_path):
119
- with open(cluster_path, "r") as file:
120
- cluster_data = json.load(file)
121
- return cluster_data["agents"]
122
- else:
123
- return None
124
-
125
- # --- Chat Interface ---
126
- def chat_interface_with_agent(input_text, agent_name):
127
- agent_prompt = load_agent_prompt(agent_name)
128
- if agent_prompt is None:
129
- return f"Agent {agent_name} not found."
130
-
131
- # Use a more powerful language model (GPT-3 or similar) for better chat experience
132
- model_name = st.session_state.selected_chat_model or "text-davinci-003" # Default to GPT-3 if not selected
133
- try:
134
- model = transformers_pipeline("text-generation", model=model_name)
135
- except EnvironmentError as e:
136
- return f"Error loading model: {e}"
137
-
138
- # Combine the agent prompt with user input
139
- combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
140
-
141
- # Generate response
142
- response = model(combined_input, max_length=200, temperature=0.7, top_p=0.95, do_sample=True)[0]['generated_text']
143
- response = response.split("Agent:")[1].strip() # Extract the agent's response
144
- return response
145
-
146
- def chat_interface_with_cluster(input_text, cluster_name):
147
- agent_names = load_agent_cluster(cluster_name)
148
- if agent_names is None:
149
- return f"Cluster {cluster_name} not found."
150
-
151
- # Use a more powerful language model (GPT-3 or similar) for better chat experience
152
- model_name = st.session_state.selected_chat_model or "text-davinci-003" # Default to GPT-3 if not selected
153
- try:
154
- model = transformers_pipeline("text-generation", model=model_name)
155
- except EnvironmentError as e:
156
- return f"Error loading model: {e}"
157
-
158
- # Combine the agent prompt with user input
159
- combined_input = f"User: {input_text}\n"
160
- for agent_name in agent_names:
161
- agent_prompt = load_agent_prompt(agent_name)
162
- combined_input += f"\n{agent_name}:\n{agent_prompt}\n"
163
-
164
- # Generate response
165
- response = model(combined_input, max_length=200, temperature=0.7, top_p=0.95, do_sample=True)[0]['generated_text']
166
- response = response.split("User:")[1].strip() # Extract the agent's response
167
  return response
168
 
169
- # --- Code Editor ---
170
- def code_editor_interface(code):
171
- """Provides code completion, formatting, and linting in the code editor."""
172
- # Format code using black
173
- try:
174
- formatted_code = black.format_str(code, mode=black.FileMode())
175
- except black.InvalidInput:
176
- formatted_code = code # Keep original code if formatting fails
 
 
 
177
 
178
- # Lint code using pylint
 
179
  try:
180
- pylint_output = StringIO()
181
- sys.stdout = pylint_output
182
- sys.stderr = pylint_output
183
- lint.Run(['--from-stdin'], stdin=StringIO(formatted_code))
184
- sys.stdout = sys.__stdout__
185
- sys.stderr = sys.__stderr__
186
- lint_message = pylint_output.getvalue()
187
  except Exception as e:
188
- lint_message = f"Pylint error: {e}"
189
 
190
- return formatted_code, lint_message
191
-
192
- # --- Workspace Management ---
193
- def workspace_interface(project_name):
194
- """Manages projects, files, and resources in the workspace."""
195
- project_path = os.path.join("projects", project_name)
196
- # Create project directory
197
- try:
198
  os.makedirs(project_path)
199
- requirements_path = os.path.join(project_path, "requirements.txt")
200
- with open(requirements_path, "w") as req_file:
201
- req_file.write("") # Initialize an empty requirements.txt file
202
- status = f'Project "{project_name}" created successfully.'
203
- st.session_state.workspace_projects[project_name] = {'files': []}
204
- except FileExistsError:
205
- status = f'Project "{project_name}" already exists.'
206
- return status
207
-
208
- def add_code_to_workspace(project_name, code, file_name):
209
- """Adds selected code files to the workspace."""
210
- project_path = os.path.join("projects", project_name)
211
  file_path = os.path.join(project_path, file_name)
212
-
213
- try:
214
- with open(file_path, "w") as code_file:
215
- code_file.write(code)
216
- status = f'File "{file_name}" added to project "{project_name}" successfully.'
217
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
218
- except Exception as e:
219
- status = f"Error: {e}"
220
- return status
221
-
222
- # --- AI Tools ---
223
- def summarize_text(text):
224
- """Summarizes a given text using a Hugging Face model."""
225
- model_name = "facebook/bart-large-cnn"
226
- try:
227
- summarizer = pipeline("summarization", model=model_name)
228
- except EnvironmentError as e:
229
- return f"Error loading model: {e}"
230
-
231
- # Truncate input text to avoid exceeding the model's maximum length
232
- max_input_length = model.config.max_length
233
- inputs = text
234
- if len(text) > max_input_length:
235
- inputs = text[:max_input_length]
236
-
237
- # Generate summary
238
- summary = summarizer(inputs, max_length=100, min_length=30, do_sample=False)[0][
239
- "summary_text"
240
- ]
241
- return summary
242
-
243
- def sentiment_analysis(text):
244
- """Performs sentiment analysis on a given text using a Hugging Face model."""
245
- model_name = "distilbert-base-uncased-finetuned-sst-2-english"
246
- try:
247
- analyzer = pipeline("sentiment-analysis", model=model_name)
248
- except EnvironmentError as e:
249
- return f"Error loading model: {e}"
250
-
251
- # Perform sentiment analysis
252
- result = analyzer(text)[0]
253
- return result
254
-
255
- def translate_code(code, source_language, target_language):
256
- """Translates code from one programming language to another using a Hugging Face model."""
257
- model_name = "Helsinki-NLP/opus-mt-en-fr" # Replace with your preferred translation model
258
- try:
259
- translator = pipeline("translation", model=model_name)
260
- except EnvironmentError as e:
261
- return f"Error loading model: {e}"
262
-
263
- # Translate code
264
- translated_code = translator(code, target_lang=target_language)[0]['translation_text']
265
- return translated_code
266
-
267
- def generate_code(idea):
268
- """Generates code based on a given idea using a Hugging Face model."""
269
- model_name = st.session_state.selected_code_model or "bigcode/starcoder" # Default to Starcoder if not selected
270
- try:
271
- model = AutoModelForCausalLM.from_pretrained(model_name)
272
- tokenizer = AutoTokenizer.from_pretrained(model_name)
273
- except EnvironmentError as e:
274
- return f"Error loading model: {e}"
275
-
276
- # Generate the code
277
- input_text = f"""
278
- # Idea: {idea}
279
- # Code:
280
- """
281
- input_ids = tokenizer.encode(input_text, return_tensors="pt")
282
- output_sequences = model.generate(
283
- input_ids=input_ids,
284
- max_length=model.config.max_length,
285
- num_return_sequences=1,
286
- no_repeat_ngram_size=2,
287
- early_stopping=True,
288
- temperature=0.7, # Adjust temperature for creativity
289
- top_k=50, # Adjust top_k for diversity
290
- )
291
- generated_code = tokenizer.decode(output_sequences[0], skip_special_tokens=True)
292
-
293
- # Remove the prompt and formatting
294
- parts = generated_code.split("\n# Code:")
295
- if len(parts) > 1:
296
- generated_code = parts[1].strip()
297
  else:
298
- generated_code = generated_code.strip()
299
-
300
- return generated_code
301
-
302
- # --- AI Personas Creator ---
303
- def create_persona_from_text(text):
304
- """Creates an AI persona from the given text."""
305
- persona_prompt = f"""
306
- As an elite expert developer with the highest level of proficiency in Streamlit, Gradio, and Hugging Face, I possess a comprehensive understanding of these technologies and their applications in web development and deployment. My expertise encompasses the following areas:
307
-
308
- Streamlit:
309
- * In-depth knowledge of Streamlit's architecture, components, and customization options.
310
- * Expertise in creating interactive and user-friendly dashboards and applications.
311
- * Proficiency in integrating Streamlit with various data sources and machine learning models.
312
-
313
- Gradio:
314
- * Thorough understanding of Gradio's capabilities for building and deploying machine learning interfaces.
315
- * Expertise in creating custom Gradio components and integrating them with Streamlit applications.
316
- * Proficiency in using Gradio to deploy models from Hugging Face and other frameworks.
317
-
318
- Hugging Face:
319
- * Comprehensive knowledge of Hugging Face's model hub and Transformers library.
320
- * Expertise in fine-tuning and deploying Hugging Face models for various NLP and computer vision tasks.
321
- * Proficiency in using Hugging Face's Spaces platform for model deployment and sharing.
322
-
323
- Deployment:
324
- * In-depth understanding of best practices for deploying Streamlit and Gradio applications.
325
- * Expertise in deploying models on cloud platforms such as AWS, Azure, and GCP.
326
- * Proficiency in optimizing deployment configurations for performance and scalability.
327
-
328
- Additional Skills:
329
- * Strong programming skills in Python and JavaScript.
330
- * Familiarity with Docker and containerization technologies.
331
- * Excellent communication and problem-solving abilities.
332
-
333
- I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications using Streamlit, Gradio, and Hugging Face. Please feel free to ask any questions or present any challenges you may encounter.
334
-
335
- Example:
336
-
337
- Task:
338
- Develop a Streamlit application that allows users to generate text using a Hugging Face model. The application should include a Gradio component for user input and model prediction.
339
-
340
- Solution:
341
-
342
- import streamlit as st
343
- import gradio as gr
344
- from transformers import pipeline
345
-
346
- # Create a Hugging Face pipeline
347
- huggingface_model = pipeline("text-generation")
348
-
349
- # Create a Streamlit app
350
- st.title("Hugging Face Text Generation App")
351
 
352
- # Define a Gradio component
353
- demo = gr.Interface(
354
- fn=huggingface_model,
355
- inputs=gr.Textbox(lines=2),
356
- outputs=gr.Textbox(lines=1),
357
- )
358
-
359
- # Display the Gradio component in the Streamlit app
360
- st.write(demo)
361
- """
362
- return persona_prompt
363
 
364
  # --- Terminal Interface ---
365
- def terminal_interface(command, project_name=None):
366
- """Executes commands in the terminal."""
367
- # Execute command
368
- try:
369
- process = subprocess.run(command.split(), capture_output=True, text=True)
370
- output = process.stdout
371
-
372
- # If the command is to install a package, update the workspace
373
- if "install" in command and project_name:
374
- requirements_path = os.path.join("projects", project_name, "requirements.txt")
375
- with open(requirements_path, "a") as req_file:
376
- package_name = command.split()[-1]
377
- req_file.write(f"{package_name}\n")
378
- except Exception as e:
379
- output = f"Error: {e}"
380
- return output
381
-
382
- # --- Build and Deploy ---
383
- def build_project(project_name):
384
- """Builds a project based on the workspace files."""
385
- project_path = os.path.join("projects", project_name)
386
- requirements_path = os.path.join(project_path, "requirements.txt")
387
-
388
- # Install dependencies
389
- os.chdir(project_path)
390
- terminal_interface(f"pip install -r {requirements_path}")
391
- os.chdir("..")
392
-
393
- # Create a temporary directory for the built project
394
- build_dir = os.path.join("build", project_name)
395
- os.makedirs(build_dir, exist_ok=True)
396
-
397
- # Copy project files to the build directory
398
- for filename in os.listdir(project_path):
399
- if filename == "requirements.txt":
400
- continue
401
- shutil.copy(os.path.join(project_path, filename), build_dir)
402
-
403
- # Create a `main.py` file if it doesn't exist
404
- main_file = os.path.join(build_dir, "main.py")
405
- if not os.path.exists(main_file):
406
- with open(main_file, "w") as f:
407
- f.write("# Your Streamlit app code goes here\n")
408
-
409
- # Return the path to the built project
410
- return build_dir
411
-
412
- def deploy_to_huggingface(build_dir, hf_token, repo_name):
413
- """Deploys the built project to Hugging Face Spaces."""
414
- # Authenticate with Hugging Face
415
- os.environ["HF_TOKEN"] = hf_token
416
-
417
- # Create a new Hugging Face Space repository
418
- try:
419
- subprocess.run(f"huggingface-cli repo create {repo_name}", shell=True, check=True)
420
- except subprocess.CalledProcessError as e:
421
- st.error(f"Error creating Hugging Face Space repository: {e}")
422
- return
423
-
424
- # Upload the built project to the repository
425
- try:
426
- subprocess.run(f"huggingface-cli upload {repo_name} {build_dir}", shell=True, check=True)
427
- except subprocess.CalledProcessError as e:
428
- st.error(f"Error uploading project to Hugging Face Space repository: {e}")
429
- return
430
-
431
- # Deploy the project to Hugging Face Spaces
432
- try:
433
- subprocess.run(f"huggingface-cli space deploy {repo_name}", shell=True, check=True)
434
- except subprocess.CalledProcessError as e:
435
- st.error(f"Error deploying project to Hugging Face Spaces: {e}")
436
- return
437
-
438
- # Display the deployment URL
439
- st.success(f"Project deployed successfully to Hugging Face Spaces: https://huggingface.co/spaces/{repo_name}")
440
-
441
- def deploy_locally(build_dir):
442
- """Deploys the built project locally."""
443
- # Run the project locally
444
- os.chdir(build_dir)
445
- subprocess.run("streamlit run main.py", shell=True, check=True)
446
- os.chdir("..")
447
-
448
- # Display a success message
449
- st.success(f"Project deployed locally!")
450
-
451
- # --- Streamlit App ---
452
- st.set_page_config(page_title="AI Agent Creator", page_icon="🤖")
453
-
454
- # --- Tabs for Navigation ---
455
- tabs = st.tabs(["AI Agent Creator", "Tool Box", "Workspace Chat App"])
456
-
457
- # --- AI Agent Creator ---
458
- with tabs[0]:
459
- st.header("Create an AI Agent from Text")
460
-
461
- st.subheader("From Text")
462
- agent_name = st.text_input("Enter agent name:")
463
- text_input = st.text_area("Enter skills (one per line):")
464
- persona_prompt_option = st.selectboxED("Choose a persona prompt", ["None", "Expert Developer"])
465
- persona_prompt = None
466
- if persona_prompt_option == "Expert Developer":
467
- persona_prompt = create_persona_from_text("Expert Developer")
468
- if st.button("Create Agent"):
469
- agent_prompt = create_agent_from_text(agent_name, text_input, persona_prompt)
470
- st.success(f"Agent '{agent_name}' created and saved successfully.")
471
- st.session_state.available_agents.append(agent_name)
472
-
473
- st.subheader("Create an Agent Cluster")
474
- cluster_name = st.text_input("Enter cluster name:")
475
- agent_names = st.multiselect("Select agents for the cluster", st.session_state.available_agents)
476
- if st.button("Create Cluster"):
477
- create_agent_cluster(cluster_name, agent_names)
478
- st.success(f"Cluster '{cluster_name}' created successfully.")
479
- st.session_state.available_clusters.append(cluster_name)
480
-
481
- # --- Tool Box ---
482
- with tabs[1]:
483
- st.header("Tool Box")
484
-
485
- # --- Workspace ---
486
- st.subheader("Workspace")
487
- project_name = st.selectboxSP("Select a project", list(st.session_state.workspace_projects.keys()), key="project_select")
488
- if project_name:
489
- st.session_state.current_project = project_name
490
- for file in st.session_state.workspace_projects[project_name]['files']:
491
- st.write(f" - {file}")
492
 
493
- # --- Chat with AI Agents ---
494
- st.subheader("Chat with AI Agents")
495
- selected_agent_or_cluster = st.selectboxSA("Select an AI agent or cluster", st.session_state.available_agents + st.session_state.available_clusters)
496
- agent_chat_input = st.text_area("Enter your message:")
497
- chat_model_options = ["text-davinci-003", "gpt-3.5-turbo"] # Add more chat models as needed
498
- selected_chat_model = st.selectboxSCM("Select a chat model", chat_model_options)
499
- if st.button("Send"):
500
- st.session_state.selected_chat_model = selected_chat_model
501
- if selected_agent_or_cluster in st.session_state.available_agents:
502
- st.session_state.current_agent = selected_agent_or_cluster
503
- st.session_state.current_cluster = None
504
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent_or_cluster)
505
- elif selected_agent_or_cluster in st.session_state.available_clusters:
506
- st.session_state.current_agent = None
507
- st.session_state.current_cluster = selected_agent_or_cluster
508
- agent_chat_response = chat_interface_with_cluster(agent_chat_input, selected_agent_or_cluster)
509
- else:
510
- agent_chat_response = "Invalid selection."
511
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
512
- st.write(f"{selected_agent_or_cluster}: {agent_chat_response}")
513
-
514
- # --- Automate Build Process ---
515
- st.subheader("Automate Build Process")
516
- if st.button("Automate"):
517
- if st.session_state.current_agent:
518
- agent = AIAgent(st.session_state.current_agent, "", []) # Load the agent without skills for now
519
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
520
- st.write("Autonomous Build Summary:")
521
- st.write(summary)
522
- st.write("Next Step:")
523
- st.write(next_step)
524
- elif st.session_state.current_cluster:
525
- # Implement cluster-based automation logic here
526
- # ...
527
- st.warning("Cluster-based automation is not yet implemented.")
528
- else:
529
- st.warning("Please select an agent or cluster first.")
530
-
531
- # --- Workspace Chat App ---
532
- with tabs[2]:
533
- st.header("Workspace Chat App")
534
-
535
- # --- Project Selection ---
536
- project_name = st.selectboxSP2("Select a project", list(st.session_state.workspace_projects.keys()), key="project_select2")
537
- if project_name:
538
- st.session_state.current_project = project_name
539
-
540
- # --- Chat with AI Agents ---
541
- st.subheader("Chat with AI Agents")
542
- selected_agent_or_cluster = st.selectboxSA2("Select an AI agent or cluster", st.session_state.available_agents + st.session_state.available_clusters)
543
- agent_chat_input = st.text_area("Enter your message:")
544
- chat_model_options = ["text-davinci-003", "gpt-3.5-turbo"] # Add more chat models as needed
545
- selected_chat_model = st.selectboxSCM2("Select a chat model", chat_model_options)
546
- if st.button("Send"):
547
- st.session_state.selected_chat_model = selected_chat_model
548
- if selected_agent_or_cluster in st.session_state.available_agents:
549
- st.session_state.current_agent = selected_agent_or_cluster
550
- st.session_state.current_cluster = None
551
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent_or_cluster)
552
- elif selected_agent_or_cluster in st.session_state.available_clusters:
553
- st.session_state.current_agent = None
554
- st.session_state.current_cluster = selected_agent_or_cluster
555
- agent_chat_response = chat_interface_with_cluster(agent_chat_input, selected_agent_or_cluster)
556
- else:
557
- agent_chat_response = "Invalid selection."
558
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
559
- st.write(f"{selected_agent_or_cluster}: {agent_chat_response}")
560
-
561
- # --- Code Editor ---
562
- st.subheader("Code Editor")
563
- code = st.text_area("Enter your code:")
564
- if st.button("Format & Lint"):
565
- formatted_code, lint_message = code_editor_interface(code)
566
- st.code(formatted_code, language="python")
567
- st.write("Linting Report:")
568
- st.write(lint_message)
569
-
570
- # --- Add Code to Workspace ---
571
- st.subheader("Add Code to Workspace")
572
- file_name = st.text_input("Enter file name:")
573
- if st.button("Add Code"):
574
- if st.session_state.current_project:
575
- status = add_code_to_workspace(st.session_state.current_project, code, file_name)
576
- st.write(status)
577
- else:
578
- st.warning("Please select a project first.")
579
-
580
- # --- Terminal ---
581
- st.subheader("Terminal")
582
- command = st.text_input("Enter a command:")
583
- if st.button("Execute"):
584
- if st.session_state.current_project:
585
- output = terminal_interface(command, st.session_state.current_project)
586
- st.write(output)
587
- else:
588
- st.warning("Please select a project first.")
589
-
590
- # --- AI Tools ---
591
- st.subheader("AI Tools")
592
- st.write("Summarize Text:")
593
- text_to_summarize = st.text_area("Enter text to summarize:")
594
- if st.button("Summarize"):
595
- summary = summarize_text(text_to_summarize)
596
- st.write(summary)
597
-
598
- st.write("Sentiment Analysis:")
599
- text_to_analyze = st.text_area("Enter text to analyze:")
600
- if st.button("Analyze"):
601
- result = sentiment_analysis(text_to_analyze)
602
- st.write(result)
603
-
604
- st.write("Code Translation:")
605
- code_to_translate = st.text_area("Enter code to translate:")
606
- source_language = st.selectboxSL("Source Language", ["Python", "JavaScript", "C++"])
607
- target_language = st.selectboxTL("Target Language", ["Python", "JavaScript", "C++"])
608
- if st.button("Translate"):
609
- translated_code = translate_code(code_to_translate, source_language, target_language)
610
- st.write(translated_code)
611
-
612
- st.write("Code Generation:")
613
- code_idea = st.text_input("Enter your code idea:")
614
- code_model_options = ["bigcode/starcoder", "google/flan-t5-xl"] # Add more code models as needed
615
- selected_code_model = st.selectboxGM("Select a code generation model", code_model_options)
616
- if st.button("Generate"):
617
- st.session_state.selected_code_model = selected_code_model
618
- generated_code = generate_code(code_idea)
619
- st.code(generated_code, language="python")
620
-
621
- # --- Build and Deploy ---
622
- st.subheader("Build and Deploy")
623
- if st.session_state.current_project:
624
- st.write(f"Current project: {st.session_state.current_project}")
625
- if st.button("Build"):
626
- build_dir = build_project(st.session_state.current_project)
627
- st.write(f"Project built successfully! Build directory: {build_dir}")
628
-
629
- st.write("Select a deployment target:")
630
- deployment_target = st.selectboxDP2HF("Deployment Target", ["Local", "Hugging Face Spaces"])
631
- if deployment_target == "Hugging Face Spaces":
632
- hf_token = st.text_input("Enter your Hugging Face token:")
633
- repo_name = st.text_input("Enter your Hugging Face Space repository name:")
634
- if st.button("Deploy to Hugging Face Spaces"):
635
- st.session_state.hf_token = hf_token
636
- st.session_state.repo_name = repo_name
637
- deploy_to_huggingface(build_dir, hf_token, repo_name)
638
- elif deployment_target == "Local":
639
- if st.button("Deploy Locally"):
640
- deploy_locally(build_dir)
641
  else:
642
- st.warning("Please select a project first.")
643
-
644
- # --- Hugging Face Space Deployment (After Building) ---
645
- if st.session_state.hf_token and st.session_state.repo_name:
646
- st.write("Deploying to Hugging Face Spaces...")
647
- deploy_to_huggingface(build_dir, st.session_state.hf_token, st.session_state.repo_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
 
 
 
 
 
 
2
  import json
3
  import time
4
+ from typing import Dict, List, Tuple
 
5
 
6
+ import gradio as gr
7
+ import streamlit as st
8
+ from huggingface_hub import InferenceClient, hf_hub_url, cached_download
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
10
+ from rich import print as rprint
11
+ from rich.panel import Panel
12
+ from rich.progress import track
13
+ from rich.table import Table
14
+ import subprocess
15
+ import threading
16
+
17
+ # --- Constants ---
18
+ MODEL_NAME = "bigscience/bloom-1b7" # Choose a suitable model
19
+ MAX_NEW_TOKENS = 1024
20
+ TEMPERATURE = 0.7
21
+ TOP_P = 0.95
22
+ REPETITION_PENALTY = 1.2
23
+
24
+ # --- Model & Tokenizer ---
25
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
26
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
27
+
28
+ # --- Agents ---
29
+ agents = {
30
+ "WEB_DEV": {
31
+ "description": "Expert in web development technologies and frameworks.",
32
+ "skills": ["HTML", "CSS", "JavaScript", "React", "Vue.js", "Flask", "Django", "Node.js", "Express.js"],
33
+ "system_prompt": "You are a web development expert. Your goal is to assist the user in building and deploying web applications. Provide code snippets, explanations, and guidance on best practices.",
34
+ },
35
+ "AI_SYSTEM_PROMPT": {
36
+ "description": "Expert in designing and implementing AI systems.",
37
+ "skills": ["Machine Learning", "Deep Learning", "Natural Language Processing", "Computer Vision", "Reinforcement Learning"],
38
+ "system_prompt": "You are an AI system expert. Your goal is to assist the user in designing and implementing AI systems. Provide code snippets, explanations, and guidance on best practices.",
39
+ },
40
+ "PYTHON_CODE_DEV": {
41
+ "description": "Expert in Python programming and development.",
42
+ "skills": ["Python", "Data Structures", "Algorithms", "Object-Oriented Programming", "Functional Programming"],
43
+ "system_prompt": "You are a Python code development expert. Your goal is to assist the user in writing and debugging Python code. Provide code snippets, explanations, and guidance on best practices.",
44
+ },
45
+ "CODE_REVIEW_ASSISTANT": {
46
+ "description": "Expert in code review and quality assurance.",
47
+ "skills": ["Code Style", "Best Practices", "Security", "Performance", "Maintainability"],
48
+ "system_prompt": "You are a code review assistant. Your goal is to assist the user in reviewing code for quality and efficiency. Provide feedback on code style, best practices, security, performance, and maintainability.",
49
+ },
50
+ "CONTENT_WRITER_EDITOR": {
51
+ "description": "Expert in content writing and editing.",
52
+ "skills": ["Grammar", "Style", "Clarity", "Conciseness", "SEO"],
53
+ "system_prompt": "You are a content writer and editor. Your goal is to assist the user in creating high-quality content. Provide suggestions on grammar, style, clarity, conciseness, and SEO.",
54
+ },
55
+ "QUESTION_GENERATOR": {
56
+ "description": "Expert in generating questions for learning and assessment.",
57
+ "skills": ["Question Types", "Cognitive Levels", "Assessment Design"],
58
+ "system_prompt": "You are a question generator. Your goal is to assist the user in generating questions for learning and assessment. Provide questions that are relevant to the topic and aligned with the cognitive levels.",
59
+ },
60
+ "HUGGINGFACE_FILE_DEV": {
61
+ "description": "Expert in developing Hugging Face files for machine learning models.",
62
+ "skills": ["Transformers", "Datasets", "Model Training", "Model Deployment"],
63
+ "system_prompt": "You are a Hugging Face file development expert. Your goal is to assist the user in creating and deploying Hugging Face files for machine learning models. Provide code snippets, explanations, and guidance on best practices.",
64
+ },
65
+ }
66
+
67
+ # --- Session State ---
68
+ if "workspace_projects" not in st.session_state:
69
  st.session_state.workspace_projects = {}
70
+ if "chat_history" not in st.session_state:
71
+ st.session_state.chat_history = []
72
+ if "active_agent" not in st.session_state:
73
+ st.session_state.active_agent = None
74
+ if "selected_agents" not in st.session_state:
75
+ st.session_state.selected_agents = []
76
+ if "current_project" not in st.session_state:
77
  st.session_state.current_project = None
78
+ if "current_agent" not in st.session_state:
79
  st.session_state.current_agent = None
80
+ if "current_cluster" not in st.session_state:
81
  st.session_state.current_cluster = None
82
+ if "hf_token" not in st.session_state:
83
  st.session_state.hf_token = None
84
+ if "repo_name" not in st.session_state:
85
  st.session_state.repo_name = None
86
+ if "selected_model" not in st.session_state:
87
  st.session_state.selected_model = None
88
+ if "selected_code_model" not in st.session_state:
89
  st.session_state.selected_code_model = None
90
+ if "selected_chat_model" not in st.session_state:
91
  st.session_state.selected_chat_model = None
92
 
93
+ # --- Functions ---
94
+ def format_prompt(message: str, history: List[Tuple[str, str]], agent_prompt: str) -> str:
95
+ """Formats the prompt for the language model."""
96
+ prompt = "<s>"
97
+ for user_prompt, bot_response in history:
98
+ prompt += f"[INST] {user_prompt} [/INST]"
99
+ prompt += f" {bot_response}</s> "
100
+ prompt += f"[INST] {agent_prompt}, {message} [/INST]"
101
+ return prompt
102
+
103
+ def generate_response(prompt: str, agent_name: str) -> str:
104
+ """Generates a response from the language model."""
105
+ agent = agents[agent_name]
106
+ system_prompt = agent["system_prompt"]
107
+ generate_kwargs = dict(
108
+ temperature=TEMPERATURE,
109
+ max_new_tokens=MAX_NEW_TOKENS,
110
+ top_p=TOP_P,
111
+ repetition_penalty=REPETITION_PENALTY,
112
+ do_sample=True,
113
+ )
114
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
115
+ output = model.generate(input_ids, **generate_kwargs)
116
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  return response
118
 
119
+ def chat_interface(chat_input: str, agent_names: List[str]) -> str:
120
+ """Handles chat interactions with the selected agents."""
121
+ if agent_names:
122
+ responses = []
123
+ for agent_name in agent_names:
124
+ prompt = format_prompt(chat_input, st.session_state.chat_history, agents[agent_name]["system_prompt"])
125
+ response = generate_response(prompt, agent_name)
126
+ responses.append(f"{agent_name}: {response}")
127
+ return "\n".join(responses)
128
+ else:
129
+ return "Please select at least one agent."
130
 
131
+ def terminal_interface(command: str, project_name: str) -> str:
132
+ """Executes a command within the specified project directory."""
133
  try:
134
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_name)
135
+ return result.stdout if result.returncode == 0 else result.stderr
 
 
 
 
 
136
  except Exception as e:
137
+ return str(e)
138
 
139
+ def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
140
+ """Adds code to a workspace project."""
141
+ project_path = os.path.join(os.getcwd(), project_name)
142
+ if not os.path.exists(project_path):
 
 
 
 
143
  os.makedirs(project_path)
 
 
 
 
 
 
 
 
 
 
 
 
144
  file_path = os.path.join(project_path, file_name)
145
+ with open(file_path, 'w') as file:
146
+ file.write(code)
147
+ if project_name not in st.session_state.workspace_projects:
148
+ st.session_state.workspace_projects[project_name] = {'files': []}
149
+ st.session_state.workspace_projects[project_name]['files'].append(file_name)
150
+ return f"Added {file_name} to {project_name}"
151
+
152
+ def display_workspace_projects():
153
+ """Displays a table of workspace projects."""
154
+ table = Table(title="Workspace Projects")
155
+ table.add_column("Project Name", style="cyan", no_wrap=True)
156
+ table.add_column("Files", style="magenta")
157
+ for project_name, details in st.session_state.workspace_projects.items():
158
+ table.add_row(project_name, ", ".join(details['files']))
159
+ rprint(Panel(table, title="[bold blue]Workspace Projects[/bold blue]"))
160
+
161
+ def display_chat_history():
162
+ """Displays the chat history in a formatted way."""
163
+ table = Table(title="Chat History")
164
+ table.add_column("User", style="cyan", no_wrap=True)
165
+ table.add_column("Agent", style="magenta")
166
+ for user_prompt, bot_response in st.session_state.chat_history:
167
+ table.add_row(user_prompt, bot_response)
168
+ rprint(Panel(table, title="[bold blue]Chat History[/bold blue]"))
169
+
170
+ def display_agent_info(agent_name: str):
171
+ """Displays information about the selected agent."""
172
+ agent = agents[agent_name]
173
+ table = Table(title=f"{agent_name} - Agent Information")
174
+ table.add_column("Description", style="cyan", no_wrap=True)
175
+ table.add_column("Skills", style="magenta")
176
+ table.add_row(agent["description"], ", ".join(agent["skills"]))
177
+ rprint(Panel(table, title=f"[bold blue]{agent_name} - Agent Information[/bold blue]"))
178
+
179
+ def run_autonomous_build(agent_names: List[str], project_name: str):
180
+ """Runs the autonomous build process."""
181
+ for agent_name in agent_names:
182
+ agent = agents[agent_name]
183
+ chat_history = st.session_state.chat_history
184
+ workspace_projects = st.session_state.workspace_projects
185
+ summary, next_step = agent.autonomous_build(chat_history, workspace_projects)
186
+ rprint(Panel(summary, title="[bold blue]Current State[/bold blue]"))
187
+ rprint(Panel(next_step, title="[bold blue]Next Step[/bold blue]"))
188
+ # Implement logic for autonomous build based on the current state
189
+ # ...
190
+
191
+ # --- Streamlit UI ---
192
+ st.title("DevToolKit: AI-Powered Development Environment")
193
+
194
+ # --- Project Management ---
195
+ st.header("Project Management")
196
+ project_name = st.text_input("Enter project name:")
197
+ if st.button("Create Project"):
198
+ if project_name not in st.session_state.workspace_projects:
199
+ st.session_state.workspace_projects[project_name] = {'files': []}
200
+ st.success(f"Created project: {project_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  else:
202
+ st.warning(f"Project {project_name} already exists")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
+ # --- Code Addition ---
205
+ st.subheader("Add Code to Workspace")
206
+ code_to_add = st.text_area("Enter code to add to workspace:")
207
+ file_name = st.text_input("Enter file name (e.g. 'app.py'):")
208
+ if st.button("Add Code"):
209
+ add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
210
+ st.success(add_code_status)
 
 
 
 
211
 
212
  # --- Terminal Interface ---
213
+ st.subheader("Terminal (Workspace Context)")
214
+ terminal_input = st.text_input("Enter a command within the workspace:")
215
+ if st.button("Run Command"):
216
+ terminal_output = terminal_interface(terminal_input, project_name)
217
+ st.code(terminal_output, language="bash")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ # --- Chat Interface ---
220
+ st.subheader("Chat with AI Agents")
221
+ selected_agents = st.multiselect("Select AI agents", list(agents.keys()), key="agent_select")
222
+ st.session_state.selected_agents = selected_agents
223
+ agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
224
+ if st.button("Send to Agents", key="agent_send"):
225
+ agent_chat_response = chat_interface(agent_chat_input, selected_agents)
226
+ st.write(agent_chat_response)
227
+
228
+ # --- Agent Control ---
229
+ st.subheader("Agent Control")
230
+ for agent_name in agents:
231
+ agent = agents[agent_name]
232
+ with st.expander(f"{agent_name} ({agent['description']})"):
233
+ if st.button(f"Activate {agent_name}", key=f"activate_{agent_name}"):
234
+ st.session_state.active_agent = agent_name
235
+ st.success(f"{agent_name} activated.")
236
+ if st.button(f"Deactivate {agent_name}", key=f"deactivate_{agent_name}"):
237
+ st.session_state.active_agent = None
238
+ st.success(f"{agent_name} deactivated.")
239
+
240
+ # --- Automate Build Process ---
241
+ st.subheader("Automate Build Process")
242
+ if st.button("Automate"):
243
+ if st.session_state.selected_agents:
244
+ run_autonomous_build(st.session_state.selected_agents, project_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  else:
246
+ st.warning("Please select at least one agent.")
247
+
248
+ # --- Display Information ---
249
+ st.sidebar.subheader("Current State")
250
+ st.sidebar.json(st.session_state.current_state)
251
+ if st.session_state.active_agent:
252
+ display_agent_info(st.session_state.active_agent)
253
+ display_workspace_projects()
254
+ display_chat_history()
255
+
256
+ # --- Gradio Interface ---
257
+ additional_inputs = [
258
+ gr.Dropdown(label="Agents", choices=[s for s in agents.keys()], value=list(agents.keys())[0], interactive=True),
259
+ gr.Textbox(label="System Prompt", max_lines=1, interactive=True),
260
+ gr.Slider(label="Temperature", value=TEMPERATURE, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
261
+ gr.Slider(label="Max new tokens", value=MAX_NEW_TOKENS, minimum=0, maximum=1000*10, step=64, interactive=True, info="The maximum numbers of new tokens"),
262
+ gr.Slider(label="Top-p (nucleus sampling)", value=TOP_P, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens"),
263
+ gr.Slider(label="Repetition penalty", value=REPETITION_PENALTY, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens"),
264
+ ]
265
+
266
+ examples = [
267
+ ["Create a simple web application using Flask", "WEB_DEV"],
268
+ ["Generate a Python script to perform a linear regression analysis", "PYTHON_CODE_DEV"],
269
+ ["Create a Dockerfile for a Node.js application", "AI_SYSTEM_PROMPT"],
270
+ # Add more examples as needed
271
+ ]
272
+
273
+ gr.ChatInterface(
274
+ fn=chat_interface,
275
+ chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
276
+ additional_inputs=additional_inputs,
277
+ title="DevToolKit AI Assistant",
278
+ examples=examples,
279
+ concurrency_limit=20,
280
+ ).launch(show_api=True)