acecalisto3 commited on
Commit
2d92c14
·
verified ·
1 Parent(s): 054c771

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -116
app.py CHANGED
@@ -1,6 +1,7 @@
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
@@ -12,7 +13,16 @@ import requests
12
  from bs4 import BeautifulSoup
13
  from typing import List, Dict, Optional
14
 
15
- # Define custom exceptions for better error handling
 
 
 
 
 
 
 
 
 
16
  class InvalidActionError(Exception):
17
  """Raised when an invalid action is provided."""
18
  pass
@@ -25,18 +35,6 @@ class CodeGenerationError(Exception):
25
  """Raised when code generation fails."""
26
  pass
27
 
28
- class CodeRefinementError(Exception):
29
- """Raised when code refinement fails."""
30
- pass
31
-
32
- class CodeTestingError(Exception):
33
- """Raised when code testing fails."""
34
- pass
35
-
36
- class CodeIntegrationError(Exception):
37
- """Raised when code integration fails."""
38
- pass
39
-
40
  class AppTestingError(Exception):
41
  """Raised when app testing fails."""
42
  pass
@@ -53,14 +51,16 @@ class SearchError(Exception):
53
  """Raised when search fails."""
54
  pass
55
 
 
56
  class AIAgent:
57
  def __init__(self):
 
