acecalisto3 commited on
Commit
f45aba3
1 Parent(s): 6a1203c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -56
app.py CHANGED
@@ -76,13 +76,11 @@ def create_agent_from_text(name, text):
76
  save_agent_to_file(agent)
77
  return agent.create_agent_prompt()
78
 
79
- # Chat interface using a selected agent
80
  def chat_interface_with_agent(input_text, agent_name):
81
  agent_prompt = load_agent_prompt(agent_name)
82
  if agent_prompt is None:
83
  return f"Agent {agent_name} not found."
84
 
85
- # Load the GPT-2 model which is compatible with AutoModelForCausalLM
86
  model_name = "gpt2"
87
  try:
88
  model = AutoModelForCausalLM.from_pretrained(model_name)
@@ -91,42 +89,107 @@ def chat_interface_with_agent(input_text, agent_name):
91
  except EnvironmentError as e:
92
  return f"Error loading model: {e}"
93
 
94
- # Combine the agent prompt with user input
95
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
96
 
97
- # Truncate input text to avoid exceeding the model's maximum length
98
- max_input_length = 900
99
  input_ids = tokenizer.encode(combined_input, return_tensors="pt")
 
100
  if input_ids.shape[1] > max_input_length:
101
  input_ids = input_ids[:, :max_input_length]
102
 
103
- # Generate chatbot response
104
  outputs = model.generate(
105
  input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True
106
  )
107
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
108
  return response
109
 
110
- # Preset commands for no-code-knowledge developers
111
- preset_commands = {
112
- "Create a new project": "create_project('project_name')",
113
- "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
114
- "Run terminal command": "terminal_interface('command', 'project_name')",
115
- "Generate code": "generate_code('code_idea')",
116
- "Summarize text": "summarize_text('text')",
117
- "Analyze sentiment": "sentiment_analysis('text')",
118
- "Translate code": "translate_code('code', 'source_language', 'target_language')",
119
- }
120
-
121
- # Streamlit App
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  st.title("AI Agent Creator")
123
 
124
- # Sidebar navigation
125
  st.sidebar.title("Navigation")
126
  app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
127
 
128
  if app_mode == "AI Agent Creator":
129
- # AI Agent Creator
130
  st.header("Create an AI Agent from Text")
131
 
132
  st.subheader("From Text")
@@ -138,23 +201,20 @@ if app_mode == "AI Agent Creator":
138
  st.session_state.available_agents.append(agent_name)
139
 
140
  elif app_mode == "Tool Box":
141
- # Tool Box
142
  st.header("AI-Powered Tools")
143
 
144
- # Chat Interface
145
  st.subheader("Chat with CodeCraft")
146
  chat_input = st.text_area("Enter your message:")
147
  if st.button("Send"):
148
  if chat_input.startswith("@"):
149
- agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
150
- chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
151
  chat_response = chat_interface_with_agent(chat_input, agent_name)
152
  else:
153
- chat_response = chat_interface(chat_input)
154
  st.session_state.chat_history.append((chat_input, chat_response))
155
  st.write(f"CodeCraft: {chat_response}")
156
 
157
- # Terminal Interface
158
  st.subheader("Terminal")
159
  terminal_input = st.text_input("Enter a command:")
160
  if st.button("Run"):
@@ -162,7 +222,6 @@ elif app_mode == "Tool Box":
162
  st.session_state.terminal_history.append((terminal_input, terminal_output))
163
  st.code(terminal_output, language="bash")
164
 
165
- # Code Editor Interface
166
  st.subheader("Code Editor")
167
  code_editor = st.text_area("Write your code:", height=300)
168
  if st.button("Format & Lint"):
@@ -170,21 +229,18 @@ elif app_mode == "Tool Box":
170
  st.code(formatted_code, language="python")
171
  st.info(lint_message)
172
 
173
- # Text Summarization Tool
174
  st.subheader("Summarize Text")
175
  text_to_summarize = st.text_area("Enter text to summarize:")
176
  if st.button("Summarize"):
