acecalisto3 commited on
Commit
f0a0e00
1 Parent(s): 14bdc5a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -93
app.py CHANGED
@@ -1,6 +1,6 @@
1
- import streamlit as st
2
  import os
3
  import subprocess
 
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
5
  import black
6
  from pylint import lint
@@ -11,6 +11,7 @@ import sys
11
  # Set your OpenAI API key here
12
  openai.api_key = "YOUR_OPENAI_API_KEY"
13
 
 
14
  PROJECT_ROOT = "projects"
15
  AGENT_DIRECTORY = "agents"
16
 
@@ -23,6 +24,11 @@ if 'workspace_projects' not in st.session_state:
23
  st.session_state.workspace_projects = {}
24
  if 'available_agents' not in st.session_state:
25
  st.session_state.available_agents = []
 
 
 
 
 
26
 
27
  class AIAgent:
28
  def __init__(self, name, description, skills):
@@ -35,6 +41,7 @@ class AIAgent:
35
  agent_prompt = f"""
36
  As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
37
  {skills_str}
 
38
  I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
39
  """
40
  return agent_prompt
@@ -46,6 +53,17 @@ I am confident that I can leverage my expertise to assist you in developing and
46
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
47
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
48
 
 
 
 
 
 
 
 
 
 
 
 
49
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
50
 
51
  return summary, next_step
@@ -82,7 +100,7 @@ def chat_interface_with_agent(input_text, agent_name):
82
 
83
  model_name = "Bin12345/AutoCoder_S_6.7B"
84
  try:
85
- pipe = pipeline("text-generation", model="Bin12345/AutoCoder_S_6.7B")
86
  tokenizer = AutoTokenizer.from_pretrained(model_name)
87
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
88
  except EnvironmentError as e:
@@ -102,42 +120,18 @@ def chat_interface_with_agent(input_text, agent_name):
102
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
103
  return response
104
 
105
- def workspace_interface(project_name):
106
- if not os.path.exists(PROJECT_ROOT):
107
- os.makedirs(PROJECT_ROOT)
108
- project_path = os.path.join(PROJECT_ROOT, project_name)
109
- if not os.path.exists(project_path):
110
- os.makedirs(project_path)
111
- st.session_state.workspace_projects[project_name] = {"files": []}
112
- return f"Project {project_name} created successfully."
113
- else:
114
- return f"Project {project_name} already exists."
115
-
116
- def add_code_to_workspace(project_name, code, file_name):
117
- project_path = os.path.join(PROJECT_ROOT, project_name)
118
- if os.path.exists(project_path):
119
- file_path = os.path.join(project_path, file_name)
120
- with open(file_path, "w") as file:
121
- file.write(code)
122
- st.session_state.workspace_projects[project_name]["files"].append(file_name)
123
- return f"Code added to {file_name} in project {project_name} successfully."
124
- else:
125
- return f"Project {project_name} does not exist."
126
-
127
  def terminal_interface(command, project_name=None):
128
  if project_name:
129
  project_path = os.path.join(PROJECT_ROOT, project_name)
130
  if not os.path.exists(project_path):
131
  return f"Project {project_name} does not exist."
132
- result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
133
  else:
134
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
135
-
136
- if result.returncode == 0:
137
- return result.stdout
138
- else:
139
- return result.stderr
140
 
 
141
  def code_editor_interface(code):
142
  try:
143
  formatted_code = black.format_str(code, mode=black.FileMode())
@@ -156,43 +150,69 @@ def code_editor_interface(code):
156
 
157
  return formatted_code, lint_message
158
 
 
159
  def summarize_text(text):
160
  summarizer = pipeline("summarization")
161
- summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
162
  return summary[0]['summary_text']
163
 
 
164
  def sentiment_analysis(text):
165
  analyzer = pipeline("sentiment-analysis")
166
- sentiment = analyzer(text)
167
- return sentiment[0]
168
 
 
169
  def translate_code(code, source_language, target_language):
170
- prompt = f"Translate this code from {source_language} to {target_language}:\n\n{code}"
171
- response = openai.ChatCompletion.create(
172
- model="gpt-4",
173
- messages=[
174
- {"role": "system", "content": "You are an expert software developer."},
175
- {"role": "user", "content": prompt}
176
- ]
177
- )
178
- return response.choices[0].message['content'].strip()
179
 
