acecalisto3 commited on
Commit
5e396de
·
verified ·
1 Parent(s): 2fd95c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -54
app.py CHANGED
@@ -1,23 +1,34 @@
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
7
  from io import StringIO
 
8
  import sys
9
 
 
 
 
 
10
  PROJECT_ROOT = "projects"
11
  AGENT_DIRECTORY = "agents"
12
 
13
- if "chat_history" not in st.session_state:
 
14
  st.session_state.chat_history = []
15
- if "terminal_history" not in st.session_state:
16
  st.session_state.terminal_history = []
17
- if "workspace_projects" not in st.session_state:
18
  st.session_state.workspace_projects = {}
19
- if "available_agents" not in st.session_state:
20
  st.session_state.available_agents = []
 
 
 
 
 
21
 
22
  class AIAgent:
23
  def __init__(self, name, description, skills):
@@ -28,20 +39,31 @@ class AIAgent:
28
  def create_agent_prompt(self):
29
  skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
30
  agent_prompt = f"""
31
- As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas: {skills_str}
 
32
 
33
- 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. """
 
34
  return agent_prompt
35
 
36
  def autonomous_build(self, chat_history, workspace_projects):
37
  """
38
  Autonomous build logic that continues based on the state of chat history and workspace projects.
39
  """
40
- # Example logic: Generate a summary of chat history and workspace state
41
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
42
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
43
 
44
- # Example: Generate the next logical step in the project
 
 
 
 
 
 
 
 
 
 
45
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
46
 
47
  return summary, next_step
@@ -76,7 +98,7 @@ def chat_interface_with_agent(input_text, agent_name):
76
  if agent_prompt is None:
77
  return f"Agent {agent_name} not found."
78
 
79
- model_name = "gpt2"
80
  try:
81
  model = AutoModelForCausalLM.from_pretrained(model_name)
82
  tokenizer = AutoTokenizer.from_pretrained(model_name)
@@ -84,101 +106,249 @@ def chat_interface_with_agent(input_text, agent_name):
84
  except EnvironmentError as e:
85
  return f"Error loading model: {e}"
86
 
87
- # Combine the agent prompt with user input
88
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
89
-
90
- # Truncate input text to avoid exceeding the model's maximum length
91
- max_input_length = 900
92
  input_ids = tokenizer.encode(combined_input, return_tensors="pt")
 
93
  if input_ids.shape[1] > max_input_length:
94
  input_ids = input_ids[:, :max_input_length]
95
 
96
- # Generate chatbot response
97
  outputs = model.generate(
98
- input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True
 
99
  )
100
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
101
  return response
102
 
 
103
  def terminal_interface(command, project_name=None):
104
  if project_name:
105
  project_path = os.path.join(PROJECT_ROOT, project_name)
 
 
106
  result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)
107
  else:
108
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
109
  return result.stdout
110
 
 
111
  def code_editor_interface(code):
112
- formatted_code = black.format_str(code, mode=black.FileMode())
113
- pylint_output = lint.Run([formatted_code], do_exit=False)
114
- pylint_output_str = StringIO()
115
- pylint_output.linter.reporter.write_messages(pylint_output_str)
116
- return formatted_code, pylint_output_str.getvalue()
 
 
 
 
 
 
 
117
 
 
 
 
 
 
118
  def summarize_text(text):
119
  summarizer = pipeline("summarization")
120
  summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
121
  return summary[0]['summary_text']
122
 
 
123
  def sentiment_analysis(text):
124
  analyzer = pipeline("sentiment-analysis")
125
  result = analyzer(text)
126
  return result[0]['label']
127
 
 
128
  def translate_code(code, source_language, target_language):
129
- # Placeholder for translation logic
130
- return f"Translated {source_language} code to {target_language}."
 
 
131
 
132
- def generate_code(idea):
133
- # Placeholder for code generation logic
134
- return f"Generated code based on the idea: {idea}."
 
 
135
 
 
 
 
 
 
 
 
 
136
  def workspace_interface(project_name):
137
  project_path = os.path.join(PROJECT_ROOT, project_name)