177
  summary = summarize_text(text_to_summarize)
178
  st.write(f"Summary: {summary}")
179
 
180
- # Sentiment Analysis Tool
181
  st.subheader("Sentiment Analysis")
182
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
183
  if st.button("Analyze Sentiment"):
184
  sentiment = sentiment_analysis(sentiment_text)
185
  st.write(f"Sentiment: {sentiment}")
186
 
187
- # Text Translation Tool (Code Translation)
188
  st.subheader("Translate Code")
189
  code_to_translate = st.text_area("Enter code to translate:")
190
  source_language = st.text_input("Enter source language (e.g. 'Python'):")
@@ -193,30 +249,34 @@ elif app_mode == "Tool Box":
193
  translated_code = translate_code(code_to_translate, source_language, target_language)
194
  st.code(translated_code, language=target_language.lower())
195
 
196
- # Code Generation
197
  st.subheader("Code Generation")
198
  code_idea = st.text_input("Enter your code idea:")
199
  if st.button("Generate Code"):
200
  generated_code = generate_code(code_idea)
201
  st.code(generated_code, language="python")
202
 
203
- # Display Preset Commands
204
  st.subheader("Preset Commands")
 
 
 
 
 
 
 
 
 
205
  for command_name, command in preset_commands.items():
206
  st.write(f"{command_name}: `{command}`")
207
 
208
  elif app_mode == "Workspace Chat App":
209
- # Workspace Chat App
210
  st.header("Workspace Chat App")
211
 
212
- # Project Workspace Creation
213
  st.subheader("Create a New Project")
214
  project_name = st.text_input("Enter project name:")
215
  if st.button("Create Project"):
216
  workspace_status = workspace_interface(project_name)
217
  st.success(workspace_status)
218
 
219
- # Add Code to Workspace
220
  st.subheader("Add Code to Workspace")
221
  code_to_add = st.text_area("Enter code to add to workspace:")
222
  file_name = st.text_input("Enter file name (e.g. 'app.py'):")
@@ -224,55 +284,55 @@ elif app_mode == "Workspace Chat App":
224
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
225
  st.success(add_code_status)
226
 
227
- # Terminal Interface with Project Context
228
  st.subheader("Terminal (Workspace Context)")
229
  terminal_input = st.text_input("Enter a command within the workspace:")
230
  if st.button("Run Command"):
231
  terminal_output = terminal_interface(terminal_input, project_name)
232
  st.code(terminal_output, language="bash")
233
 
234
- # Chat Interface for Guidance
235
  st.subheader("Chat with CodeCraft for Guidance")
236
  chat_input = st.text_area("Enter your message for guidance:")
237
  if st.button("Get Guidance"):
238
- chat_response = chat_interface(chat_input)
239
  st.session_state.chat_history.append((chat_input, chat_response))
240
  st.write(f"CodeCraft: {chat_response}")
241
 
242
- # Display Chat History
243
  st.subheader("Chat History")
244
  for user_input, response in st.session_state.chat_history:
245
  st.write(f"User: {user_input}")
246
  st.write(f"CodeCraft: {response}")
247
 
248
- # Display Terminal History
249
  st.subheader("Terminal History")
250
  for command, output in st.session_state.terminal_history:
251
  st.write(f"Command: {command}")
252
  st.code(output, language="bash")
253
 
254
- # Display Projects and Files
255
  st.subheader("Workspace Projects")
256
  for project, details in st.session_state.workspace_projects.items():
257
  st.write(f"Project: {project}")
258
  for file in details['files']:
259
  st.write(f" - {file}")
260
 
261
- # Chat with AI Agents
262
  st.subheader("Chat with AI Agents")
263
- selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
264
- agent_chat_input = st.text_area("Enter your message for the agent:")
265
- if st.button("Send to Agent"):
266
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
267
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
268
- st.write(f"{selected_agent}: {agent_chat_response}")
269
-
270
- # Automate Build Process
 
 
271
  st.subheader("Automate Build Process")
272
  if st.button("Automate"):