180
  def generate_code(code_idea):
181
- response = openai.ChatCompletion.create(
182
- model="gpt-4",
183
- messages=[
184
- {"role": "system", "content": "You are an expert software developer."},
185
- {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
186
- ]
187
- )
188
- return response.choices[0].message['content'].strip()
 
 
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  st.title("AI Agent Creator")
191
 
 
192
  st.sidebar.title("Navigation")
193
  app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
194
 
195
  if app_mode == "AI Agent Creator":
 
196
  st.header("Create an AI Agent from Text")
197
 
198
  st.subheader("From Text")
@@ -204,20 +224,18 @@ if app_mode == "AI Agent Creator":
204
  st.session_state.available_agents.append(agent_name)
205
 
206
  elif app_mode == "Tool Box":
 
207
  st.header("AI-Powered Tools")
208
 
 
209
  st.subheader("Chat with CodeCraft")
210
  chat_input = st.text_area("Enter your message:")
211
  if st.button("Send"):
212
- if chat_input.startswith("@"):
213
- agent_name = chat_input.split(" ")[0][1:]
214
- chat_input = " ".join(chat_input.split(" ")[1:])
215
- chat_response = chat_interface_with_agent(chat_input, agent_name)
216
- else:
217
- chat_response = "Chat interface function not provided."
218
  st.session_state.chat_history.append((chat_input, chat_response))
219
  st.write(f"CodeCraft: {chat_response}")
220
 
 
221
  st.subheader("Terminal")
222
  terminal_input = st.text_input("Enter a command:")
223
  if st.button("Run"):
@@ -225,6 +243,7 @@ elif app_mode == "Tool Box":
225
  st.session_state.terminal_history.append((terminal_input, terminal_output))
226
  st.code(terminal_output, language="bash")
227
 
 
228
  st.subheader("Code Editor")
229
  code_editor = st.text_area("Write your code:", height=300)
230
  if st.button("Format & Lint"):
@@ -232,110 +251,104 @@ elif app_mode == "Tool Box":
232
  st.code(formatted_code, language="python")
233
  st.info(lint_message)
234
 
 
235
  st.subheader("Summarize Text")
236
  text_to_summarize = st.text_area("Enter text to summarize:")
237
  if st.button("Summarize"):
238
  summary = summarize_text(text_to_summarize)
239
  st.write(f"Summary: {summary}")
240
 
 
241
  st.subheader("Sentiment Analysis")
242
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
243
  if st.button("Analyze Sentiment"):
244
  sentiment = sentiment_analysis(sentiment_text)
245
  st.write(f"Sentiment: {sentiment}")
246
 
 
247
  st.subheader("Translate Code")
248
  code_to_translate = st.text_area("Enter code to translate:")
249
- source_language = st.text_input("Enter source language (e.g. 'Python'):")
250
- target_language = st.text_input("Enter target language (e.g. 'JavaScript'):")
251
  if st.button("Translate Code"):
252
  translated_code = translate_code(code_to_translate, source_language, target_language)
253
  st.code(translated_code, language=target_language.lower())
254
 
 
255
  st.subheader("Code Generation")
256
  code_idea = st.text_input("Enter your code idea:")
257
  if st.button("Generate Code"):
258
  generated_code = generate_code(code_idea)
259
  st.code(generated_code, language="python")
260
 
261
- st.subheader("Preset Commands")
262
- preset_commands = {
263
- "Create a new project": "create_project('project_name')",
264
- "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
265
- "Run terminal command": "terminal_interface('command', 'project_name')",
266
- "Generate code": "generate_code('code_idea')",
267
- "Summarize text": "summarize_text('text')",
268
- "Analyze sentiment": "sentiment_analysis('text')",
269
- "Translate code": "translate_code('code', 'source_language', 'target_language')",
270
- }
271
- for command_name, command in preset_commands.items():
272
- st.write(f"{command_name}: `{command}`")
273
-
274
  elif app_mode == "Workspace Chat App":
 
275
  st.header("Workspace Chat App")
276
 
 
277
  st.subheader("Create a New Project")
278
  project_name = st.text_input("Enter project name:")
279
  if st.button("Create Project"):
280
  workspace_status = workspace_interface(project_name)
281
  st.success(workspace_status)
282
 
 
283
  st.subheader("Add Code to Workspace")
284
  code_to_add = st.text_area("Enter code to add to workspace:")
285
- file_name = st.text_input("Enter file name (e.g. 'app.py'):")
286
  if st.button("Add Code"):
287
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
288
  st.success(add_code_status)
289
 
 
290
  st.subheader("Terminal (Workspace Context)")
291
  terminal_input = st.text_input("Enter a command within the workspace:")
292
  if st.button("Run Command"):
293
  terminal_output = terminal_interface(terminal_input, project_name)
294
  st.code(terminal_output, language="bash")
295
 
 
296
  st.subheader("Chat with CodeCraft for Guidance")
297
  chat_input = st.text_area("Enter your message for guidance:")
298
  if st.button("Get Guidance"):
299
- chat_response = "Chat interface function not provided."
300
  st.session_state.chat_history.append((chat_input, chat_response))
301
  st.write(f"CodeCraft: {chat_response}")
302
 
 
303
  st.subheader("Chat History")
304
  for user_input, response in st.session_state.chat_history:
305
  st.write(f"User: {user_input}")
306
  st.write(f"CodeCraft: {response}")
307
 
 
308
  st.subheader("Terminal History")
309
  for command, output in st.session_state.terminal_history:
310
  st.write(f"Command: {command}")
311
  st.code(output, language="bash")
312
 
 
313
  st.subheader("Workspace Projects")
314
  for project, details in st.session_state.workspace_projects.items():
315
  st.write(f"Project: {project}")
316
  for file in details['files']:
317
  st.write(f" - {file}")
318
 
 
319
  st.subheader("Chat with AI Agents")
320
- if st.session_state.available_agents:
321
- selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
322
- agent_chat_input = st.text_area("Enter your message for the agent:")
323
- if st.button("Send to Agent"):
324
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
325
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
326
- st.write(f"{selected_agent}: {agent_chat_response}")
327
- else:
328
- st.write("No agents available. Please create an agent first.")
329
-
330
  st.subheader("Automate Build Process")
331
  if st.button("Automate"):
332
- if st.session_state.available_agents:
333
- selected_agent = st.session_state.available_agents[0]
334
- agent = AIAgent(selected_agent, "", [])
335
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
336
- st.write("Autonomous Build Summary:")
337
- st.write(summary)
338
- st.write("Next Step:")
339
- st.write(next_step)
340
- else:
341
- st.write("No agents available. Please create an agent first.")
 
 
1
  import os
2
  import subprocess
3
+ import streamlit as st
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
5
  import black
6
  from pylint import lint
 
11
  # Set your OpenAI API key here
12
  openai.api_key = "YOUR_OPENAI_API_KEY"
13
 
14
+ HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
15
  PROJECT_ROOT = "projects"
16
  AGENT_DIRECTORY = "agents"
17
 
 
24
  st.session_state.workspace_projects = {}
25
  if 'available_agents' not in st.session_state:
26
  st.session_state.available_agents = []
27
+ if 'current_state' not in st.session_state:
28
+ st.session_state.current_state = {
29
+ 'toolbox': {},
30
+ 'workspace_chat': {}
31
+ }
32
 
33
  class AIAgent:
34
  def __init__(self, name, description, skills):
 
41
  agent_prompt = f"""
42
  As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
43
  {skills_str}
44
+
45
  I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
46
  """
47
  return agent_prompt
 
53
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
54
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
55
 
56
+ # Analyze chat history and workspace projects to suggest actions
57
+ # Example:
58
+ # - Check if the user has requested to create a new file
59
+ # - Check if the user has requested to install a package
60
+ # - Check if the user has requested to run a command
61
+ # - Check if the user has requested to generate code
62
+ # - Check if the user has requested to translate code
63
+ # - Check if the user has requested to summarize text
64
+ # - Check if the user has requested to analyze sentiment
65
+
66
+ # Generate a response based on the analysis
67
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
68
 
69
  return summary, next_step
 
100
 
101
  model_name = "Bin12345/AutoCoder_S_6.7B"
102
  try:
103
+ model = AutoModelForCausalLM.from_pretrained(model_name)
104
  tokenizer = AutoTokenizer.from_pretrained(model_name)
105
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
106
  except EnvironmentError as e:
 
120
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
121
  return response
122
 
123
+ # Terminal interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def terminal_interface(command, project_name=None):
125
  if project_name:
126
  project_path = os.path.join(PROJECT_ROOT, project_name)
127
  if not os.path.exists(project_path):
128
  return f"Project {project_name} does not exist."
129
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)
130
  else:
131
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
132
+ return result.stdout
 
 
 
 
133
 
134
+ # Code editor interface
135
  def code_editor_interface(code):
136
  try:
137
  formatted_code = black.format_str(code, mode=black.FileMode())
 
150
 
151
  return formatted_code, lint_message
152
 
153
+ # Text summarization tool
154
  def summarize_text(text):
155
  summarizer = pipeline("summarization")
156
+ summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
157
  return summary[0]['summary_text']
158
 
159
+ # Sentiment analysis tool
160
  def sentiment_analysis(text):
161
  analyzer = pipeline("sentiment-analysis")
162
+ result = analyzer(text)
163
+ return result[0]['label']
164
 
165
+ # Text translation tool (code translation)
166
  def translate_code(code, source_language, target_language):
167
+ # Use a Hugging Face translation model instead of OpenAI
168
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es") # Example: English to Spanish
169
+ translated_code = translator(code, target_lang=target_language)[0]['translation_text']
170
+ return translated_code
 
 
 
 
 
171
 
172
  def generate_code(code_idea):
173
+ # Use a Hugging Face code generation model instead of OpenAI
174
+ generator = pipeline('text-generation', model='bigcode/starcoder')
175
+ generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
176
+ return generated_code
177
+
178
+ def chat_interface(input_text):
179
+ """Handles general chat interactions with the user."""
180
+ # Use a Hugging Face chatbot model or your own logic
181
+ chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
182
+ response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
183
+ return response
184
 
