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

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