acecalisto3 commited on
Commit
f8447d7
·
verified ·
1 Parent(s): a37df9c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -57
app.py CHANGED
@@ -17,30 +17,51 @@ class InvalidActionError(Exception):
17
  """Raised when an invalid action is provided."""
18
  pass
19
 
 
20
  class InvalidInputError(Exception):
21
  """Raised when invalid input is provided for an action."""
22
  pass
23
 
 
24
  class CodeGenerationError(Exception):
25
  """Raised when code generation fails."""
26
  pass
27
 
 
28
  class AppTestingError(Exception):
29
  """Raised when app testing fails."""
30
  pass
31
 
 
32
  class WorkspaceExplorerError(Exception):
33
  """Raised when workspace exploration fails."""
34
  pass
35
 
 
36
  class PromptManagementError(Exception):
37
  """Raised when prompt management fails."""
38
  pass
39
 
 
40
  class SearchError(Exception):
41
  """Raised when search fails."""
42
  pass
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # --- AI Agent Class ---
45
  class AIAgent:
46
  def __init__(self):
@@ -48,9 +69,9 @@ class AIAgent:
48
  self.tools = {
49
  "SEARCH": self.search,
50
  "CODEGEN": self.code_generation,
51
- "REFINE-CODE": self.refine_code, # Implemented within the class
52
- "TEST-CODE": self.test_code, # Implemented within the class
53
- "INTEGRATE-CODE": self.integrate_code, # Implemented within the class
54
  "TEST-APP": self.test_app,
55
  "GENERATE-REPORT": self.generate_report,
56
  "WORKSPACE-EXPLORER": self.workspace_explorer,
@@ -89,17 +110,17 @@ class AIAgent:
89
  def code_generation(self, snippet: str) -> str:
90
  """Generates code based on the provided snippet or description."""
91
  try:
92
- generated_text = self.code_generator(snippet, max_length=500, num_return_sequences=1)[0]['generated_text']
 
 
93
  return generated_text
94
  except Exception as e:
95
  raise CodeGenerationError(f"Error during code generation: {e}")
96
 
97
  # --- Code Refinement Functionality ---
98
- def refine_code(self, file_path: str) -> str:
99
- """Refines the code in the specified file."""
100
  try:
101
- with open(file_path, 'r') as f:
102
- code = f.read()
103
  refined_code = black.format_str(code, mode=black.FileMode())
104
  return refined_code
105
  except black.InvalidInput:
@@ -108,13 +129,15 @@ class AIAgent:
108
  raise CodeRefinementError(f"Error during code refinement: {e}")
109
 
110
  # --- Code Testing Functionality ---
111
- def test_code(self, file_path: str) -> str:
112
- """Tests the code in the specified file."""
113
  try:
114
- results = lint.run(file_path, do_exit=False)
115
- report = StringIO()
116
- results.report(report=report)
117
- return report.getvalue()
 
 
118
  except Exception as e:
119
  raise CodeTestingError(f"Error during code testing: {e}")
120
 
@@ -122,12 +145,11 @@ class AIAgent:
122
  def integrate_code(self, file_path: str, code_snippet: str) -> str:
123
  """Integrates the code snippet into the specified file."""
124
  try:
125
- with open(file_path, 'r') as f:
126
- existing_code = f.read()
127
- integrated_code = existing_code + "\n" + code_snippet
128
- with open(file_path, 'w') as f:
129
- f.write(integrated_code)
130
- return f"Code snippet integrated into {file_path} successfully."
131
  except Exception as e:
132
  raise CodeIntegrationError(f"Error during code integration: {e}")
133
 
@@ -185,11 +207,11 @@ class AIAgent:
185
  elif action == "CODEGEN":
186
  return "Provide a code snippet to generate code from, or describe what you want the code to do."
187
  elif action == "REFINE-CODE":
188
- return "Provide the file path of the code to refine."
189
  elif action == "TEST-CODE":
190
- return "Provide the file path of the code to test."
191
  elif action == "INTEGRATE-CODE":
192
- return "Provide the file path and code snippet to integrate."
193
  elif action == "TEST-APP":
194
  return "Test the application."
195
  elif action == "GENERATE-REPORT":
@@ -289,40 +311,66 @@ class AIAgent:
289
  if action in self.tools:
290
  if args:
291
  try:
292
- self.task_history.append({
293
- "action": action,
294
- "input": " ".join(args),
295
- "output": self.tools[action](" ".join(args))
296
- })
297
- print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: {self.tools[action](' '.join(args))}")
 
 
 
 
298
  except Exception as e:
299
- self.task_history.append({
300
- "action": action,
301
- "input": " ".join(args),
302
- "output": f"Error: {e}"
303
- })
304
- print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: Error: {e}")
 
 
 
 
305
  else:
306
  try:
307
- self.task_history.append({
308
- "action": action,
309
- "input": None,
310
- "output": self.tools[action]()
311
- })
312
- print(f"Action: {action}\nInput: None\nOutput: {self.tools[action]()}")
 
 
 
 
313
  except Exception as e:
314
- self.task_history.append({
315
- "action": action,
316
- "input": None,
317
- "output": f"Error: {e}"
318
- })
319
- print(f"Action: {action}\nInput: None\nOutput: Error: {e}")
 
 
 
 
320
  else:
321
- raise InvalidActionError("Invalid action. Please choose a valid action from the list of tools.")
322
- except (InvalidActionError, InvalidInputError, CodeGenerationError,
323
- CodeRefinementError, CodeTestingError, CodeIntegrationError,
324
- AppTestingError, WorkspaceExplorerError, PromptManagementError,
325
- SearchError) as e:
 
 
 
 
 
 
 
 
 
 
326
  print(f"Error: {e}")
327
 
328
  # --- Main Loop of the Agent ---
@@ -332,31 +380,34 @@ class AIAgent:
332
  input_str = input("Enter a command for the AI Agent: ")
333
  self.handle_input(input_str)
334
 
 
335
  # --- Streamlit Integration ---
336
- if __name__ == '__main__':
337
  agent = AIAgent()
338
  st.title("AI Agent")
339
  st.write("Enter a command for the AI Agent:")
340
  input_str = st.text_input("")
341
- agent.handle_input(input_str)
342
- agent.run()
 
343
 
344
  # --- Gradio Integration ---
345
  def gradio_interface(input_text):
346
  """Gradio interface function."""
347
  try:
348
  agent.handle_input(input_text)
349
- output = agent.task_history[-1]['output'] # Get the latest output
350
  return output
351
  except Exception as e:
352
  return f"Error: {e}"
353
 
 
354
  iface = gr.Interface(
355
  fn=gradio_interface,
356
  inputs=gr.Textbox(label="Enter Command"),
357
  outputs=gr.Textbox(label="Output"),
358
  title="AI Agent",
359
- description="Interact with the AI Agent."
360
  )
361
 
362
  iface.launch()
 
17
  """Raised when an invalid action is provided."""
18
  pass
19
 
20
+
21
  class InvalidInputError(Exception):
22
  """Raised when invalid input is provided for an action."""
23
  pass
24
 
25
+
26
  class CodeGenerationError(Exception):
27
  """Raised when code generation fails."""
28
  pass
29
 
30
+
31
  class AppTestingError(Exception):
32
  """Raised when app testing fails."""
33
  pass
34
 
35
+
36
  class WorkspaceExplorerError(Exception):
37
  """Raised when workspace exploration fails."""
38
  pass
39
 
40
+
41
  class PromptManagementError(Exception):
42
  """Raised when prompt management fails."""
43
  pass
44
 
45
+
46
  class SearchError(Exception):
47
  """Raised when search fails."""
48
  pass
49
 
50
+
51
+ class CodeRefinementError(Exception):
52
+ """Raised when code refinement fails."""
53
+ pass
54
+
55
+
56
+ class CodeTestingError(Exception):
57
+ """Raised when code testing fails."""
58
+ pass
59
+
60
+
61
+ class CodeIntegrationError(Exception):
62
+ """Raised when code integration fails."""
63
+ pass
64
+
65
  # --- AI Agent Class ---
66
  class AIAgent:
67
  def __init__(self):
 
69
  self.tools = {
70
  "SEARCH": self.search,
71
  "CODEGEN": self.code_generation,
72
+ "REFINE-CODE": self.refine_code, # Use internal function
73
+ "TEST-CODE": self.test_code, # Use internal function
74
+ "INTEGRATE-CODE": self.integrate_code, # Use internal function
75
  "TEST-APP": self.test_app,
76
  "GENERATE-REPORT": self.generate_report,
77
  "WORKSPACE-EXPLORER": self.workspace_explorer,
 
110
  def code_generation(self, snippet: str) -> str:
111
  """Generates code based on the provided snippet or description."""
112
  try:
113
+ generated_text = self.code_generator(snippet, max_length=500, num_return_sequences=1)[0][
114
+ 'generated_text'
115
+ ]
116
  return generated_text
117
  except Exception as e:
118
  raise CodeGenerationError(f"Error during code generation: {e}")
119
 
120
  # --- Code Refinement Functionality ---
121
+ def refine_code(self, code: str) -> str:
122
+ """Refines the provided code string."""
123
  try:
 
 
124
  refined_code = black.format_str(code, mode=black.FileMode())
125
  return refined_code
126
  except black.InvalidInput:
 
129
  raise CodeRefinementError(f"Error during code refinement: {e}")
130
 
131
  # --- Code Testing Functionality ---
132
+ def test_code(self, code: str) -> str:
133
+ """Tests the provided code string using pylint."""
134
  try:
135
+ # Use pylint to lint the code
136
+ lint_output = StringIO()
137
+ sys.stdout = lint_output
138
+ lint.Run(code.split('\n'), do_exit=False)
139
+ sys.stdout = sys.__stdout__
140
+ return lint_output.getvalue()
141
  except Exception as e:
142
  raise CodeTestingError(f"Error during code testing: {e}")
143
 
 
145
  def integrate_code(self, file_path: str, code_snippet: str) -> str:
146
  """Integrates the code snippet into the specified file."""
147
  try:
148
+ # For simplicity, we'll just append the code snippet to the file
149
+ # In a real scenario, you'd need more sophisticated logic
150
+ with open(file_path, 'a') as f:
151
+ f.write(code_snippet)
152
+ return f"Code snippet integrated into {file_path}"
 
153
  except Exception as e:
154
  raise CodeIntegrationError(f"Error during code integration: {e}")
155
 
 
207
  elif action == "CODEGEN":
208
  return "Provide a code snippet to generate code from, or describe what you want the code to do."
209
  elif action == "REFINE-CODE":
210
+ return "Provide the code to refine."
211
  elif action == "TEST-CODE":
212
+ return "Provide the code to test."
213
  elif action == "INTEGRATE-CODE":
214
+ return "Provide the file path and code snippet to integrate. For example: /path/to/your/file.py \"\"\"print('Hello, World!')\"\"\""
215
  elif action == "TEST-APP":
216
  return "Test the application."
217
  elif action == "GENERATE-REPORT":
 
311
  if action in self.tools:
312
  if args:
313
  try:
314
+ self.task_history.append(
315
+ {
316
+ "action": action,
317
+ "input": " ".join(args),
318
+ "output": self.tools[action](" ".join(args)),
319
+ }
320
+ )
321
+ print(
322
+ f"Action: {action}\nInput: {' '.join(args)}\nOutput: {self.tools[action](' '.join(args))}"
323
+ )
324
  except Exception as e:
325
+ self.task_history.append(
326
+ {
327
+ "action": action,
328
+ "input": " ".join(args),
329
+ "output": f"Error: {e}",
330
+ }
331
+ )
332
+ print(
333
+ f"Action: {action}\nInput: {' '.join(args)}\nOutput: Error: {e}"
334
+ )
335
  else:
336
  try:
337
+ self.task_history.append(
338
+ {
339
+ "action": action,
340
+ "input": None,
341
+ "output": self.tools[action](),
342
+ }
343
+ )
344
+ print(
345
+ f"Action: {action}\nInput: None\nOutput: {self.tools[action]()}"
346
+ )
347
  except Exception as e:
348
+ self.task_history.append(
349
+ {
350
+ "action": action,
351
+ "input": None,
352
+ "output": f"Error: {e}",
353
+ }
354
+ )
355
+ print(
356
+ f"Action: {action}\nInput: None\nOutput: Error: {e}"
357
+ )
358
  else:
359
+ raise InvalidActionError(
360
+ "Invalid action. Please choose a valid action from the list of tools."
361
+ )
362
+ except (
363
+ InvalidActionError,
364
+ InvalidInputError,
365
+ CodeGenerationError,
366
+ CodeRefinementError,
367
+ CodeTestingError,
368
+ CodeIntegrationError,
369
+ AppTestingError,
370
+ WorkspaceExplorerError,
371
+ PromptManagementError,
372
+ SearchError,
373
+ ) as e:
374
  print(f"Error: {e}")
375
 
376
  # --- Main Loop of the Agent ---
 
380
  input_str = input("Enter a command for the AI Agent: ")
381
  self.handle_input(input_str)
382
 
383
+
384
  # --- Streamlit Integration ---
385
+ if __name__ == "__main__":
386
  agent = AIAgent()
387
  st.title("AI Agent")
388
  st.write("Enter a command for the AI Agent:")
389
  input_str = st.text_input("")
390
+ if input_str:
391
+ agent.handle_input(input_str)
392
+ # agent.run() # Removed to avoid conflict with Streamlit
393
 
394
  # --- Gradio Integration ---
395
  def gradio_interface(input_text):
396
  """Gradio interface function."""
397
  try:
398
  agent.handle_input(input_text)
399
+ output = agent.task_history[-1]["output"] # Get the latest output
400
  return output
401
  except Exception as e:
402
  return f"Error: {e}"
403
 
404
+
405
  iface = gr.Interface(
406
  fn=gradio_interface,
407
  inputs=gr.Textbox(label="Enter Command"),
408
  outputs=gr.Textbox(label="Output"),
409
  title="AI Agent",
410
+ description="Interact with the AI Agent.",
411
  )
412
 
413
  iface.launch()