185
+ # Workspace interface
186
+ def workspace_interface(project_name):
187
+ project_path = os.path.join(PROJECT_ROOT, project_name)
188
+ if not os.path.exists(project_path):
189
+ os.makedirs(project_path)
190
+ st.session_state.workspace_projects[project_name] = {'files': []}
191
+ return f"Project '{project_name}' created successfully."
192
+ else:
193
+ return f"Project '{project_name}' already exists."
194
+
195
+ # Add code to workspace
196
+ def add_code_to_workspace(project_name, code, file_name):
197
+ project_path = os.path.join(PROJECT_ROOT, project_name)
198
+ if not os.path.exists(project_path):
199
+ return f"Project '{project_name}' does not exist."
200
+
201
+ file_path = os.path.join(project_path, file_name)
202
+ with open(file_path, "w") as file:
203
+ file.write(code)
204
+ st.session_state.workspace_projects[project_name]['files'].append(file_name)
205
+ return f"Code added to '{file_name}' in project '{project_name}'."
206
+
207
+ # Streamlit App
208
  st.title("AI Agent Creator")
209
 
210
+ # Sidebar navigation
211
  st.sidebar.title("Navigation")
212
  app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
213
 
214
  if app_mode == "AI Agent Creator":
215
+ # AI Agent Creator
216
  st.header("Create an AI Agent from Text")
217
 
218
  st.subheader("From Text")
 
224
  st.session_state.available_agents.append(agent_name)
225
 
226
  elif app_mode == "Tool Box":
227
+ # Tool Box
228
  st.header("AI-Powered Tools")
229
 
230
+ # Chat Interface
231
  st.subheader("Chat with CodeCraft")
232
  chat_input = st.text_area("Enter your message:")
233
  if st.button("Send"):
234
+ chat_response = chat_interface(chat_input)
 
 
 
 
 
235
  st.session_state.chat_history.append((chat_input, chat_response))
236
  st.write(f"CodeCraft: {chat_response}")
237
 
238
+ # Terminal Interface
239
  st.subheader("Terminal")
240
  terminal_input = st.text_input("Enter a command:")
241
  if st.button("Run"):
 
243
  st.session_state.terminal_history.append((terminal_input, terminal_output))
244
  st.code(terminal_output, language="bash")
245
 
246
+ # Code Editor Interface
247
  st.subheader("Code Editor")
248
  code_editor = st.text_area("Write your code:", height=300)
