Spaces:
Runtime error
Runtime error
Commit Β·
d3be828
1
Parent(s): 0dbe277
Mini agent improved
Browse filesMarkdown code improved to clarify cells in Jupyter, more prints added for troubleshooting, UI changed to make it more user-friendly
- examples/data_agent_demo.ipynb +229 -97
examples/data_agent_demo.ipynb
CHANGED
|
@@ -9,10 +9,15 @@
|
|
| 9 |
"\n",
|
| 10 |
"## Prerequisites\n",
|
| 11 |
"\n",
|
| 12 |
-
"
|
| 13 |
-
" - Supabase\n",
|
| 14 |
-
" - OpenAI\n",
|
| 15 |
"\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"\n",
|
| 17 |
" Before starting your work install all the required tools:"
|
| 18 |
],
|
|
@@ -24,7 +29,22 @@
|
|
| 24 |
{
|
| 25 |
"cell_type": "code",
|
| 26 |
"source": [
|
| 27 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
],
|
| 29 |
"metadata": {
|
| 30 |
"id": "L0KlJIwcdCed"
|
|
@@ -34,47 +54,73 @@
|
|
| 34 |
"id": "L0KlJIwcdCed"
|
| 35 |
},
|
| 36 |
{
|
| 37 |
-
"cell_type": "
|
| 38 |
"source": [
|
| 39 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
],
|
| 41 |
"metadata": {
|
| 42 |
-
"id": "
|
| 43 |
},
|
| 44 |
-
"id": "
|
|
|
|
|
|
|
| 45 |
},
|
| 46 |
{
|
| 47 |
"cell_type": "code",
|
| 48 |
-
"execution_count": null,
|
| 49 |
-
"metadata": {
|
| 50 |
-
"id": "u3Py4qe6PlP7"
|
| 51 |
-
},
|
| 52 |
-
"outputs": [],
|
| 53 |
"source": [
|
| 54 |
"import os\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
"from IPython.display import Markdown, HTML, display\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
"from langchain_openai import AzureChatOpenAI\n",
|
| 57 |
-
"from
|
| 58 |
-
"from langchain.agents.agent_types import AgentType\n",
|
| 59 |
"from langchain.agents import initialize_agent\n",
|
|
|
|
| 60 |
"from langchain.tools import tool\n",
|
| 61 |
"from langchain.memory import ConversationTokenBufferMemory\n",
|
| 62 |
"from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent\n",
|
| 63 |
-
"import gradio as gr\n",
|
| 64 |
-
"import pandas as pd\n",
|
| 65 |
-
"import io\n",
|
| 66 |
-
"import contextlib\n",
|
| 67 |
-
"from sqlalchemy import (Engine,create_engine,MetaData,Table,Column,String,Integer,Float,insert,inspect,text)\n",
|
| 68 |
-
"from langchain_core.messages import HumanMessage\n",
|
| 69 |
-
"from langgraph.prebuilt import create_react_agent\n",
|
| 70 |
"from langchain_community.agent_toolkits import SQLDatabaseToolkit\n",
|
| 71 |
"from langchain_community.utilities import SQLDatabase\n",
|
| 72 |
-
"import
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
"from
|
|
|
|
|
|
|
| 76 |
],
|
| 77 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
},
|
| 79 |
{
|
| 80 |
"cell_type": "markdown",
|
|
@@ -97,8 +143,7 @@
|
|
| 97 |
"outputs": [],
|
| 98 |
"source": [
|
| 99 |
"os.environ[\"AZURE_OPENAI_ENDPOINT\"] = \"INSERT THE AZURE OPENAI ENDPOINT\"\n",
|
| 100 |
-
"os.environ[\"AZURE_OPENAI_API_KEY\"] = \"INSERT YOUR AZURE OPENAI API KEY\"
|
| 101 |
-
"os.environ[\"OPENAI_API_KEY\"] = \"INSERT YOUR OPENAI API KEY\""
|
| 102 |
],
|
| 103 |
"id": "5ldGnv_jPlP8"
|
| 104 |
},
|
|
@@ -139,7 +184,13 @@
|
|
| 139 |
{
|
| 140 |
"cell_type": "markdown",
|
| 141 |
"source": [
|
| 142 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
],
|
| 144 |
"metadata": {
|
| 145 |
"id": "9cMbxsJuyMPb"
|
|
@@ -151,7 +202,7 @@
|
|
| 151 |
"source": [
|
| 152 |
"# Prompt prefix to set the tone for the agent.\n",
|
| 153 |
"#By specifying the prompt prefix you may make the results of the agent more specific and consistent.\n",
|
| 154 |
-
"#The following prompt can be substituted with
|
| 155 |
"CSV_PROMPT_PREFIX = \"\"\"\n",
|
| 156 |
"Set pandas to show all columns.\n",
|
| 157 |
"Get the column names and infer data types.\n",
|
|
@@ -209,7 +260,19 @@
|
|
| 209 |
"\"\"\".format(\n",
|
| 210 |
" dialect=\"SQLite\",\n",
|
| 211 |
" top_k=5,\n",
|
| 212 |
-
")\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
],
|
| 214 |
"metadata": {
|
| 215 |
"id": "B6dGxRmnyJHS"
|
|
@@ -221,7 +284,9 @@
|
|
| 221 |
{
|
| 222 |
"cell_type": "markdown",
|
| 223 |
"source": [
|
| 224 |
-
"The following block is responsible for the logic of the agent and the output that it produces."
|
|
|
|
|
|
|
| 225 |
],
|
| 226 |
"metadata": {
|
| 227 |
"id": "bWNgj913yo8h"
|
|
@@ -280,7 +345,15 @@
|
|
| 280 |
{
|
| 281 |
"cell_type": "markdown",
|
| 282 |
"source": [
|
| 283 |
-
"The block below deals with creating SQL code."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
],
|
| 285 |
"metadata": {
|
| 286 |
"id": "buR79jvcJSnf"
|
|
@@ -292,16 +365,24 @@
|
|
| 292 |
"source": [
|
| 293 |
"#function create_db receives a dictionary with table names as a key and tables as values\n",
|
| 294 |
"def create_db(files):\n",
|
| 295 |
-
"
|
| 296 |
-
"
|
| 297 |
-
"
|
| 298 |
-
"
|
| 299 |
-
"
|
| 300 |
-
" for
|
| 301 |
-
"
|
| 302 |
-
"\n",
|
| 303 |
-
"
|
| 304 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
],
|
| 306 |
"metadata": {
|
| 307 |
"id": "uajELHHaJjUS"
|
|
@@ -310,38 +391,73 @@
|
|
| 310 |
"execution_count": null,
|
| 311 |
"outputs": []
|
| 312 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
{
|
| 314 |
"cell_type": "code",
|
| 315 |
"source": [
|
| 316 |
"#Initialization of a LLM model for SQL queries\n",
|
| 317 |
"def start_llm(database):\n",
|
|
|
|
|
|
|
| 318 |
" toolkit = SQLDatabaseToolkit(db=database, llm=model) #creates a tool for working with SQL databases\n",
|
| 319 |
" tools = toolkit.get_tools()\n",
|
| 320 |
-
"
|
|
|
|
|
|
|
|
|
|
| 321 |
"\n",
|
| 322 |
"\n",
|
| 323 |
"def extract_code(HumanMessage):\n",
|
| 324 |
-
"
|
| 325 |
-
"
|
| 326 |
-
"
|
| 327 |
-
"
|
| 328 |
-
"
|
| 329 |
-
"
|
| 330 |
-
"
|
| 331 |
-
"\n",
|
|
|
|
|
|
|
| 332 |
"#Function that receives dataframes, puts them in a database and uses an AI agent to create quieries based on the user's question\n",
|
| 333 |
"def sql_pipeline(tables,question):\n",
|
|
|
|
| 334 |
" db = create_db(tables) #uploads the files added by the user and puts them in a database\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
" llm, tools = start_llm(db) #returns the agent and the tools for working with the database\n",
|
| 336 |
-
"
|
| 337 |
-
"
|
| 338 |
-
"
|
| 339 |
-
"
|
| 340 |
-
"
|
| 341 |
-
"
|
| 342 |
-
"
|
| 343 |
-
"
|
| 344 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
],
|
| 346 |
"metadata": {
|
| 347 |
"id": "35sreALjyVuA"
|
|
@@ -432,7 +548,40 @@
|
|
| 432 |
{
|
| 433 |
"cell_type": "markdown",
|
| 434 |
"source": [
|
| 435 |
-
"The next section creates
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
],
|
| 437 |
"metadata": {
|
| 438 |
"id": "-oxO_Rkq0ZMv"
|
|
@@ -486,49 +635,32 @@
|
|
| 486 |
"\n",
|
| 487 |
" gr.Markdown(\"<h2 id='title'>π NexDatawork Data Agent</h2>\")\n",
|
| 488 |
"\n",
|
| 489 |
-
"\n",
|
| 490 |
-
"\n",
|
| 491 |
" with gr.Column():\n",
|
| 492 |
-
" result_display = gr.Markdown(label=\"π Report Output (Markdown)\")\n",
|
| 493 |
-
" trace_display = gr.Textbox(label=\"π οΈ Data Agent Reasoning - Your Explainable Agent\", lines=20)\n",
|
| 494 |
-
"\n",
|
| 495 |
-
" with gr.Row(equal_height=True):\n",
|
| 496 |
-
" file_input = gr.File(label=\"π Upload CSV(s)\", file_types=[\".csv\"], file_count=\"multiple\")\n",
|
| 497 |
-
" with gr.Column():\n",
|
| 498 |
"\n",
|
| 499 |
-
"
|
| 500 |
-
" label=\"π¬ Ask Your Data\",\n",
|
| 501 |
-
" placeholder=\"e.g., What is the trend for revenue over time?\",\n",
|
| 502 |
-
" lines=2\n",
|
| 503 |
-
" )\n",
|
| 504 |
-
" sql_button = gr.Button('Create Prompt')\n",
|
| 505 |
-
"\n",
|
| 506 |
-
" sql_code = gr.Textbox(\n",
|
| 507 |
-
" label=\"SQL code\",lines=10\n",
|
| 508 |
-
" )\n",
|
| 509 |
-
" sql_button.click(\n",
|
| 510 |
-
" fn=sql_pipeline,\n",
|
| 511 |
-
" inputs=[file_input,question_input],\n",
|
| 512 |
-
" outputs = sql_code\n",
|
| 513 |
-
" )\n",
|
| 514 |
"\n",
|
|
|
|
| 515 |
"\n",
|
|
|
|
| 516 |
"\n",
|
|
|
|
| 517 |
"\n",
|
| 518 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
"\n",
|
| 520 |
-
"
|
| 521 |
-
" fn=ask_agent,\n",
|
| 522 |
-
" inputs=[file_input, question_input],\n",
|
| 523 |
-
" outputs=[result_display, trace_display]\n",
|
| 524 |
-
" )\n",
|
| 525 |
"\n",
|
| 526 |
-
"demo.launch(share=True)"
|
| 527 |
],
|
| 528 |
"metadata": {
|
| 529 |
-
"id": "
|
| 530 |
},
|
| 531 |
-
"id": "
|
| 532 |
"execution_count": null,
|
| 533 |
"outputs": []
|
| 534 |
},
|
|
@@ -536,9 +668,9 @@
|
|
| 536 |
"cell_type": "code",
|
| 537 |
"source": [],
|
| 538 |
"metadata": {
|
| 539 |
-
"id": "
|
| 540 |
},
|
| 541 |
-
"id": "
|
| 542 |
"execution_count": null,
|
| 543 |
"outputs": []
|
| 544 |
}
|
|
|
|
| 9 |
"\n",
|
| 10 |
"## Prerequisites\n",
|
| 11 |
"\n",
|
| 12 |
+
"- langchain\n",
|
|
|
|
|
|
|
| 13 |
"\n",
|
| 14 |
+
"- langgraph\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"- sqlalchemy\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"- pandas\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"- gradio\n",
|
| 21 |
"\n",
|
| 22 |
" Before starting your work install all the required tools:"
|
| 23 |
],
|
|
|
|
| 29 |
{
|
| 30 |
"cell_type": "code",
|
| 31 |
"source": [
|
| 32 |
+
"# Clean out any mixed installs first\n",
|
| 33 |
+
"%pip uninstall -y langchain langchain-core langchain-community langchain-openai langchain-anthropic langchain-google-vertexai langchain-experimental langgraph\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Install a consistent, modern set\n",
|
| 36 |
+
"%pip install -U \\\n",
|
| 37 |
+
" \"langchain==0.3.*\" \\\n",
|
| 38 |
+
" \"langchain-core==0.3.*\" \\\n",
|
| 39 |
+
" \"langchain-community==0.3.*\" \\\n",
|
| 40 |
+
" \"langgraph>=0.2,<0.3\" \\\n",
|
| 41 |
+
" \"langchain-openai>=0.2.0\" \\\n",
|
| 42 |
+
" \"langchain-anthropic>=0.2.0\" \\\n",
|
| 43 |
+
" \"langchain-google-vertexai>=2.0.0\" \\\n",
|
| 44 |
+
" \"sqlalchemy>=2.0\" \\\n",
|
| 45 |
+
" \"pandas>=2.0\" \\\n",
|
| 46 |
+
" \"gradio>=4.0\" \\\n",
|
| 47 |
+
" \"langchain-experimental\""
|
| 48 |
],
|
| 49 |
"metadata": {
|
| 50 |
"id": "L0KlJIwcdCed"
|
|
|
|
| 54 |
"id": "L0KlJIwcdCed"
|
| 55 |
},
|
| 56 |
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
"source": [
|
| 59 |
+
"import sys, importlib.util, importlib.metadata as md\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"def v(p):\n",
|
| 62 |
+
" try:\n",
|
| 63 |
+
" return md.version(p)\n",
|
| 64 |
+
" except md.PackageNotFoundError:\n",
|
| 65 |
+
" return \"not installed\"\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"print(\"Kernel Python:\", sys.executable)\n",
|
| 68 |
+
"print(\"langchain:\", v(\"langchain\"))\n",
|
| 69 |
+
"print(\"langchain-core:\", v(\"langchain-core\"))\n",
|
| 70 |
+
"print(\"langchain-community:\", v(\"langchain-community\"))\n",
|
| 71 |
+
"print(\"langgraph:\", v(\"langgraph\"))\n",
|
| 72 |
+
"print(\"langchain-openai:\", v(\"langchain-openai\"))\n",
|
| 73 |
+
"print(\"langchain-anthropic:\", v(\"langchain-anthropic\"))\n",
|
| 74 |
+
"print(\"langchain-google-vertexai:\", v(\"langchain-google-vertexai\"))\n",
|
| 75 |
+
"print(\"langchain-experimental:\", v(\"langchain-experimental\"))\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"print(\"langgraph importable?\", importlib.util.find_spec(\"langgraph\") is not None)"
|
| 78 |
],
|
| 79 |
"metadata": {
|
| 80 |
+
"id": "AWWI1FJ6ChHN"
|
| 81 |
},
|
| 82 |
+
"id": "AWWI1FJ6ChHN",
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
},
|
| 86 |
{
|
| 87 |
"cell_type": "code",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
"source": [
|
| 89 |
"import os\n",
|
| 90 |
+
"import io\n",
|
| 91 |
+
"import contextlib\n",
|
| 92 |
+
"import pandas as pd\n",
|
| 93 |
+
"import gradio as gr\n",
|
| 94 |
"from IPython.display import Markdown, HTML, display\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"from sqlalchemy import (\n",
|
| 97 |
+
" Engine, create_engine, MetaData, Table, Column,\n",
|
| 98 |
+
" String, Integer, Float, insert, inspect, text\n",
|
| 99 |
+
")\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"# LangChain 0.3.x import paths\n",
|
| 102 |
"from langchain_openai import AzureChatOpenAI\n",
|
| 103 |
+
"from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",
|
|
|
|
| 104 |
"from langchain.agents import initialize_agent\n",
|
| 105 |
+
"from langchain.agents.agent_types import AgentType\n",
|
| 106 |
"from langchain.tools import tool\n",
|
| 107 |
"from langchain.memory import ConversationTokenBufferMemory\n",
|
| 108 |
"from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
"from langchain_community.agent_toolkits import SQLDatabaseToolkit\n",
|
| 110 |
"from langchain_community.utilities import SQLDatabase\n",
|
| 111 |
+
"from langchain_core.messages import HumanMessage\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"# LangGraph\n",
|
| 114 |
+
"from langgraph.prebuilt import create_react_agent\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"print(\"β
Imports OK\")"
|
| 117 |
],
|
| 118 |
+
"metadata": {
|
| 119 |
+
"id": "g9izxdgGCl-V"
|
| 120 |
+
},
|
| 121 |
+
"id": "g9izxdgGCl-V",
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
},
|
| 125 |
{
|
| 126 |
"cell_type": "markdown",
|
|
|
|
| 143 |
"outputs": [],
|
| 144 |
"source": [
|
| 145 |
"os.environ[\"AZURE_OPENAI_ENDPOINT\"] = \"INSERT THE AZURE OPENAI ENDPOINT\"\n",
|
| 146 |
+
"os.environ[\"AZURE_OPENAI_API_KEY\"] = \"INSERT YOUR AZURE OPENAI API KEY\""
|
|
|
|
| 147 |
],
|
| 148 |
"id": "5ldGnv_jPlP8"
|
| 149 |
},
|
|
|
|
| 184 |
{
|
| 185 |
"cell_type": "markdown",
|
| 186 |
"source": [
|
| 187 |
+
"The following block contains prompts that define the agents behaviour.\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"```CSV_PROMPT_PREFIX``` is responsible for the data agent logic, i.e. steps that it takes to complete a task. The prefix can be modified to change analytical methodology, add specific data processing steps, implement a certain data validation technique and more.\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"```CSV_PROMPT_SUFFIX``` defines the structure and the content of the agent's output. Suffix can be modified to change the report structure, add sections, include additional insights and so on.\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"```system_message``` is for creating SQL queries. It specifies the behaviour of the agent, making it certify its results and restricting it from changing the database."
|
| 194 |
],
|
| 195 |
"metadata": {
|
| 196 |
"id": "9cMbxsJuyMPb"
|
|
|
|
| 202 |
"source": [
|
| 203 |
"# Prompt prefix to set the tone for the agent.\n",
|
| 204 |
"#By specifying the prompt prefix you may make the results of the agent more specific and consistent.\n",
|
| 205 |
+
"#The following prompt can be substituted with an original one.\n",
|
| 206 |
"CSV_PROMPT_PREFIX = \"\"\"\n",
|
| 207 |
"Set pandas to show all columns.\n",
|
| 208 |
"Get the column names and infer data types.\n",
|
|
|
|
| 260 |
"\"\"\".format(\n",
|
| 261 |
" dialect=\"SQLite\",\n",
|
| 262 |
" top_k=5,\n",
|
| 263 |
+
")\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"sql_suffix_prompt = '''\n",
|
| 266 |
+
"ALWAYS end your answer as follows:\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"### Final answer\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"Your query here\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"--\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"The answer here\n",
|
| 275 |
+
"'''"
|
| 276 |
],
|
| 277 |
"metadata": {
|
| 278 |
"id": "B6dGxRmnyJHS"
|
|
|
|
| 284 |
{
|
| 285 |
"cell_type": "markdown",
|
| 286 |
"source": [
|
| 287 |
+
"The following block is responsible for the logic of the agent and the output that it produces.\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"```ask_agent``` function concatenates the dataframes into one and starts an AI agent for working with the concatenated dataframes. It uses the prompts from the previous blocks for its logic."
|
| 290 |
],
|
| 291 |
"metadata": {
|
| 292 |
"id": "bWNgj913yo8h"
|
|
|
|
| 345 |
{
|
| 346 |
"cell_type": "markdown",
|
| 347 |
"source": [
|
| 348 |
+
"The block below deals with creating SQL code.\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"```create_db``` creates a database where all the uploaded dataframes are stored for the data agent to work with.\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"```start_llm``` starts a tool for working with SQL databases.\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"```extract_code``` is used for extracting the SQL query from the agent's output.\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"```sql_pipeline``` defines the pipeline, starting from creating a database with the uploaded dataframes, starting the agent for working with databases and creating the query according to the user's question."
|
| 357 |
],
|
| 358 |
"metadata": {
|
| 359 |
"id": "buR79jvcJSnf"
|
|
|
|
| 365 |
"source": [
|
| 366 |
"#function create_db receives a dictionary with table names as a key and tables as values\n",
|
| 367 |
"def create_db(files):\n",
|
| 368 |
+
" print(\"=\"*10+\"\\nCREATE_DB\\n\"+\"=\"*10)\n",
|
| 369 |
+
" try:\n",
|
| 370 |
+
" print(\"Attempting to create database...\") # Added print statement here\n",
|
| 371 |
+
" engine = create_engine(\"sqlite:///database.db\")\n",
|
| 372 |
+
" dataframes = dict()\n",
|
| 373 |
+
" print(\"=\"*10+f\"CREATE_DB:\\nfiles:{[f.name for f in files]}\\n\"+\"=\"*10)\n",
|
| 374 |
+
" for f in files:\n",
|
| 375 |
+
" table_name = os.path.splitext(os.path.basename(f.name))[0]\n",
|
| 376 |
+
" dataframes[table_name] = pd.read_csv(f.name)\n",
|
| 377 |
+
" with engine.begin() as connection:\n",
|
| 378 |
+
" for name,table in zip(dataframes.keys(),dataframes.values()):\n",
|
| 379 |
+
" table.to_sql(name,connection,if_exists=\"replace\",index=False) #writes the tables into a database\n",
|
| 380 |
+
"\n",
|
| 381 |
+
" db = SQLDatabase.from_uri(\"sqlite:///database.db\")\n",
|
| 382 |
+
" print(\"DATABASE database.db CREATED\")\n",
|
| 383 |
+
" except Exception as e:\n",
|
| 384 |
+
" return f\"Database error: {e}\"\n",
|
| 385 |
+
" return db"
|
| 386 |
],
|
| 387 |
"metadata": {
|
| 388 |
"id": "uajELHHaJjUS"
|
|
|
|
| 391 |
"execution_count": null,
|
| 392 |
"outputs": []
|
| 393 |
},
|
| 394 |
+
{
|
| 395 |
+
"cell_type": "code",
|
| 396 |
+
"source": [
|
| 397 |
+
"asdf='''\n",
|
| 398 |
+
"asdfasdfadfasdfdf\n",
|
| 399 |
+
"asdfasdfqwerqwer\n",
|
| 400 |
+
"\n",
|
| 401 |
+
"asdfasdf### Final answer\n",
|
| 402 |
+
"thjmthjmtjm\n",
|
| 403 |
+
";lklkjb;lkj\n",
|
| 404 |
+
"'''"
|
| 405 |
+
],
|
| 406 |
+
"metadata": {
|
| 407 |
+
"id": "JIAwzne3pzHp"
|
| 408 |
+
},
|
| 409 |
+
"id": "JIAwzne3pzHp",
|
| 410 |
+
"execution_count": null,
|
| 411 |
+
"outputs": []
|
| 412 |
+
},
|
| 413 |
{
|
| 414 |
"cell_type": "code",
|
| 415 |
"source": [
|
| 416 |
"#Initialization of a LLM model for SQL queries\n",
|
| 417 |
"def start_llm(database):\n",
|
| 418 |
+
" try:\n",
|
| 419 |
+
" print(\"=\"*10+\"\\nSTART_LLM\\n\"+\"=\"*10)\n",
|
| 420 |
" toolkit = SQLDatabaseToolkit(db=database, llm=model) #creates a tool for working with SQL databases\n",
|
| 421 |
" tools = toolkit.get_tools()\n",
|
| 422 |
+
" except Exception as e:\n",
|
| 423 |
+
" return f\"Couldn't retrieve SQLDatabaseToolkit: {e}\"\n",
|
| 424 |
+
" print(\"\\nSQLDatabaseToolkit CREATED\\n\")\n",
|
| 425 |
+
" return model, tools\n",
|
| 426 |
"\n",
|
| 427 |
"\n",
|
| 428 |
"def extract_code(HumanMessage):\n",
|
| 429 |
+
" print(\"=\"*10+\"\\nEXTRACT_CODE\\n\"+\"=\"*10)\n",
|
| 430 |
+
" try:\n",
|
| 431 |
+
" FRONT_INDENT = len('\\n\\n')\n",
|
| 432 |
+
" BACK_INDENT = len('\\n')\n",
|
| 433 |
+
" p1 = HumanMessage.find('### Final answer')\n",
|
| 434 |
+
" print(p1,HumanMessage[p1:p1+50])\n",
|
| 435 |
+
" p2 = p1+FRONT_INDENT\n",
|
| 436 |
+
" return HumanMessage[p1:]\n",
|
| 437 |
+
" except Exception as e:\n",
|
| 438 |
+
" print(f'Extraction error: {e}')\n",
|
| 439 |
"#Function that receives dataframes, puts them in a database and uses an AI agent to create quieries based on the user's question\n",
|
| 440 |
"def sql_pipeline(tables,question):\n",
|
| 441 |
+
" print(\"=\"*10+\"\\nSQL_PIPELINE\\n\"+\"=\"*10)\n",
|
| 442 |
" db = create_db(tables) #uploads the files added by the user and puts them in a database\n",
|
| 443 |
+
"\n",
|
| 444 |
+
" if not os.path.exists(\"database.db\"):\n",
|
| 445 |
+
" print(\"Database doesn't exist\")\n",
|
| 446 |
+
" return \"Database doesn't exist\"\n",
|
| 447 |
" llm, tools = start_llm(db) #returns the agent and the tools for working with the database\n",
|
| 448 |
+
" try:\n",
|
| 449 |
+
" agent_executor = create_react_agent(llm, tools, prompt=system_message+sql_suffix_prompt)\n",
|
| 450 |
+
" output = \"\"\n",
|
| 451 |
+
" for step in agent_executor.stream(\n",
|
| 452 |
+
" {\"messages\": [{\"role\": \"user\", \"content\": question}]},\n",
|
| 453 |
+
" stream_mode=\"values\",\n",
|
| 454 |
+
" ):\n",
|
| 455 |
+
" output += step[\"messages\"][-1].content\n",
|
| 456 |
+
" #query = extract_code(output)\n",
|
| 457 |
+
" final_answer = extract_code(output)\n",
|
| 458 |
+
" return output, final_answer\n",
|
| 459 |
+
" except Exception as e:\n",
|
| 460 |
+
" return f\"SQL agent error: {e}\""
|
| 461 |
],
|
| 462 |
"metadata": {
|
| 463 |
"id": "35sreALjyVuA"
|
|
|
|
| 548 |
{
|
| 549 |
"cell_type": "markdown",
|
| 550 |
"source": [
|
| 551 |
+
"The next section creates a web interface using Gradio, providing a user-friendly way to analyze data and create SQL queries.\n",
|
| 552 |
+
"\n",
|
| 553 |
+
"\n",
|
| 554 |
+
"```\n",
|
| 555 |
+
"with gr.Blocks(\n",
|
| 556 |
+
" css=\"\"\"\n",
|
| 557 |
+
" Change the code here to modify the styling of the UI\n",
|
| 558 |
+
" \"\"\"\n",
|
| 559 |
+
" ) as demo:\n",
|
| 560 |
+
"```\n",
|
| 561 |
+
"\n",
|
| 562 |
+
"\n",
|
| 563 |
+
"\n",
|
| 564 |
+
"**Display Area**:\n",
|
| 565 |
+
"- `result_display`: Markdown report output\n",
|
| 566 |
+
"- `trace_display`: Agent reasoning trace\n",
|
| 567 |
+
"\n",
|
| 568 |
+
"**Input Section**:\n",
|
| 569 |
+
"- `file_input`: Multiple CSV upload\n",
|
| 570 |
+
"- `question_input`: User query box\n",
|
| 571 |
+
"\n",
|
| 572 |
+
"**Action Buttons**:\n",
|
| 573 |
+
"- `sql_button`: Generate SQL queries β `sql_pipeline` function\n",
|
| 574 |
+
"- `ask_button`: Run analysis β `ask_agent` function\n",
|
| 575 |
+
"\n",
|
| 576 |
+
"**Styling**\n",
|
| 577 |
+
"- Light theme with rounded corners\n",
|
| 578 |
+
"- Custom CSS for professional appearance\n",
|
| 579 |
+
"\n",
|
| 580 |
+
"**Launch**\n",
|
| 581 |
+
"\n",
|
| 582 |
+
"`demo.launch(share=True,debug=False)` - Public access enabled, debugging disabled\n",
|
| 583 |
+
"\n",
|
| 584 |
+
"For debugging use `debug=True` in odrder to see the messages in the console.\n"
|
| 585 |
],
|
| 586 |
"metadata": {
|
| 587 |
"id": "-oxO_Rkq0ZMv"
|
|
|
|
| 635 |
"\n",
|
| 636 |
" gr.Markdown(\"<h2 id='title'>π NexDatawork Data Agent</h2>\")\n",
|
| 637 |
"\n",
|
|
|
|
|
|
|
| 638 |
" with gr.Column():\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
"\n",
|
| 640 |
+
" result_display = gr.Markdown(label=\"π Report Output (Markdown)\")\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
"\n",
|
| 642 |
+
" with gr.Row():\n",
|
| 643 |
"\n",
|
| 644 |
+
" trace_display = gr.Textbox(label=\"π οΈ Data Agent Reasoning - Your Explainable Agent\", lines=20)\n",
|
| 645 |
"\n",
|
| 646 |
+
" sql_display = gr.Textbox(label='SQL Code',lines=20)\n",
|
| 647 |
"\n",
|
| 648 |
+
" with gr.Row(equal_height=True):\n",
|
| 649 |
+
" file_input = gr.File(label=\"π Upload CSV(s)\", file_types=[\".csv\"], file_count=\"multiple\",height=120)\n",
|
| 650 |
+
" question_input = gr.Textbox(label=\"π¬ Ask Your Agent\",placeholder=\"e.g., What is the trend for revenue over time?\",lines=2)\n",
|
| 651 |
+
" with gr.Row():\n",
|
| 652 |
+
" ask_button = gr.Button(\"π‘ Analyze\")\n",
|
| 653 |
+
" sql_button = gr.Button('Create Query')\n",
|
| 654 |
"\n",
|
| 655 |
+
" sql_button.click(fn=sql_pipeline,inputs=[file_input,question_input],outputs = [sql_display,result_display])\n",
|
| 656 |
+
" ask_button.click(fn=ask_agent,inputs=[file_input, question_input],outputs=[result_display, trace_display])\n",
|
|
|
|
|
|
|
|
|
|
| 657 |
"\n",
|
| 658 |
+
"demo.launch(share=True,debug=False)"
|
| 659 |
],
|
| 660 |
"metadata": {
|
| 661 |
+
"id": "OhM41SDzIQdI"
|
| 662 |
},
|
| 663 |
+
"id": "OhM41SDzIQdI",
|
| 664 |
"execution_count": null,
|
| 665 |
"outputs": []
|
| 666 |
},
|
|
|
|
| 668 |
"cell_type": "code",
|
| 669 |
"source": [],
|
| 670 |
"metadata": {
|
| 671 |
+
"id": "_cjnKT-o8SS5"
|
| 672 |
},
|
| 673 |
+
"id": "_cjnKT-o8SS5",
|
| 674 |
"execution_count": null,
|
| 675 |
"outputs": []
|
| 676 |
}
|