138
  if not os.path.exists(project_path):
139
  os.makedirs(project_path)
140
  st.session_state.workspace_projects[project_name] = {'files': []}
141
- return f"Project '{project_name}' created successfully."
 
 
142
 
 
143
  def add_code_to_workspace(project_name, code, file_name):
144
  project_path = os.path.join(PROJECT_ROOT, project_name)
145
  if not os.path.exists(project_path):
146
  return f"Project '{project_name}' does not exist."
147
-
148
  file_path = os.path.join(project_path, file_name)
149
  with open(file_path, "w") as file:
150
  file.write(code)
151
  st.session_state.workspace_projects[project_name]['files'].append(file_name)
152
  return f"Code added to '{file_name}' in project '{project_name}'."
153
 
154
- def chat_interface_with_agent(input_text, agent_name):
155
- agent_prompt = load_agent_prompt(agent_name)
156
- if agent_prompt is None:
157
- return f"Agent {agent_name} not found."
158
 
159
- model_name = "gpt2"
160
- try:
161
- model = AutoModelForCausalLM.from_pretrained(model_name)
162
- tokenizer = AutoTokenizer.from_pretrained(model_name)
163
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
164
- except EnvironmentError as e:
165
- return f"Error loading model: {e}"
166
 
167
- # Combine the agent prompt with user input
168
- combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
 
169
 
170
- # Truncate input text to avoid exceeding the model's maximum length
171
- max_input_length = 900
172
- input_ids = tokenizer.encode(combined_input, return_tensors="pt")
173
- if input_ids.shape[1] > max_input_length:
174
- input_ids = input_ids[:, :max_input_length]
 
 
175
 
176
- # Adjust max_new_tokens if needed
177
- max_new_tokens = 50 # Reduce if necessary
 
178
 
179
- # Generate chatbot response
180
- outputs = model.generate(
181
- input_ids, max_new_tokens=max_new_tokens, num_return_sequences=1, do_sample=True
182
- )
183
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
184
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
7
  from io import StringIO
8
+ import openai
9
  import sys
10
 
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
 
18
+ # Global state to manage communication between Tool Box and Workspace Chat App
19
+ if 'chat_history' not in st.session_state:
20
  st.session_state.chat_history = []
21
+ if 'terminal_history' not in st.session_state:
22
  st.session_state.terminal_history = []
23
+ if 'workspace_projects' not in st.session_state:
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):
 
39
  def create_agent_prompt(self):
40
  skills_str = '\n'.join([f"* {skill}" for skill in self.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
48
 
49
  def autonomous_build(self, chat_history, workspace_projects):
50
  """
51
  Autonomous build logic that continues based on the state of chat history and workspace projects.
52
  """
 
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
 
98
  if agent_prompt is None:
99
  return f"Agent {agent_name} not found."
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)
 
106
  except EnvironmentError as e:
107
  return f"Error loading model: {e}"
108
 
 
109
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
110
+
 
 
111
  input_ids = tokenizer.encode(combined_input, return_tensors="pt")
112
+ max_input_length = 900
113
  if input_ids.shape[1] > max_input_length:
114
  input_ids = input_ids[:, :max_input_length]
115
 
 
116
  outputs = model.generate(
117
+ input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True,
118
+ pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
119
  )
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())
138
+ except black.NothingChanged:
139
+ formatted_code = code
140
+
141
+ result = StringIO()
142
+ sys.stdout = result
143
+ sys.stderr = result
144
+
145
+ (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
146
+ sys.stdout = sys.__stdout__
147
+ sys.stderr = sys.__stderr__
148
 
149
+ lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
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")
219
+ agent_name = st.text_input("Enter agent name:")
220
+ text_input = st.text_area("Enter skills (one per line):")
221
+ if st.button("Create Agent"):
222
+ agent_prompt = create_agent_from_text(agent_name, text_input)
223
+ st.success(f"Agent '{agent_name}' created and saved successfully.")
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"):
242
+ terminal_output = terminal_interface(terminal_input)
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"):
250
+ formatted_code, lint_message = code_editor_interface(code_editor)
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)