examples.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. "This file lists some popular examples on how to use Gorilla Execution Engine"
  2. """
  3. PythonAPIExecutor
  4. - Create a python command in attempt to perform actions for the given prompt
  5. - If key(s) are needed, make sure they are in secret_store.json
  6. """
  7. import os
  8. from exec_engine.db_manager import MySQLManager, SQLiteManager
  9. from main import ExecutionEngine, PythonAPIExecutor
  10. from exec_engine.utils import SQL_Type, RESTful_Type, Filesystem_Type
  11. from pathlib import Path
  12. from dotenv import load_dotenv
  13. ROOT_FOLDER_PATH = os.path.dirname(Path(os.path.realpath(__file__)))
  14. def mysql_insert_new_row_with_dry_run(api_call=None):
  15. load_dotenv()
  16. # DB tests
  17. mysql_config = {
  18. 'user': os.environ.get('DATABASE_USER'),
  19. 'password': os.environ.get('DATABASE_PASSWORD'),
  20. 'host': os.environ.get('DATABASE_HOST'),
  21. 'database': os.environ.get('DATABASE_NAME')
  22. }
  23. if not api_call or not neg_api_call:
  24. api_call = "INSERT INTO students (name, year, major) VALUES ('Roy Huang', 4, 'Computer Science');"
  25. neg_api_call = """DELETE FROM students WHERE id IN (
  26. SELECT * FROM (
  27. SELECT MAX(id) FROM students
  28. ) AS subquery
  29. );
  30. """
  31. check_call = "SELECT * FROM students;"
  32. engine = ExecutionEngine()
  33. engine.set_dry_run(SQL_Type, True)
  34. db_manager = MySQLManager(mysql_config, docker_sandbox=engine.docker_sandbox)
  35. db_manager.connect()
  36. engine.initialize_db(debug_manager=db_manager)
  37. # avoid dry running the SELECTs
  38. print("DB before the insertion")
  39. print(engine._exec_sql_call(check_call))
  40. engine.exec_api_call(api_call=api_call, debug_neg=neg_api_call, api_type=SQL_Type)
  41. print("DB after the insertion")
  42. print(engine._exec_sql_call(check_call))
  43. engine._exec_sql_call(neg_api_call)
  44. print("DB after the reversion")
  45. print(engine._exec_sql_call(check_call))
  46. def create_new_file():
  47. test_dir = 'test'
  48. os.makedirs(test_dir, exist_ok=True)
  49. engine = ExecutionEngine()
  50. engine.initialize_fs(debug_path=test_dir)
  51. # Example usage
  52. engine.exec_api_call('ls -a', Filesystem_Type)
  53. engine.exec_api_call('echo "Hello, World!" > hello.txt', Filesystem_Type)
  54. engine.exec_api_call('ls -a', Filesystem_Type)
  55. engine.exec_api_call('cat hello.txt', Filesystem_Type)
  56. def prompt_api_execute(prompt):
  57. engine = ExecutionEngine()
  58. engine.api_executor = PythonAPIExecutor(engine.docker_sandbox)
  59. creds, services = engine.api_executor.prepare_credentials(prompt)
  60. forward_call, backward_call = engine.gen_api_pair(prompt, api_type=RESTful_Type, credentials=creds, model="gpt-4-turbo-preview")
  61. print(forward_call)
  62. output = engine.api_executor.execute_api_call(forward_call, services)
  63. return output
  64. def send_slack_message(content, display_name):
  65. prompt = """
  66. Send the message ({content}) to @{display_name} on slack .
  67. """.format(content=content, display_name=display_name.replace(" ", ""))
  68. print(prompt_api_execute(prompt))
  69. def delete_slack_message(display_name):
  70. prompt = """
  71. Delete the latest message I sent to the user {display_name} on slack direct message.
  72. """.format(display_name=display_name.replace(" ", "")).lower()
  73. print(prompt_api_execute(prompt))
  74. def latest_n_emails_gmail(n):
  75. prompt = """
  76. Who are the senders of the {n} most recent email in my gmail inbox?
  77. """.format(n=n)
  78. print(prompt_api_execute(prompt))
  79. def ask_general_question(question):
  80. print(prompt_api_execute(question))
  81. """
  82. FS management system
  83. """
  84. def full_file_system_demo():
  85. test_dir = 'test'
  86. os.makedirs(test_dir, exist_ok=True)
  87. engine = ExecutionEngine(path=test_dir)
  88. engine.initialize_fs(debug_path=test_dir)
  89. # Example usage
  90. engine._exec_filesystem_call('ls -a')
  91. engine.exec_api_call('echo "Hello, World!" > hello.txt', Filesystem_Type)
  92. engine._exec_filesystem_call('ls -a')
  93. engine._exec_filesystem_call('cat hello.txt')
  94. engine.commit_api_call(Filesystem_Type)
  95. print('\n\nCommited!\n\n')
  96. engine.exec_api_call('echo "Bad File!" > not_good.txt', Filesystem_Type)
  97. engine._exec_filesystem_call('ls -a', Filesystem_Type)
  98. engine._exec_filesystem_call('cat not_good.txt', Filesystem_Type)
  99. engine.undo_api_call(Filesystem_Type)
  100. print('\n\nReverted!\n\n')
  101. engine.exec_api_call('ls -a', Filesystem_Type)
  102. def mysql_insert_new_row_no_dry_run(api_call=None):
  103. load_dotenv()
  104. # DB tests
  105. mysql_config = {
  106. 'user': os.environ.get('DATABASE_USER'),
  107. 'password': os.environ.get('DATABASE_PASSWORD'),
  108. 'host': os.environ.get('DATABASE_HOST'),
  109. 'database': os.environ.get('DATABASE_NAME')
  110. }
  111. if not api_call or not neg_api_call:
  112. api_call = "INSERT INTO students (name, year, major) VALUES ('Roy Huang', 4, 'Computer Science');"
  113. neg_api_call = """
  114. DELETE FROM students WHERE id IN (
  115. SELECT * FROM (
  116. SELECT MAX(id) FROM students
  117. ) AS subquery
  118. );
  119. """
  120. check_call = "SELECT * FROM students;"
  121. engine = ExecutionEngine()
  122. db_manager = MySQLManager(mysql_config, docker_sandbox=engine.docker_sandbox)
  123. db_manager.connect()
  124. engine.initialize_db(debug_manager=db_manager)
  125. print('Current State:')
  126. print(engine._exec_sql_call(check_call))
  127. engine.exec_api_call("INSERT INTO students (name, year, major) VALUES ('Ray Huang', 4, 'Computer Science');", api_type=SQL_Type)
  128. print('New Commited State:')
  129. print(engine._exec_sql_call(check_call))
  130. engine.commit_api_call(SQL_Type)
  131. engine.exec_api_call("INSERT INTO students (name, year, major) VALUES ('Wrong dude', 1, 'high schooler');", api_type=SQL_Type)
  132. print('Uncommited Changed State:')
  133. print(engine._exec_sql_call(check_call))
  134. engine.undo_api_call(SQL_Type)
  135. print('Previous Commited Changed State:')
  136. print(engine._exec_sql_call(check_call))
  137. def fs_all_in():
  138. test_dir = 'test'
  139. os.makedirs(test_dir, exist_ok=True)
  140. engine = ExecutionEngine()
  141. engine.initialize_fs(debug_path=test_dir)
  142. # Example usage
  143. engine.exec_api_call('ls -a')
  144. engine.exec_api_call('echo "Hello, World!" > hello.txt')
  145. engine.exec_api_call('ls -a')
  146. engine.exec_api_call('cat hello.txt')
  147. engine.commit_api_call(Filesystem_Type)
  148. print('\n\nCommited!\n\n')
  149. engine.exec_api_call('echo "Bad File!" > not_good.txt')
  150. engine.exec_api_call('ls -a')
  151. engine.exec_api_call('cat not_good.txt')
  152. engine.undo_api_call(SQL_Type)
  153. print('\n\nReverted!\n\n')
  154. engine.exec_api_call('ls -a')
  155. def mysql_end_to_end_insert():
  156. load_dotenv()
  157. # DB tests
  158. mysql_config = {
  159. 'user': os.environ.get('DATABASE_USER'),
  160. 'password': os.environ.get('DATABASE_PASSWORD'),
  161. 'host': os.environ.get('DATABASE_HOST'),
  162. 'database': os.environ.get('DATABASE_NAME')
  163. }
  164. check_call = "SELECT * FROM students;"
  165. engine = ExecutionEngine()
  166. engine.set_dry_run(SQL_Type, True)
  167. db_manager = MySQLManager(mysql_config, docker_sandbox=engine.docker_sandbox)
  168. db_manager.connect()
  169. engine.initialize_db(debug_manager=db_manager)
  170. prompt = "i want to insert a new student name Shishir Patil who's a 1st year and a computer science major into the students table"
  171. # prompt = "i want to delete a student named ray Doe in the students table"
  172. print("Before execution:")
  173. print(engine._exec_sql_call(check_call))
  174. engine.run_prompt(prompt, SQL_Type)
  175. print("After execution:")
  176. print(engine._exec_sql_call(check_call))
  177. def sqlite_insert_with_dry_run_llm_reversion():
  178. engine = ExecutionEngine()
  179. db_path = os.path.join(ROOT_FOLDER_PATH, 'docker/sqllite_docker/example_sqlite.db')
  180. config = {'path': db_path}
  181. db_manager = SQLiteManager(config, engine.docker_sandbox)
  182. db_manager.connect()
  183. engine.initialize_db(debug_manager=db_manager)
  184. engine.set_dry_run(SQL_Type, True)
  185. check_call = "SELECT * FROM projects;"
  186. prompt = "i want to insert a new example row into the projects table"
  187. print("Before execution:")
  188. print(engine._exec_sql_call(check_call))
  189. engine.run_prompt(prompt, SQL_Type)
  190. print("After execution:")
  191. print(engine._exec_sql_call(check_call))
  192. engine.undo_api_call(SQL_Type)
  193. def fs_joke_prompt_demo():
  194. test_dir = 'test'
  195. os.makedirs(test_dir, exist_ok=True)
  196. engine = ExecutionEngine(path=test_dir)
  197. engine.initialize_fs(debug_path=test_dir)
  198. engine.set_dry_run(Filesystem_Type, True)
  199. # Example usage
  200. print("Before execution:")
  201. print(engine._exec_filesystem_call('ls -a'))
  202. engine.run_prompt("I want to create a file named joke.txt with a witty joke inside", Filesystem_Type)
  203. engine.commit_api_call(Filesystem_Type)
  204. print("After execution:")
  205. print(engine._exec_filesystem_call('ls -a'))
  206. print(engine._exec_filesystem_call('cat joke.txt'))
  207. if __name__ == "__main__":
  208. """
  209. NOTE: Feel free to uncomment any of the tests below to run the demo
  210. IMPORTANT: Follow the README to get set up
  211. """
  212. """
  213. File System Examples
  214. You can see the actual file changes inside test/ directory
  215. """
  216. # full_file_system_demo()
  217. # create_new_file()
  218. # fs_joke_prompt_demo()
  219. """
  220. MySQL Examples
  221. """
  222. # mysql_insert_new_row_with_dry_run()
  223. # mysql_insert_new_row_no_dry_run()
  224. # mysql_end_to_end_insert()
  225. """
  226. sqllite Examples
  227. """
  228. # sqlite_insert_with_dry_run_llm_reversion()
  229. """
  230. RESTful Examples
  231. """
  232. # SLACK (requires OAuth)
  233. # send_slack_message("yo", "Shishir Patil")
  234. # delete_slack_message("Shishir Patil")
  235. # SPOTIFY (requires OAuth)
  236. # spotify is sometimes a bit spotty (heh) and does not always work
  237. # create a new file in my dropbox account with some jokes
  238. # ask_general_question("find the user info associated with my spotify account")
  239. # DROPBOX (requires OAuth)
  240. # ask_general_question("create a new file in my dropbox account with some jokes")
  241. # ask_general_question("list all files in my dropbox account")
  242. # STRIPE (requires API key)
  243. # ask_general_question("create a new customer with email aaronhao@berkeley.edu on stripe")
  244. # ask_general_question("add 300 dollars to the balance of the customer with email aaronhao@berkeley.edu on stripe")
  245. # GITHUB (requires oauth)
  246. # ask_general_question("get my profile information from github")
  247. # ask_general_question("raise a github issue for my repository at [REPO] with text: [TEXT]")
  248. # DISCORD (requires oauth)
  249. # ask_general_question("what is the email associated with my discord account")
  250. # ask_general_question("What's the top rising stock today on alphavantage?")
  251. # ask_general_question("What's the weather today in San Francisco?")
  252. # ask_general_question("What's the estimated time of arrival to the Salesforce tower Sanfrancisco if I leave berkeley right now with Bart")
  253. pass