acecalisto3 commited on
Commit
dc81bad
·
verified ·
1 Parent(s): 20947d8

Update app2.py

Browse files
Files changed (1) hide show
  1. app2.py +220 -214
app2.py CHANGED
@@ -1,229 +1,235 @@
1
  import streamlit as st
2
- from langchain.llms import GoogleSearchAPIWrapper
3
  from langchain.chains import ConversationChain
4
  from langchain.memory import ConversationBufferMemory
5
  import subprocess
6
  import git
7
 
8
- # Replace with your actual Google Search API key
9
- GOOGLE_API_KEY = "YOUR_API_KEY"
10
-
11
- # Initialize Google Search API Wrapper
12
- search = GoogleSearchAPIWrapper(google_api_key=GOOGLE_API_KEY)
13
-
14
- # Agents
15
- agents = {
16
- "WEB_DEV": {
17
- "description": "Expert in web development technologies and frameworks.",
18
- "skills": ["HTML", "CSS", "JavaScript", "React", "Vue.js", "Flask", "Django", "Node.js", "Express.js"],
19
- "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.",
20
- },
21
- "AI_SYSTEM_PROMPT": {
22
- "description": "Expert in designing and implementing AI systems.",
23
- "skills": ["Machine Learning", "Deep Learning", "Natural Language Processing", "Computer Vision", "Reinforcement Learning"],
24
- "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.",
25
- },
26
- "PYTHON_CODE_DEV": {
27
- "description": "Expert in Python programming and development.",
28
- "skills": ["Python", "Data Structures", "Algorithms", "Object-Oriented Programming", "Functional Programming"],
29
- "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.",
30
- },
31
- "CODE_REVIEW_ASSISTANT": {
32
- "description": "Expert in code review and quality assurance.",
33
- "skills": ["Code Style", "Best Practices", "Security", "Performance", "Maintainability"],
34
- "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.",
35
- },
36
- }
37
-
38
- # Session State
39
- if "workspace_projects" not in st.session_state:
40
- st.session_state.workspace_projects = {}
41
- if "chat_history" not in st.session_state:
42
- st.session_state.chat_history = []
43
- if "active_agent" not in st.session_state:
44
- st.session_state.active_agent = None
45
- if "selected_agents" not in st.session_state:
46
- st.session_state.selected_agents = []
47
- if "current_project" not in st.session_state:
48
- st.session_state.current_project = None
49
-
50
- # Helper Functions
51
- def add_code_to_workspace(project_name: str, code: str, file_name: str):
52
- if project_name in st.session_state.workspace_projects:
53
- st.session_state.workspace_projects[project_name]['files'].append({'file_name': file_name, 'code': code})
54
- return f"Added code to {file_name} in project {project_name}"
55
- else:
56
- return f"Project {project_name} does not exist"
57
-
58
- def terminal_interface(command: str, project_name: str):
59
- try:
60
  if project_name in st.session_state.workspace_projects:
61
- result = subprocess.run(command, cwd=project_name, shell=True, capture_output=True, text=True)
62
- return result.stdout + result.stderr
63
  else:
64
  return f"Project {project_name} does not exist"
