acecalisto3 commited on
Commit
e1f2f22
·
verified ·
1 Parent(s): 43154fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -161
app.py CHANGED
@@ -13,30 +13,32 @@ from rich.progress import track
13
  from rich.table import Table
14
  import subprocess
15
  import threading
 
16
  from langchain.llms import HuggingFaceHub
17
  from langchain.chains import ConversationChain
18
  from langchain.memory import ConversationBufferMemory
19
  from langchain.chains.question_answering import load_qa_chain
20
- from langchain.document_loaders import TextLoader
21
  from langchain.text_splitter import CharacterTextSplitter
22
- from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM, Seq2SeqLMForCausalGeneration
23
-
24
- def create_causal_lm(model_name: str):
25
- tokenizer = AutoTokenizer.from_pretrained(model_name)
26
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name).causal_decoder
27
- return model, tokenizer
28
-
29
- AutoModelForCausalLM = lambda model_name: create_causal_lm(model_name)[0]
30
- AutoTokenizerForCausalLM = lambda model_name: create_causal_lm(model_name)[1]
31
-
32
 
33
  # --- Constants ---
34
- MODEL_NAME = "bigscience/bloom-1b7"
35
- MAX_NEW_TOKENS = 1024
36
  TEMPERATURE = 0.7
37
  TOP_P = 0.95
38
  REPETITION_PENALTY = 1.2
39
 
 
 
 
 
 
 
 
 
 
40
  # --- Agents ---
