LangChain LangGraph
Module 1 Module 2 Module 3
Module 2 · Tools, State and Multi-Agent
1 2.1 MCP
2 2.1 Travel Agent
3 2.2 Runtime Context
4 2.2 State
5 2.3 Multi Agent
6 2.4 Wedding Planners
7 Bonus: RAG
8 Bonus: SQL
SUM Module Summary
HomeLangChainModule 2 · Tools, State and Multi-AgentBonus: SQL
📓 Notebook 📖 Explained
LANGCHAIN MODULE 2 · BONUS SQL

Bonus SQL: letting an Agent query a relational database
SQLDatabase · Tool · Query Trace

This section uses the Use Chinook SQLite Data library to encapsulate a SQL query tool, allowing the Agent to generate SQL based on natural language questions, execute the query, and organize the final answer.

1 Why SQL works well as an Agent tool

A lot of business data already exists in relational data libraries. Rather than putting the entire table into the prompt, it is better to give the Agent a controlled SQL query tool and let it query on demand.

Wayadvantagerisk
PutData copied into promptSimple and directThe context is limited and the data is easily expired.
Let the Agent adjust the SQL toolQuery real data on demandNeed to restrict permissions and handle error SQL
Objectives of this lesson

Let the Agent start from the natural language question, generate SQL query Chinook.db, and then use the query results to answer "Which artist starting with S is the most popular?"

2 Connect to the Chinook SQLite database

Notebook uses LangChain Community's SQLDatabase tool class to connect local SQLite files.

Python
from langchain_community.utilities import SQLDatabase

db = SQLDatabase.from_uri("sqlite:///resources/Chinook.db")
Chinook

Chinook is a common sample music database with tables such as Artist, Album, Track and InvoiceLine, making it useful for SQL Agent demos.

3 Wrap the sql_query tool

The tool receives a SQL string and executes db.run(query). If the SQL fails, the tool returns the error so the model has a chance to correct the query.

Python
@tool
def sql_query(query: str) -> str:
    """Obtain information from the database using SQL queries"""
    try:
        return db.run(query)
    except Exception as e:
        return f"Error: {e}"

sql_query.invoke("SELECT * FROM Artist LIMIT 10")
Safety boundary

The course tool does not enforce permissions. In production, restrict it to read-only queries, limit table access, add timeouts and row limits, and prevent dangerous SQL generation.

4 Create the SQL Agent

Give sql_query to the Agent as its only tool. The model decides what SQL to write from the question and passes that SQL as the tool argument.

Python
agent = create_agent(
    model=deepseek_model(),
    tools=[sql_query],
)

question = HumanMessage(
    content="Who is the most popular artist beginning with 'S' in this database?"
)

response = agent.invoke({"messages": [question]})
What the model does

The model does not directly know the database answer. It first infers which tables and fields to query, then calls sql_query to get the result.

5 Inspect the SQL generated by the model

The notebook deliberately prints the tool-call arguments from the third-to-last message to inspect the SQL the model actually sent to the database.

Python
print(response["messages"][-3].tool_calls[0]["args"]["query"])
print(response["messages"][-1].content)
Why inspect SQL

The debugging focus for a SQL Agent is whether the query is correct. A plausible final answer does not prove the SQL used the right table, join or ordering.

6 Ways to improve the SQL Agent

Summary

SQL tools let Agents access structured business data, but SQL correctness and safety must be handled at the tool boundary rather than relying on the model's judgment alone.