58
  self.tools = {
59
  "SEARCH": self.search,
60
  "CODEGEN": self.code_generation,
61
- "REFINE-CODE": self.refine_code,
62
- "TEST-CODE": self.test_code,
63
- "INTEGRATE-CODE": self.integrate_code,
64
  "TEST-APP": self.test_app,
65
  "GENERATE-REPORT": self.generate_report,
66
  "WORKSPACE-EXPLORER": self.workspace_explorer,
@@ -82,10 +82,9 @@ class AIAgent:
82
  self.prompts: List[str] = [] # Store prompts for future use
83
  self.code_generator = pipeline('text-generation', model='gpt2') # Initialize code generator
84
 
 
85
  def search(self, query: str) -> List[str]:
86
- """
87
- Performs a web search using the specified search engine.
88
- """
89
  search_url = self.search_engine_url + query
90
  try:
91
  response = requests.get(search_url)
@@ -96,68 +95,27 @@ class AIAgent:
96
  except requests.exceptions.RequestException as e:
97
  raise SearchError(f"Error during search: {e}")
98
 
 
99
  def code_generation(self, snippet: str) -> str:
100
- """
101
- Generates code based on the provided snippet.
102
- """
103
  try:
104
  generated_text = self.code_generator(snippet, max_length=500, num_return_sequences=1)[0]['generated_text']
105
  return generated_text
106
  except Exception as e:
107
  raise CodeGenerationError(f"Error during code generation: {e}")
108
 
109
- def refine_code(self, file_path: str) -> str:
110
- """
111
- Refines the code in the specified file.
112
- """
113
- try:
114
- with open(file_path, 'r') as f:
115
- code = f.read()
116
- refined_code = black.format_str(code, mode=black.FileMode())
117
- return refined_code
118
- except black.InvalidInput:
119
- raise CodeRefinementError("Error: Invalid code input for black formatting.")
120
- except Exception as e:
121
- raise CodeRefinementError(f"Error during code refinement: {e}")
122
-
123
- def test_code(self, file_path: str) -> str:
124
- """
125
- Tests the code in the specified file.
126
- """
127
- try:
128
- with open(file_path, 'r') as f:
129
- code = f.read()
130
- output = StringIO()
131
- lint.run(code, output=output)
132
- return output.getvalue()
133
- except Exception as e:
134
- raise CodeTestingError(f"Error during code testing: {e}")
135
-
136
- def integrate_code(self, file_path: str, code_snippet: str) -> str:
137
- """
138
- Integrates the code snippet into the specified file.
139
- """
140
- try:
141
- with open(file_path, 'a') as f:
142
- f.write(code_snippet)
143
- return "Code integrated successfully."
144
- except Exception as e:
145
- raise CodeIntegrationError(f"Error during code integration: {e}")
146
-
147
  def test_app(self) -> str:
148
- """
149
- Tests the functionality of the app.
150
- """
151
  try:
152
  subprocess.run(['streamlit', 'run', 'app.py'], check=True)
153
  return "App tested successfully."
154
  except subprocess.CalledProcessError as e:
155
  raise AppTestingError(f"Error during app testing: {e}")
156
 
 
157
  def generate_report(self) -> str:
158
- """
159
- Generates a report based on the task history.
160
- """
161
  report = f"## Task Report: {self.current_task}\n\n"
162
  for task in self.task_history:
163
  report += f"**Action:** {task['action']}\n"
@@ -165,10 +123,9 @@ class AIAgent:
165
  report += f"**Output:** {task['output']}\n\n"
166
  return report
167
 
 
168
  def workspace_explorer(self) -> str:
169
- """
170
- Provides a workspace explorer functionality.
171
- """
172
  try:
173
  current_directory = os.getcwd()
174
  directories = []
@@ -183,20 +140,18 @@ class AIAgent:
183
  except Exception as e:
184
  raise WorkspaceExplorerError(f"Error during workspace exploration: {e}")
185
 
 
186
  def add_prompt(self, prompt: str) -> str:
187
- """
188
- Adds a new prompt to the agent's knowledge base.
189
- """
190
  try:
191
  self.prompts.append(prompt)
192
  return f"Prompt '{prompt}' added successfully."
193
  except Exception as e:
194
  raise PromptManagementError(f"Error adding prompt: {e}")
195
 
 
196
  def action_prompt(self, action: str) -> str:
197
- """
198
- Provides a prompt for a specific action.
199
- """
200
  try:
201
  if action == "SEARCH":
202
  return "What do you want to search for?"
@@ -241,29 +196,25 @@ class AIAgent:
241
  except InvalidActionError as e:
242
  raise e
243
 
 
244
  def compress_history_prompt(self) -> str:
245
- """
246
- Provides a prompt to compress the task history.
247
- """
248
  return "Do you want to compress the task history?"
249
 
 
250
  def log_prompt(self) -> str:
251
- """
252
- Provides a prompt to log a specific event.
253
- """
254
  return "What event do you want to log?"
255
 
 
256
  def log_response(self, event: str) -> str:
257
- """
258
- Logs the specified event.
259
- """
260
  print(f"Event logged: {event}")
261
  return "Event logged successfully."
262
 
 
263
  def modify_prompt(self, prompt: str) -> str:
264
- """
265
- Modifies an existing prompt.
266
- """
267
  try:
268
  # Find the prompt to modify
269
  # Update the prompt
@@ -271,46 +222,42 @@ class AIAgent:
271
  except Exception as e:
272
  raise PromptManagementError(f"Error modifying prompt: {e}")
273
 
 
274
  def prefix(self, text: str) -> str:
275
- """
276
- Adds a prefix to the provided text.
277
- """
278
  return f"PREFIX: {text}"
279
 
 
280
  def search_query(self, query: str) -> str:
281
- """
282
- Provides a search query for the specified topic.
283
- """
284
  return f"Search query: {query}"
285
 
 
286
  def read_prompt(self, file_path: str) -> str:
287
- """
288
- Provides a prompt to read the contents of a file.
289
- """
290
  try:
291
  with open(file_path, 'r') as f:
292
  contents = f.read()
293
  return contents
 
 
294
  except Exception as e:
295
  raise InvalidInputError(f"Error reading file: {e}")
296
 
 
297
  def task_prompt(self) -> str:
298
- """
299
- Provides a prompt to start a new task.
300
- """
301
  return "What task do you want to start?"
302
 
 
303
  def understand_test_results_prompt(self) -> str:
304
- """
305
- Provides a prompt to understand the test results.
306
- """
307
  return "What do you want to know about the test results?"
308
 
 
309
  def handle_input(self, input_str: str):
310
- """
311
- Handles user input and executes the corresponding action.
312
- """
313
- if input_str:
314
  action, *args = input_str.split()
315
  if action in self.tools:
316
  if args:
@@ -328,22 +275,20 @@ class AIAgent:
328
  print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: {self.tools[action](' '.join(args))}")
329
  else:
330
  raise InvalidActionError("Invalid action. Please choose a valid action from the list of tools.")
331
- else:
332
- # Handle empty input (e.g., display a message or do nothing)
333
- print("Please provide input.")
334
- except (InvalidActionError, InvalidInputError, CodeGenerationError, CodeRefinementError,
335
- CodeTestingError, CodeIntegrationError, AppTestingError, WorkspaceExplorerError,
336
- PromptManagementError, SearchError) as e:
337
  print(f"Error: {e}")
338
 
 
339
  def run(self):
340
- """
341
- Runs the agent continuously, waiting for user input.
342
- """
343
  while True:
344
  input_str = input("Enter a command for the AI Agent: ")
345
  self.handle_input(input_str)
346
 
 
347
  if __name__ == '__main__':
348
  agent = AIAgent()
349
  st.title("AI Agent")
 
1
  import os
2
  import subprocess
3
+ import streamlit as st # For Streamlit
4
+ import gradio as gr # For Gradio
5
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
6
  import black
7
  from pylint import lint
 
13
  from bs4 import BeautifulSoup
14
  from typing import List, Dict, Optional
15
 
16
+ from utils.code_utils import (
17
+ refine_code,
18
+ test_code,
19
+ integrate_code,
20
+ CodeRefinementError,
21
+ CodeTestingError,
22
+ CodeIntegrationError,
23
+ )
24
+
25
+ # --- Define custom exceptions for better error handling ---
26
  class InvalidActionError(Exception):
27
  """Raised when an invalid action is provided."""
28
  pass
 
35
  """Raised when code generation fails."""
36
  pass
37
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  class AppTestingError(Exception):
39
  """Raised when app testing fails."""
40
  pass
 
51
  """Raised when search fails."""
52
  pass
53
 
54
+ # --- Define a class for the AI Agent ---
55
  class AIAgent:
56
  def __init__(self):
57
+ # --- Initialize tools and attributes ---
58
  self.tools = {
59
  "SEARCH": self.search,
60
  "CODEGEN": self.code_generation,
61
+ "REFINE-CODE": refine_code, # Use external function
62
+ "TEST-CODE": test_code, # Use external function
63
+ "INTEGRATE-CODE": integrate_code, # Use external function
64
  "TEST-APP": self.test_app,
65
  "GENERATE-REPORT": self.generate_report,
66
  "WORKSPACE-EXPLORER": self.workspace_explorer,
 
82
  self.prompts: List[str] = [] # Store prompts for future use
83
  self.code_generator = pipeline('text-generation', model='gpt2') # Initialize code generator
84
 
85
+ # --- Implement search functionality ---
86
  def search(self, query: str) -> List[str]:
87
+ """Performs a web search using the specified search engine."""
 
 
88
  search_url = self.search_engine_url + query
89
  try:
90
  response = requests.get(search_url)
 
95
  except requests.exceptions.RequestException as e:
96
  raise SearchError(f"Error during search: {e}")
97
 
98
+ # --- Implement code generation functionality ---
99
  def code_generation(self, snippet: str) -> str:
100
+ """Generates code based on the provided snippet."""
 
 
101
  try:
102
  generated_text = self.code_generator(snippet, max_length=500, num_return_sequences=1)[0]['generated_text']
103
  return generated_text
104
  except Exception as e:
105
  raise CodeGenerationError(f"Error during code generation: {e}")
106
 
107
+ # --- Implement app testing functionality ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  def test_app(self) -> str:
109
+ """Tests the functionality of the app."""
 
 
110
  try:
111
  subprocess.run(['streamlit', 'run', 'app.py'], check=True)
112
  return "App tested successfully."
113
  except subprocess.CalledProcessError as e:
114
  raise AppTestingError(f"Error during app testing: {e}")
115
 
116
+ # --- Implement report generation functionality ---
117
  def generate_report(self) -> str:
118
+ """Generates a report based on the task history."""
 
 
119
  report = f"## Task Report: {self.current_task}\n\n"
120
  for task in self.task_history:
121
  report += f"**Action:** {task['action']}\n"
 
123
  report += f"**Output:** {task['output']}\n\n"
124
  return report
125
 
126
+ # --- Implement workspace exploration functionality ---
127
  def workspace_explorer(self) -> str:
128
+ """Provides a workspace explorer functionality."""
 
 
129
  try:
130
  current_directory = os.getcwd()
131
  directories = []
 
140
  except Exception as e:
141
  raise WorkspaceExplorerError(f"Error during workspace exploration: {e}")
142
 
143
+ # --- Implement prompt management functionality ---
144
  def add_prompt(self, prompt: str) -> str:
145
+ """Adds a new prompt to the agent's knowledge base."""
 
 
146
  try:
147
  self.prompts.append(prompt)
148
  return f"Prompt '{prompt}' added successfully."
149
  except Exception as e:
150
  raise PromptManagementError(f"Error adding prompt: {e}")
151
 
152
+ # --- Implement prompt generation functionality ---
153
  def action_prompt(self, action: str) -> str:
154
+ """Provides a prompt for a specific action."""
 
 
155
  try:
156
  if action == "SEARCH":
157
  return "What do you want to search for?"
 
196
  except InvalidActionError as e:
197
  raise e
198
 
199
+ # --- Implement prompt generation functionality ---
200
  def compress_history_prompt(self) -> str:
201
+ """Provides a prompt to compress the task history."""
 
 
202
  return "Do you want to compress the task history?"
203
 
204
+ # --- Implement prompt generation functionality ---
205
  def log_prompt(self) -> str:
206
+ """Provides a prompt to log a specific event."""
 
 
207
  return "What event do you want to log?"
208
 
209
+ # --- Implement logging functionality ---
210
  def log_response(self, event: str) -> str:
211
+ """Logs the specified event."""
 
 
212
  print(f"Event logged: {event}")
213
  return "Event logged successfully."
214
 
215
+ # --- Implement prompt modification functionality ---
216
  def modify_prompt(self, prompt: str) -> str:
217
+ """Modifies an existing prompt."""
 
 
218
  try:
219
  # Find the prompt to modify
220
  # Update the prompt
 
222
  except Exception as e:
223
  raise PromptManagementError(f"Error modifying prompt: {e}")
224
 
225
+ # --- Implement prefix functionality ---
226
  def prefix(self, text: str) -> str:
227
+ """Adds a prefix to the provided text."""
 
 
228
  return f"PREFIX: {text}"
229
 
230
+ # --- Implement search query generation functionality ---
231
  def search_query(self, query: str) -> str:
232
+ """Provides a search query for the specified topic."""
 
 
233
  return f"Search query: {query}"
234
 
235
+ # --- Implement file reading functionality ---
236
  def read_prompt(self, file_path: str) -> str:
237
+ """Provides a prompt to read the contents of a file."""
 
 
238
  try:
239
  with open(file_path, 'r') as f:
240
  contents = f.read()
241
  return contents
242
+ except FileNotFoundError:
243
+ raise InvalidInputError(f"Error: File not found: {file_path}")
244
  except Exception as e:
245
  raise InvalidInputError(f"Error reading file: {e}")
246
 
247
+ # --- Implement task prompt generation functionality ---
248
  def task_prompt(self) -> str:
249
+ """Provides a prompt to start a new task."""
 
 
250
  return "What task do you want to start?"
251
 
252
+ # --- Implement test results understanding prompt generation functionality ---
253
  def understand_test_results_prompt(self) -> str:
254
+ """Provides a prompt to understand the test results."""
 
 
255
  return "What do you want to know about the test results?"
256
 
257
+ # --- Implement input handling functionality ---
258
  def handle_input(self, input_str: str):
259
+ """Handles user input and executes the corresponding action."""
260
+ try:
 
 
261
  action, *args = input_str.split()
262
  if action in self.tools:
263
  if args:
 
275
  print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: {self.tools[action](' '.join(args))}")
276
  else:
277
  raise InvalidActionError("Invalid action. Please choose a valid action from the list of tools.")
278
+ except (InvalidActionError, InvalidInputError, CodeGenerationError,
279
+ CodeRefinementError, CodeTestingError, CodeIntegrationError,
280
+ AppTestingError, WorkspaceExplorerError, PromptManagementError,
281
+ SearchError) as e:
 
 
282
  print(f"Error: {e}")
283
 
284
+ # --- Implement the main loop of the agent ---
285
  def run(self):
286
+ """Runs the agent continuously, waiting for user input."""
 
 
287
  while True:
288
  input_str = input("Enter a command for the AI Agent: ")
289
  self.handle_input(input_str)
290
 
291
+ # --- Streamlit Integration ---
292
  if __name__ == '__main__':
293
  agent = AIAgent()
294
  st.title("AI Agent")