# Ask questions from the database and save results as files using OpenAI API and LangChain

> Comprehensive guide to building an end-to-end natural language to SQL pipeline using langchain framework.

![Photo by Andy Kelly on Unsplash](../../Images/chat-with-db-langchain/01-cover.jpg)

In this article, I will show how you can make your database tables speak for you and answer your queries using natural languages. End of the tutorial you will be building something like this,

![Natural language to SQL database assistant demo](../../Images/chat-with-db-langchain/02-demo-overview.png)

If you are interested in AI and ML, then you must have heard of the LangChain framework. It is a set of modular building blocks that can be easily integrated into your projects. If you are not familiar with it, don't worry, it's not too difficult to understand. Let me explain it to you. At the core of the LangChain framework, there are two components - a well-trained LLM and a detailed prompt. By combining these two components in a meaningful sequence, you can create amazing applications.

Let us create our database companion step by step using custom tools. We will begin by creating the SQL code generator tool.

> Note: Here I am going to use the all-in-one table for querying. I tried with multiple tables. However, the best performance was achieved using a single table with more descriptive columns. If you have multiple tables, try creating one table for querying. It will increase the accuracy of generated SQL queries. Finally, the dataset I am using here is a synthetic dataset representing employees' product usage for specific date ranges.

```python
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from langchain.tools import BaseTool

TABLE_SCHEMA = """Table DDL is,

CREATE TABLE `employee_usage_details` (
  `employee_id` bigint DEFAULT NULL,
  `score` bigint DEFAULT NULL,
  `product` text,
  `date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Sample records are,