65
- except FileNotFoundError:
66
- return f"Error: Command not found. Please check your command."
67
- except Exception as e:
68
- logging.error(f"An error occurred: {e}")
69
- return f"An unexpected error occurred while running the command."
70
-
71
- def get_agent_response(message: str, system_prompt: str):
72
- llm = GoogleSearchAPIWrapper(google_api_key=GOOGLE_API_KEY)
73
- memory = ConversationBufferMemory()
74
- conversation = ConversationChain(llm=llm, memory=memory)
75
- response = conversation.run(system_prompt + "\n" + message)
76
- return response
77
-
78
- def display_agent_info(agent_name: str):
79
- agent = agents[agent_name]
80
- st.sidebar.subheader(f"Active Agent: {agent_name}")
81
- st.sidebar.write(f"Description: {agent['description']}")
82
- st.sidebar.write(f"Skills: {', '.join(agent['skills'])}")
83
-
84
- def display_workspace_projects():
85
- st.subheader("Workspace Projects")
86
- for project_name, project_data in st.session_state.workspace_projects.items():
87
- with st.expander(project_name):
88
- for file in project_data['files']:
89
- st.text(file['file_name'])
90
- st.code(file['code'], language="python")
91
-
92
- def display_chat_history():
93
- st.subheader("Chat History")
94
- for message in st.session_state.chat_history:
95
- st.text(message)
96
-
97
- def run_autonomous_build(selected_agents: list[str], project_name: str):
98
- st.info("Starting autonomous build process...")
99
- for agent in selected_agents:
100
- st.write(f"Agent {agent} is working on the project...")
101
- code = get_agent_response(f"Generate code for a simple web application in project {project_name}", agents[agent]['system_prompt'])
102
- add_code_to_workspace(project_name, code, f"{agent.lower()}_app.py")
103
- st.write(f"Agent {agent} has completed its task.")
104
- st.success("Autonomous build process completed!")
105
-
106
- def collaborative_agent_example(selected_agents: list[str], project_name: str, task: str):
107
- st.info(f"Starting collaborative task: {task}")
108
- responses = {}
109
- for agent in selected_agents:
110
- st.write(f"Agent {agent} is working on the task...")
111
- response = get_agent_response(task, agents[agent]['system_prompt'])
112
- responses[agent] = response
113
-
114
- combined_response = combine_and_process_responses(responses, task)
115
- st.success("Collaborative task completed!")
116
- st.write(combined_response)
117
-
118
- def combine_and_process_responses(responses: dict[str, str], task: str) -> str:
119
- combined = "\n\n".join([f"{agent}: {response}" for agent, response in responses.items()])
120
- return f"Combined response for task '{task}':\n\n{combined}"
121
-
122
- # Streamlit UI
123
- st.title("DevToolKit: AI-Powered Development Environment")
124
-
125
- # Project Management
126
- st.header("Project Management")
127
- project_name = st.text_input("Enter project name:")
128
- if st.button("Create Project"):
129
- if project_name and project_name not in st.session_state.workspace_projects:
130
- st.session_state.workspace_projects[project_name] = {'files': []}
131
- st.success(f"Created project: {project_name}")
132
- elif project_name in st.session_state.workspace_projects:
133
- st.warning(f"Project {project_name} already exists")
134
- else:
135
- st.warning("Please enter a project name")
136
-
137
- # Code Editor
138
- st.subheader("Code Editor")
139
- if st.session_state.workspace_projects:
140
- selected_project = st.selectbox("Select project", list(st.session_state.workspace_projects.keys()))
141
- if selected_project:
142
- files = [file['file_name'] for file in st.session_state.workspace_projects[selected_project]['files']]
143
- selected_file = st.selectbox("Select file to edit", files) if files else None
144
- if selected_file:
145
- file_content = next((file['code'] for file in st.session_state.workspace_projects[selected_project]['files'] if file['file_name'] == selected_file), "")
146
- edited_code = st.text_area("Edit code", value=file_content, height=300) # Using st.text_area for now
147
- if st.button("Save Changes"):
148
- for file in st.session_state.workspace_projects[selected_project]['files']:
149
- if file['file_name'] == selected_file:
150
- file['code'] = edited_code
151
- st.success("Changes saved successfully!")
152
- break
153
- else:
154
- st.info("No files in the project. Use the chat interface to generate code.")
155
- else:
156
- st.info("No projects created yet. Create a project to start coding.")
157
-
158
- # Terminal Interface
159
- st.subheader("Terminal (Workspace Context)")
160
- if st.session_state.workspace_projects:
161
- selected_project = st.selectbox("Select project for terminal", list(st.session_state.workspace_projects.keys()))
162
- terminal_input = st.text_input("Enter a command within the workspace:")
163
- if st.button("Run Command"):
164
- terminal_output = terminal_interface(terminal_input, selected_project)
165
- st.code(terminal_output, language="bash")
166
- else:
167
- st.info("No projects created yet. Create a project to use the terminal.")
168
-
169
- # Chat Interface
170
- st.subheader("Chat with AI Agents")
171
- selected_agents = st.multiselect("Select AI agents", list(agents.keys()), key="agent_select")
172
- st.session_state.selected_agents = selected_agents
173
- agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
174
- if st.button("Send to Agents", key="agent_send"):
175
- if selected_agents and agent_chat_input:
176
  responses = {}
177
  for agent in selected_agents:
178
- response = get_agent_response(agent_chat_input, agents[agent]['system_prompt'])
 
179
  responses[agent] = response