249
  if st.button("Format & Lint"):
 
251
  st.code(formatted_code, language="python")
252
  st.info(lint_message)
253
 
254
+ # Text Summarization Tool
255
  st.subheader("Summarize Text")
256
  text_to_summarize = st.text_area("Enter text to summarize:")
257
  if st.button("Summarize"):
258
  summary = summarize_text(text_to_summarize)
259
  st.write(f"Summary: {summary}")
260
 
261
+ # Sentiment Analysis Tool
262
  st.subheader("Sentiment Analysis")
263
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
264
  if st.button("Analyze Sentiment"):
265
  sentiment = sentiment_analysis(sentiment_text)
266
  st.write(f"Sentiment: {sentiment}")
267
 
268
+ # Text Translation Tool (Code Translation)
269
  st.subheader("Translate Code")
270
  code_to_translate = st.text_area("Enter code to translate:")
271
+ source_language = st.text_input("Enter source language (e.g., 'Python'):")
272
+ target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")
273
  if st.button("Translate Code"):
274
  translated_code = translate_code(code_to_translate, source_language, target_language)
275
  st.code(translated_code, language=target_language.lower())
276
 
277
+ # Code Generation
278
  st.subheader("Code Generation")
279
  code_idea = st.text_input("Enter your code idea:")
280
  if st.button("Generate Code"):
281
  generated_code = generate_code(code_idea)
282
  st.code(generated_code, language="python")
283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  elif app_mode == "Workspace Chat App":
285
+ # Workspace Chat App
286
  st.header("Workspace Chat App")
287
 
288
+ # Project Workspace Creation
289
  st.subheader("Create a New Project")
290
  project_name = st.text_input("Enter project name:")
291
  if st.button("Create Project"):
292
  workspace_status = workspace_interface(project_name)
293
  st.success(workspace_status)
294
 
295
+ # Add Code to Workspace
296
  st.subheader("Add Code to Workspace")
297
  code_to_add = st.text_area("Enter code to add to workspace:")
298
+ file_name = st.text_input("Enter file name (e.g., 'app.py'):")
299
  if st.button("Add Code"):
300
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
301
  st.success(add_code_status)
302
 
303
+ # Terminal Interface with Project Context
304
  st.subheader("Terminal (Workspace Context)")
305
  terminal_input = st.text_input("Enter a command within the workspace:")
306
  if st.button("Run Command"):
307
  terminal_output = terminal_interface(terminal_input, project_name)
308
  st.code(terminal_output, language="bash")
309
 
310
+ # Chat Interface for Guidance
311
  st.subheader("Chat with CodeCraft for Guidance")
312
  chat_input = st.text_area("Enter your message for guidance:")
313
  if st.button("Get Guidance"):
314
+ chat_response = chat_interface(chat_input)
315
  st.session_state.chat_history.append((chat_input, chat_response))
316
  st.write(f"CodeCraft: {chat_response}")
317
 
318
+ # Display Chat History
319
  st.subheader("Chat History")
320
  for user_input, response in st.session_state.chat_history:
321
  st.write(f"User: {user_input}")
322
  st.write(f"CodeCraft: {response}")
323
 
324
+ # Display Terminal History
325
  st.subheader("Terminal History")
326
  for command, output in st.session_state.terminal_history:
327
  st.write(f"Command: {command}")
328
  st.code(output, language="bash")
329
 
330
+ # Display Projects and Files
331
  st.subheader("Workspace Projects")
332
  for project, details in st.session_state.workspace_projects.items():
333
  st.write(f"Project: {project}")
334
  for file in details['files']:
335
  st.write(f" - {file}")
336
 
337
+ # Chat with AI Agents
338
  st.subheader("Chat with AI Agents")
339
+ selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
340
+ agent_chat_input = st.text_area("Enter your message for the agent:")
341
+ if st.button("Send to Agent"):
342
+ agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
343
+ st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
344
+ st.write(f"{selected_agent}: {agent_chat_response}")
345
+
346
+ # Automate Build Process
 
 
347
  st.subheader("Automate Build Process")
348
  if st.button("Automate"):
349
+ agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
350
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
351
+ st.write("Autonomous Build Summary:")
352
+ st.write(summary)
353
+ st.write("Next Step:")
354
+ st.write(next_step)