Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
import os
|
2 |
import subprocess
|
3 |
-
import streamlit as st
|
4 |
-
import gradio as gr
|
5 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
6 |
import black
|
7 |
from pylint import lint
|
@@ -22,7 +22,7 @@ from utils.code_utils import (
|
|
22 |
CodeIntegrationError,
|
23 |
)
|
24 |
|
25 |
-
# ---
|
26 |
class InvalidActionError(Exception):
|
27 |
"""Raised when an invalid action is provided."""
|
28 |
pass
|
@@ -51,10 +51,10 @@ class SearchError(Exception):
|
|
51 |
"""Raised when search fails."""
|
52 |
pass
|
53 |
|
54 |
-
# ---
|
55 |
class AIAgent:
|
56 |
def __init__(self):
|
57 |
-
# --- Initialize
|
58 |
self.tools = {
|
59 |
"SEARCH": self.search,
|
60 |
"CODEGEN": self.code_generation,
|
@@ -81,8 +81,9 @@ class AIAgent:
|
|
81 |
self.search_engine_url: str = "https://www.google.com/search?q=" # Default search engine
|
82 |
self.prompts: List[str] = [] # Store prompts for future use
|
83 |
self.code_generator = pipeline('text-generation', model='gpt2') # Initialize code generator
|
|
|
84 |
|
85 |
-
# ---
|
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
|
@@ -95,16 +96,30 @@ class AIAgent:
|
|
95 |
except requests.exceptions.RequestException as e:
|
96 |
raise SearchError(f"Error during search: {e}")
|
97 |
|
98 |
-
# ---
|
99 |
def code_generation(self, snippet: str) -> str:
|
100 |
-
"""Generates code based on the provided snippet."""
|
101 |
try:
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
except Exception as e:
|
105 |
raise CodeGenerationError(f"Error during code generation: {e}")
|
106 |
|
107 |
-
# ---
|
108 |
def test_app(self) -> str:
|
109 |
"""Tests the functionality of the app."""
|
110 |
try:
|
@@ -113,7 +128,7 @@ class AIAgent:
|
|
113 |
except subprocess.CalledProcessError as e:
|
114 |
raise AppTestingError(f"Error during app testing: {e}")
|
115 |
|
116 |
-
# ---
|
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"
|
@@ -123,7 +138,7 @@ class AIAgent:
|
|
123 |
report += f"**Output:** {task['output']}\n\n"
|
124 |
return report
|
125 |
|
126 |
-
# ---
|
127 |
def workspace_explorer(self) -> str:
|
128 |
"""Provides a workspace explorer functionality."""
|
129 |
try:
|
@@ -140,7 +155,7 @@ class AIAgent:
|
|
140 |
except Exception as e:
|
141 |
raise WorkspaceExplorerError(f"Error during workspace exploration: {e}")
|
142 |
|
143 |
-
# ---
|
144 |
def add_prompt(self, prompt: str) -> str:
|
145 |
"""Adds a new prompt to the agent's knowledge base."""
|
146 |
try:
|
@@ -149,14 +164,14 @@ class AIAgent:
|
|
149 |
except Exception as e:
|
150 |
raise PromptManagementError(f"Error adding prompt: {e}")
|
151 |
|
152 |
-
# ---
|
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?"
|
158 |
elif action == "CODEGEN":
|
159 |
-
return "Provide a code snippet to generate code from."
|
160 |
elif action == "REFINE-CODE":
|
161 |
return "Provide the file path of the code to refine."
|
162 |
elif action == "TEST-CODE":
|
@@ -196,23 +211,23 @@ class AIAgent:
|
|
196 |
except InvalidActionError as e:
|
197 |
raise e
|
198 |
|
199 |
-
# ---
|
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 |
-
# ---
|
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 |
-
# ---
|
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 |
-
# ---
|
216 |
def modify_prompt(self, prompt: str) -> str:
|
217 |
"""Modifies an existing prompt."""
|
218 |
try:
|
@@ -222,17 +237,17 @@ class AIAgent:
|
|
222 |
except Exception as e:
|
223 |
raise PromptManagementError(f"Error modifying prompt: {e}")
|
224 |
|
225 |
-
# ---
|
226 |
def prefix(self, text: str) -> str:
|
227 |
"""Adds a prefix to the provided text."""
|
228 |
return f"PREFIX: {text}"
|
229 |
|
230 |
-
# ---
|
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 |
-
# ---
|
236 |
def read_prompt(self, file_path: str) -> str:
|
237 |
"""Provides a prompt to read the contents of a file."""
|
238 |
try:
|
@@ -244,35 +259,52 @@ class AIAgent:
|
|
244 |
except Exception as e:
|
245 |
raise InvalidInputError(f"Error reading file: {e}")
|
246 |
|
247 |
-
# ---
|
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 |
-
# ---
|
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 |
-
# ---
|
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:
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
else:
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
276 |
else:
|
277 |
raise InvalidActionError("Invalid action. Please choose a valid action from the list of tools.")
|
278 |
except (InvalidActionError, InvalidInputError, CodeGenerationError,
|
@@ -281,7 +313,7 @@ class AIAgent:
|
|
281 |
SearchError) as e:
|
282 |
print(f"Error: {e}")
|
283 |
|
284 |
-
# ---
|
285 |
def run(self):
|
286 |
"""Runs the agent continuously, waiting for user input."""
|
287 |
while True:
|
@@ -295,4 +327,24 @@ if __name__ == '__main__':
|
|
295 |
st.write("Enter a command for the AI Agent:")
|
296 |
input_str = st.text_input("")
|
297 |
agent.handle_input(input_str)
|
298 |
-
agent.run()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import subprocess
|
3 |
+
import streamlit as st
|
4 |
+
import gradio as gr
|
5 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
6 |
import black
|
7 |
from pylint import lint
|
|
|
22 |
CodeIntegrationError,
|
23 |
)
|
24 |
|
25 |
+
# --- Custom Exceptions for Enhanced Error Handling ---
|
26 |
class InvalidActionError(Exception):
|
27 |
"""Raised when an invalid action is provided."""
|
28 |
pass
|
|
|
51 |
"""Raised when search fails."""
|
52 |
pass
|
53 |
|
54 |
+
# --- AI Agent Class ---
|
55 |
class AIAgent:
|
56 |
def __init__(self):
|
57 |
+
# --- Initialize Tools and Attributes ---
|
58 |
self.tools = {
|
59 |
"SEARCH": self.search,
|
60 |
"CODEGEN": self.code_generation,
|
|
|
81 |
self.search_engine_url: str = "https://www.google.com/search?q=" # Default search engine
|
82 |
self.prompts: List[str] = [] # Store prompts for future use
|
83 |
self.code_generator = pipeline('text-generation', model='gpt2') # Initialize code generator
|
84 |
+
self.openai_api_key = os.getenv("OPENAI_API_KEY") # Get OpenAI API Key from Environment Variable
|
85 |
|
86 |
+
# --- Search Functionality ---
|
87 |
def search(self, query: str) -> List[str]:
|
88 |
"""Performs a web search using the specified search engine."""
|
89 |
search_url = self.search_engine_url + query
|
|
|
96 |
except requests.exceptions.RequestException as e:
|
97 |
raise SearchError(f"Error during search: {e}")
|
98 |
|
99 |
+
# --- Code Generation Functionality ---
|
100 |
def code_generation(self, snippet: str) -> str:
|
101 |
+
"""Generates code based on the provided snippet or description."""
|
102 |
try:
|
103 |
+
# Use OpenAI's GPT-3 for more advanced code generation
|
104 |
+
if self.openai_api_key:
|
105 |
+
openai.api_key = self.openai_api_key
|
106 |
+
response = openai.Completion.create(
|
107 |
+
engine="text-davinci-003",
|
108 |
+
prompt=f"```python\n{snippet}\n```\nGenerate Python code based on this snippet or description:",
|
109 |
+
max_tokens=500,
|
110 |
+
temperature=0.7,
|
111 |
+
top_p=1,
|
112 |
+
frequency_penalty=0,
|
113 |
+
presence_penalty=0
|
114 |
+
)
|
115 |
+
return response.choices[0].text
|
116 |
+
else:
|
117 |
+
generated_text = self.code_generator(snippet, max_length=500, num_return_sequences=1)[0]['generated_text']
|
118 |
+
return generated_text
|
119 |
except Exception as e:
|
120 |
raise CodeGenerationError(f"Error during code generation: {e}")
|
121 |
|
122 |
+
# --- App Testing Functionality ---
|
123 |
def test_app(self) -> str:
|
124 |
"""Tests the functionality of the app."""
|
125 |
try:
|
|
|
128 |
except subprocess.CalledProcessError as e:
|
129 |
raise AppTestingError(f"Error during app testing: {e}")
|
130 |
|
131 |
+
# --- Report Generation Functionality ---
|
132 |
def generate_report(self) -> str:
|
133 |
"""Generates a report based on the task history."""
|
134 |
report = f"## Task Report: {self.current_task}\n\n"
|
|
|
138 |
report += f"**Output:** {task['output']}\n\n"
|
139 |
return report
|
140 |
|
141 |
+
# --- Workspace Exploration Functionality ---
|
142 |
def workspace_explorer(self) -> str:
|
143 |
"""Provides a workspace explorer functionality."""
|
144 |
try:
|
|
|
155 |
except Exception as e:
|
156 |
raise WorkspaceExplorerError(f"Error during workspace exploration: {e}")
|
157 |
|
158 |
+
# --- Prompt Management Functionality ---
|
159 |
def add_prompt(self, prompt: str) -> str:
|
160 |
"""Adds a new prompt to the agent's knowledge base."""
|
161 |
try:
|
|
|
164 |
except Exception as e:
|
165 |
raise PromptManagementError(f"Error adding prompt: {e}")
|
166 |
|
167 |
+
# --- Prompt Generation Functionality ---
|
168 |
def action_prompt(self, action: str) -> str:
|
169 |
"""Provides a prompt for a specific action."""
|
170 |
try:
|
171 |
if action == "SEARCH":
|
172 |
return "What do you want to search for?"
|
173 |
elif action == "CODEGEN":
|
174 |
+
return "Provide a code snippet to generate code from, or describe what you want the code to do."
|
175 |
elif action == "REFINE-CODE":
|
176 |
return "Provide the file path of the code to refine."
|
177 |
elif action == "TEST-CODE":
|
|
|
211 |
except InvalidActionError as e:
|
212 |
raise e
|
213 |
|
214 |
+
# --- Prompt Generation Functionality ---
|
215 |
def compress_history_prompt(self) -> str:
|
216 |
"""Provides a prompt to compress the task history."""
|
217 |
return "Do you want to compress the task history?"
|
218 |
|
219 |
+
# --- Prompt Generation Functionality ---
|
220 |
def log_prompt(self) -> str:
|
221 |
"""Provides a prompt to log a specific event."""
|
222 |
return "What event do you want to log?"
|
223 |
|
224 |
+
# --- Logging Functionality ---
|
225 |
def log_response(self, event: str) -> str:
|
226 |
"""Logs the specified event."""
|
227 |
print(f"Event logged: {event}")
|
228 |
return "Event logged successfully."
|
229 |
|
230 |
+
# --- Prompt Modification Functionality ---
|
231 |
def modify_prompt(self, prompt: str) -> str:
|
232 |
"""Modifies an existing prompt."""
|
233 |
try:
|
|
|
237 |
except Exception as e:
|
238 |
raise PromptManagementError(f"Error modifying prompt: {e}")
|
239 |
|
240 |
+
# --- Prefix Functionality ---
|
241 |
def prefix(self, text: str) -> str:
|
242 |
"""Adds a prefix to the provided text."""
|
243 |
return f"PREFIX: {text}"
|
244 |
|
245 |
+
# --- Search Query Generation Functionality ---
|
246 |
def search_query(self, query: str) -> str:
|
247 |
"""Provides a search query for the specified topic."""
|
248 |
return f"Search query: {query}"
|
249 |
|
250 |
+
# --- File Reading Functionality ---
|
251 |
def read_prompt(self, file_path: str) -> str:
|
252 |
"""Provides a prompt to read the contents of a file."""
|
253 |
try:
|
|
|
259 |
except Exception as e:
|
260 |
raise InvalidInputError(f"Error reading file: {e}")
|
261 |
|
262 |
+
# --- Task Prompt Generation Functionality ---
|
263 |
def task_prompt(self) -> str:
|
264 |
"""Provides a prompt to start a new task."""
|
265 |
return "What task do you want to start?"
|
266 |
|
267 |
+
# --- Test Results Understanding Prompt Generation Functionality ---
|
268 |
def understand_test_results_prompt(self) -> str:
|
269 |
"""Provides a prompt to understand the test results."""
|
270 |
return "What do you want to know about the test results?"
|
271 |
|
272 |
+
# --- Input Handling Functionality ---
|
273 |
def handle_input(self, input_str: str):
|
274 |
"""Handles user input and executes the corresponding action."""
|
275 |
try:
|
276 |
action, *args = input_str.split()
|
277 |
if action in self.tools:
|
278 |
if args:
|
279 |
+
try:
|
280 |
+
self.task_history.append({
|
281 |
+
"action": action,
|
282 |
+
"input": " ".join(args),
|
283 |
+
"output": self.tools[action](" ".join(args))
|
284 |
+
})
|
285 |
+
print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: {self.tools[action](' '.join(args))}")
|
286 |
+
except Exception as e:
|
287 |
+
self.task_history.append({
|
288 |
+
"action": action,
|
289 |
+
"input": " ".join(args),
|
290 |
+
"output": f"Error: {e}"
|
291 |
+
})
|
292 |
+
print(f"Action: {action}\nInput: {' '.join(args)}\nOutput: Error: {e}")
|
293 |
else:
|
294 |
+
try:
|
295 |
+
self.task_history.append({
|
296 |
+
"action": action,
|
297 |
+
"input": None,
|
298 |
+
"output": self.tools[action]()
|
299 |
+
})
|
300 |
+
print(f"Action: {action}\nInput: None\nOutput: {self.tools[action]()}")
|
301 |
+
except Exception as e:
|
302 |
+
self.task_history.append({
|
303 |
+
"action": action,
|
304 |
+
"input": None,
|
305 |
+
"output": f"Error: {e}"
|
306 |
+
})
|
307 |
+
print(f"Action: {action}\nInput: None\nOutput: Error: {e}")
|
308 |
else:
|
309 |
raise InvalidActionError("Invalid action. Please choose a valid action from the list of tools.")
|
310 |
except (InvalidActionError, InvalidInputError, CodeGenerationError,
|
|
|
313 |
SearchError) as e:
|
314 |
print(f"Error: {e}")
|
315 |
|
316 |
+
# --- Main Loop of the Agent ---
|
317 |
def run(self):
|
318 |
"""Runs the agent continuously, waiting for user input."""
|
319 |
while True:
|
|
|
327 |
st.write("Enter a command for the AI Agent:")
|
328 |
input_str = st.text_input("")
|
329 |
agent.handle_input(input_str)
|
330 |
+
agent.run()
|
331 |
+
|
332 |
+
# --- Gradio Integration ---
|
333 |
+
def gradio_interface(input_text):
|
334 |
+
"""Gradio interface function."""
|
335 |
+
try:
|
336 |
+
agent.handle_input(input_text)
|
337 |
+
output = agent.task_history[-1]['output'] # Get the latest output
|
338 |
+
return output
|
339 |
+
except Exception as e:
|
340 |
+
return f"Error: {e}"
|
341 |
+
|
342 |
+
iface = gr.Interface(
|
343 |
+
fn=gradio_interface,
|
344 |
+
inputs=gr.Textbox(label="Enter Command"),
|
345 |
+
outputs=gr.Textbox(label="Output"),
|
346 |
+
title="AI Agent",
|
347 |
+
description="Interact with the AI Agent."
|
348 |
+
)
|
349 |
+
|
350 |
+
iface.launch()
|