180
- st.session_state.chat_history.append(f"User: {agent_chat_input}")
181
- for agent, response in responses.items():
182
- st.session_state.chat_history.append(f"{agent}: {response}")
183
- st.text_area("Chat History", value='\n'.join(st.session_state.chat_history), height=300)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  else:
185
- st.warning("Please select at least one agent and enter a message.")
186
-
187
- # Agent Control
188
- st.subheader("Agent Control")
189
- for agent_name in agents:
190
- agent = agents[agent_name]
191
- with st.expander(f"{agent_name} ({agent['description']})"):
192
- if st.button(f"Activate {agent_name}", key=f"activate_{agent_name}"):
193
- st.session_state.active_agent = agent_name
194
- st.success(f"{agent_name} activated.")
195
- if st.button(f"Deactivate {agent_name}", key=f"deactivate_{agent_name}"):
196
- st.session_state.active_agent = None
197
- st.success(f"{agent_name} deactivated.")
198
-
199
- # Automate Build Process
200
- st.subheader("Automate Build Process")
201
- if st.button("Automate"):
202
- if st.session_state.selected_agents and project_name:
203
- run_autonomous_build(st.session_state.selected_agents, project_name)
204
  else:
205
- st.warning("Please select at least one agent and create a project.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
- # Version Control
208
- st.subheader("Version Control")
209
- repo_url = st.text_input("Enter repository URL:")
210
- if st.button("Clone Repository"):
211
- if repo_url and project_name:
212
- try:
213
- git.Repo.clone_from(repo_url, project_name)
214
- st.success(f"Repository cloned successfully to {project_name}")
215
- except git.GitCommandError as e:
216
- st.error(f"Error cloning repository: {e}")
217
- else:
218
- st.warning("Please enter a repository URL and create a project.")
219
-
220
- # Collaborative Agent Example
221
- st.subheader("Collaborative Agent Example")
222
- collab_agents = st.multiselect("Select AI agents for collaboration", list(agents.keys()), key="collab_agent_select")
223
- collab_project = st.text_input("Enter project name for collaboration:")
224
- collab_task = st.text_input("Enter collaborative task:")
225
- if st.button("Start Collaborative Task"):
226
- if collab_agents and collab_project and collab_task:
227
- collaborative_agent_example(collab_agents, collab_project, collab_task)
228
- else:
229
- st.warning("Please select agents, enter a project name, and a task.")
 
1
  import streamlit as st
2
+ from langchain.utilities import GoogleSearchAPIWrapper # Corrected import
3
  from langchain.chains import ConversationChain
4
  from langchain.memory import ConversationBufferMemory
5
  import subprocess
6
  import git
7
 
8
+ # API Key Input
9
+ if "GOOGLE_API_KEY" not in st.session_state:
10
+ st.session_state.GOOGLE_API_KEY = ""
11
+
12
+ st.header("Enter your Google Search API Key")
13
+ st.session_state.GOOGLE_API_KEY = st.text_input("API Key:", value=st.session_state.GOOGLE_API_KEY, type="password")
14
+
15
+ # Initialize Google Search API Wrapper (only if API key is provided)
16
+ if st.session_state.GOOGLE_API_KEY:
17
+ search = GoogleSearchAPIWrapper(google_api_key=st.session_state.GOOGLE_API_KEY)
18
+ # Agents
19
+ agents = {
20
+ "WEB_DEV": {
21
+ "description": "Expert in web development technologies and frameworks.",
22
+ "skills": ["HTML", "CSS", "JavaScript", "React", "Vue.js", "Flask", "Django", "Node.js", "Express.js"],
23
+ "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.",
24
+ },
25
+ "AI_SYSTEM_PROMPT": {
26
+ "description": "Expert in designing and implementing AI systems.",
27
+ "skills": ["Machine Learning", "Deep Learning", "Natural Language Processing", "Computer Vision", "Reinforcement Learning"],
28
+ "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.",
29
+ },
30
+ "PYTHON_CODE_DEV": {
31
+ "description": "Expert in Python programming and development.",
32
+ "skills": ["Python", "Data Structures", "Algorithms", "Object-Oriented Programming", "Functional Programming"],
33
+ "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.",
34
+ },
35
+ "CODE_REVIEW_ASSISTANT": {
36
+ "description": "Expert in code review and quality assurance.",
37
+ "skills": ["Code Style", "Best Practices", "Security", "Performance", "Maintainability"],
38
+ "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.",
39
+ },
40
+ }
41
+
42
+ # Session State
43
+ if "workspace_projects" not in st.session_state:
44
+ st.session_state.workspace_projects = {}
45
+ if "chat_history" not in st.session_state:
46
+ st.session_state.chat_history = []
47
+ if "active_agent" not in st.session_state:
48
+ st.session_state.active_agent = None
49
+ if "selected_agents" not in st.session_state:
50
+ st.session_state.selected_agents = []
51
+ if "current_project" not in st.session_state:
52
+ st.session_state.current_project = None
53
+
54
+ # Helper Functions
55
+ def add_code_to_workspace(project_name: str, code: str, file_name: str):
 
 
 
 
56
  if project_name in st.session_state.workspace_projects:
57
+ st.session_state.workspace_projects[project_name]['files'].append({'file_name': file_name, 'code': code})
58
+ return f"Added code to {file_name} in project {project_name}"
59
  else:
60
  return f"Project {project_name} does not exist"
61
+
62
+ def terminal_interface(command: str, project_name: str):
63
+ try:
64
+ if project_name in st.session_state.workspace_projects:
65
+ result = subprocess.run(command, cwd=project_name, shell=True, capture_output=True, text=True)
66
+ return result.stdout + result.stderr
67
+ else:
68
+ return f"Project {project_name} does not exist"
69
+ except FileNotFoundError:
70
+ return f"Error: Command not found. Please check your command."
71
+ except Exception as e:
72
+ logging.error(f"An error occurred: {e}")
73
+ return f"An unexpected error occurred while running the command."
74
+
75
+ def get_agent_response(message: str, system_prompt: str):
76
+ llm = GoogleSearchAPIWrapper(google_api_key=st.session_state.GOOGLE_API_KEY) # Access API key from session state
77
+ memory = ConversationBufferMemory()
78
+ conversation = ConversationChain(llm=llm, memory=memory)
79
+ response = conversation.run(system_prompt + "\n" + message)
80
+ return response
81
+
82
+ def display_agent_info(agent_name: str):
83
+ agent = agents[agent_name]
84
+ st.sidebar.subheader(f"Active Agent: {agent_name}")
85
+ st.sidebar.write(f"Description: {agent['description']}")
86
+ st.sidebar.write(f"Skills: {', '.join(agent['skills'])}")
87
+
88
+ def display_workspace_projects():
89
+ st.subheader("Workspace Projects")
90
+ for project_name, project_data in st.session_state.workspace_projects.items():
91
+ with st.expander(project_name):
92
+ for file in project_data['files']:
93
+ st.text(file['file_name'])
94
+ st.code(file['code'], language="python")
95
+
96
+ def display_chat_history():
97
+ st.subheader("Chat History")
98
+ for message in st.session_state.chat_history:
99
+ st.text(message)
100
+
101
+ def run_autonomous_build(selected_agents: list[str], project_name: str):
102
+ st.info("Starting autonomous build process...")
103
+ for agent in selected_agents:
104
+ st.write(f"Agent {agent} is working on the project...")
105
+ code = get_agent_response(f"Generate code for a simple web application in project {project_name}", agents[agent]['system_prompt'])
106
+ add_code_to_workspace(project_name, code, f"{agent.lower()}_app.py")
107
+ st.write(f"Agent {agent} has completed its task.")
108
+ st.success("Autonomous build process completed!")
109
+
110
+ def collaborative_agent_example(selected_agents: list[str], project_name: str, task: str):
111
+ st.info(f"Starting collaborative task: {task}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  responses = {}
113
  for agent in selected_agents:
114
+ st.write(f"Agent {agent} is working on the task...")
115
+ response = get_agent_response(task, agents[agent]['system_prompt'])
116
  responses[agent] = response
117
+
118
+ combined_response = combine_and_process_responses(responses, task)
119
+ st.success("Collaborative task completed!")
120
+ st.write(combined_response)
121
+
122
+ def combine_and_process_responses(responses: dict[str, str], task: str) -> str:
123
+ combined = "\n\n".join([f"{agent}: {response}" for agent, response in responses.items()])
124
+ return f"Combined response for task '{task}':\n\n{combined}"
125
+ # Streamlit UI
126
+ st.title("DevToolKit: AI-Powered Development Environment")
127
+
128
+ # Project Management
129
+ st.header("Project Management")
130
+ project_name = st.text_input("Enter project name:")
131
+ if st.button("Create Project"):
132
+ if project_name and project_name not in st.session_state.workspace_projects:
133
+ st.session_state.workspace_projects[project_name] = {'files': []}
134
+ st.success(f"Created project: {project_name}")
135
+ elif project_name in st.session_state.workspace_projects:
136
+ st.warning(f"Project {project_name} already exists")
137
+ else:
138
+ st.warning("Please enter a project name")
139
+
140
+ # Code Editor
141
+ st.subheader("Code Editor")
142
+ if st.session_state.workspace_projects:
143
+ selected_project = st.selectbox("Select project", list(st.session_state.workspace_projects.keys()))
144
+ if selected_project:
145
+ files = [file['file_name'] for file in st.session_state.workspace_projects[selected_project]['files']]
146
+ selected_file = st.selectbox("Select file to edit", files) if files else None
147
+ if selected_file:
148
+ file_content = next((file['code'] for file in st.session_state.workspace_projects[selected_project]['files'] if file['file_name'] == selected_file), "")
149
+ edited_code = st.text_area("Edit code", value=file_content, height=300) # Using st.text_area for now
150
+ if st.button("Save Changes"):
151
+ for file in st.session_state.workspace_projects[selected_project]['files']:
152
+ if file['file_name'] == selected_file:
153
+ file['code'] = edited_code
154
+ st.success("Changes saved successfully!")
155
+ break
156
+ else:
157
+ st.info("No files in the project. Use the chat interface to generate code.")
158
  else:
159
+ st.info("No projects created yet. Create a project to start coding.")
160
+
161
+ # Terminal Interface
162
+ st.subheader("Terminal (Workspace Context)")
163
+ if st.session_state.workspace_projects:
164
+ selected_project = st.selectbox("Select project for terminal", list(st.session_state.workspace_projects.keys()))
165
+ terminal_input = st.text_input("Enter a command within the workspace:")
166
+ if st.button("Run Command"):
167
+ terminal_output = terminal_interface(terminal_input, selected_project)
168
+ st.code(terminal_output, language="bash")
 
 
 
 
 
 
 
 
 
169
  else:
170
+ st.info("No projects created yet. Create a project to use the terminal.")
171
+
172
+ # Chat Interface
173
+ st.subheader("Chat with AI Agents")
174
+ selected_agents = st.multiselect("Select AI agents", list(agents.keys()), key="agent_select")
175
+ st.session_state.selected_agents = selected_agents
176
+ agent_chat_input = st.text_area("Enter your message for the agents:", key="agent_input")
177
+ if st.button("Send to Agents", key="agent_send"):
178
+ if selected_agents and agent_chat_input:
179
+ responses = {}
180
+ for agent in selected_agents:
181
+ response = get_agent_response(agent_chat_input, agents[agent]['system_prompt'])
182
+ responses[agent] = response
183
+ st.session_state.chat_history.append(f"User: {agent_chat_input}")
184
+ for agent, response in responses.items():
185
+ st.session_state.chat_history.append(f"{agent}: {response}")
186
+ st.text_area("Chat History", value='\n'.join(st.session_state.chat_history), height=300)
187
+ else:
188
+ st.warning("Please select at least one agent and enter a message.")
189
+
190
+ # Agent Control
191
+ st.subheader("Agent Control")
192
+ for agent_name in agents:
193
+ agent = agents[agent_name]
194
+ with st.expander(f"{agent_name} ({agent['description']})"):
195
+ if st.button(f"Activate {agent_name}", key=f"activate_{agent_name}"):
196
+ st.session_state.active_agent = agent_name
197
+ st.success(f"{agent_name} activated.")
198
+ if st.button(f"Deactivate {agent_name}", key=f"deactivate_{agent_name}"):
199
+ st.session_state.active_agent = None
200
+ st.success(f"{agent_name} deactivated.")
201
+
202
+ # Automate Build Process
203
+ st.subheader("Automate Build Process")
204
+ if st.button("Automate"):
205
+ if st.session_state.selected_agents and project_name:
206
+ run_autonomous_build(st.session_state.selected_agents, project_name)
207
+ else:
208
+ st.warning("Please select at least one agent and create a project.")
209
+
210
+ # Version Control
211
+ st.subheader("Version Control")
212
+ repo_url = st.text_input("Enter repository URL:")
213
+ if st.button("Clone Repository"):
214
+ if repo_url and project_name:
215
+ try:
216
+ git.Repo.clone_from(repo_url, project_name)
217
+ st.success(f"Repository cloned successfully to {project_name}")
218
+ except git.GitCommandError as e:
219
+ st.error(f"Error cloning repository: {e}")
220
+ else:
221
+ st.warning("Please enter a repository URL and create a project.")
222
+
223
+ # Collaborative Agent Example
224
+ st.subheader("Collaborative Agent Example")
225
+ collab_agents = st.multiselect("Select AI agents for collaboration", list(agents.keys()), key="collab_agent_select")
226
+ collab_project = st.text_input("Enter project name for collaboration:")
227
+ collab_task = st.text_input("Enter collaborative task:")
228
+ if st.button("Start Collaborative Task"):
229
+ if collab_agents and collab_project and collab_task:
230
+ collaborative_agent_example(collab_agents, collab_project, collab_task)
231
+ else:
232
+ st.warning("Please select agents, enter a project name, and a task.")
233
 
234
+ else:
235
+ st.warning("Please enter your Google Search API Key to continue.")