This Python program is a LangChain-based conversational system that answers user questions by generating and executing SQL queries on a MySQL database. Here's a detailed description of what it does:
- Connects to a MySQL database named
financesusing usernamerootand a password stored in the variablepwd. - Initializes a chat model from
langchain_ollamawith the model"llama3.1"and zero temperature (deterministic responses). - Defines structured data types using Python
TypedDictto enforce expected keys for the data flow (StateandQueryOutput).
- Constructs a system prompt instructing the LLM to act as a MySQL expert who generates strict syntactically correct SQL queries.
- The prompt restricts queries to:
- Use provided tables, columns, and sample rows.
- Limit results to a maximum number of rows (default 10).
- Avoid explanations, markdown, or code fence outputs.
- Explicitly instructs date filtering to use MySQL date functions like
DATE_FORMAT(Date, '%Y-%m')orLEFT(Date, 7)rather than string pattern matching. - Assembles the prompt as a
ChatPromptTemplatewith system and human message roles.
- Defines a LangChain SQL query chain via
create_sql_query_chainthat:- Receives a user question.
- Injects database schema info (
table_info) dynamically. - Uses the configured LLM and prompt template.
- The function
write_query(state: State)generates a SQL query text by invoking the LLM with structured output.
- Uses
QuerySQLDatabaseToolfrom LangChain Community utilities to run SQL queries on the connected MySQL database. - The function
execute_query(state: State)accepts a dictionary with a"query"key and returns the SQL result.
- The function
generate_answer(state: State)creates a natural language answer by passing the user question, SQL query, and SQL results back through the chat model. - The prompt for answer generation includes these components and instructs the LLM to answer the user question accordingly.
- A sample question
"How much money did I spend in February 2024?"is defined. - The system:
- Calls
write_queryto generate the appropriate SQL query. - Calls
execute_queryto run the SQL query against the MySQL database. - Feeds the question, query, and result to
generate_answerto produce the final answer in natural language.
- Calls
- Regex-based SQL extractor (
extract_sql) strips extraneous text or markdown to isolate pure SQL statements from model outputs. - TypedDict definitions enhance code clarity and error-checking with expected dictionary schemas for states and outputs.
This program provides an end-to-end pipeline enabling conversational querying over a MySQL database by:
- Translating natural language questions to valid MySQL SQL queries,
- Executing those queries,
- Interpreting the raw results into human-readable answers,
leveraging LangChain framework for chaining together LLMs, prompt templates, and database access tools in Python.
It is specifically tailored to your finances MySQL database schema and enforces best practices for date filtering in SQL queries.