Skip to content

自定义 SQL Agent

直接在 LangGraph 中实现 SQL Agent,获得最大灵活性。

本教程展示如何使用 LangGraph 原语构建一个 SQL Agent,可以回答数据库相关问题。

安装

bash
pip install langchain langgraph langchain-openai

创建数据库工具

python
import sqlite3
from langchain.tools import tool

@tool
def list_tables() -> str:
    """列出数据库中所有表"""
    con = sqlite3.connect("Chinook.db")
    cursor = con.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = [row[0] for row in cursor.fetchall()]
    con.close()
    return ", ".join(tables)

@tool
def get_schema(table_names: str) -> str:
    """获取表的 schema 信息"""
    con = sqlite3.connect("Chinook.db")
    cursor = con.cursor()
    results = []
    for table in table_names.split(","):
        table = table.strip()
        cursor.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name=?;",
            (table,)
        )
        row = cursor.fetchone()
        if row:
            results.append(row[0])
    con.close()
    return "\n\n".join(results)

@tool
def run_query(query: str) -> str:
    """执行 SQL 查询并返回结果"""
    con = sqlite3.connect("Chinook.db")
    cursor = con.cursor()
    cursor.execute(query)
    result = str(cursor.fetchall())
    con.close()
    return result

创建 Agent

python
from langchain.agents import create_agent

agent = create_agent(
    model="openai:gpt-4o",
    tools=[list_tables, get_schema, run_query],
    system_prompt="You are a SQL agent. Use the provided tools to answer questions.",
)

运行

python
result = agent.invoke({
    "messages": [
        {"role": "user", "content": "How many tracks are in the database?"}
    ]
})
print(result["messages"][-1].content)

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。