acecalisto3 commited on
Commit
9a0589c
·
verified ·
1 Parent(s): d85bce5

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +249 -0
app2.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import gradio as gr
3
+ from sqlalchemy.exc import SQLAlchemyError
4
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
5
+ from sqlalchemy.future import select # Correct async query API
6
+ from sqlalchemy.orm import sessionmaker
7
+ import logging
8
+ import os
9
+ import sys
10
+ import subprocess
11
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
12
+ import openai
13
+ import streamlit as st
14
+ from io import StringIO
15
+ from rich import print as rprint
16
+ from rich.panel import Panel
17
+ from rich.progress import track
18
+ from rich.table import Table
19
+ import git
20
+ from langchain.llms import HuggingFaceHub
21
+ from langchain.chains import ConversationChain
22
+ from langchain.memory import ConversationBufferMemory
23
+
24
+ # Constants
25
+ MODEL_NAME = "google/flan-t5-xl"
26
+ MAX_NEW_TOKENS = 2048
27
+ TEMPERATURE = 0.7
28
+ TOP_P = 0.95
29
+ REPETITION_PENALTY = 1.2
30
+
31
+ # Load Model and Tokenizer
32
+ @st.cache_resource
33
+ def load_model_and_tokenizer():
34
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")
35
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
36
+ return model, tokenizer
37
+
38
+ model, tokenizer = load_model_and_tokenizer()
39
+
40
+ # Agents
41
+ agents = {
42
+ "WEB_DEV": {
43
+ "description": "Expert in web development technologies and frameworks.",
44
+ "skills": ["HTML", "CSS", "JavaScript", "React", "Vue.js", "Flask", "Django", "Node.js", "Express.js"],
45
+ "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.",
46
+ },
47
+ "AI_SYSTEM_PROMPT": {
48
+ "description": "Expert in designing and implementing AI systems.",
49
+ "skills": ["Machine Learning", "Deep Learning", "Natural Language Processing", "Computer Vision", "Reinforcement Learning"],
50
+ "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.",
51
+ },
52
+ "PYTHON_CODE_DEV": {
53
+ "description": "Expert in Python programming and development.",
54
+ "skills": ["Python", "Data Structures", "Algorithms", "Object-Oriented Programming", "Functional Programming"],
55
+ "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.",
56
+ },
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 expert. Your goal is to assist the user in reviewing and improving their code. Provide feedback on code quality, style, and best practices.",
61
+ },
62
+ }
63
+
64
+ # Session State
65
+ if "workspace_projects" not in st.session_state:
66
+ st.session_state.workspace_projects = {}
67
+ if "chat_history" not in st.session_state:
68
+ st.session_state.chat_history = []
69
+ if "active_agent" not in st.session_state:
70
+ st.session_state.active_agent = None
71
+ if "selected_agents" not in st.session_state:
72
+ st.session_state.selected_agents = []
73
+ if "current_project" not in st.session_state:
74
+ st.session_state.current_project = None
75
+
76
+ # Helper Functions
77
+ def add_code_to_workspace(project_name: str, code: str, file_name: str):
78
+ if project_name in st.session_state.workspace_projects:
79
+ st.session_state.workspace_projects[project_name]['files'].append({'file_name': file_name, 'code': code})
80
+ return f"Added code to {file_name} in project {project_name}"
81
+ else:
82
+ return f"Project {project_name} does not exist"
83
+
84
+ def terminal_interface(command: str, project_name: str):
85
+ if project_name in st.session_state.workspace_projects:
86
+ result = subprocess.run(command, cwd=project_name, shell=True, capture_output=True, text=True)
87
+ return result.stdout + result.stderr
88
+ else:
89
+ return f"Project {project_name} does not exist"
90
+
91
+ def get_agent_response(message: str, system_prompt: str):
92
+ llm = HuggingFaceHub(repo_id=MODEL_NAME, model_kwargs={"temperature": TEMPERATURE, "top_p": TOP_P, "repetition_penalty": REPETITION_PENALTY, "max_length": MAX_NEW_TOKENS})
93
+ memory = ConversationBufferMemory()
94
+ conversation = ConversationChain(llm=llm, memory=memory)
95
+ response = conversation.run(system_prompt + "\n" + message)
96
+ return response
97
+
98
+ def display_agent_info(agent_name: str):
99
+ agent = agents[agent_name]
100
+ st.sidebar.subheader(f"Active Agent: {agent_name}")
101
+ st.sidebar.write(f"Description: {agent['description']}")
102
+ st.sidebar.write(f"Skills: {', '.join(agent['skills'])}")
103
+
104
+ def display_workspace_projects():
105
+ st.subheader("Workspace Projects")
106
+ for project_name, project_data in st.session_state.workspace_projects.items():
107
+ with st.expander(project_name):
108
+ for file in project_data['files']:
109
+ st.text(file['file_name'])
110
+ st.code(file['code'], language="python")
111
+
112
+ def display_chat_history():
113
+ st.subheader("Chat History")
114
+ for message in st.session_state.chat_history:
115
+ st.text(message)
116
+
117
+ def run_autonomous_build(selected_agents: List[str], project_name: str):
118
+ st.info("Starting autonomous build process...")
119
+ for agent in selected_agents:
120
+ st.write(f"Agent {agent} is working on the project...")
121
+ code = get_agent_response(f"Generate code for a simple web application in project {project_name}", agents[agent]['system_prompt'])
122
+ add_code_to_workspace(project_name, code, f"{agent.lower()}_app.py")
123
+ st.write(f"Agent {agent} has completed its task.")
124
+ st.success("Autonomous build process completed!")
125
+
126
+ def collaborative_agent_example(selected_agents: List[str], project_name: str, task: str):
127
+ st.info(f"Starting collaborative task: {task}")
128
+ responses = {}
129
+ for agent in selected_agents:
130
+ st.write(f"Agent {agent} is working on the task...")
131
+ response = get_agent_response(task, agents[agent]['system_prompt'])
132
+ responses[agent] = response
133
+
134
+ combined_response = combine_and_process_responses(responses, task)
135
+ st.success("Collaborative task completed!")
136
+ st.write(combined_response)
137
+
138
+ def combine_and_process_responses(responses: Dict[str, str], task: str) -> str:
139
+ combined = "\n\n".join([f"{agent}: {response}" for agent, response in responses.items()])
140
+ return f"Combined response for task '{task}':\n\n{combined}"
141
+
142
+ # Streamlit UI
143
+ st.title("DevToolKit: AI-Powered Development Environment")
144
+
145
+ # Project Management
146
+ st.header("Project Management")
147
+ project_name = st.text_input("Enter project name:")
148
+ if st.button("Create Project"):
149
+ if project_name and project_name not in st.session_state.workspace_projects:
150
+ st.session_state.workspace_projects[project_name] = {'files': []}
151
+ st.success(f"Created project: {project_name}")
152
+ elif project_name in st.session_state.workspace_projects:
153
+ st.warning(f"Project {project_name} already exists")
154
+ else:
155
+ st.warning("Please enter a project name")
156
+
157
+ # Code Editor
158
+ st.subheader("Code Editor")
159
+ if st.session_state.workspace_projects:
160
+ selected_project = st.selectbox("Select project", list(st.session_state.workspace_projects.keys()))
161
+ if selected_project:
162
+ files = [file['file_name'] for file in st.session_state.workspace_projects[selected_project]['files']]
163
+ selected_file = st.selectbox("Select file to edit", files) if files else None
164
+ if selected_file:
165
+ file_content = next((file['code'] for file in st.session_state.workspace_projects[selected_project]['files'] if file['file_name'] == selected_file), "")
166
+ edited_code = st_ace(value=file_content, language="python", theme="monokai", key="code_editor")
167
+ if st.button("Save Changes"):
168
+ for file in st.session_state.workspace_projects[selected_project]['files']:
169
+ if file['file_name'] == selected_file:
170
+ file['code'] = edited_code
171
+ st.success("Changes saved successfully!")
172
+ break
173
+ else:
174
+ st.info("No files in the project. Use the chat interface to generate code.")
175
+ else:
176
+ st.info("No projects created yet. Create a project to start coding.")
177
+
178
+ # Terminal Interface
179
+ st.subheader("Terminal (Workspace Context)")
180
+ if st.session_state.workspace_projects:
181
+ selected_project = st.selectbox("Select project for terminal", list(st.session_state.workspace_projects.keys()))
182
+ terminal_input = st.text_input("Enter a command within the workspace:")
183
+ if st.button("Run Command"):
184
+ terminal_output = terminal_interface(terminal_input, selected_project)
185
+ st.code(terminal_output, language="bash")
186
+ else:
187
+ st.info("No projects created yet. Create a project to use the terminal.")
188
+
189
+ # Chat Interface
190
+ st.subheader("Chat with AI Agents")
191
+ selected_agents = st.multiselect("Select AI agents", list(agents.keys()), key="agent_select")
192
+ st.session_state.selected_agents = selected_agents
193
+ agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
194
+ if st.button("Send to Agents", key="agent_send"):
195
+ if selected_agents and agent_chat_input:
196
+ responses = {}
197
+ for agent in selected_agents:
198
+ response = get_agent_response(agent_chat_input, agents[agent]['system_prompt'])
199
+ responses[agent] = response
200
+ st.session_state.chat_history.append(f"User: {agent_chat_input}")
201
+ for agent, response in responses.items():
202
+ st.session_state.chat_history.append(f"{agent}: {response}")
203
+ st.text_area("Chat History", value='\n'.join(st.session_state.chat_history), height=300)
204
+ else:
205
+ st.warning("Please select at least one agent and enter a message.")
206
+
207
+ # Agent Control
208
+ st.subheader("Agent Control")
209
+ for agent_name in agents:
210
+ agent = agents[agent_name]
211
+ with st.expander(f"{agent_name} ({agent['description']})"):
212
+ if st.button(f"Activate {agent_name}", key=f"activate_{agent_name}"):
213
+ st.session_state.active_agent = agent_name
214
+ st.success(f"{agent_name} activated.")
215
+ if st.button(f"Deactivate {agent_name}", key=f"deactivate_{agent_name}"):
216
+ st.session_state.active_agent = None
217
+ st.success(f"{agent_name} deactivated.")
218
+
219
+ # Automate Build Process
220
+ st.subheader("Automate Build Process")
221
+ if st.button("Automate"):
222
+ if st.session_state.selected_agents and project_name:
223
+ run_autonomous_build(st.session_state.selected_agents, project_name)
224
+ else:
225
+ st.warning("Please select at least one agent and create a project.")
226
+
227
+ # Version Control
228
+ st.subheader("Version Control")
229
+ repo_url = st.text_input("Enter repository URL:")
230
+ if st.button("Clone Repository"):
231
+ if repo_url and project_name:
232
+ try:
233
+ git.Repo.clone_from(repo_url, project_name)
234
+ st.success(f"Repository cloned successfully to {project_name}")
235
+ except git.GitCommandError as e:
236
+ st.error(f"Error cloning repository: {e}")
237
+ else:
238
+ st.warning("Please enter a repository URL and create a project.")
239
+
240
+ # Collaborative Agent Example
241
+ st.subheader("Collaborative Agent Example")
242
+ collab_agents = st.multiselect("Select AI agents for collaboration", list(agents.keys()), key="collab_agent_select")
243
+ collab_project = st.text_input("Enter project name for collaboration:")
244
+ collab_task = st.text_input("Enter collaborative task:")
245
+ if st.button("Start Collaborative Task"):
246
+ if collab_agents and collab_project and collab_task:
247
+ collaborative_agent_example(collab_agents, collab_project, collab_task)
248
+ else:
249
+ st.warning("Please select agents, enter a project name, and a task.")