{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9f853e403eabd4f8",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# An agent for interacting with a SQL database\n",
    "\n",
    "In this tutorial, we will walk through how to build an agent that can answer questions about a SQL database. \n",
    "\n",
    "At a high level, the agent will:\n",
    "1. Fetch the available tables from the database\n",
    "2. Decide which tables are relevant to the question\n",
    "3. Fetch the DDL for the relevant tables\n",
    "4. Generate a query based on the question and information from the DDL\n",
    "5. Double-check the query for common mistakes using an LLM\n",
    "6. Execute the query and return the results\n",
    "7. Correct mistakes surfaced by the database engine until the query is successful\n",
    "8. Formulate a response based on the results\n",
    "\n",
    "The end-to-end workflow will look something like below:\n",
    "\n",
    "![](sql-agent-diagram.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5a87813ffe7e4d2",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Set up environment\n",
    "\n",
    "We'll set up our environment variables for OpenAI, and optionally, to enable tracing with [LangSmith](https://smith.langchain.com)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6c05a600f1afb5b6",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T21:24:00.532147Z",
     "start_time": "2024-06-12T21:24:00.526043Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"sk-...\"\n",
    "os.environ[\"LANGSMITH_API_KEY\"] = \"lsv2_pt_...\"\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "04d73c39-1cc9-4b94-a454-b0a4f604713c",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"LANGCHAIN_PROJECT\"] = \"sql-agent\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "877d8c85825089d8",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Configure the database\n",
    "\n",
    "We will be creating a SQLite database for this tutorial. SQLite is a lightweight database that is easy to set up and use. We will be loading the `chinook` database, which is a sample database that represents a digital media store.\n",
    "Find more information about the database [here](https://www.sqlitetutorial.net/sqlite-sample-database/).\n",
    "\n",
    "For convenience, we have hosted the database (`Chinook.db`) on a public GCS bucket."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "64b0bf1b14c2e902",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T21:24:09.918436Z",
     "start_time": "2024-06-12T21:24:09.608563Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "File downloaded and saved as Chinook.db\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "url = \"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db\"\n",
    "\n",
    "response = requests.get(url)\n",
    "\n",
    "if response.status_code == 200:\n",
    "    # Open a local file in binary write mode\n",
    "    with open(\"Chinook.db\", \"wb\") as file:\n",
    "        # Write the content of the response (the file) to the local file\n",
    "        file.write(response.content)\n",
    "    print(\"File downloaded and saved as Chinook.db\")\n",
    "else:\n",
    "    print(f\"Failed to download the file. Status code: {response.status_code}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61c8304aa5ceb6a5",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "We will use a handy SQL database wrapper available in the `langchain_community` package to interact with the database. The wrapper provides a simple interface to execute SQL queries and fetch results. We will also use the `langchain_openai` package to interact with the OpenAI API for language models later in the tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a60191bd3489f278",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T21:24:14.663745Z",
     "start_time": "2024-06-12T21:24:13.527958Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "%%capture --no-stderr --no-display\n",
    "!pip install langgraph langchain_community langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1f1e1f4f86ed54",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T21:24:15.891582Z",
     "start_time": "2024-06-12T21:24:15.289782Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sqlite\n",
      "['Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"[(1, 'AC/DC'), (2, 'Accept'), (3, 'Aerosmith'), (4, 'Alanis Morissette'), (5, 'Alice In Chains'), (6, 'Antônio Carlos Jobim'), (7, 'Apocalyptica'), (8, 'Audioslave'), (9, 'BackBeat'), (10, 'Billy Cobham')]\""
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.utilities import SQLDatabase\n",
    "\n",
    "db = SQLDatabase.from_uri(\"sqlite:///Chinook.db\")\n",
    "print(db.dialect)\n",
    "print(db.get_usable_table_names())\n",
    "db.run(\"SELECT * FROM Artist LIMIT 10;\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6959e93141d8099c",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Utility functions\n",
    "\n",
    "We will define a few utility functions to help us with the agent implementation. Specifically, we will wrap a `ToolNode` with a fallback to handle errors and surface them to the agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "deae8460e4cf72b1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T21:24:17.557848Z",
     "start_time": "2024-06-12T21:24:17.508550Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from typing import Any\n",
    "\n",
    "from langchain_core.messages import ToolMessage\n",
    "from langchain_core.runnables import RunnableLambda, RunnableWithFallbacks\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "\n",
    "def create_tool_node_with_fallback(tools: list) -> RunnableWithFallbacks[Any, dict]:\n",
    "    \"\"\"\n",
    "    Create a ToolNode with a fallback to handle errors and surface them to the agent.\n",
    "    \"\"\"\n",
    "    return ToolNode(tools).with_fallbacks(\n",
    "        [RunnableLambda(handle_tool_error)], exception_key=\"error\"\n",
    "    )\n",
    "\n",
    "\n",
    "def handle_tool_error(state) -> dict:\n",
    "    error = state.get(\"error\")\n",
    "    tool_calls = state[\"messages\"][-1].tool_calls\n",
    "    return {\n",
    "        \"messages\": [\n",
    "            ToolMessage(\n",
    "                content=f\"Error: {repr(error)}\\n please fix your mistakes.\",\n",
    "                tool_call_id=tc[\"id\"],\n",
    "            )\n",
    "            for tc in tool_calls\n",
    "        ]\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0196604f8cbb07b",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Define tools for the agent\n",
    "\n",
    "We will define a few tools that the agent will use to interact with the database.\n",
    "\n",
    "1. `list_tables_tool`: Fetch the available tables from the database\n",
    "2. `get_schema_tool`: Fetch the DDL for a table\n",
    "3. `db_query_tool`: Execute the query and fetch the results OR return an error message if the query fails\n",
    "\n",
    "For the first two tools, we will grab them from the `SQLDatabaseToolkit`, also available in the `langchain_community` package."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "452d049a3d2a4406",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T20:18:15.838940Z",
     "start_time": "2024-06-12T20:18:15.734199Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, Track\n",
      "\n",
      "CREATE TABLE \"Artist\" (\n",
      "\t\"ArtistId\" INTEGER NOT NULL, \n",
      "\t\"Name\" NVARCHAR(120), \n",
      "\tPRIMARY KEY (\"ArtistId\")\n",
      ")\n",
      "\n",
      "/*\n",
      "3 rows from Artist table:\n",
      "ArtistId\tName\n",
      "1\tAC/DC\n",
      "2\tAccept\n",
      "3\tAerosmith\n",
      "*/\n"
     ]
    }
   ],
   "source": [
    "from langchain_community.agent_toolkits import SQLDatabaseToolkit\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "toolkit = SQLDatabaseToolkit(db=db, llm=ChatOpenAI(model=\"gpt-4o\"))\n",
    "tools = toolkit.get_tools()\n",
    "\n",
    "list_tables_tool = next(tool for tool in tools if tool.name == \"sql_db_list_tables\")\n",
    "get_schema_tool = next(tool for tool in tools if tool.name == \"sql_db_schema\")\n",
    "\n",
    "print(list_tables_tool.invoke(\"\"))\n",
    "\n",
    "print(get_schema_tool.invoke(\"Artist\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c16359edada327fa",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "The third will be defined manually. For the `db_query_tool`, we will execute the query against the database and return the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f7eb708ecb4c7cfc",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T20:39:35.759834Z",
     "start_time": "2024-06-12T20:39:35.740255Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(1, 'AC/DC'), (2, 'Accept'), (3, 'Aerosmith'), (4, 'Alanis Morissette'), (5, 'Alice In Chains'), (6, 'Antônio Carlos Jobim'), (7, 'Apocalyptica'), (8, 'Audioslave'), (9, 'BackBeat'), (10, 'Billy Cobham')]\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.tools import tool\n",
    "\n",
    "\n",
    "@tool\n",
    "def db_query_tool(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Execute a SQL query against the database and get back the result.\n",
    "    If the query is not correct, an error message will be returned.\n",
    "    If an error is returned, rewrite the query, check the query, and try again.\n",
    "    \"\"\"\n",
    "    result = db.run_no_throw(query)\n",
    "    if not result:\n",
    "        return \"Error: Query failed. Please rewrite your query and try again.\"\n",
    "    return result\n",
    "\n",
    "\n",
    "print(db_query_tool.invoke(\"SELECT * FROM Artist LIMIT 10;\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1d66db8b8621639",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "While not strictly a tool, we will prompt an LLM to check for common mistakes in the query and later add this as a node in the workflow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "293017e8f05ac2b3",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T20:18:19.658322Z",
     "start_time": "2024-06-12T20:18:18.756256Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_5zdRt3uWwY23FSYmKZT7crGF', 'function': {'arguments': '{\"query\":\"SELECT * FROM Artist LIMIT 10;\"}', 'name': 'db_query_tool'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 20, 'prompt_tokens': 222, 'total_tokens': 242}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_319be4768e', 'finish_reason': 'stop', 'logprobs': None}, id='run-a062c91e-084e-4a91-bba8-fdbb957e2a5c-0', tool_calls=[{'name': 'db_query_tool', 'args': {'query': 'SELECT * FROM Artist LIMIT 10;'}, 'id': 'call_5zdRt3uWwY23FSYmKZT7crGF'}], usage_metadata={'input_tokens': 222, 'output_tokens': 20, 'total_tokens': 242})"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "query_check_system = \"\"\"You are a SQL expert with a strong attention to detail.\n",
    "Double check the SQLite query for common mistakes, including:\n",
    "- Using NOT IN with NULL values\n",
    "- Using UNION when UNION ALL should have been used\n",
    "- Using BETWEEN for exclusive ranges\n",
    "- Data type mismatch in predicates\n",
    "- Properly quoting identifiers\n",
    "- Using the correct number of arguments for functions\n",
    "- Casting to the correct data type\n",
    "- Using the proper columns for joins\n",
    "\n",
    "If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.\n",
    "\n",
    "You will call the appropriate tool to execute the query after running this check.\"\"\"\n",
    "\n",
    "query_check_prompt = ChatPromptTemplate.from_messages(\n",
    "    [(\"system\", query_check_system), (\"placeholder\", \"{messages}\")]\n",
    ")\n",
    "query_check = query_check_prompt | ChatOpenAI(model=\"gpt-4o\", temperature=0).bind_tools(\n",
    "    [db_query_tool], tool_choice=\"required\"\n",
    ")\n",
    "\n",
    "query_check.invoke({\"messages\": [(\"user\", \"SELECT * FROM Artist LIMIT 10;\")]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66f88452151e8188",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Define the workflow\n",
    "\n",
    "We will then define the workflow for the agent. The agent will first force-call the `list_tables_tool` to fetch the available tables from the database, then follow the steps mentioned at the beginning of the tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "90d04ceea7b6b010",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T20:21:09.799829Z",
     "start_time": "2024-06-12T20:21:09.765928Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from typing import Annotated, Literal\n",
    "\n",
    "from langchain_core.messages import AIMessage\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "from langchain_openai import ChatOpenAI\n",
    "from typing_extensions import TypedDict\n",
    "\n",
    "from langgraph.graph import END, StateGraph, START\n",
    "from langgraph.graph.message import AnyMessage, add_messages\n",
    "\n",
    "\n",
    "# Define the state for the agent\n",
    "class State(TypedDict):\n",
    "    messages: Annotated[list[AnyMessage], add_messages]\n",
    "\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(State)\n",
    "\n",
    "\n",
    "# Add a node for the first tool call\n",
    "def first_tool_call(state: State) -> dict[str, list[AIMessage]]:\n",
    "    return {\n",
    "        \"messages\": [\n",
    "            AIMessage(\n",
    "                content=\"\",\n",
    "                tool_calls=[\n",
    "                    {\n",
    "                        \"name\": \"sql_db_list_tables\",\n",
    "                        \"args\": {},\n",
    "                        \"id\": \"tool_abcd123\",\n",
    "                    }\n",
    "                ],\n",
    "            )\n",
    "        ]\n",
    "    }\n",
    "\n",
    "\n",
    "def model_check_query(state: State) -> dict[str, list[AIMessage]]:\n",
    "    \"\"\"\n",
    "    Use this tool to double-check if your query is correct before executing it.\n",
    "    \"\"\"\n",
    "    return {\"messages\": [query_check.invoke({\"messages\": [state[\"messages\"][-1]]})]}\n",
    "\n",
    "\n",
    "workflow.add_node(\"first_tool_call\", first_tool_call)\n",
    "\n",
    "# Add nodes for the first two tools\n",
    "workflow.add_node(\n",
    "    \"list_tables_tool\", create_tool_node_with_fallback([list_tables_tool])\n",
    ")\n",
    "workflow.add_node(\"get_schema_tool\", create_tool_node_with_fallback([get_schema_tool]))\n",
    "\n",
    "# Add a node for a model to choose the relevant tables based on the question and available tables\n",
    "model_get_schema = ChatOpenAI(model=\"gpt-4o\", temperature=0).bind_tools(\n",
    "    [get_schema_tool]\n",
    ")\n",
    "workflow.add_node(\n",
    "    \"model_get_schema\",\n",
    "    lambda state: {\n",
    "        \"messages\": [model_get_schema.invoke(state[\"messages\"])],\n",
    "    },\n",
    ")\n",
    "\n",
    "\n",
    "# Describe a tool to represent the end state\n",
    "class SubmitFinalAnswer(BaseModel):\n",
    "    \"\"\"Submit the final answer to the user based on the query results.\"\"\"\n",
    "\n",
    "    final_answer: str = Field(..., description=\"The final answer to the user\")\n",
    "\n",
    "\n",
    "# Add a node for a model to generate a query based on the question and schema\n",
    "query_gen_system = \"\"\"You are a SQL expert with a strong attention to detail.\n",
    "\n",
    "Given an input question, output a syntactically correct SQLite query to run, then look at the results of the query and return the answer.\n",
    "\n",
    "DO NOT call any tool besides SubmitFinalAnswer to submit the final answer.\n",
    "\n",
    "When generating the query:\n",
    "\n",
    "Output the SQL query that answers the input question without a tool call.\n",
    "\n",
    "Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most 5 results.\n",
    "You can order the results by a relevant column to return the most interesting examples in the database.\n",
    "Never query for all the columns from a specific table, only ask for the relevant columns given the question.\n",
    "\n",
    "If you get an error while executing a query, rewrite the query and try again.\n",
    "\n",
    "If you get an empty result set, you should try to rewrite the query to get a non-empty result set. \n",
    "NEVER make stuff up if you don't have enough information to answer the query... just say you don't have enough information.\n",
    "\n",
    "If you have enough information to answer the input question, simply invoke the appropriate tool to submit the final answer to the user.\n",
    "\n",
    "DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\"\"\"\n",
    "query_gen_prompt = ChatPromptTemplate.from_messages(\n",
    "    [(\"system\", query_gen_system), (\"placeholder\", \"{messages}\")]\n",
    ")\n",
    "query_gen = query_gen_prompt | ChatOpenAI(model=\"gpt-4o\", temperature=0).bind_tools(\n",
    "    [SubmitFinalAnswer]\n",
    ")\n",
    "\n",
    "\n",
    "def query_gen_node(state: State):\n",
    "    message = query_gen.invoke(state)\n",
    "\n",
    "    # Sometimes, the LLM will hallucinate and call the wrong tool. We need to catch this and return an error message.\n",
    "    tool_messages = []\n",
    "    if message.tool_calls:\n",
    "        for tc in message.tool_calls:\n",
    "            if tc[\"name\"] != \"SubmitFinalAnswer\":\n",
    "                tool_messages.append(\n",
    "                    ToolMessage(\n",
    "                        content=f\"Error: The wrong tool was called: {tc['name']}. Please fix your mistakes. Remember to only call SubmitFinalAnswer to submit the final answer. Generated queries should be outputted WITHOUT a tool call.\",\n",
    "                        tool_call_id=tc[\"id\"],\n",
    "                    )\n",
    "                )\n",
    "    else:\n",
    "        tool_messages = []\n",
    "    return {\"messages\": [message] + tool_messages}\n",
    "\n",
    "\n",
    "workflow.add_node(\"query_gen\", query_gen_node)\n",
    "\n",
    "# Add a node for the model to check the query before executing it\n",
    "workflow.add_node(\"correct_query\", model_check_query)\n",
    "\n",
    "# Add node for executing the query\n",
    "workflow.add_node(\"execute_query\", create_tool_node_with_fallback([db_query_tool]))\n",
    "\n",
    "\n",
    "# Define a conditional edge to decide whether to continue or end the workflow\n",
    "def should_continue(state: State) -> Literal[END, \"correct_query\", \"query_gen\"]:\n",
    "    messages = state[\"messages\"]\n",
    "    last_message = messages[-1]\n",
    "    # If there is a tool call, then we finish\n",
    "    if getattr(last_message, \"tool_calls\", None):\n",
    "        return END\n",
    "    if last_message.content.startswith(\"Error:\"):\n",
    "        return \"query_gen\"\n",
    "    else:\n",
    "        return \"correct_query\"\n",
    "\n",
    "\n",
    "# Specify the edges between the nodes\n",
    "workflow.add_edge(START, \"first_tool_call\")\n",
    "workflow.add_edge(\"first_tool_call\", \"list_tables_tool\")\n",
    "workflow.add_edge(\"list_tables_tool\", \"model_get_schema\")\n",
    "workflow.add_edge(\"model_get_schema\", \"get_schema_tool\")\n",
    "workflow.add_edge(\"get_schema_tool\", \"query_gen\")\n",
    "workflow.add_conditional_edges(\n",
    "    \"query_gen\",\n",
    "    should_continue,\n",
    ")\n",
    "workflow.add_edge(\"correct_query\", \"execute_query\")\n",
    "workflow.add_edge(\"execute_query\", \"query_gen\")\n",
    "\n",
    "# Compile the workflow into a runnable\n",
    "app = workflow.compile()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c344ae086ba8d22",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Visualize the graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "4f200d1813897000",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-06-12T20:21:11.813905Z",
     "start_time": "2024-06-12T20:21:11.712945Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 34588 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "from langchain_core.runnables.graph import MermaidDrawMethod\n",
    "\n",
    "display(\n",
    "    Image(\n",
    "        app.get_graph().draw_mermaid_png(\n",
    "            draw_method=MermaidDrawMethod.API,\n",
    "        )\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdf78dc68548522c",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Run the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "85958809-03c5-4e52-97cc-e7c0ae986f60",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The sales agent who made the most in sales in 2009 is Steve Johnson with total sales of 164.34.'"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "messages = app.invoke(\n",
    "    {\"messages\": [(\"user\", \"Which sales agent made the most in sales in 2009?\")]}\n",
    ")\n",
    "json_str = messages[\"messages\"][-1].additional_kwargs[\"tool_calls\"][0][\"function\"][\n",
    "    \"arguments\"\n",
    "]\n",
    "json.loads(json_str)[\"final_answer\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bf7709f-500c-4f28-bb85-dda317286c63",
   "metadata": {},
   "outputs": [],
   "source": [
    "for event in app.stream(\n",
    "    {\"messages\": [(\"user\", \"Which sales agent made the most in sales in 2009?\")]}\n",
    "):\n",
    "    print(event)"
   ]
  },
  {
   "attachments": {
    "b92325b1-2c9a-4efa-94f5-49a75b1ffb64.png": {
     "image/png": "[encoded data, 255188 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "490f07a9-d816-4b53-b784-b33dbc6d74b1",
   "metadata": {},
   "source": [
    "## Eval\n",
    "\n",
    "Now, we can evaluate this agent! We previously defined [simple SQL agent](https://github.com/langchain-ai/langsmith-cookbook/blob/main/testing-examples/agent-evals-with-langgraph/langgraph_sql_agent_eval.ipynb) as part of our LangSmith evaluation cookbooks, and evaluated responses to 5 questions about our database. We can compare this agent to our prior one on the same dataset. [Agent evaluation](https://docs.smith.langchain.com/concepts/evaluation#agents) can focus on 3 things:\n",
    "\n",
    "* `Response`: The inputs are a prompt and a list of tools. The output is the agent response.\n",
    "* `Single tool`: As before, the inputs are a prompt and a list of tools. The output the tool call.\n",
    "* `Trajectory`: As before, the inputs are a prompt and a list of tools. The output is the list of tool calls\n",
    "\n",
    "![Screenshot 2024-06-13 at 2.13.30 PM.png](attachment:b92325b1-2c9a-4efa-94f5-49a75b1ffb64.png)\n",
    "\n",
    "### Response\n",
    "\n",
    "We'll evaluate end-to-end responses of our agent relative to reference answers. Let's run [response evaluation](https://docs.smith.langchain.com/concepts/evaluation#evaluating-an-agents-final-response) [on the same dataset](https://smith.langchain.com/public/20808486-67c3-4e30-920b-6d49d6f2b6b8/d)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "a80f4adc-a8dc-403c-9bef-6de5e873b9bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "\n",
    "def predict_sql_agent_answer(example: dict):\n",
    "    \"\"\"Use this for answer evaluation\"\"\"\n",
    "    msg = {\"messages\": (\"user\", example[\"input\"])}\n",
    "    messages = app.invoke(msg)\n",
    "    json_str = messages[\"messages\"][-1].additional_kwargs[\"tool_calls\"][0][\"function\"][\n",
    "        \"arguments\"\n",
    "    ]\n",
    "    response = json.loads(json_str)[\"final_answer\"]\n",
    "    return {\"response\": response}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "1040233f-3751-4bd3-902f-709fc2e1ecf5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# Grade prompt\n",
    "grade_prompt_answer_accuracy = prompt = hub.pull(\"langchain-ai/rag-answer-vs-reference\")\n",
    "\n",
    "\n",
    "def answer_evaluator(run, example) -> dict:\n",
    "    \"\"\"\n",
    "    A simple evaluator for RAG answer accuracy\n",
    "    \"\"\"\n",
    "\n",
    "    # Get question, ground truth answer, chain\n",
    "    input_question = example.inputs[\"input\"]\n",
    "    reference = example.outputs[\"output\"]\n",
    "    prediction = run.outputs[\"response\"]\n",
    "\n",
    "    # LLM grader\n",
    "    llm = ChatOpenAI(model=\"gpt-4-turbo\", temperature=0)\n",
    "\n",
    "    # Structured prompt\n",
    "    answer_grader = grade_prompt_answer_accuracy | llm\n",
    "\n",
    "    # Run evaluator\n",
    "    score = answer_grader.invoke(\n",
    "        {\n",
    "            \"question\": input_question,\n",
    "            \"correct_answer\": reference,\n",
    "            \"student_answer\": prediction,\n",
    "        }\n",
    "    )\n",
    "    score = score[\"Score\"]\n",
    "\n",
    "    return {\"key\": \"answer_v_reference_score\", \"score\": score}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb814b85-70ba-4699-9038-20266b53efbd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langsmith.evaluation import evaluate\n",
    "\n",
    "dataset_name = \"SQL Agent Response\"\n",
    "experiment_results = evaluate(\n",
    "    predict_sql_agent_answer,\n",
    "    data=dataset_name,\n",
    "    evaluators=[answer_evaluator],\n",
    "    num_repetitions=3,\n",
    "    experiment_prefix=\"sql-agent-multi-step-response-v-reference\",\n",
    "    metadata={\"version\": \"Chinook, gpt-4o multi-step-agent\"},\n",
    ")"
   ]
  },
  {
   "attachments": {
    "e9a91890-3299-4b71-9ab2-21d737a120ba.png": {
     "image/png": "[encoded data, 93996 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "23ddb587-d52c-45d5-9316-ff0e86f90ef6",
   "metadata": {},
   "source": [
    "Summary metrics (see dataset [here](https://smith.langchain.com/public/20808486-67c3-4e30-920b-6d49d6f2b6b8/d)):\n",
    "\n",
    "* The `multi-step` agent here out performs the previously defined [base case SQL agent](https://github.com/langchain-ai/langsmith-cookbook/blob/main/testing-examples/agent-evals-with-langgraph/langgraph_sql_agent_eval.ipynb)\n",
    "\n",
    "![Screenshot 2024-06-13 at 2.09.57 PM.png](attachment:e9a91890-3299-4b71-9ab2-21d737a120ba.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fb7f738-11d4-4a55-8b28-58727ead9838",
   "metadata": {},
   "source": [
    "### Trajectory\n",
    "\n",
    "Let's run [trajectory evaluation](https://docs.smith.langchain.com/concepts/evaluation#evaluating-an-agents-trajectory) on this same dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "ef84d2f7-fa52-46ca-8939-616e5ac4d101",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These are the tools that we expect the agent to use\n",
    "expected_trajectory = [\n",
    "    \"sql_db_list_tables\",  # first: list_tables_tool node\n",
    "    \"sql_db_schema\",  # second: get_schema_tool node\n",
    "    \"db_query_tool\",  # third: execute_query node\n",
    "    \"SubmitFinalAnswer\",\n",
    "]  # fourth: query_gen"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "1b7b007a-1dd2-4f3e-b157-b9d7ec2ea0a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict_sql_agent_messages(example: dict):\n",
    "    \"\"\"Use this for answer evaluation\"\"\"\n",
    "    msg = {\"messages\": (\"user\", example[\"input\"])}\n",
    "    messages = app.invoke(msg)\n",
    "    return {\"response\": messages}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "ae2fe538-1c6d-4186-80dd-1d240d253f40",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langsmith.schemas import Example, Run\n",
    "\n",
    "\n",
    "def find_tool_calls(messages):\n",
    "    \"\"\"\n",
    "    Find all tool calls in the messages returned\n",
    "    \"\"\"\n",
    "    tool_calls = [\n",
    "        tc[\"name\"] for m in messages[\"messages\"] for tc in getattr(m, \"tool_calls\", [])\n",
    "    ]\n",
    "    return tool_calls\n",
    "\n",
    "\n",
    "def contains_all_tool_calls_in_order_exact_match(\n",
    "    root_run: Run, example: Example\n",
    ") -> dict:\n",
    "    \"\"\"\n",
    "    Check if all expected tools are called in exact order and without any additional tool calls.\n",
    "    \"\"\"\n",
    "    expected_trajectory = [\n",
    "        \"sql_db_list_tables\",\n",
    "        \"sql_db_schema\",\n",
    "        \"db_query_tool\",\n",
    "        \"SubmitFinalAnswer\",\n",
    "    ]\n",
    "    messages = root_run.outputs[\"response\"]\n",
    "    tool_calls = find_tool_calls(messages)\n",
    "\n",
    "    # Print the tool calls for debugging\n",
    "    print(\"Here are my tool calls:\")\n",
    "    print(tool_calls)\n",
    "\n",
    "    # Check if the tool calls match the expected trajectory exactly\n",
    "    if tool_calls == expected_trajectory:\n",
    "        score = 1\n",
    "    else:\n",
    "        score = 0\n",
    "\n",
    "    return {\"score\": int(score), \"key\": \"multi_tool_call_in_exact_order\"}\n",
    "\n",
    "\n",
    "def contains_all_tool_calls_in_order(root_run: Run, example: Example) -> dict:\n",
    "    \"\"\"\n",
    "    Check if all expected tools are called in order,\n",
    "    but it allows for other tools to be called in between the expected ones.\n",
    "    \"\"\"\n",
    "    messages = root_run.outputs[\"response\"]\n",
    "    tool_calls = find_tool_calls(messages)\n",
    "\n",
    "    # Print the tool calls for debugging\n",
    "    print(\"Here are my tool calls:\")\n",
    "    print(tool_calls)\n",
    "\n",
    "    it = iter(tool_calls)\n",
    "    if all(elem in it for elem in expected_trajectory):\n",
    "        score = 1\n",
    "    else:\n",
    "        score = 0\n",
    "    return {\"score\": int(score), \"key\": \"multi_tool_call_in_order\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf02e843-438d-4168-a27a-8f1e0266f8d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "experiment_results = evaluate(\n",
    "    predict_sql_agent_messages,\n",
    "    data=dataset_name,\n",
    "    evaluators=[\n",
    "        contains_all_tool_calls_in_order,\n",
    "        contains_all_tool_calls_in_order_exact_match,\n",
    "    ],\n",
    "    num_repetitions=3,\n",
    "    experiment_prefix=\"sql-agent-multi-step-tool-calling-trajecory-in-order\",\n",
    "    metadata={\"version\": \"Chinook, gpt-4o multi-step-agent\"},\n",
    ")"
   ]
  },
  {
   "attachments": {
    "9a1084c0-4c7c-4e6f-8329-80499d293e0a.png": {
     "image/png": "[encoded data, 38980 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "a34d5022-c0c5-4037-afc5-75c173b882f6",
   "metadata": {},
   "source": [
    "The aggregate scores show that we never correctly call the tools in exact order:\n",
    "\n",
    "![Screenshot 2024-06-13 at 2.46.34 PM.png](attachment:9a1084c0-4c7c-4e6f-8329-80499d293e0a.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9e4a0e6-fc0f-4101-bda5-d96d1294cbb9",
   "metadata": {},
   "source": [
    "Looking at the logging, we can see something interesting - \n",
    "\n",
    "```\n",
    "['sql_db_list_tables', 'sql_db_schema', 'sql_db_query', 'db_query_tool', 'SubmitFinalAnswer']\n",
    "```\n",
    "\n",
    "We appear to inject a hallucinated tool call, `sql_db_query`, into our trajectory for most of the runs.\n",
    "\n",
    "This is why `multi_tool_call_in_exact_order` fails, but `multi_tool_call_in_order` still passes. \n",
    "\n",
    "We will explore ways to resolve this using LangGraph in future cookbooks!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0681b6e0-196e-440c-ab16-1a530411719e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