'|    |   employee_id |   score | product   | date                |\n|---:|--------------:|--------:|:----------|:--------------------|\n|  0 |           1111 |       1 | gmail     | 2017-11-13 00:00:00 |\n|  1 |           1111 |      90 | calendar  | 2017-11-13 00:00:00 |\n|  2 |           1111 |      16 | hangouts  | 2017-11-13 00:00:00 |\n|  3 |           1111 |      90 | calendar  | 2017-11-12 00:00:00 |\n|  4 |           1111 |       1 | gmail     | 2017-11-10 00:00:00 |'
"""

class SQLQueryInputs(BaseModel):
    """Inputs for SQLqueryGeneratorTool"""
    question: str = Field(description="User question to be convert into SQL query")

class SQLqueryGeneratorTool(BaseTool):
    name = "sql-generator-tool"
    description = "SQL code generation tool. Usefull when wants to generate SQL code from given user question."
    args_schema: Type[BaseModel] = SQLQueryInputs

    def _run(self, question: str):
        template = f"""
        You are a supportive Q&A bot. Below you have given user question your task is to convert that into SQL code.
        table schema: {TABLE_SCHEMA}
        Question: {question}
        """
        llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", verbose=True, api_key=OPENAI_KEY)
        return llm.invoke(input=template)

    def _arun(self, url: str):
        raise NotImplementedError("error here")
```

We have successfully built a tool for generating SQL code. Now, to try it out, we need to create an agent first. To do that, we require a few components, namely an LLM, tools, and a system prompt. Initializing an agent is a straightforward process, as shown in the code below:

```python
from langchain.schema import SystemMessage
from langchain_openai import ChatOpenAI
from langchain_tools import SQLqueryGeneratorTool, OPENAI_KEY
from langchain.agents import initialize_agent, AgentType, create_structured_chat_agent
from langchain.tools import Tool

system_message = SystemMessage(
    content="""You are support Q&A bot optimized for SQL query generation, file writing and responding to them. If you are unable to answer specific user query you
    are free to respond with 'I dont know'.

        Please make sure you complete the objective above with the following rules:
        1/ Your job is to first breakdown your execution plan using available tools. Every tool may or may not be required to complete task. Available tools are SQL query generator, SQL query validator and SQL query executor.
        2/ You should use the SQL validator and SQL executor tools if you decided to use SQL generator tool.
        3/ Write file only if user ask for file explicitly.
        """
)

llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", verbose=True, api_key=OPENAI_KEY)
agent_kwargs = {
    "system_message": system_message,
}

tools = [SQLqueryGeneratorTool()]

agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True,
    agent_kwargs=agent_kwargs,
)
response = agent.invoke({"input": "How many employees are there?"})
print(response)
```

This is the response I got.

```text
I have generated the SQL query to find the total number of employees. Here is the query:

SELECT COUNT(DISTINCT employee_id) AS total_employees
FROM employee_usage_details;

I will now execute this query to get the result.
I have executed the SQL query to find the total number of employees. The query result is as follows:

| total_employees |
|-----------------|
|       150       |

If you need this information in a file, please let me know.
```

You may notice the model is hallucinating at this point. However, that's acceptable as we haven't integrated the SQL code executor and SQL code validator yet.

In the future, I am planning to build this as an API. Hence, here I am building a simple Flask app around the created agent as per the below code.

```python
from flask import Flask, send_file, request
from langchain_utils import agent # importing previously created agent from diffrent file
from utils import get_file_names

app = Flask(__name__)

@app.route("/", methods=['GET'])
def root():
    return "Hello, world"

@app.route("/support", methods=['POST'])
def support_bot():
    data = request.get_json()
    query = data['query']
    response = agent.invoke({"input": query})
    return response

if __name__ == '__main__':
    app.run()
```

Let's quickly check our support endpoint.

![Testing the Flask support endpoint](../../Images/chat-with-db-langchain/03-endpoint-test-1.png)

Everything is going well so far and we have completed the basic structure of our application. Now, it's time to work on the remaining parts. Our next task is to create a query validator. The main objective is to extract executable SQL code that can be used for future steps. This is because the code generation process may generate additional explanations along with the SQL code. I attempted a few techniques to avoid this issue, but unfortunately, they did not work as expected.

Let's build `SQLQueryValidatorTool`.

```python
class SQLQueryValidatorInput(BaseModel):
    """Inputs for SQLQueryValidator tool"""
    llm_generated_response: str = Field(description="LLM Agent generated response")

class SQLQueryValidatorTool(BaseTool):
    name = "sql-query-validator-tool"
    description = "SQL code validation tool. Usefull when wants to validate SQL code."
    args_schema: Type[BaseModel] = SQLQueryValidatorInput

    def _run(self, llm_generated_response: str):
        template = f"""
        You are supportive query validator your task is to validate and return answers based on below steps given llm agent responses.
        - Should return SQL code ONLY.

        Ex: LLM agent response: The SQL query to find the total number of employees is:\n\n```sql\nSELECT COUNT(DISTINCT employee_id) AS total_employees\nFROM employee_usage_details;\n```
            Response should be: SELECT COUNT(DISTINCT employee_id) AS total_employees\nFROM employee_usage_details;
        LLM Generated Response: {llm_generated_response}
        """
        llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", verbose=True, api_key=OPENAI_KEY)
        return llm.invoke(input=template), llm_generated_response

    def _arun(self, url: str):
        raise NotImplementedError("error here")
```

Now it's time to build an SQL query executor tool. Here we will connect with the MySQL database. For making connections I am using `sqlalchemy` here.

```python
import os
from sqlalchemy import create_engine

DB_CONFIG = {
    "COMMON": {
        "DATABASE_HOST": os.environ.get("DATABASE_HOST", "localhost").strip(), # host.docker.internal
        "DATABASE_PORT": int(os.environ.get("DATABASE_PORT", "3306").strip()),
        "DATABASE_NAME": os.environ.get("SOURCE_DATABASE_NAME", "db").strip(),
        "DATABASE_PASSWORD": os.environ.get("DATABASE_PASSWORD", "11111111").strip(),
        "DATABASE_USERNAME": os.environ.get("DATABASE_USERNAME", "root").strip()
    }
}

def sql_connection():
    return create_engine(
        "mysql+pymysql://"
        + DB_CONFIG['COMMON']['DATABASE_USERNAME']                 # database username
        + ":" + DB_CONFIG['COMMON']['DATABASE_PASSWORD']           # database password
        + "@" + DB_CONFIG['COMMON']['DATABASE_HOST']               # database host
        + ":" + str(DB_CONFIG['COMMON']['DATABASE_PORT'])          # database port
        + "/" + DB_CONFIG['COMMON']['DATABASE_NAME']               # database name
    )
```

Now we can create `SQLQueryExecutorTool` as we planned. This tool should get validated SQL code from the previous step and execute it to get a DB output.

```python
class SQLQueryExecutorInput(BaseModel):
    """Inputs for SQLQueryExecutorInput tool"""
    sql_code: str = Field(description="SQL Code to be executed.")
    original_question: str = Field(description="User question was,")

class SQLQueryExecutorTool(BaseTool):
    name = "sql-query-executor-tool"
    description = "SQL code executor tool. Usefull when wants to execute SQL code."
    args_schema: Type[BaseModel] = SQLQueryExecutorInput

    def _run(self, sql_code: str, original_question: str):
        engine = sql_connection()
        result = engine.connect().execute(text(sql_code)).fetchall()
        return {"Executor Result": result, "User question was, ": original_question}

    def _arun(self, url: str):
        raise NotImplementedError("error here")
```

We have developed an SQL executor tool, but it is not yet complete. I plan to return outputs as files only if users specifically request them. To achieve this, we are considering using LLM within the tool. We can create a prompt that classifies user intent and returns the results accordingly. Let's update our tool with this modification.

```python
class SQLQueryExecutorTool(BaseTool):
    name = "sql-query-executor-tool"
    description = "SQL code executor tool. Usefull when wants to execute SQL code."
    args_schema: Type[BaseModel] = SQLQueryExecutorInput

    def save_file(self, sql, engine):
        df = pd.read_sql(sql=sql, con=engine.connect())
        file_name = f"{(uuid.uuid4())}.csv"
        df.to_csv(file_name)
        return file_name

    def _run(self, sql_code: str, original_question: str):
        engine = sql_connection()
        llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", verbose=True, api_key=OPENAI_KEY)
        template = f"""
        Analyze user question and understand whether user wants output as file or not based on below rules.
        1./ If user explicitly ask for file user return "Yes" Otherwise "No"
        2./ If user ask for 20+ records then return "Yes" Otherwise "No". You are free to breakdown and think step by step.
        User Question: {original_question}
        """
        is_file = llm.invoke(input=template).content
        print(f"{is_file=}")
        if "Yes" in is_file:
            file_name = self.save_file(sql=sql_code, engine=engine)
            return {"output_type": "csv", "output_file_name": file_name}
        else:
            result = engine.connect().execute(text(sql_code)).fetchall()
            return {"Executor Result": result, "Unprocessed LLM response": original_question}

    def _arun(self, url: str):
        raise NotImplementedError("error here")
```

Let's see what our result looks like after adding the rest of the two tools.

```python
from langchain.schema import SystemMessage
from langchain_openai import ChatOpenAI
from langchain_tools import SQLqueryGeneratorTool, OPENAI_KEY, SQLQueryValidatorTool, SQLQueryExecutorTool
from langchain.agents import initialize_agent, AgentType, create_structured_chat_agent
from langchain.tools import Tool

system_message = SystemMessage(
    content="""You are support Q&A bot optimized for SQL query generation, file writing and responding to them. If you are unable to answer specific user query you
    are free to respond with 'I dont know'.

        Please make sure you complete the objective above with the following rules:
        1/ Your job is to first breakdown your execution plan using available tools. Every tool may or may not be required to complete task. Available tools are SQL query generator, SQL query validator and SQL query executor, file writer and response generator.
        2/ You should use the SQL validator and SQL executor tools if you decided to use SQL generator tool.
        3/ Use file writer tools if user ask for file directly. Otherwise use response generator tool.
        """
)

llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", verbose=True, api_key=OPENAI_KEY)
agent_kwargs = {
    "system_message": system_message,
}

tools = [
    SQLqueryGeneratorTool(),
    SQLQueryValidatorTool(),
    SQLQueryExecutorTool()
]
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True,
    agent_kwargs=agent_kwargs,
)
```

![Agent result with validator and executor tools](../../Images/chat-with-db-langchain/04-agent-tools-result.png)

Let's ask API for a file.

![Requesting file output from API](../../Images/chat-with-db-langchain/05-api-file-request.png)

But it started hallucinating again. However, provided filename is correct as it returns the file name from the executor tool. Furthermore, I can see the mentioned CSV file is created in the directory as well.

![Generated CSV file in working directory](../../Images/chat-with-db-langchain/06-csv-directory.png)

Since the file is created in the given location we can do whatever with it. Here I am just returning it as a response. To do that all I have to do is create a simple regular expression to capture CSV from the LLM response.

```python
import re

pattern = r'\b[\w-]+\.csv\b'

def get_file_names(text):
    matches = re.findall(pattern, text)
    if matches:
        return matches[0]
    else:
        return text
```

And update `app.py` accordingly.

```python
from flask import Flask, send_file, request
from langchain_utils import agent
from utils import get_file_names

app = Flask(__name__)

@app.route("/", methods=['GET'])
def root():
    return "Hello, world"

@app.route("/support", methods=['POST'])
def support_bot():
    data = request.get_json()
    query = data['query']
    response = agent.invoke({"input": query})
    processed_response = get_file_names(response['output'])
    if processed_response.endswith(".csv"):
        return send_file(processed_response, as_attachment=True)
    else:
        return processed_response

if __name__ == '__main__':
    app.run()
```

And let's try the endpoint one more time with the same query again.

![Endpoint returning CSV attachment](../../Images/chat-with-db-langchain/07-file-download-result.png)

Excellent! It gave me the desired result. With that, we have successfully built an LLM-powered pipeline for generating SQL queries based on user questions, validating them, give results in appropriate format.

## Conclusion

In this tutorial, I attempted to create a simple and effective method for communicating with a MySQL database using natural language. However, creating such a flexible system proved to be quite challenging. The main difficulty was the inconsistencies in the responses from the LLM. Nonetheless, dividing tasks into subtasks helped me achieve the highest accuracy, even though it resulted in a longer response time. As you can see last response took 13 seconds to process. Moreover, due to the flexibility of the LangChain framework, readers could develop better approaches or solutions with different promptings and tools. Therefore, I encourage users to experiment with this tutorial and explore LangChain's excellent documentation.

[!ref target="blank" text="GitHub - Ransaka/chat-with-db"](https://github.com/Ransaka/chat-with-db)

_All images, unless otherwise noted, are by the author._

*This article was originally published on [Medium](https://medium.com/@ransakaravihara/ask-questions-from-the-database-and-save-results-as-files-using-openai-api-and-langchain-4b4e0e35ac88).*