41
  agents = {
42
  "WEB_DEV": {
@@ -57,22 +59,7 @@ agents = {
57
  "CODE_REVIEW_ASSISTANT": {
58
  "description": "Expert in code review and quality assurance.",
59
  "skills": ["Code Style", "Best Practices", "Security", "Performance", "Maintainability"],
60
- "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.",
61
- },
62
- "CONTENT_WRITER_EDITOR": {
63
- "description": "Expert in content writing and editing.",
64
- "skills": ["Grammar", "Style", "Clarity", "Conciseness", "SEO"],
65
- "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.",
66
- },
67
- "QUESTION_GENERATOR": {
68
- "description": "Expert in generating questions for learning and assessment.",
69
- "skills": ["Question Types", "Cognitive Levels", "Assessment Design"],
70
- "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.",
71
- },
72
- "HUGGINGFACE_FILE_DEV": {
73
- "description": "Expert in developing Hugging Face files for machine learning models.",
74
- "skills": ["Transformers", "Datasets", "Model Training", "Model Deployment"],
75
- "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.",
76
  },
77
  }
78
 
@@ -87,17 +74,8 @@ if "selected_agents" not in st.session_state:
87
  st.session_state.selected_agents = []
88
  if "current_project" not in st.session_state:
89
  st.session_state.current_project = None
90
- if "current_agent" not in st.session_state:
91
- st.session_state.current_agent = None
92
- if "current_cluster" not in st.session_state:
93
- st.session_state.current_cluster = None
94
- if "hf_token" not in st.session_state:
95
- st.session_state.hf_token = None
96
- if "repo_name" not in st.session_state:
97
- st.session_state.repo_name = None
98
- if "selected_model" not in st.session_state:
99
- st.session_state.selected_model = None
100
 
 
101
  def add_code_to_workspace(project_name: str, code: str, file_name: str):
102
  if project_name in st.session_state.workspace_projects:
103
  st.session_state.workspace_projects[project_name]['files'].append({'file_name': file_name, 'code': code})
@@ -112,19 +90,59 @@ def terminal_interface(command: str, project_name: str):
112
  else:
113
  return f"Project {project_name} does not exist"
114
 
115
- def chat_interface(message: str, selected_agents: List[str]):
116
- responses = {}
117
- for agent in selected_agents:
118
- responses[agent] = get_agent_response(message, agents[agent]['system_prompt'])
119
- return responses
120
-
121
  def get_agent_response(message: str, system_prompt: str):
122
- llm = HuggingFaceHub(repo_id=MODEL_NAME, model_kwargs={"temperature": TEMPERATURE, "top_p": TOP_P, "repetition_penalty": REPETITION_PENALTY})
123
  memory = ConversationBufferMemory()
124
  conversation = ConversationChain(llm=llm, memory=memory)
125
  response = conversation.run(system_prompt + "\n" + message)
126
  return response
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  # --- Streamlit UI ---
129
  st.title("DevToolKit: AI-Powered Development Environment")
130
 
@@ -132,26 +150,45 @@ st.title("DevToolKit: AI-Powered Development Environment")
132
  st.header("Project Management")
133
  project_name = st.text_input("Enter project name:")
134
  if st.button("Create Project"):
135
- if project_name not in st.session_state.workspace_projects:
136
  st.session_state.workspace_projects[project_name] = {'files': []}
137
  st.success(f"Created project: {project_name}")
138
- else:
139
  st.warning(f"Project {project_name} already exists")
140
-
141
- # --- Code Addition ---
142
- st.subheader("Add Code to Workspace")
143
- code_to_add = st.text_area("Enter code to add to workspace:")
144
- file_name = st.text_input("Enter file name (e.g. 'app.py'):")
145
- if st.button("Add Code"):
146
- add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
147
- st.success(add_code_status)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  # --- Terminal Interface ---
150
  st.subheader("Terminal (Workspace Context)")
151
- terminal_input = st.text_input("Enter a command within the workspace:")
152
- if st.button("Run Command"):
153
- terminal_output = terminal_interface(terminal_input, project_name)
154
- st.code(terminal_output, language="bash")
 
 
 
 
155
 
156
  # --- Chat Interface ---
157
  st.subheader("Chat with AI Agents")
@@ -159,8 +196,17 @@ selected_agents = st.multiselect("Select AI agents", list(agents.keys()), key="a
159
  st.session_state.selected_agents = selected_agents
160
  agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
161
  if st.button("Send to Agents", key="agent_send"):
162
- agent_chat_response = chat_interface(agent_chat_input, selected_agents)
163
- st.write(agent_chat_response)
 
 
 
 
 
 
 
 
 
164
 
165
  # --- Agent Control ---
166
  st.subheader("Agent Control")
@@ -177,10 +223,34 @@ for agent_name in agents:
177
  # --- Automate Build Process ---
178
  st.subheader("Automate Build Process")
179
  if st.button("Automate"):
180
- if st.session_state.selected_agents:
181
  run_autonomous_build(st.session_state.selected_agents, project_name)
182
  else:
183
- st.warning("Please select at least one agent.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  # --- Display Information ---
186
  st.sidebar.subheader("Current State")
@@ -190,100 +260,6 @@ if st.session_state.active_agent:
190
  display_workspace_projects()
191
  display_chat_history()
192
 
193
- # --- Gradio Interface ---
194
- additional_inputs = [
195
- gr.Dropdown(label="Agents", choices=[s for s in agents.keys()], value=list(agents.keys())[0], interactive=True),
196
- gr.Textbox(label="System Prompt", max_lines=1, interactive=True),
197
- gr.Slider(label="Temperature", value=TEMPERATURE, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
198
- gr.Slider(label="Max new tokens", value=MAX_NEW_TOKENS, minimum=0, maximum=10240, step=64, interactive=True, info="The maximum numbers of new tokens"),
199
- 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"),
200
- gr.Slider(label="Repetition penalty", value=REPETITION_PENALTY, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens"),
201
- ]
202
-
203
- examples = [
204
- ["Create a simple web application using Flask", "WEB_DEV"],
205
- ["Generate a Python script to perform a linear regression analysis", "PYTHON_CODE_DEV"],
206
- ["Create a Dockerfile for a Node.js application", "AI_SYSTEM_PROMPT"],
207
- # Add more examples as needed
208
- ]
209
-
210
- gr.ChatInterface(
211
- fn=chat_interface,
212
- chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
213
- additional_inputs=additional_inputs,
214
- title="DevToolKit AI Assistant",
215
- examples=examples,
216
- concurrency_limit=20,
217
- ).launch(show_api=True)
218
-
219
- # --- Helper Functions ---
220
-
221
- def display_agent_info(agent_name: str):
222
- agent = agents[agent_name]
223
- st.sidebar.subheader(f"Active Agent: {agent_name}")
224
- st.sidebar.write(f"Description: {agent['description']}")
225
- st.sidebar.write(f"Skills: {', '.join(agent['skills'])}")
226
-
227
- def display_workspace_projects():
228
- st.sidebar.subheader("Workspace Projects")
229
- if st.session_state.workspace_projects:
230
- for project_name in st.session_state.workspace_projects:
231
- st.sidebar.write(f"- {project_name}")
232
- else:
233
- st.sidebar.write("No projects created yet.")
234
-
235
- def display_chat_history():
236
- st.sidebar.subheader("Chat History")
237
- if st.session_state.chat_history:
238
- for message in st.session_state.chat_history:
239
- st.sidebar.write(message)
240
- else:
241
- st.sidebar.write("No chat history yet.")
242
-
243
- def run_autonomous_build(selected_agents: List[str], project_name: str):
244
- # This function should implement the autonomous build process
245
- # It should use the selected agents and the project name to generate code and run commands
246
- # You can use the `get_agent_response` function to get responses from agents
247
- # You can use the `add_code_to_workspace` and `terminal_interface` functions to manage the workspace
248
- st.write("Running autonomous build...")
249
- for agent in selected_agents:
250
- # Example: Get code from the agent
251
- code = get_agent_response(f"Generate code for a simple web application in project {project_name}", agents[agent]['system_prompt'])
252
- # Example: Add code to the workspace
253
- add_code_to_workspace(project_name, code, "app.py")
254
- # Example: Run a command in the workspace
255
- terminal_interface("python app.py", project_name)
256
- st.write("Autonomous build completed.")
257
-
258
- # --- Collaborative Agent Example ---
259
-
260
- def collaborative_agent_example(selected_agents: List[str], project_name: str, task: str):
261
- # Example: Collaborative code generation
262
- st.write(f"Running collaborative task: {task}")
263
- responses = []
264
- for agent in selected_agents:
265
- response = get_agent_response(f"As a {agent}, please contribute to the following task: {task}", agents[agent]['system_prompt'])
266
- responses.append(response)
267
-
268
- # Combine responses and process them
269
- combined_response = "\n".join(responses)
270
- st.write(f"Combined response:\n{combined_response}")
271
-
272
- # Example: Use code review agent for feedback
273
- if "CODE_REVIEW_ASSISTANT" in selected_agents:
274
- review_response = get_agent_response(f"Review the following code and provide feedback: {combined_response}", agents["CODE_REVIEW_ASSISTANT"]['system_prompt'])
275
- st.write(f"Code Review Feedback:\n{review_response}")
276
-
277
- # Example: Use content writer for documentation
278
- if "CONTENT_WRITER_EDITOR" in selected_agents:
279
- documentation_response = get_agent_response(f"Generate documentation for the following code: {combined_response}", agents["CONTENT_WRITER_EDITOR"]['system_prompt'])
280
- st.write(f"Documentation:\n{documentation_response}")
281
-
282
- # --- Streamlit UI for Collaborative Agent Example ---
283
-
284
- st.subheader("Collaborative Agent Example")
285
- selected_agents_example = st.multiselect("Select AI agents for collaboration", list(agents.keys()), key="agent_select_example")
286
- project_name_example = st.text_input("Enter project name (for example purposes):")
287
- task_example = st.text_input("Enter a task for the agents to collaborate on:")
288
- if st.button("Run Collaborative Task"):
289
- collaborative_agent_example(selected_agents_example, project_name_example, task_example)
 
13
  from rich.table import Table
14
  import subprocess
15
  import threading
16
+ import git
17
  from langchain.llms import HuggingFaceHub
18
  from langchain.chains import ConversationChain
19
  from langchain.memory import ConversationBufferMemory
20
  from langchain.chains.question_answering import load_qa_chain
 
21
  from langchain.text_splitter import CharacterTextSplitter
22
+ from langchain_community.document_loaders import TextLoader
23
+ from streamlit_ace import st_ace
24
+ from streamlit_chat import st_chat
 
 
 
 
 
 
 
25
 
26
  # --- Constants ---
27
+ MODEL_NAME = "google/flan-t5-xl" # Consider using a more powerful model like 'google/flan-t5-xl'
28
+ MAX_NEW_TOKENS = 2048 # Increased for better code generation
29
  TEMPERATURE = 0.7
30
  TOP_P = 0.95
31
  REPETITION_PENALTY = 1.2
32
 
33
+ # --- Model & Tokenizer ---
34
+ @st.cache_resource
35
+ def load_model_and_tokenizer():
36
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto") # Use 'auto' for optimal device selection
37
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
38
+ return model, tokenizer
39
+
40
+ model, tokenizer = load_model_and_tokenizer()
41
+
42
  # --- Agents ---
43
  agents = {
44
  "WEB_DEV": {
 
59
  "CODE_REVIEW_ASSISTANT": {
60
  "description": "Expert in code review and quality assurance.",
61
  "skills": ["Code Style", "Best Practices", "Security", "Performance", "Maintainability"],
62
+ "system_prompt": "You are a code review expert. Your goal is to assist the user in reviewing and improving their code. Provide feedback on code quality, style, and best practices.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  },
64
  }
65
 
 
74
  st.session_state.selected_agents = []
75
  if "current_project" not in st.session_state:
76
  st.session_state.current_project = None
 
 
 
 
 
 
 
 
 
 
77
 
78
+ # --- Helper Functions ---
79
  def add_code_to_workspace(project_name: str, code: str, file_name: str):
80
  if project_name in st.session_state.workspace_projects:
81
  st.session_state.workspace_projects[project_name]['files'].append({'file_name': file_name, 'code': code})
 
90
  else:
91
  return f"Project {project_name} does not exist"
92
 
 
 
 
 
 
 
93
  def get_agent_response(message: str, system_prompt: str):
94
+ llm = HuggingFaceHub(repo_id=MODEL_NAME, model_kwargs={"temperature": TEMPERATURE, "top_p": TOP_P, "repetition_penalty": REPETITION_PENALTY, "max_length": MAX_NEW_TOKENS})
95
  memory = ConversationBufferMemory()
96
  conversation = ConversationChain(llm=llm, memory=memory)
97
  response = conversation.run(system_prompt + "\n" + message)
98
  return response
99
 
100
+ def display_agent_info(agent_name: str):
101
+ agent = agents[agent_name]
102
+ st.sidebar.subheader(f"Active Agent: {agent_name}")
103
+ st.sidebar.write(f"Description: {agent['description']}")
104
+ st.sidebar.write(f"Skills: {', '.join(agent['skills'])}")
105
+
106
+ def display_workspace_projects():
107
+ st.subheader("Workspace Projects")
108
+ for project_name, project_data in st.session_state.workspace_projects.items():
109
+ with st.expander(project_name):
110
+ for file in project_data['files']:
111
+ st.text(file['file_name'])
112
+ st.code(file['code'], language="python")
113
+
114
+ def display_chat_history():
115
+ st.subheader("Chat History")
116
+ for message in st.session_state.chat_history:
117
+ st.text(message)
118
+
119
+ def run_autonomous_build(selected_agents: List[str], project_name: str):
120
+ st.info("Starting autonomous build process...")
121
+ for agent in selected_agents:
122
+ st.write(f"Agent {agent} is working on the project...")
123
+ code = get_agent_response(f"Generate code for a simple web application in project {project_name}", agents[agent]['system_prompt'])
124
+ add_code_to_workspace(project_name, code, f"{agent.lower()}_app.py")
125
+ st.write(f"Agent {agent} has completed its task.")
126
+ st.success("Autonomous build process completed!")
127
+
128
+ def collaborative_agent_example(selected_agents: List[str], project_name: str, task: str):
129
+ st.info(f"Starting collaborative task: {task}")
130
+ responses = {}
131
+ for agent in selected_agents:
132
+ st.write(f"Agent {agent} is working on the task...")
133
+ response = get_agent_response(task, agents[agent]['system_prompt'])
134
+ responses[agent] = response
135
+
136
+ combined_response = combine_and_process_responses(responses, task)
137
+ st.success("Collaborative task completed!")
138
+ st.write(combined_response)
139
+
140
+ def combine_and_process_responses(responses: Dict[str, str], task: str) -> str:
141
+ # This is a placeholder function. In a real-world scenario, you would implement
142
+ # more sophisticated logic to combine and process the responses.
143
+ combined = "\n\n".join([f"{agent}: {response}" for agent, response in responses.items()])
144
+ return f"Combined response for task '{task}':\n\n{combined}"
145
+
146
  # --- Streamlit UI ---
147
  st.title("DevToolKit: AI-Powered Development Environment")
148
 
 
150
  st.header("Project Management")
151
  project_name = st.text_input("Enter project name:")
152
  if st.button("Create Project"):
153
+ if project_name and project_name not in st.session_state.workspace_projects:
154
  st.session_state.workspace_projects[project_name] = {'files': []}
155
  st.success(f"Created project: {project_name}")
156
+ elif project_name in st.session_state.workspace_projects:
157
  st.warning(f"Project {project_name} already exists")
158
+ else:
159
+ st.warning("Please enter a project name")
160
+
161
+ # --- Code Editor ---
162
+ st.subheader("Code Editor")
163
+ if st.session_state.workspace_projects:
164
+ selected_project = st.selectbox("Select project", list(st.session_state.workspace_projects.keys()))
165
+ if selected_project:
166
+ files = [file['file_name'] for file in st.session_state.workspace_projects[selected_project]['files']]
167
+ selected_file = st.selectbox("Select file to edit", files) if files else None
168
+ if selected_file:
169
+ file_content = next((file['code'] for file in st.session_state.workspace_projects[selected_project]['files'] if file['file_name'] == selected_file), "")
170
+ edited_code = st_ace(value=file_content, language="python", theme="monokai", key="code_editor")
171
+ if st.button("Save Changes"):
172
+ for file in st.session_state.workspace_projects[selected_project]['files']:
173
+ if file['file_name'] == selected_file:
174
+ file['code'] = edited_code
175
+ st.success("Changes saved successfully!")
176
+ break
177
+ else:
178
+ st.info("No files in the project. Use the chat interface to generate code.")
179
+ else:
180
+ st.info("No projects created yet. Create a project to start coding.")
181
 
182
  # --- Terminal Interface ---
183
  st.subheader("Terminal (Workspace Context)")
184
+ if st.session_state.workspace_projects:
185
+ selected_project = st.selectbox("Select project for terminal", list(st.session_state.workspace_projects.keys()))
186
+ terminal_input = st.text_input("Enter a command within the workspace:")
187
+ if st.button("Run Command"):
188
+ terminal_output = terminal_interface(terminal_input, selected_project)
189
+ st.code(terminal_output, language="bash")
190
+ else:
191
+ st.info("No projects created yet. Create a project to use the terminal.")
192
 
193
  # --- Chat Interface ---
194
  st.subheader("Chat with AI Agents")
 
196
  st.session_state.selected_agents = selected_agents
197
  agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
198
  if st.button("Send to Agents", key="agent_send"):
199
+ if selected_agents and agent_chat_input:
200
+ responses = {}
201
+ for agent in selected_agents:
202
+ response = get_agent_response(agent_chat_input, agents[agent]['system_prompt'])
203
+ responses[agent] = response
204
+ st.session_state.chat_history.append(f"User: {agent_chat_input}")
205
+ for agent, response in responses.items():
206
+ st.session_state.chat_history.append(f"{agent}: {response}")
207
+ st_chat(st.session_state.chat_history) # Display chat history using st_chat
208
+ else:
209
+ st.warning("Please select at least one agent and enter a message.")
210
 
211
  # --- Agent Control ---
212
  st.subheader("Agent Control")
 
223
  # --- Automate Build Process ---
224
  st.subheader("Automate Build Process")
225
  if st.button("Automate"):
226
+ if st.session_state.selected_agents and project_name:
227
  run_autonomous_build(st.session_state.selected_agents, project_name)
228
  else:
229
+ st.warning("Please select at least one agent and create a project.")
230
+
231
+ # --- Version Control ---
232
+ st.subheader("Version Control")
233
+ repo_url = st.text_input("Enter repository URL:")
234
+ if st.button("Clone Repository"):
235
+ if repo_url and project_name:
236
+ try:
237
+ git.Repo.clone_from(repo_url, project_name)
238
+ st.success(f"Repository cloned successfully to {project_name}")
239
+ except git.GitCommandError as e:
240
+ st.error(f"Error cloning repository: {e}")
241
+ else:
242
+ st.warning("Please enter a repository URL and create a project.")
243
+
244
+ # --- Collaborative Agent Example ---
245
+ st.subheader("Collaborative Agent Example")
246
+ collab_agents = st.multiselect("Select AI agents for collaboration", list(agents.keys()), key="collab_agent_select")
247
+ collab_project = st.text_input("Enter project name for collaboration:")
248
+ collab_task = st.text_input("Enter a task for the agents to collaborate on:")
249
+ if st.button("Run Collaborative Task"):
250
+ if collab_agents and collab_project and collab_task:
251
+ collaborative_agent_example(collab_agents, collab_project, collab_task)
252
+ else:
253
+ st.warning("Please select agents, enter a project name, and specify a task.")
254
 
255
  # --- Display Information ---
256
  st.sidebar.subheader("Current State")
 
260
  display_workspace_projects()
261
  display_chat_history()
262
 
263
+ if __name__ == "__main__":
264
+ st.sidebar.title("DevToolKit")
265
+ st.sidebar.info("This is an AI-powered development environment.")