{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "674a0d41-e3e3-4423-a995-25d40128c518",
   "metadata": {},
   "source": [
    "# How to do question answering over CSVs\n",
    "\n",
    "LLMs are great for building question-answering systems over various types of data sources. In this section we'll go over how to build Q&A systems over data stored in a CSV file(s). Like working with SQL databases, the key to working with CSV files is to give an LLM access to tools for querying and interacting with the data. The two main ways to do this are to either:\n",
    "\n",
    "* **RECOMMENDED**: Load the CSV(s) into a SQL database, and use the approaches outlined in the [SQL tutorial](/docs/tutorials/sql_qa).\n",
    "* Give the LLM access to a Python environment where it can use libraries like Pandas to interact with the data.\n",
    "\n",
    "We will cover both approaches in this guide.\n",
    "\n",
    "## ⚠️ Security note ⚠️\n",
    "\n",
    "Both approaches mentioned above carry significant risks. Using SQL requires executing model-generated SQL queries. Using a library like Pandas requires letting the model execute Python code. Since it is easier to tightly scope SQL connection permissions and sanitize SQL queries than it is to sandbox Python environments, **we HIGHLY recommend interacting with CSV data via SQL.** For more on general security best practices, [see here](/docs/security)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d20c20d7-71e1-4808-9012-48278f3a9b94",
   "metadata": {},
   "source": [
    "## Setup\n",
    "Dependencies for this guide:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3fcf245-b0aa-4aee-8f0a-9c9cf94b065e",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -qU langchain langchain-openai langchain-community langchain-experimental pandas"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f2e34a3-0978-4856-8844-d8dfc6d5ac51",
   "metadata": {},
   "source": [
    "Set required environment variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "53913d79-4a11-4bc6-bb49-dea2cc8c453b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Using LangSmith is recommended but not required. Uncomment below lines to use.\n",
    "# import os\n",
    "# os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "# os.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c23b4232-2f6a-4eb5-b0cb-1d48a9e02fcc",
   "metadata": {},
   "source": [
    "Download the [Titanic dataset](https://www.kaggle.com/datasets/yasserh/titanic-dataset) if you don't already have it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c9099c7-5247-4edb-ba5d-10c3c4c60db4",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv -O titanic.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ad029641-6d6c-44cc-b16f-2d5472672adf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(887, 8)\n",
      "['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare']\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"titanic.csv\")\n",
    "print(df.shape)\n",
    "print(df.columns.tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1779ab07-b715-49e5-ab2a-2e6be7d02927",
   "metadata": {},
   "source": [
    "## SQL\n",
    "\n",
    "Using SQL to interact with CSV data is the recommended approach because it is easier to limit permissions and sanitize queries than with arbitrary Python.\n",
    "\n",
    "Most SQL databases make it easy to load a CSV file in as a table ([DuckDB](https://duckdb.org/docs/data/csv/overview.html), [SQLite](https://www.sqlite.org/csv.html), etc.). Once you've done this you can use all of the chain and agent-creating techniques outlined in the [SQL tutorial](/docs/tutorials/sql_qa). Here's a quick example of how we might do this with SQLite:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f61e9886-4713-4c88-87d4-dab439687f43",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "887"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.utilities import SQLDatabase\n",
    "from sqlalchemy import create_engine\n",
    "\n",
    "engine = create_engine(\"sqlite:///titanic.db\")\n",
    "df.to_sql(\"titanic\", engine, index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3275fc91-3777-4f78-8edf-d148001684b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sqlite\n",
      "['titanic']\n",
      "[(1, 2, 'Master. Alden Gates Caldwell', 'male', 0.83, 0, 2, 29.0), (0, 3, 'Master. Eino Viljami Panula', 'male', 1.0, 4, 1, 39.6875), (1, 3, 'Miss. Eleanor Ileen Johnson', 'female', 1.0, 1, 1, 11.1333), (1, 2, 'Master. Richard F Becker', 'male', 1.0, 2, 1, 39.0), (1, 1, 'Master. Hudson Trevor Allison', 'male', 0.92, 1, 2, 151.55), (1, 3, 'Miss. Maria Nakid', 'female', 1.0, 0, 2, 15.7417), (0, 3, 'Master. Sidney Leonard Goodwin', 'male', 1.0, 5, 2, 46.9), (1, 3, 'Miss. Helene Barbara Baclini', 'female', 0.75, 2, 1, 19.2583), (1, 3, 'Miss. Eugenie Baclini', 'female', 0.75, 2, 1, 19.2583), (1, 2, 'Master. Viljo Hamalainen', 'male', 0.67, 1, 1, 14.5), (1, 3, 'Master. Bertram Vere Dean', 'male', 1.0, 1, 2, 20.575), (1, 3, 'Master. Assad Alexander Thomas', 'male', 0.42, 0, 1, 8.5167), (1, 2, 'Master. Andre Mallet', 'male', 1.0, 0, 2, 37.0042), (1, 2, 'Master. George Sibley Richards', 'male', 0.83, 1, 1, 18.75)]\n"
     ]
    }
   ],
   "source": [
    "db = SQLDatabase(engine=engine)\n",
    "print(db.dialect)\n",
    "print(db.get_usable_table_names())\n",
    "print(db.run(\"SELECT * FROM titanic WHERE Age < 2;\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42f5a3c3-707c-4331-9f5f-0cb4919763dd",
   "metadata": {},
   "source": [
    "And create a [SQL agent](/docs/tutorials/sql_qa) to interact with it:\n",
    "\n",
    "```{=mdx}\n",
    "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
    "\n",
    "<ChatModelTabs customVarName=\"llm\" />\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e868a586-4f4e-4b1d-ab11-fae1271dd551",
   "metadata": {},
   "outputs": [],
   "source": [
    "# | output: false\n",
    "# | echo: false\n",
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "edd92649-b178-47bd-b2b7-d5d4e14b3512",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.agent_toolkits import create_sql_agent\n",
    "\n",
    "agent_executor = create_sql_agent(llm, db=db, agent_type=\"openai-tools\", verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7aefe929-5e39-4ed1-b135-aaf88edce2eb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SQL Agent Executor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `sql_db_list_tables` with `{}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[38;5;200m\u001b[1;3mtitanic\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `sql_db_schema` with `{'table_names': 'titanic'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[33;1m\u001b[1;3m\n",
      "CREATE TABLE titanic (\n",
      "\t\"Survived\" BIGINT, \n",
      "\t\"Pclass\" BIGINT, \n",
      "\t\"Name\" TEXT, \n",
      "\t\"Sex\" TEXT, \n",
      "\t\"Age\" FLOAT, \n",
      "\t\"Siblings/Spouses Aboard\" BIGINT, \n",
      "\t\"Parents/Children Aboard\" BIGINT, \n",
      "\t\"Fare\" FLOAT\n",
      ")\n",
      "\n",
      "/*\n",
      "3 rows from titanic table:\n",
      "Survived\tPclass\tName\tSex\tAge\tSiblings/Spouses Aboard\tParents/Children Aboard\tFare\n",
      "0\t3\tMr. Owen Harris Braund\tmale\t22.0\t1\t0\t7.25\n",
      "1\t1\tMrs. John Bradley (Florence Briggs Thayer) Cumings\tfemale\t38.0\t1\t0\t71.2833\n",
      "1\t3\tMiss. Laina Heikkinen\tfemale\t26.0\t0\t0\t7.925\n",
      "*/\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `sql_db_query` with `{'query': 'SELECT AVG(Age) AS Average_Age FROM titanic WHERE Survived = 1'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[(28.408391812865496,)]\u001b[0m\u001b[32;1m\u001b[1;3mThe average age of survivors in the Titanic dataset is approximately 28.41 years.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's the average age of survivors\",\n",
       " 'output': 'The average age of survivors in the Titanic dataset is approximately 28.41 years.'}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"what's the average age of survivors\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d1eb128-842b-4018-87ab-bb269147f6ec",
   "metadata": {},
   "source": [
    "This approach easily generalizes to multiple CSVs, since we can just load each of them into our database as its own table. See the [Multiple CSVs](/docs/how_to/sql_csv#multiple-csvs) section below."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe7f2d91-2377-49dd-97a3-19d48a750715",
   "metadata": {},
   "source": [
    "## Pandas\n",
    "\n",
    "Instead of SQL we can also use data analysis libraries like pandas and the code generating abilities of LLMs to interact with CSV data. Again, **this approach is not fit for production use cases unless you have extensive safeguards in place**. For this reason, our code-execution utilities and constructors live in the `langchain-experimental` package.\n",
    "\n",
    "### Chain\n",
    "\n",
    "Most LLMs have been trained on enough pandas Python code that they can generate it just by being asked to:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "27c84b27-9367-4c58-8a88-ade1fbf6683c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```python\n",
      "correlation = df['Age'].corr(df['Fare'])\n",
      "correlation\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "ai_msg = llm.invoke(\n",
    "    \"I have a pandas DataFrame 'df' with columns 'Age' and 'Fare'. Write code to compute the correlation between the two columns. Return Markdown for a Python code snippet and nothing else.\"\n",
    ")\n",
    "print(ai_msg.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5e84003-5c39-496b-afa7-eaa50a01b7bb",
   "metadata": {},
   "source": [
    "We can combine this ability with a Python-executing tool to create a simple data analysis chain. We'll first want to load our CSV table as a dataframe, and give the tool access to this dataframe:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "16abe312-b1a3-413f-bb9a-0e613d1e550b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "32.30542018038331"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_experimental.tools import PythonAstREPLTool\n",
    "\n",
    "df = pd.read_csv(\"titanic.csv\")\n",
    "tool = PythonAstREPLTool(locals={\"df\": df})\n",
    "tool.invoke(\"df['Fare'].mean()\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab1b2e7c-6ea8-4674-98eb-a43c69f5c19d",
   "metadata": {},
   "source": [
    "To help enforce proper use of our Python tool, we'll using [tool calling](/docs/how_to/tool_calling):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c6a9c8ec-1d06-4870-a584-b8d7b6c6ddfe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_SBrK246yUbdnJemXFC8Iod05', 'function': {'arguments': '{\"query\":\"df.corr()[\\'Age\\'][\\'Fare\\']\"}', 'name': 'python_repl_ast'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 13, 'prompt_tokens': 125, 'total_tokens': 138}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}, id='run-1fd332ba-fa72-4351-8182-d464e7368311-0', tool_calls=[{'name': 'python_repl_ast', 'args': {'query': \"df.corr()['Age']['Fare']\"}, 'id': 'call_SBrK246yUbdnJemXFC8Iod05'}])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm_with_tools = llm.bind_tools([tool], tool_choice=tool.name)\n",
    "response = llm_with_tools.invoke(\n",
    "    \"I have a dataframe 'df' and want to know the correlation between the 'Age' and 'Fare' columns\"\n",
    ")\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b0e4015c-236d-42d7-ba8f-16052fa4f405",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'name': 'python_repl_ast',\n",
       "  'args': {'query': \"df.corr()['Age']['Fare']\"},\n",
       "  'id': 'call_SBrK246yUbdnJemXFC8Iod05'}]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.tool_calls"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdec46fb-7296-443c-9e97-cfa9045ff21d",
   "metadata": {},
   "source": [
    "We'll add a tools output parser to extract the function call as a dict:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "476128f2-aa61-47f5-a371-dcff7b391d19",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'query': \"df[['Age', 'Fare']].corr()\"}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.output_parsers.openai_tools import JsonOutputKeyToolsParser\n",
    "\n",
    "parser = JsonOutputKeyToolsParser(key_name=tool.name, first_tool_only=True)\n",
    "(llm_with_tools | parser).invoke(\n",
    "    \"I have a dataframe 'df' and want to know the correlation between the 'Age' and 'Fare' columns\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59362ea0-cc5a-4841-b87c-51d6a87d5810",
   "metadata": {},
   "source": [
    "And combine with a prompt so that we can just specify a question without needing to specify the dataframe info every invocation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9e87a820-e4ce-417e-b580-043fb2d5c8f2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'query': \"df[['Age', 'Fare']].corr()\"}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "system = f\"\"\"You have access to a pandas dataframe `df`. \\\n",
    "Here is the output of `df.head().to_markdown()`:\n",
    "\n",
    "```\n",
    "{df.head().to_markdown()}\n",
    "```\n",
    "\n",
    "Given a user question, write the Python code to answer it. \\\n",
    "Return ONLY the valid Python code and nothing else. \\\n",
    "Don't assume you have access to any libraries other than built-in Python ones and pandas.\"\"\"\n",
    "prompt = ChatPromptTemplate.from_messages([(\"system\", system), (\"human\", \"{question}\")])\n",
    "code_chain = prompt | llm_with_tools | parser\n",
    "code_chain.invoke({\"question\": \"What's the correlation between age and fare\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63989e47-c0af-409e-9766-83c3fe6d69bb",
   "metadata": {},
   "source": [
    "And lastly we'll add our Python tool so that the generated code is actually executed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2e56a891-4c3f-4e5a-a5ee-3973112ffeb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.11232863699941621"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain = prompt | llm_with_tools | parser | tool\n",
    "chain.invoke({\"question\": \"What's the correlation between age and fare\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbb12764-4a90-4e84-88b4-a25949084ea2",
   "metadata": {},
   "source": [
    "And just like that we have a simple data analysis chain. We can take a peak at the intermediate steps by looking at the LangSmith trace: https://smith.langchain.com/public/b1309290-7212-49b7-bde2-75b39a32b49a/r\n",
    "\n",
    "We could add an additional LLM call at the end to generate a conversational response, so that we're not just responding with the tool output. For this we'll want to add a chat history `MessagesPlaceholder` to our prompt:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "3fe3818d-0657-4729-ac46-ab5d4860d8f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from operator import itemgetter\n",
    "\n",
    "from langchain_core.messages import ToolMessage\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.prompts import MessagesPlaceholder\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "\n",
    "system = f\"\"\"You have access to a pandas dataframe `df`. \\\n",
    "Here is the output of `df.head().to_markdown()`:\n",
    "\n",
    "```\n",
    "{df.head().to_markdown()}\n",
    "```\n",
    "\n",
    "Given a user question, write the Python code to answer it. \\\n",
    "Don't assume you have access to any libraries other than built-in Python ones and pandas.\n",
    "Respond directly to the question once you have enough information to answer it.\"\"\"\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            system,\n",
    "        ),\n",
    "        (\"human\", \"{question}\"),\n",
    "        # This MessagesPlaceholder allows us to optionally append an arbitrary number of messages\n",
    "        # at the end of the prompt using the 'chat_history' arg.\n",
    "        MessagesPlaceholder(\"chat_history\", optional=True),\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "def _get_chat_history(x: dict) -> list:\n",
    "    \"\"\"Parse the chain output up to this point into a list of chat history messages to insert in the prompt.\"\"\"\n",
    "    ai_msg = x[\"ai_msg\"]\n",
    "    tool_call_id = x[\"ai_msg\"].additional_kwargs[\"tool_calls\"][0][\"id\"]\n",
    "    tool_msg = ToolMessage(tool_call_id=tool_call_id, content=str(x[\"tool_output\"]))\n",
    "    return [ai_msg, tool_msg]\n",
    "\n",
    "\n",
    "chain = (\n",
    "    RunnablePassthrough.assign(ai_msg=prompt | llm_with_tools)\n",
    "    .assign(tool_output=itemgetter(\"ai_msg\") | parser | tool)\n",
    "    .assign(chat_history=_get_chat_history)\n",
    "    .assign(response=prompt | llm | StrOutputParser())\n",
    "    .pick([\"tool_output\", \"response\"])\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ff6e98ec-52f1-4ffd-9ea8-bacedfa29f28",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'tool_output': 0.11232863699941616,\n",
       " 'response': 'The correlation between age and fare is approximately 0.1123.'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke({\"question\": \"What's the correlation between age and fare\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "245a5a91-c6d2-4a40-9b9f-eb38f78c9d22",
   "metadata": {},
   "source": [
    "Here's the LangSmith trace for this run: https://smith.langchain.com/public/14e38d70-45b1-4b81-8477-9fd2b7c07ea6/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c24b4f4-abbf-4891-b200-814eb9c35bec",
   "metadata": {},
   "source": [
    "### Agent\n",
    "\n",
    "For complex questions it can be helpful for an LLM to be able to iteratively execute code while maintaining the inputs and outputs of its previous executions. This is where Agents come into play. They allow an LLM to decide how many times a tool needs to be invoked and keep track of the executions it's made so far. The [create_pandas_dataframe_agent](https://api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent.html) is a built-in agent that makes it easy to work with dataframes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "35ea904e-795f-411b-bef8-6484dbb6e35c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `python_repl_ast` with `{'query': \"df[['Age', 'Fare']].corr().iloc[0,1]\"}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m0.11232863699941621\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `python_repl_ast` with `{'query': \"df[['Fare', 'Survived']].corr().iloc[0,1]\"}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m0.2561785496289603\u001b[0m\u001b[32;1m\u001b[1;3mThe correlation between Age and Fare is approximately 0.112, and the correlation between Fare and Survival is approximately 0.256.\n",
      "\n",
      "Therefore, the correlation between Fare and Survival (0.256) is greater than the correlation between Age and Fare (0.112).\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"What's the correlation between age and fare? is that greater than the correlation between fare and survival?\",\n",
       " 'output': 'The correlation between Age and Fare is approximately 0.112, and the correlation between Fare and Survival is approximately 0.256.\\n\\nTherefore, the correlation between Fare and Survival (0.256) is greater than the correlation between Age and Fare (0.112).'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_experimental.agents import create_pandas_dataframe_agent\n",
    "\n",
    "agent = create_pandas_dataframe_agent(llm, df, agent_type=\"openai-tools\", verbose=True)\n",
    "agent.invoke(\n",
    "    {\n",
    "        \"input\": \"What's the correlation between age and fare? is that greater than the correlation between fare and survival?\"\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a65322f3-b13c-4949-82b2-4517b9a0859d",
   "metadata": {},
   "source": [
    "Here's the LangSmith trace for this run: https://smith.langchain.com/public/6a86aee2-4f22-474a-9264-bd4c7283e665/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68492261-faef-47e7-8009-e20ef1420d5a",
   "metadata": {},
   "source": [
    "### Multiple CSVs {#multiple-csvs}\n",
    "\n",
    "To handle multiple CSVs (or dataframes) we just need to pass multiple dataframes to our Python tool. Our `create_pandas_dataframe_agent` constructor can do this out of the box, we can pass in a list of dataframes instead of just one. If we're constructing a chain ourselves, we can do something like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "77a70e1b-d3ee-4fa6-a4a0-d2e5005e6c8a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.14384991262954416"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_1 = df[[\"Age\", \"Fare\"]]\n",
    "df_2 = df[[\"Fare\", \"Survived\"]]\n",
    "\n",
    "tool = PythonAstREPLTool(locals={\"df_1\": df_1, \"df_2\": df_2})\n",
    "llm_with_tool = llm.bind_tools(tools=[tool], tool_choice=tool.name)\n",
    "df_template = \"\"\"```python\n",
    "{df_name}.head().to_markdown()\n",
    ">>> {df_head}\n",
    "```\"\"\"\n",
    "df_context = \"\\n\\n\".join(\n",
    "    df_template.format(df_head=_df.head().to_markdown(), df_name=df_name)\n",
    "    for _df, df_name in [(df_1, \"df_1\"), (df_2, \"df_2\")]\n",
    ")\n",
    "\n",
    "system = f\"\"\"You have access to a number of pandas dataframes. \\\n",
    "Here is a sample of rows from each dataframe and the python code that was used to generate the sample:\n",
    "\n",
    "{df_context}\n",
    "\n",
    "Given a user question about the dataframes, write the Python code to answer it. \\\n",
    "Don't assume you have access to any libraries other than built-in Python ones and pandas. \\\n",
    "Make sure to refer only to the variables mentioned above.\"\"\"\n",
    "prompt = ChatPromptTemplate.from_messages([(\"system\", system), (\"human\", \"{question}\")])\n",
    "\n",
    "chain = prompt | llm_with_tool | parser | tool\n",
    "chain.invoke(\n",
    "    {\n",
    "        \"question\": \"return the difference in the correlation between age and fare and the correlation between fare and survival\"\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7043363f-4ab1-41de-9318-c556e4ae66bc",
   "metadata": {},
   "source": [
    "Here's the LangSmith trace for this run: https://smith.langchain.com/public/cc2a7d7f-7c5a-4e77-a10c-7b5420fcd07f/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2256d09-23c2-4e52-bfc6-c84eba538586",
   "metadata": {},
   "source": [
    "### Sandboxed code execution\n",
    "\n",
    "There are a number of tools like [E2B](/docs/integrations/tools/e2b_data_analysis) and [Bearly](/docs/integrations/tools/bearly) that provide sandboxed environments for Python code execution, to allow for safer code-executing chains and agents."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1728e791-f114-41e6-aa12-0436fdeeedae",
   "metadata": {},
   "source": [
    "## Next steps\n",
    "\n",
    "For more advanced data analysis applications we recommend checking out:\n",
    "\n",
    "* [SQL tutorial](/docs/tutorials/sql_qa): Many of the challenges of working with SQL db's and CSV's are generic to any structured data type, so it's useful to read the SQL techniques even if you're using Pandas for CSV data analysis.\n",
    "* [Tool use](/docs/how_to/tool_calling): Guides on general best practices when working with chains and agents that invoke tools\n",
    "* [Agents](/docs/tutorials/agents): Understand the fundamentals of building LLM agents.\n",
    "* Integrations: Sandboxed envs like [E2B](/docs/integrations/tools/e2b_data_analysis) and [Bearly](/docs/integrations/tools/bearly), utilities like [SQLDatabase](https://api.python.langchain.com/en/latest/utilities/langchain_community.utilities.sql_database.SQLDatabase.html#langchain_community.utilities.sql_database.SQLDatabase), related agents like [Spark DataFrame agent](/docs/integrations/toolkits/spark)."
   ]
  }
 ],
 "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.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
