You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

agentchat_sql_spider.ipynb 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# SQL Agent for Spider text-to-SQL benchmark"
  8. ]
  9. },
  10. {
  11. "cell_type": "markdown",
  12. "metadata": {},
  13. "source": [
  14. "This notebook demonstrates a basic SQL agent that translates natural language questions into SQL queries."
  15. ]
  16. },
  17. {
  18. "cell_type": "markdown",
  19. "metadata": {},
  20. "source": [
  21. "## Environment\n",
  22. "\n",
  23. "For this demo, we use a SQLite database environment based on a standard text-to-sql benchmark called [Spider](https://yale-lily.github.io/spider). The environment provides a gym-like interface and can be used as follows."
  24. ]
  25. },
  26. {
  27. "cell_type": "code",
  28. "execution_count": 13,
  29. "metadata": {},
  30. "outputs": [
  31. {
  32. "name": "stdout",
  33. "output_type": "stream",
  34. "text": [
  35. "Loading cached Spider dataset from /home/wangdazhang/.cache/spider\n",
  36. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/flight_4\n",
  37. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/small_bank_1\n",
  38. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/icfp_1\n",
  39. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/twitter_1\n",
  40. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/epinions_1\n",
  41. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/chinook_1\n",
  42. "Schema file not found for /home/wangdazhang/.cache/spider/spider/database/company_1\n"
  43. ]
  44. }
  45. ],
  46. "source": [
  47. "# %pip install spider-env\n",
  48. "from spider_env import SpiderEnv\n",
  49. "\n",
  50. "from autogen import UserProxyAgent, ConversableAgent, config_list_from_json\n",
  51. "from typing import Annotated, Dict\n",
  52. "import json\n",
  53. "import os\n",
  54. "\n",
  55. "gym = SpiderEnv()\n",
  56. "\n",
  57. "# Randomly select a question from Spider\n",
  58. "observation, info = gym.reset()"
  59. ]
  60. },
  61. {
  62. "cell_type": "code",
  63. "execution_count": 14,
  64. "metadata": {},
  65. "outputs": [
  66. {
  67. "name": "stdout",
  68. "output_type": "stream",
  69. "text": [
  70. "Find the famous titles of artists that do not have any volume.\n"
  71. ]
  72. }
  73. ],
  74. "source": [
  75. "# The natural language question\n",
  76. "question = observation[\"instruction\"]\n",
  77. "print(question)"
  78. ]
  79. },
  80. {
  81. "cell_type": "code",
  82. "execution_count": 15,
  83. "metadata": {},
  84. "outputs": [
  85. {
  86. "name": "stdout",
  87. "output_type": "stream",
  88. "text": [
  89. "CREATE TABLE \"artist\" (\n",
  90. "\"Artist_ID\" int,\n",
  91. "\"Artist\" text,\n",
  92. "\"Age\" int,\n",
  93. "\"Famous_Title\" text,\n",
  94. "\"Famous_Release_date\" text,\n",
  95. "PRIMARY KEY (\"Artist_ID\")\n",
  96. ");\n",
  97. "CREATE TABLE \"volume\" (\n",
  98. "\"Volume_ID\" int,\n",
  99. "\"Volume_Issue\" text,\n",
  100. "\"Issue_Date\" text,\n",
  101. "\"Weeks_on_Top\" real,\n",
  102. "\"Song\" text,\n",
  103. "\"Artist_ID\" int,\n",
  104. "PRIMARY KEY (\"Volume_ID\"),\n",
  105. "FOREIGN KEY (\"Artist_ID\") REFERENCES \"artist\"(\"Artist_ID\")\n",
  106. ");\n",
  107. "CREATE TABLE \"music_festival\" (\n",
  108. "\"ID\" int,\n",
  109. "\"Music_Festival\" text,\n",
  110. "\"Date_of_ceremony\" text,\n",
  111. "\"Category\" text,\n",
  112. "\"Volume\" int,\n",
  113. "\"Result\" text,\n",
  114. "PRIMARY KEY (\"ID\"),\n",
  115. "FOREIGN KEY (\"Volume\") REFERENCES \"volume\"(\"Volume_ID\")\n",
  116. ");\n",
  117. "\n"
  118. ]
  119. }
  120. ],
  121. "source": [
  122. "# The schema of the corresponding database\n",
  123. "schema = info[\"schema\"]\n",
  124. "print(schema)"
  125. ]
  126. },
  127. {
  128. "cell_type": "markdown",
  129. "metadata": {},
  130. "source": [
  131. "## Agent Implementation\n",
  132. "\n",
  133. "Using AutoGen, a SQL agent can be implemented with a ConversableAgent. The gym environment executes the generated SQL query and the agent can take execution results as feedback to improve its generation in multiple rounds of conversations."
  134. ]
  135. },
  136. {
  137. "cell_type": "code",
  138. "execution_count": 16,
  139. "metadata": {},
  140. "outputs": [],
  141. "source": [
  142. "os.environ[\"AUTOGEN_USE_DOCKER\"] = \"False\"\n",
  143. "config_list = config_list_from_json(env_or_file=\"OAI_CONFIG_LIST\")\n",
  144. "\n",
  145. "\n",
  146. "def check_termination(msg: Dict):\n",
  147. " if \"tool_responses\" not in msg:\n",
  148. " return False\n",
  149. " json_str = msg[\"tool_responses\"][0][\"content\"]\n",
  150. " obj = json.loads(json_str)\n",
  151. " return \"error\" not in obj or obj[\"error\"] is None and obj[\"reward\"] == 1\n",
  152. "\n",
  153. "\n",
  154. "sql_writer = ConversableAgent(\n",
  155. " \"sql_writer\",\n",
  156. " llm_config={\"config_list\": config_list},\n",
  157. " system_message=\"You are good at writing SQL queries. Always respond with a function call to execute_sql().\",\n",
  158. " is_termination_msg=check_termination,\n",
  159. ")\n",
  160. "user_proxy = UserProxyAgent(\"user_proxy\", human_input_mode=\"NEVER\", max_consecutive_auto_reply=5)\n",
  161. "\n",
  162. "\n",
  163. "@sql_writer.register_for_llm(description=\"Function for executing SQL query and returning a response\")\n",
  164. "@user_proxy.register_for_execution()\n",
  165. "def execute_sql(\n",
  166. " reflection: Annotated[str, \"Think about what to do\"], sql: Annotated[str, \"SQL query\"]\n",
  167. ") -> Annotated[Dict[str, str], \"Dictionary with keys 'result' and 'error'\"]:\n",
  168. " observation, reward, _, _, info = gym.step(sql)\n",
  169. " error = observation[\"feedback\"][\"error\"]\n",
  170. " if not error and reward == 0:\n",
  171. " error = \"The SQL query returned an incorrect result\"\n",
  172. " if error:\n",
  173. " return {\n",
  174. " \"error\": error,\n",
  175. " \"wrong_result\": observation[\"feedback\"][\"result\"],\n",
  176. " \"correct_result\": info[\"gold_result\"],\n",
  177. " }\n",
  178. " else:\n",
  179. " return {\n",
  180. " \"result\": observation[\"feedback\"][\"result\"],\n",
  181. " }"
  182. ]
  183. },
  184. {
  185. "cell_type": "markdown",
  186. "metadata": {},
  187. "source": [
  188. "The agent can then take as input the schema and the text question, and generate the SQL query."
  189. ]
  190. },
  191. {
  192. "cell_type": "code",
  193. "execution_count": 17,
  194. "metadata": {},
  195. "outputs": [
  196. {
  197. "name": "stdout",
  198. "output_type": "stream",
  199. "text": [
  200. "\u001b[33muser_proxy\u001b[0m (to sql_writer):\n",
  201. "\n",
  202. "Below is the schema for a SQL database:\n",
  203. "CREATE TABLE \"artist\" (\n",
  204. "\"Artist_ID\" int,\n",
  205. "\"Artist\" text,\n",
  206. "\"Age\" int,\n",
  207. "\"Famous_Title\" text,\n",
  208. "\"Famous_Release_date\" text,\n",
  209. "PRIMARY KEY (\"Artist_ID\")\n",
  210. ");\n",
  211. "CREATE TABLE \"volume\" (\n",
  212. "\"Volume_ID\" int,\n",
  213. "\"Volume_Issue\" text,\n",
  214. "\"Issue_Date\" text,\n",
  215. "\"Weeks_on_Top\" real,\n",
  216. "\"Song\" text,\n",
  217. "\"Artist_ID\" int,\n",
  218. "PRIMARY KEY (\"Volume_ID\"),\n",
  219. "FOREIGN KEY (\"Artist_ID\") REFERENCES \"artist\"(\"Artist_ID\")\n",
  220. ");\n",
  221. "CREATE TABLE \"music_festival\" (\n",
  222. "\"ID\" int,\n",
  223. "\"Music_Festival\" text,\n",
  224. "\"Date_of_ceremony\" text,\n",
  225. "\"Category\" text,\n",
  226. "\"Volume\" int,\n",
  227. "\"Result\" text,\n",
  228. "PRIMARY KEY (\"ID\"),\n",
  229. "FOREIGN KEY (\"Volume\") REFERENCES \"volume\"(\"Volume_ID\")\n",
  230. ");\n",
  231. "\n",
  232. "Generate a SQL query to answer the following question:\n",
  233. "Find the famous titles of artists that do not have any volume.\n",
  234. "\n",
  235. "\n",
  236. "--------------------------------------------------------------------------------\n",
  237. "\u001b[31m\n",
  238. ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
  239. "\u001b[33msql_writer\u001b[0m (to user_proxy):\n",
  240. "\n",
  241. "\u001b[32m***** Suggested tool Call (call_eAu0OEzS8l3QvN3jQSn4w0hJ): execute_sql *****\u001b[0m\n",
  242. "Arguments: \n",
  243. "{\"reflection\":\"Generating SQL to find famous titles of artists without any volume\",\"sql\":\"SELECT a.Artist, a.Famous_Title FROM artist a WHERE NOT EXISTS (SELECT 1 FROM volume v WHERE v.Artist_ID = a.Artist_ID)\"}\n",
  244. "\u001b[32m****************************************************************************\u001b[0m\n",
  245. "\n",
  246. "--------------------------------------------------------------------------------\n",
  247. "\u001b[35m\n",
  248. ">>>>>>>> EXECUTING FUNCTION execute_sql...\u001b[0m\n",
  249. "\u001b[33muser_proxy\u001b[0m (to sql_writer):\n",
  250. "\n",
  251. "\u001b[33muser_proxy\u001b[0m (to sql_writer):\n",
  252. "\n",
  253. "\u001b[32m***** Response from calling tool \"call_eAu0OEzS8l3QvN3jQSn4w0hJ\" *****\u001b[0m\n",
  254. "{\"error\": \"The SQL query returned an incorrect result\", \"wrong_result\": [[\"Ophiolatry\", \"Antievangelistical Process (re-release)\"], [\"Triumfall\", \"Antithesis of All Flesh\"]], \"correct_result\": [[\"Antievangelistical Process (re-release)\"], [\"Antithesis of All Flesh\"]]}\n",
  255. "\u001b[32m**********************************************************************\u001b[0m\n",
  256. "\n",
  257. "--------------------------------------------------------------------------------\n",
  258. "\u001b[31m\n",
  259. ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
  260. "\u001b[33msql_writer\u001b[0m (to user_proxy):\n",
  261. "\n",
  262. "\u001b[32m***** Suggested tool Call (call_5LXoKqdZ17kPCOHJbbpSz2yk): execute_sql *****\u001b[0m\n",
  263. "Arguments: \n",
  264. "{\"reflection\":\"Adjusting SQL to only select famous titles and exclude artist names for artists without any volume.\",\"sql\":\"SELECT a.Famous_Title FROM artist a WHERE NOT EXISTS (SELECT 1 FROM volume v WHERE v.Artist_ID = a.Artist_ID)\"}\n",
  265. "\u001b[32m****************************************************************************\u001b[0m\n",
  266. "\n",
  267. "--------------------------------------------------------------------------------\n",
  268. "\u001b[35m\n",
  269. ">>>>>>>> EXECUTING FUNCTION execute_sql...\u001b[0m\n",
  270. "\u001b[33muser_proxy\u001b[0m (to sql_writer):\n",
  271. "\n",
  272. "\u001b[33muser_proxy\u001b[0m (to sql_writer):\n",
  273. "\n",
  274. "\u001b[32m***** Response from calling tool \"call_5LXoKqdZ17kPCOHJbbpSz2yk\" *****\u001b[0m\n",
  275. "{\"result\": [[\"Antievangelistical Process (re-release)\"], [\"Antithesis of All Flesh\"]]}\n",
  276. "\u001b[32m**********************************************************************\u001b[0m\n",
  277. "\n",
  278. "--------------------------------------------------------------------------------\n",
  279. "\u001b[31m\n",
  280. ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n"
  281. ]
  282. }
  283. ],
  284. "source": [
  285. "message = f\"\"\"Below is the schema for a SQL database:\n",
  286. "{schema}\n",
  287. "Generate a SQL query to answer the following question:\n",
  288. "{question}\n",
  289. "\"\"\"\n",
  290. "\n",
  291. "user_proxy.initiate_chat(sql_writer, message=message)"
  292. ]
  293. }
  294. ],
  295. "metadata": {
  296. "kernelspec": {
  297. "display_name": ".venv",
  298. "language": "python",
  299. "name": "python3"
  300. },
  301. "language_info": {
  302. "codemirror_mode": {
  303. "name": "ipython",
  304. "version": 3
  305. },
  306. "file_extension": ".py",
  307. "mimetype": "text/x-python",
  308. "name": "python",
  309. "nbconvert_exporter": "python",
  310. "pygments_lexer": "ipython3",
  311. "version": "3.9.18"
  312. }
  313. },
  314. "nbformat": 4,
  315. "nbformat_minor": 2
  316. }