273
- agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
274
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
275
- st.write("Autonomous Build Summary:")
276
- st.write(summary)
277
- st.write("Next Step:")
278
- st.write(next_step)
 
 
 
 
 
76
  save_agent_to_file(agent)
77
  return agent.create_agent_prompt()
78
 
 
79
  def chat_interface_with_agent(input_text, agent_name):
80
  agent_prompt = load_agent_prompt(agent_name)
81
  if agent_prompt is None:
82
  return f"Agent {agent_name} not found."
83
 
 
84
  model_name = "gpt2"
85
  try:
86
  model = AutoModelForCausalLM.from_pretrained(model_name)
 
89
  except EnvironmentError as e:
90
  return f"Error loading model: {e}"
91
 
 
92
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
93
 
 
 
94
  input_ids = tokenizer.encode(combined_input, return_tensors="pt")
95
+ max_input_length = 900
96
  if input_ids.shape[1] > max_input_length:
97
  input_ids = input_ids[:, :max_input_length]
98
 
 
99
  outputs = model.generate(
100
  input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True
101
  )
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())
144
+ except black.NothingChanged:
145
+ formatted_code = code
146
+
147
+ result = StringIO()
148
+ sys.stdout = result
149
+ sys.stderr = result
150
+
151
+ (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
152
+ sys.stdout = sys.__stdout__
153
+ sys.stderr = sys.__stderr__
154
+
155
+ lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
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.Completion.create(
172
+ engine="davinci-codex",
173
+ prompt=prompt,
174
+ max_tokens=150
175
+ )
176
+ return response.choices[0].text.strip()
177
+
178
+ def generate_code(code_idea):
179
+ prompt = f"Generate a Python code snippet for the following idea:\n\n{code_idea}"
180
+ response = openai.Completion.create(
181
+ engine="davinci-codex",
182
+ prompt=prompt,
183
+ max_tokens=150
184
+ )
185
+ return response.choices[0].text.strip()
186
+
187
  st.title("AI Agent Creator")
188
 
 
189
  st.sidebar.title("Navigation")
190
  app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
191
 
192
  if app_mode == "AI Agent Creator":
 
193
  st.header("Create an AI Agent from Text")
194
 
195
  st.subheader("From Text")
 
201
  st.session_state.available_agents.append(agent_name)
202
 
203
  elif app_mode == "Tool Box":
 
204
  st.header("AI-Powered Tools")
205
 
 
206
  st.subheader("Chat with CodeCraft")
207
  chat_input = st.text_area("Enter your message:")
208
  if st.button("Send"):
209
  if chat_input.startswith("@"):
210
+ agent_name = chat_input.split(" ")[0][1:]
211
+ chat_input = " ".join(chat_input.split(" ")[1:])
212
  chat_response = chat_interface_with_agent(chat_input, agent_name)
213
  else:
214
+ chat_response = "Chat interface function not provided."
215
  st.session_state.chat_history.append((chat_input, chat_response))
216
  st.write(f"CodeCraft: {chat_response}")
217
 
 
218
  st.subheader("Terminal")
219
  terminal_input = st.text_input("Enter a command:")
220
  if st.button("Run"):
 
222
  st.session_state.terminal_history.append((terminal_input, terminal_output))
223
  st.code(terminal_output, language="bash")
224
 
 
225
  st.subheader("Code Editor")
226
  code_editor = st.text_area("Write your code:", height=300)
227
  if st.button("Format & Lint"):
 
229
  st.code(formatted_code, language="python")
230
  st.info(lint_message)
231
 
 
232
  st.subheader("Summarize Text")
233
  text_to_summarize = st.text_area("Enter text to summarize:")
234
  if st.button("Summarize"):
235
  summary = summarize_text(text_to_summarize)
236
  st.write(f"Summary: {summary}")
237
 
 
238
  st.subheader("Sentiment Analysis")
239
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
240
  if st.button("Analyze Sentiment"):
241
  sentiment = sentiment_analysis(sentiment_text)
242
  st.write(f"Sentiment: {sentiment}")
243
 
 
244
  st.subheader("Translate Code")
245
  code_to_translate = st.text_area("Enter code to translate:")
246
  source_language = st.text_input("Enter source language (e.g. 'Python'):")
 
249
  translated_code = translate_code(code_to_translate, source_language, target_language)
250
  st.code(translated_code, language=target_language.lower())
251
 
 
252
  st.subheader("Code Generation")
253
  code_idea = st.text_input("Enter your code idea:")
254
  if st.button("Generate Code"):
255
  generated_code = generate_code(code_idea)
256
  st.code(generated_code, language="python")
257
 
 
258
  st.subheader("Preset Commands")
259
+ preset_commands = {
260
+ "Create a new project": "create_project('project_name')",
261
+ "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
262
+ "Run terminal command": "terminal_interface('command', 'project_name')",
263
+ "Generate code": "generate_code('code_idea')",
264
+ "Summarize text": "summarize_text('text')",
265
+ "Analyze sentiment": "sentiment_analysis('text')",
266
+ "Translate code": "translate_code('code', 'source_language', 'target_language')",
267
+ }
268
  for command_name, command in preset_commands.items():
269
  st.write(f"{command_name}: `{command}`")
270
 
271
  elif app_mode == "Workspace Chat App":
 
272
  st.header("Workspace Chat App")
273
 
 
274
  st.subheader("Create a New Project")
275
  project_name = st.text_input("Enter project name:")
276
  if st.button("Create Project"):
277
  workspace_status = workspace_interface(project_name)
278
  st.success(workspace_status)
279
 
 
280
  st.subheader("Add Code to Workspace")
281
  code_to_add = st.text_area("Enter code to add to workspace:")
282
  file_name = st.text_input("Enter file name (e.g. 'app.py'):")
 
284
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
285
  st.success(add_code_status)
286
 
 
287
  st.subheader("Terminal (Workspace Context)")
288
  terminal_input = st.text_input("Enter a command within the workspace:")
289
  if st.button("Run Command"):
290
  terminal_output = terminal_interface(terminal_input, project_name)
291
  st.code(terminal_output, language="bash")
292
 
 
293
  st.subheader("Chat with CodeCraft for Guidance")
294
  chat_input = st.text_area("Enter your message for guidance:")
295
  if st.button("Get Guidance"):
296
+ chat_response = "Chat interface function not provided."
297
  st.session_state.chat_history.append((chat_input, chat_response))
298
  st.write(f"CodeCraft: {chat_response}")
299
 
 
300
  st.subheader("Chat History")
301
  for user_input, response in st.session_state.chat_history:
302
  st.write(f"User: {user_input}")
303
  st.write(f"CodeCraft: {response}")
304
 
 
305
  st.subheader("Terminal History")
306
  for command, output in st.session_state.terminal_history:
307
  st.write(f"Command: {command}")
308
  st.code(output, language="bash")
309
 
 
310
  st.subheader("Workspace Projects")
311
  for project, details in st.session_state.workspace_projects.items():
312
  st.write(f"Project: {project}")
313
  for file in details['files']:
314
  st.write(f" - {file}")
315
 
 
316
  st.subheader("Chat with AI Agents")
317
+ if st.session_state.available_agents:
318
+ selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
319
+ agent_chat_input = st.text_area("Enter your message for the agent:")
320
+ if st.button("Send to Agent"):
321
+ agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
322
+ st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
323
+ st.write(f"{selected_agent}: {agent_chat_response}")
324
+ else:
325
+ st.write("No agents available. Please create an agent first.")
326
+
327
  st.subheader("Automate Build Process")
328
  if st.button("Automate"):
329
+ if st.session_state.available_agents:
330
+ selected_agent = st.session_state.available_agents[0]
331
+ agent = AIAgent(selected_agent, "", [])
332
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
333
+ st.write("Autonomous Build Summary:")
334
+ st.write(summary)
335
+ st.write("Next Step:")
336
+ st.write(next_step)
337
+ else:
338
+ st.write("No agents available. Please create an agent first.")