daniel-kim commited on
Commit
2d3ad6d
·
1 Parent(s): fce4752

Delete app,py

Browse files
Files changed (1) hide show
  1. autogpt/app.py +0 -330
autogpt/app.py DELETED
@@ -1,330 +0,0 @@
1
- """ Command and Control """
2
- import json
3
- from typing import Dict, List, NoReturn, Union
4
-
5
- from autogpt.agent.agent_manager import AgentManager
6
- from autogpt.commands.analyze_code import analyze_code
7
- from autogpt.commands.audio_text import read_audio_from_file
8
- from autogpt.commands.execute_code import (
9
- execute_python_file,
10
- execute_shell,
11
- execute_shell_popen,
12
- )
13
- from autogpt.commands.file_operations import (
14
- append_to_file,
15
- delete_file,
16
- download_file,
17
- read_file,
18
- search_files,
19
- write_to_file,
20
- )
21
- from autogpt.commands.git_operations import clone_repository
22
- from autogpt.commands.google_search import google_official_search, google_search
23
- from autogpt.commands.image_gen import generate_image
24
- from autogpt.commands.improve_code import improve_code
25
- from autogpt.commands.twitter import send_tweet
26
- from autogpt.commands.web_requests import scrape_links, scrape_text
27
- from autogpt.commands.web_selenium import browse_website
28
- from autogpt.commands.write_tests import write_tests
29
- from autogpt.config import Config
30
- from autogpt.json_utils.json_fix_llm import fix_and_parse_json
31
- from autogpt.memory import get_memory
32
- from autogpt.processing.text import summarize_text
33
- from autogpt.speech import say_text
34
-
35
- CFG = Config()
36
- AGENT_MANAGER = AgentManager()
37
-
38
-
39
- def is_valid_int(value: str) -> bool:
40
- """Check if the value is a valid integer
41
-
42
- Args:
43
- value (str): The value to check
44
-
45
- Returns:
46
- bool: True if the value is a valid integer, False otherwise
47
- """
48
- try:
49
- int(value)
50
- return True
51
- except ValueError:
52
- return False
53
-
54
-
55
- def get_command(response_json: Dict):
56
- """Parse the response and return the command name and arguments
57
-
58
- Args:
59
- response_json (json): The response from the AI
60
-
61
- Returns:
62
- tuple: The command name and arguments
63
-
64
- Raises:
65
- json.decoder.JSONDecodeError: If the response is not valid JSON
66
-
67
- Exception: If any other error occurs
68
- """
69
- try:
70
- if "command" not in response_json:
71
- return "Error:", "Missing 'command' object in JSON"
72
-
73
- if not isinstance(response_json, dict):
74
- return "Error:", f"'response_json' object is not dictionary {response_json}"
75
-
76
- command = response_json["command"]
77
- if not isinstance(command, dict):
78
- return "Error:", "'command' object is not a dictionary"
79
-
80
- if "name" not in command:
81
- return "Error:", "Missing 'name' field in 'command' object"
82
-
83
- command_name = command["name"]
84
-
85
- # Use an empty dictionary if 'args' field is not present in 'command' object
86
- arguments = command.get("args", {})
87
-
88
- return command_name, arguments
89
- except json.decoder.JSONDecodeError:
90
- return "Error:", "Invalid JSON"
91
- # All other errors, return "Error: + error message"
92
- except Exception as e:
93
- return "Error:", str(e)
94
-
95
-
96
- def map_command_synonyms(command_name: str):
97
- """Takes the original command name given by the AI, and checks if the
98
- string matches a list of common/known hallucinations
99
- """
100
- synonyms = [
101
- ("write_file", "write_to_file"),
102
- ("create_file", "write_to_file"),
103
- ("search", "google"),
104
- ]
105
- for seen_command, actual_command_name in synonyms:
106
- if command_name == seen_command:
107
- return actual_command_name
108
- return command_name
109
-
110
-
111
- def execute_command(command_name: str, arguments):
112
- """Execute the command and return the result
113
-
114
- Args:
115
- command_name (str): The name of the command to execute
116
- arguments (dict): The arguments for the command
117
-
118
- Returns:
119
- str: The result of the command
120
- """
121
- try:
122
- command_name = map_command_synonyms(command_name.lower())
123
- if command_name == "google":
124
- # Check if the Google API key is set and use the official search method
125
- # If the API key is not set or has only whitespaces, use the unofficial
126
- # search method
127
- key = CFG.google_api_key
128
- if key and key.strip() and key != "your-google-api-key":
129
- google_result = google_official_search(arguments["input"])
130
- return google_result
131
- else:
132
- google_result = google_search(arguments["input"])
133
-
134
- # google_result can be a list or a string depending on the search results
135
- if isinstance(google_result, list):
136
- safe_message = [
137
- google_result_single.encode("utf-8", "ignore")
138
- for google_result_single in google_result
139
- ]
140
- else:
141
- safe_message = google_result.encode("utf-8", "ignore")
142
-
143
- return safe_message.decode("utf-8")
144
- elif command_name == "memory_add":
145
- memory = get_memory(CFG)
146
- return memory.add(arguments["string"])
147
- elif command_name == "start_agent":
148
- return start_agent(
149
- arguments["name"], arguments["task"], arguments["prompt"]
150
- )
151
- elif command_name == "message_agent":
152
- return message_agent(arguments["key"], arguments["message"])
153
- elif command_name == "list_agents":
154
- return list_agents()
155
- elif command_name == "delete_agent":
156
- return delete_agent(arguments["key"])
157
- elif command_name == "get_text_summary":
158
- return get_text_summary(arguments["url"], arguments["question"])
159
- elif command_name == "get_hyperlinks":
160
- return get_hyperlinks(arguments["url"])
161
- elif command_name == "clone_repository":
162
- return clone_repository(
163
- arguments["repository_url"], arguments["clone_path"]
164
- )
165
- elif command_name == "read_file":
166
- return read_file(arguments["file"])
167
- elif command_name == "write_to_file":
168
- return write_to_file(arguments["file"], arguments["text"])
169
- elif command_name == "append_to_file":
170
- return append_to_file(arguments["file"], arguments["text"])
171
- elif command_name == "delete_file":
172
- return delete_file(arguments["file"])
173
- elif command_name == "search_files":
174
- return search_files(arguments["directory"])
175
- elif command_name == "download_file":
176
- if not CFG.allow_downloads:
177
- return "Error: You do not have user authorization to download files locally."
178
- return download_file(arguments["url"], arguments["file"])
179
- elif command_name == "browse_website":
180
- return browse_website(arguments["url"], arguments["question"])
181
- # TODO: Change these to take in a file rather than pasted code, if
182
- # non-file is given, return instructions "Input should be a python
183
- # filepath, write your code to file and try again"
184
- elif command_name == "analyze_code":
185
- return analyze_code(arguments["code"])
186
- elif command_name == "improve_code":
187
- return improve_code(arguments["suggestions"], arguments["code"])
188
- elif command_name == "write_tests":
189
- return write_tests(arguments["code"], arguments.get("focus"))
190
- elif command_name == "execute_python_file": # Add this command
191
- return execute_python_file(arguments["file"])
192
- elif command_name == "execute_shell":
193
- if CFG.execute_local_commands:
194
- return execute_shell(arguments["command_line"])
195
- else:
196
- return (
197
- "You are not allowed to run local shell commands. To execute"
198
- " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
199
- "in your config. Do not attempt to bypass the restriction."
200
- )
201
- elif command_name == "execute_shell_popen":
202
- if CFG.execute_local_commands:
203
- return execute_shell_popen(arguments["command_line"])
204
- else:
205
- return (
206
- "You are not allowed to run local shell commands. To execute"
207
- " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
208
- "in your config. Do not attempt to bypass the restriction."
209
- )
210
- elif command_name == "read_audio_from_file":
211
- return read_audio_from_file(arguments["file"])
212
- elif command_name == "generate_image":
213
- return generate_image(arguments["prompt"])
214
- elif command_name == "send_tweet":
215
- return send_tweet(arguments["text"])
216
- elif command_name == "do_nothing":
217
- return "No action performed."
218
- elif command_name == "task_complete":
219
- shutdown()
220
- else:
221
- return (
222
- f"Unknown command '{command_name}'. Please refer to the 'COMMANDS'"
223
- " list for available commands and only respond in the specified JSON"
224
- " format."
225
- )
226
- except Exception as e:
227
- return f"Error: {str(e)}"
228
-
229
-
230
- def get_text_summary(url: str, question: str) -> str:
231
- """Return the results of a Google search
232
-
233
- Args:
234
- url (str): The url to scrape
235
- question (str): The question to summarize the text for
236
-
237
- Returns:
238
- str: The summary of the text
239
- """
240
- text = scrape_text(url)
241
- summary = summarize_text(url, text, question)
242
- return f""" "Result" : {summary}"""
243
-
244
-
245
- def get_hyperlinks(url: str) -> Union[str, List[str]]:
246
- """Return the results of a Google search
247
-
248
- Args:
249
- url (str): The url to scrape
250
-
251
- Returns:
252
- str or list: The hyperlinks on the page
253
- """
254
- return scrape_links(url)
255
-
256
-
257
- def shutdown() -> NoReturn:
258
- """Shut down the program"""
259
- print("Shutting down...")
260
- quit()
261
-
262
-
263
- def start_agent(name: str, task: str, prompt: str, model=CFG.fast_llm_model) -> str:
264
- """Start an agent with a given name, task, and prompt
265
-
266
- Args:
267
- name (str): The name of the agent
268
- task (str): The task of the agent
269
- prompt (str): The prompt for the agent
270
- model (str): The model to use for the agent
271
-
272
- Returns:
273
- str: The response of the agent
274
- """
275
- # Remove underscores from name
276
- voice_name = name.replace("_", " ")
277
-
278
- first_message = f"""You are {name}. Respond with: "Acknowledged"."""
279
- agent_intro = f"{voice_name} here, Reporting for duty!"
280
-
281
- # Create agent
282
- if CFG.speak_mode:
283
- say_text(agent_intro, 1)
284
- key, ack = AGENT_MANAGER.create_agent(task, first_message, model)
285
-
286
- if CFG.speak_mode:
287
- say_text(f"Hello {voice_name}. Your task is as follows. {task}.")
288
-
289
- # Assign task (prompt), get response
290
- agent_response = AGENT_MANAGER.message_agent(key, prompt)
291
-
292
- return f"Agent {name} created with key {key}. First response: {agent_response}"
293
-
294
-
295
- def message_agent(key: str, message: str) -> str:
296
- """Message an agent with a given key and message"""
297
- # Check if the key is a valid integer
298
- if is_valid_int(key):
299
- agent_response = AGENT_MANAGER.message_agent(int(key), message)
300
- else:
301
- return "Invalid key, must be an integer."
302
-
303
- # Speak response
304
- if CFG.speak_mode:
305
- say_text(agent_response, 1)
306
- return agent_response
307
-
308
-
309
- def list_agents():
310
- """List all agents
311
-
312
- Returns:
313
- str: A list of all agents
314
- """
315
- return "List of agents:\n" + "\n".join(
316
- [str(x[0]) + ": " + x[1] for x in AGENT_MANAGER.list_agents()]
317
- )
318
-
319
-
320
- def delete_agent(key: str) -> str:
321
- """Delete an agent with a given key
322
-
323
- Args:
324
- key (str): The key of the agent to delete
325
-
326
- Returns:
327
- str: A message indicating whether the agent was deleted or not
328
- """
329
- result = AGENT_MANAGER.delete_agent(key)
330
- return f"Agent {key} deleted." if result else f"Agent {key} does not exist."