外观
概述
在本教程中,你将学习如何使用 LangChain 智能体 构建一个能够回答 SQL 数据库相关问题的智能体。
从高层次来看,该智能体将:
- 从数据库获取可用的表与模式(schema)
- 判断哪些表与问题相关
- 获取相关表的模式(schema)
- 根据问题以及模式中的信息生成查询
- 使用 LLM 复查查询中的常见错误
- 执行查询并返回结果
- 修正数据库引擎发现的错误,直到查询成功
- 根据结果生成回答
WARNING
构建 SQL 数据库的问答系统需要执行模型生成的 SQL 查询。这样做存在固有风险。请确保你的数据库连接权限始终尽可能窄地限定在你的智能体需求范围内。这有助于降低(尽管无法完全消除)构建模型驱动系统的风险。
概念
本教程涵盖以下概念:
准备工作
安装依赖
bash
pip install langchain langgraphbash
npm i langchain @langchain/core sqlite3 zodbash
yarn add langchain @langchain/core sqlite3 zodbash
pnpm add langchain @langchain/core sqlite3 zod配置 LangSmith
配置 LangSmith 以检查你的链或智能体内部发生的情况。然后设置以下环境变量:
bash
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."构建你的 SQL 智能体
选择 LLM
选择一个支持工具调用的模型:
OpenAI
👉 Read the [OpenAI chat model integration docs](/oss/python/integrations/chat/openai)
bash
pip install -U "langchain[openai]"python
import os
from langchain.chat_models import init_chat_model
os.environ["OPENAI_API_KEY"] = "sk-..."
model = init_chat_model("gpt-5.5")python
import os
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = "sk-..."
model = ChatOpenAI(model="gpt-5.5")Anthropic
👉 Read the [Anthropic chat model integration docs](/oss/python/integrations/chat/anthropic)
bash
pip install -U "langchain[anthropic]"python
import os
from langchain.chat_models import init_chat_model
os.environ["ANTHROPIC_API_KEY"] = "sk-..."
model = init_chat_model("claude-sonnet-4-6")python
import os
from langchain_anthropic import ChatAnthropic
os.environ["ANTHROPIC_API_KEY"] = "sk-..."
model = ChatAnthropic(model="claude-sonnet-4-6")Azure
👉 Read the [Azure chat model integration docs](/oss/python/integrations/chat/azure_chat_openai)
bash
pip install -U "langchain[openai]"python
import os
from langchain.chat_models import init_chat_model
os.environ["AZURE_OPENAI_API_KEY"] = "..."
os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"
model = init_chat_model(
"azure_openai:gpt-5.5",
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
)python
import os
from langchain_openai import AzureChatOpenAI
os.environ["AZURE_OPENAI_API_KEY"] = "..."
os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"
model = AzureChatOpenAI(
model="gpt-5.5",
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"]
)Google Gemini
👉 Read the [Google GenAI chat model integration docs](/oss/python/integrations/chat/google_generative_ai)
bash
pip install -U "langchain[google-genai]"python
import os
from langchain.chat_models import init_chat_model
os.environ["GOOGLE_API_KEY"] = "..."
model = init_chat_model("google_genai:gemini-2.5-flash-lite")python
import os
from langchain_google_genai import ChatGoogleGenerativeAI
os.environ["GOOGLE_API_KEY"] = "..."
model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite")AWS Bedrock
👉 Read the [AWS Bedrock chat model integration docs](/oss/python/integrations/chat/bedrock)
bash
pip install -U "langchain[aws]"python
from langchain.chat_models import init_chat_model
# 按照以下步骤配置你的凭证:
# https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
model = init_chat_model(
"us.anthropic.claude-sonnet-4-6",
model_provider="bedrock_converse",
)python
from langchain_aws import ChatBedrock
model = ChatBedrock(model="us.anthropic.claude-sonnet-4-6")HuggingFace
👉 Read the [HuggingFace chat model integration docs](/oss/python/integrations/chat/huggingface)
bash
pip install -U "langchain[huggingface]"python
import os
from langchain.chat_models import init_chat_model
os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..."
model = init_chat_model(
"microsoft/Phi-3-mini-4k-instruct",
model_provider="huggingface",
temperature=0.7,
max_tokens=1024,
)python
import os
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..."
llm = HuggingFaceEndpoint(
repo_id="microsoft/Phi-3-mini-4k-instruct",
temperature=0.7,
max_length=1024,
)
model = ChatHuggingFace(llm=llm)OpenRouter
👉 Read the [OpenRouter chat model integration docs](/oss/python/integrations/chat/openrouter)
bash
pip install -U "langchain-openrouter"python
import os
from langchain.chat_models import init_chat_model
os.environ["OPENROUTER_API_KEY"] = "sk-..."
model = init_chat_model(
"auto",
model_provider="openrouter",
)python
import os
from langchain_openrouter import ChatOpenRouter
os.environ["OPENROUTER_API_KEY"] = "sk-..."
model = ChatOpenRouter(model="auto")选择一个支持工具调用的模型:
OpenAI
👉 Read the [OpenAI chat model integration docs](/oss/javascript/integrations/chat/openai)
bash
npm install @langchain/openaibash
pnpm install @langchain/openaibash
yarn add @langchain/openaibash
bun add @langchain/openaitypescript
import { initChatModel } from "langchain";
process.env.OPENAI_API_KEY = "your-api-key";
const model = await initChatModel("gpt-5.5");typescript
import { ChatOpenAI } from "@langchain/openai";
const model = new ChatOpenAI({
model: "gpt-5.5",
apiKey: "your-api-key"
});Anthropic
👉 Read the [Anthropic chat model integration docs](/oss/javascript/integrations/chat/anthropic)
bash
npm install @langchain/anthropicbash
pnpm install @langchain/anthropicbash
yarn add @langchain/anthropicbash
pnpm add @langchain/anthropictypescript
import { initChatModel } from "langchain";
process.env.ANTHROPIC_API_KEY = "your-api-key";
const model = await initChatModel("claude-sonnet-4-6");typescript
import { ChatAnthropic } from "@langchain/anthropic";
const model = new ChatAnthropic({
model: "claude-sonnet-4-6",
apiKey: "your-api-key"
});Azure
👉 Read the [Azure chat model integration docs](/oss/javascript/integrations/chat/azure)
bash
npm install @langchain/azurebash
pnpm install @langchain/azurebash
yarn add @langchain/azurebash
bun add @langchain/azuretypescript
import { initChatModel } from "langchain";
process.env.AZURE_OPENAI_API_KEY = "your-api-key";
process.env.AZURE_OPENAI_ENDPOINT = "your-endpoint";
process.env.OPENAI_API_VERSION = "your-api-version";
const model = await initChatModel("azure_openai:gpt-5.5");typescript
import { AzureChatOpenAI } from "@langchain/openai";
const model = new AzureChatOpenAI({
model: "gpt-5.5",
azureOpenAIApiKey: "your-api-key",
azureOpenAIApiEndpoint: "your-endpoint",
azureOpenAIApiVersion: "your-api-version"
});Google Gemini
👉 Read the [Google GenAI chat model integration docs](/oss/javascript/integrations/chat/google_generative_ai)
bash
npm install @langchain/google-genaibash
pnpm install @langchain/google-genaibash
yarn add @langchain/google-genaibash
bun add @langchain/google-genaitypescript
import { initChatModel } from "langchain";
process.env.GOOGLE_API_KEY = "your-api-key";
const model = await initChatModel("google-genai:gemini-2.5-flash-lite");typescript
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
const model = new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash-lite",
apiKey: "your-api-key"
});Bedrock Converse
👉 Read the [AWS Bedrock chat model integration docs](/oss/javascript/integrations/chat/bedrock_converse)
bash
npm install @langchain/awsbash
pnpm install @langchain/awsbash
yarn add @langchain/awsbash
bun add @langchain/awstypescript
import { initChatModel } from "langchain";
// 按照以下步骤配置你的凭证:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const model = await initChatModel("bedrock:gpt-5.5");typescript
import { ChatBedrockConverse } from "@langchain/aws";
// 按照以下步骤配置你的凭证:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const model = new ChatBedrockConverse({
model: "gpt-5.5",
region: "us-east-2"
});下面示例中展示的输出使用了 OpenAI。
配置数据库
在本教程中,你将创建一个 SQLite 数据库。SQLite 是一个轻量级数据库,易于安装和使用。我们将加载 chinook 数据库,这是一个代表数字媒体商店的示例数据库。
为方便起见,我们将数据库(Chinook.db)托管在一个公共 GCS 存储桶中。
python
import pathlib
import requests
url = "https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db"
local_path = pathlib.Path("Chinook.db")
if local_path.exists():
print(f"{local_path} already exists, skipping download.")
else:
response = requests.get(url, timeout=60)
if response.status_code == 200:
local_path.write_bytes(response.content)
print(f"File downloaded and saved as {local_path}")
else:
print(f"Failed to download the file. Status code: {response.status_code}")ts
import fs from "node:fs/promises";
import path from "node:path";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}我们将使用 Python 内置的 sqlite3 模块与数据库交互:
python
import sqlite3
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() if not row[0].startswith("sqlite_")]
print("Dialect: sqlite")
print(f"Available tables: {tables}")
cursor.execute("SELECT * FROM Artist LIMIT 5;")
print(f"Sample output: {cursor.fetchall()}")
con.close()Dialect: sqlite
Available tables: ['Album', 'Artist', 'Customer', 'Employee', 'Genre', 'Invoice', 'InvoiceLine', 'MediaType', 'Playlist', 'PlaylistTrack', 'Track']
Sample output: [(1, 'AC/DC'), (2, 'Accept'), (3, 'Aerosmith'), (4, 'Alanis Morissette'), (5, 'Alice In Chains')]添加数据库交互工具
WARNING
以下数据库工具仅为演示目的而设的最小包装器。它们并非为了安全或生产环境使用而设计。在执行模型生成的 SQL 之前,请使用窄范围限定的数据库权限,并添加应用特定的验证。
我们可以使用 langchain.tools 中的 @tool 装饰器将数据库工具实现为轻量包装器:
python
import sqlite3
from langchain.tools import tool
# 以下是为演示目的提供的最小工具集。
# 它们并非为安全或生产环境使用而设计。
@tool
def sql_db_list_tables() -> str:
"""Input is an empty string, output is a comma-separated list of tables in the database."""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")]
return ", ".join(tables)
finally:
con.close()
@tool
def sql_db_schema(table_names: str) -> str:
"""Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Be sure that the tables actually exist by calling sql_db_list_tables first!
Example Input: table1, table2, table3"""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
valid_tables = {row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")}
results = []
for table in table_names.split(","):
table = table.strip()
if table not in valid_tables:
results.append(f"Error: table_names {{{table!r}}} not found in database")
continue
cursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?;", (table,))
schema_row = cursor.fetchone()
if schema_row:
results.append(schema_row[0])
try:
quoted_table = '"' + table.replace('"', '""') + '"'
cursor.execute(f"SELECT * FROM {quoted_table} LIMIT 3;")
rows = cursor.fetchall()
if rows:
col_names = [description[0] for description in cursor.description]
results.append(
f"/*\n3 rows from {table} table:\n"
+ "\t".join(col_names)
+ "\n"
+ "\n".join("\t".join(str(x) for x in row) for row in rows)
+ "\n*/"
)
except Exception as e:
results.append(f"Error fetching sample rows: {e}")
return "\n\n".join(results)
finally:
con.close()
@tool
def sql_db_query(query: str) -> str:
"""Input to this tool is a detailed and correct SQL query, output is a result from the database.
If the query is not correct, an error message will be returned.
If an error is returned, rewrite the query, check the query, and try again.
If you encounter an issue with Unknown column 'xxxx' in 'field list', use sql_db_schema to query the correct table fields."""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute(query)
res = cursor.fetchall()
return str(res)
except Exception as e:
return f"Error: {e}"
finally:
con.close()
@tool
def sql_db_query_checker(query: str) -> str:
"""Use this tool to double check if your query is correct before executing it.
Always use this tool before executing a query with sql_db_query!"""
trigger_prompt = """{query}
Double check the sqlite query above for common mistakes, including:
- Using NOT IN with NULL values
- Using UNION when UNION ALL should have been used
- Using BETWEEN for exclusive ranges
- Data type mismatch in predicates
- Properly quoting identifiers
- Using the correct number of arguments for functions
- Casting to the correct data type
- Using the proper columns for joins
If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.
Output the final SQL query only.
SQL Query: """.format(query=query)
response = model.invoke(trigger_prompt)
return response.text.strip()
tools = [sql_db_list_tables, sql_db_schema, sql_db_query, sql_db_query_checker]
# 使用独立的循环变量,避免遮蔽 `tool` 装饰器
for t in tools:
print(f"{t.name}: {t.description}\n")sql_db_query: Input to this tool is a detailed and correct SQL query, output is a result from the database.
If the query is not correct, an error message will be returned.
If an error is returned, rewrite the query, check the query, and try again.
If you encounter an issue with Unknown column 'xxxx' in 'field list', use sql_db_schema to query the correct table fields.
sql_db_schema: Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Be sure that the tables actually exist by calling sql_db_list_tables first!
Example Input: table1, table2, table3
sql_db_list_tables: Input is an empty string, output is a comma-separated list of tables in the database.
sql_db_query_checker: Use this tool to double check if your query is correct before executing it.
Always use this tool before executing a query with sql_db_query!我们将使用 sqlite3 库来查询数据库并获取模式(schema):
ts
import sqlite3 from "sqlite3";
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<any[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => row.sql).join("\n\n");
}创建智能体
使用 create_agent 以最少的代码构建 ReAct 智能体。该智能体会解释请求并生成 SQL 命令,由工具执行。如果命令出错,错误消息会返回给模型。然后模型可以检查原始请求和新的错误消息,并生成新命令。此过程会一直持续,直到 LLM 成功生成命令或达到结束计数。这种为模型提供反馈(在本例中为错误消息)的模式非常强大。
使用描述性的系统提示词初始化智能体,以自定义其行为:
python
system_prompt = """
You are an agent designed to interact with a SQL database.
Given an input question, create a syntactically correct {dialect} query to run,
then look at the results of the query and return the answer. Unless the user
specifies a specific number of examples they wish to obtain, always limit your
query to at most {top_k} results.
You can order the results by a relevant column to return the most interesting
examples in the database. Never query for all the columns from a specific table,
only ask for the relevant columns given the question.
You MUST double check your query before executing it. If you get an error while
executing a query, rewrite the query and try again.
DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the
database.
To start you should ALWAYS look at the tables in the database to see what you
can query. Do NOT skip this step.
Then you should query the schema of the most relevant tables.
""".format(
dialect="sqlite",
top_k=5,
)现在,使用模型、工具和提示词创建智能体:
python
from langchain.agents import create_agent
agent = create_agent(
model,
tools,
system_prompt=system_prompt,
)在执行命令之前,先在 _safe_sql 中检查 LLM 生成的命令:
ts
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q) {
let query = String(q ?? "").trim();
// 阻止多条语句(允许末尾有一个可选分号)
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
// 只读检查
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
// 仅在尚未包含 LIMIT 时追加
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}然后,使用 execute_sql 工具执行命令:
ts
import { tool } from "langchain";
import * as z from "zod";
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);使用 createAgent 以最少的代码构建 ReAct 智能体。该智能体会解释请求并生成 SQL 命令。工具会先检查命令的安全性,然后尝试执行该命令。如果命令出错,错误消息会返回给模型。然后模型可以检查原始请求和新的错误消息,并生成新命令。此过程会一直持续,直到 LLM 成功生成命令或达到结束计数。这种为模型提供反馈(在本例中为错误消息)的模式非常强大。
使用描述性的系统提示词初始化智能体,以自定义其行为:
ts
import { SystemMessage } from "langchain";
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);现在,使用模型、工具和提示词创建智能体:
ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "openai:gpt-5.5",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import { createAgent } from "langchain";
let agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});运行智能体
在示例查询上运行智能体并观察其行为:
python
question = "Which genre on average has the longest tracks?"
stream = agent.stream_events(
{"messages": [{"role": "user", "content": question}]},
version="v3",
)
for kind, item in stream.interleave("messages", "tool_calls"):
if kind == "messages":
for token in item.text:
print(token, end="", flush=True)
elif kind == "tool_calls":
print(f"\nTool call: {item.tool_name}({item.input})")
for delta in item.output_deltas:
print(delta, end="", flush=True)
print(f"\nTool result: {item.output}")
final_state = stream.output================================ Human Message =================================
Which genre on average has the longest tracks?
================================== Ai Message ==================================
Tool Calls:
sql_db_list_tables (call_BQsWg8P65apHc8BTJ1NPDvnM)
Call ID: call_BQsWg8P65apHc8BTJ1NPDvnM
Args:
================================= Tool Message =================================
Name: sql_db_list_tables
Album, Artist, Customer, Employee, Genre, Invoice, InvoiceLine, MediaType, Playlist, PlaylistTrack, Track
================================== Ai Message ==================================
Tool Calls:
sql_db_schema (call_i89tjKECFSeERbuACYm4w0cU)
Call ID: call_i89tjKECFSeERbuACYm4w0cU
Args:
table_names: Track, Genre
================================= Tool Message =================================
Name: sql_db_schema
CREATE TABLE "Genre" (
"GenreId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("GenreId")
)
/*
3 rows from Genre table:
GenreId Name
1 Rock
2 Jazz
3 Metal
*/
CREATE TABLE "Track" (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
"AlbumId" INTEGER,
"MediaTypeId" INTEGER NOT NULL,
"GenreId" INTEGER,
"Composer" NVARCHAR(220),
"Milliseconds" INTEGER NOT NULL,
"Bytes" INTEGER,
"UnitPrice" NUMERIC(10, 2) NOT NULL,
PRIMARY KEY ("TrackId"),
FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"),
FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"),
FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId")
)
/*
3 rows from Track table:
TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice
1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99
2 Balls to the Wall 2 2 1 U. Dirkschneider, W. Hoffmann, H. Frank, P. Baltes, S. Kaufmann, G. Hoffmann 342562 5510424 0.99
3 Fast As a Shark 3 2 1 F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman 230619 3990994 0.99
*/
================================== Ai Message ==================================
Tool Calls:
sql_db_query_checker (call_G64yYm6R6UauiVPCXJZMA49b)
Call ID: call_G64yYm6R6UauiVPCXJZMA49b
Args:
query: SELECT Genre.Name, AVG(Track.Milliseconds) AS AverageLength FROM Track INNER JOIN Genre ON Track.GenreId = Genre.GenreId GROUP BY Genre.Name ORDER BY AverageLength DESC LIMIT 5;
================================= Tool Message =================================
Name: sql_db_query_checker
SELECT Genre.Name, AVG(Track.Milliseconds) AS AverageLength FROM Track INNER JOIN Genre ON Track.GenreId = Genre.GenreId GROUP BY Genre.Name ORDER BY AverageLength DESC LIMIT 5;
================================== Ai Message ==================================
Tool Calls:
sql_db_query (call_AnO3SrhD0ODJBxh6dHMwvHwZ)
Call ID: call_AnO3SrhD0ODJBxh6dHMwvHwZ
Args:
query: SELECT Genre.Name, AVG(Track.Milliseconds) AS AverageLength FROM Track INNER JOIN Genre ON Track.GenreId = Genre.GenreId GROUP BY Genre.Name ORDER BY AverageLength DESC LIMIT 5;
================================= Tool Message =================================
Name: sql_db_query
[('Sci Fi & Fantasy', 2911783.0384615385), ('Science Fiction', 2625549.076923077), ('Drama', 2575283.78125), ('TV Shows', 2145041.0215053763), ('Comedy', 1585263.705882353)]
================================== Ai Message ==================================
On average, the genre with the longest tracks is "Sci Fi & Fantasy" with an average track length of approximately 2,911,783 milliseconds. This is followed by "Science Fiction," "Drama," "TV Shows," and "Comedy."该智能体正确地编写了查询、检查了查询,并执行查询以得出最终回答。
INFO
你可以在 LangSmith 追踪 中查看上述运行的所有细节,包括所执行的步骤、调用的工具、LLM 看到的提示词等。
在示例查询上运行智能体并观察其行为:
ts
let question = "Which genre, on average, has the longest tracks?";
const stream = await agent.streamEvents(
{ messages: [{ role: "user", content: question }] },
{ version: "v3" },
);
await Promise.all([
(async () => {
for await (const message of stream.messages) {
for await (const token of message.text) {
process.stdout.write(token);
}
}
})(),
(async () => {
for await (const call of stream.toolCalls) {
console.log(`\nTool call: ${call.name}(${JSON.stringify(call.input)})`);
console.log(`Tool result: ${await call.output}`);
}
})(),
]);
const finalState = await stream.output;human: Which genre, on average, has the longest tracks?
ai:
tool: [{"Genre":"Sci Fi & Fantasy","AvgMilliseconds":2911783.0384615385}]
ai: Sci Fi & Fantasy — average track length ≈ 48.5 minutes (about 2,911,783 ms).该智能体正确地编写了查询、检查了查询,并执行查询以得出最终回答。
INFO
你可以在 LangSmith 追踪 中查看上述运行的所有细节,包括所执行的步骤、调用的工具、LLM 看到的提示词等。
(可选)使用 Studio
Studio 提供了"客户端"循环以及记忆功能,因此你可以将其作为聊天界面运行并查询数据库。你可以提出诸如"Tell me the scheme of the database"或"Show me the invoices for the 5 top customers"之类的问题。你将看到生成的 SQL 命令以及相应的输出。有关如何启动的详细信息如下。
在 Studio 中运行你的智能体
除了之前提到的软件包之外,你还需要:
bash
pip install -U langgraph-cli[inmem]>=0.4.0在你将要运行的目录中,你需要一个包含以下内容的 langgraph.json 文件:
json
{
"dependencies": ["."],
"graphs": {
"agent": "./sql_agent.py:agent",
"graph": "./sql_agent_langgraph.py:graph"
},
"env": ".env"
}创建一个 sql_agent.py 文件并插入以下内容:
python
# 供 Studio 使用的 sql_agent.py
import pathlib
import sqlite3
import requests
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
# 初始化 LLM
model = init_chat_model("gpt-5.5")
# 获取数据库并将其保存在本地
url = "https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db"
local_path = pathlib.Path("Chinook.db")
if local_path.exists():
print(f"{local_path} already exists, skipping download.")
else:
response = requests.get(url, timeout=60)
if response.status_code == 200:
local_path.write_bytes(response.content)
print(f"File downloaded and saved as {local_path}")
else:
print(f"Failed to download the file. Status code: {response.status_code}")
# 以下是为演示目的提供的最小工具集。
@tool
def sql_db_list_tables() -> str:
"""Input is an empty string, output is a comma-separated list of tables in the database."""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")]
return ", ".join(tables)
finally:
con.close()
@tool
def sql_db_schema(table_names: str) -> str:
"""Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Be sure that the tables actually exist by calling sql_db_list_tables first!
Example Input: table1, table2, table3"""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
valid_tables = {row[0] for row in cursor.fetchall() if not row[0].startswith("sqlite_")}
results = []
for table in table_names.split(","):
table = table.strip()
if table not in valid_tables:
results.append(f"Error: table_names {{{table!r}}} not found in database")
continue
cursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?;", (table,))
schema_row = cursor.fetchone()
if schema_row:
results.append(schema_row[0])
try:
quoted_table = '"' + table.replace('"', '""') + '"'
cursor.execute(f"SELECT * FROM {quoted_table} LIMIT 3;")
rows = cursor.fetchall()
if rows:
col_names = [description[0] for description in cursor.description]
results.append(
f"/*\n3 rows from {table} table:\n"
+ "\t".join(col_names)
+ "\n"
+ "\n".join("\t".join(str(x) for x in row) for row in rows)
+ "\n*/"
)
except Exception as e:
results.append(f"Error fetching sample rows: {e}")
return "\n\n".join(results)
finally:
con.close()
@tool
def sql_db_query(query: str) -> str:
"""Input to this tool is a detailed and correct SQL query, output is a result from the database.
If the query is not correct, an error message will be returned.
If an error is returned, rewrite the query, check the query, and try again.
If you encounter an issue with Unknown column 'xxxx' in 'field list', use sql_db_schema to query the correct table fields."""
con = sqlite3.connect("Chinook.db")
try:
cursor = con.cursor()
cursor.execute(query)
res = cursor.fetchall()
return str(res)
except Exception as e:
return f"Error: {e}"
finally:
con.close()
@tool
def sql_db_query_checker(query: str) -> str:
"""Use this tool to double check if your query is correct before executing it.
Always use this tool before executing a query with sql_db_query!"""
trigger_prompt = """{query}
Double check the sqlite query above for common mistakes, including:
- Using NOT IN with NULL values
- Using UNION when UNION ALL should have been used
- Using BETWEEN for exclusive ranges
- Data type mismatch in predicates
- Properly quoting identifiers
- Using the correct number of arguments for functions
- Casting to the correct data type
- Using the proper columns for joins
If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.
Output the final SQL query only.
SQL Query: """.format(query=query)
response = model.invoke(trigger_prompt)
return response.text.strip()
tools = [sql_db_list_tables, sql_db_schema, sql_db_query, sql_db_query_checker]
# 使用独立的循环变量,避免遮蔽 `tool` 装饰器
for t in tools:
print(f"{t.name}: {t.description}\n")
# 使用 create_agent
system_prompt = """
You are an agent designed to interact with a SQL database.
Given an input question, create a syntactically correct {dialect} query to run,
then look at the results of the query and return the answer. Unless the user
specifies a specific number of examples they wish to obtain, always limit your
query to at most {top_k} results.
You can order the results by a relevant column to return the most interesting
examples in the database. Never query for all the columns from a specific table,
only ask for the relevant columns given the question.
You MUST double check your query before executing it. If you get an error while
executing a query, rewrite the query and try again.
DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the
database.
To start you should ALWAYS look at the tables in the database to see what you
can query. Do NOT skip this step.
Then you should query the schema of the most relevant tables.
""".format(
dialect="sqlite",
top_k=5,
)
agent = create_agent(
model,
tools,
system_prompt=system_prompt,
)Studio 提供了"客户端"循环以及记忆功能,因此你可以将其作为聊天界面运行并查询数据库。你可以提出诸如"Tell me the scheme of the database"或"Show me the invoices for the 5 top customers"之类的问题。你将看到生成的 SQL 命令以及相应的输出。有关如何启动的详细信息如下。
在 Studio 中运行你的智能体
除了之前提到的软件包之外,你还需要:
bash
npm i -g @langchain/langgraph-cli@latest在你将要运行的目录中,你需要一个包含以下内容的 langgraph.json 文件:
json
{
"dependencies": ["."],
"graphs": {
"agent": "./sqlAgent.ts:agent",
"graph": "./sqlAgentLanggraph.ts:graph"
},
"env": ".env"
}创建一个 sqlAgent.ts 文件并插入以下内容:
ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "openai:gpt-5.5",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});ts
import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { SystemMessage, createAgent, tool } from "langchain";
import * as z from "zod";
const url =
"https://storage.googleapis.com/benchmarks-artifacts/chinook/Chinook.db";
const localPath = path.resolve("Chinook.db");
async function resolveDbPath() {
try {
await fs.access(localPath);
return localPath;
} catch {
// 本地不存在 Chinook.db;下载它。
}
const resp = await fetch(url);
if (!resp.ok)
throw new Error(`Failed to download DB. Status code: ${resp.status}`);
const buf = Buffer.from(await resp.arrayBuffer());
await fs.writeFile(localPath, buf);
return localPath;
}
// 以下是为演示目的提供的最小工具集。
async function runQuery(query: string): Promise<Record<string, unknown>[]> {
const dbPath = await resolveDbPath();
const db = new sqlite3.Database(dbPath);
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
db.close();
if (err) reject(err);
else resolve(rows as Record<string, unknown>[]);
});
});
}
async function getSchema() {
const tables = await runQuery(
"SELECT sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';",
);
return tables.map((row) => String(row.sql)).join("\n\n");
}
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q: string) {
let query = String(q ?? "").trim();
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
const executeSql = tool(
async ({ query }) => {
const q = sanitizeSqlQuery(query);
try {
const result = await runQuery(q);
return JSON.stringify(result, null, 2);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
throw new Error(message);
}
},
{
name: "execute_sql",
description: "Execute a READ-ONLY SQLite SELECT query and return results.",
schema: z.object({
query: z.string().describe("SQLite SELECT query to execute (read-only)."),
}),
},
);
const getSystemPrompt = async () =>
new SystemMessage(`You are a careful SQLite analyst.
Authoritative schema (do not invent columns/tables):
${await getSchema()}
Rules:
- Think step-by-step.
- When you need data, call the tool \`execute_sql\` with ONE SELECT query.
- Read-only; no INSERT/UPDATE/DELETE/ALTER/DROP/CREATE/REPLACE/TRUNCATE.
- Limit to 5 rows unless user explicitly asks otherwise.
- If the tool returns 'Error:', revise the SQL and try again.
- Limit the number of attempts to 5.
- If you are not successful after 5 attempts, return a note to the user.
- Prefer explicit column lists; avoid SELECT *.
`);
export const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
});实现人在回路审查
在执行智能体的 SQL 查询之前,检查其是否存在任何意外操作或低效之处是明智的做法。
LangChain 智能体内置了对人在回路中间件的支持,可为智能体工具调用增加监督。让我们将智能体配置为在调用 sql_db_query 工具时暂停以等待人工审查:
python
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model,
tools,
system_prompt=system_prompt,
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={"sql_db_query": True},
description_prefix="Tool execution pending approval",
),
],
checkpointer=InMemorySaver(),
)运行智能体时,它现在会在执行 sql_db_query 工具之前暂停以等待审查:
python
question = "Which genre on average has the longest tracks?"
config = {"configurable": {"thread_id": "1"}}
stream = agent.stream_events(
{"messages": [{"role": "user", "content": question}]},
config,
version="v3",
)
for kind, item in stream.interleave("messages", "tool_calls"):
if kind == "messages":
for token in item.text:
print(token, end="", flush=True)
elif kind == "tool_calls":
print(f"\nTool call: {item.tool_name}({item.input})")
if stream.interrupted:
print("INTERRUPTED:")
interrupt = stream.interrupts[0]
for request in interrupt.value["action_requests"]:
print(request["description"]) ...
INTERRUPTED:
Tool execution pending approval
Tool: sql_db_query
Args: {'query': 'SELECT g.Name AS Genre, AVG(t.Milliseconds) AS AvgTrackLength FROM Track t JOIN Genre g ON t.GenreId = g.GenreId GROUP BY g.Name ORDER BY AvgTrackLength DESC LIMIT 1;'}我们可以使用 Command 恢复执行,在本例中即接受该查询:
python
from langgraph.types import Command
stream = agent.stream_events(
Command(resume={"decisions": [{"type": "approve"}]}),
config,
version="v3",
)
for kind, item in stream.interleave("messages", "tool_calls"):
if kind == "messages":
for token in item.text:
print(token, end="", flush=True)
elif kind == "tool_calls":
print(f"\nTool call: {item.tool_name}({item.input})")
if stream.interrupted:
print("INTERRUPTED:")
interrupt = stream.interrupts[0]
for request in interrupt.value["action_requests"]:
print(request["description"])================================== Ai Message ==================================
Tool Calls:
sql_db_query (call_7oz86Epg7lYRqi9rQHbZPS1U)
Call ID: call_7oz86Epg7lYRqi9rQHbZPS1U
Args:
query: SELECT Genre.Name, AVG(Track.Milliseconds) AS AvgDuration FROM Track JOIN Genre ON Track.GenreId = Genre.GenreId GROUP BY Genre.Name ORDER BY AvgDuration DESC LIMIT 5;
================================= Tool Message =================================
Name: sql_db_query
[('Sci Fi & Fantasy', 2911783.0384615385), ('Science Fiction', 2625549.076923077), ('Drama', 2575283.78125), ('TV Shows', 2145041.0215053763), ('Comedy', 1585263.705882353)]
================================== Ai Message ==================================
The genre with the longest average track length is "Sci Fi & Fantasy" with an average duration of about 2,911,783 milliseconds, followed by "Science Fiction" and "Drama."有关详细信息,请参阅人在回路指南。
在执行智能体的 SQL 查询之前,检查其是否存在任何意外操作或低效之处是明智的做法。
LangChain 智能体内置了对人在回路中间件的支持,可为智能体工具调用增加监督。让我们将智能体配置为在调用 execute_sql 工具时暂停以等待人工审查:
ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "openai:gpt-5.5",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});ts
import { humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [executeSql],
systemPrompt: await getSystemPrompt(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: {
execute_sql: true,
},
descriptionPrefix: "Tool execution pending approval",
}),
],
checkpointer: new MemorySaver(),
});运行智能体时,它现在会在执行 execute_sql 工具之前暂停以等待审查:
ts
question = "Which genre, on average, has the longest tracks?";
const config = { configurable: { thread_id: "1" } };
const hitlStream = await agent.streamEvents(
{ messages: [{ role: "user", content: question }] },
{ ...config, version: "v3" },
);
await Promise.all([
(async () => {
for await (const message of hitlStream.messages) {
for await (const token of message.text) {
process.stdout.write(token);
}
}
})(),
(async () => {
for await (const call of hitlStream.toolCalls) {
console.log(`\nTool call: ${call.name}(${JSON.stringify(call.input)})`);
}
})(),
]);
if (hitlStream.interrupted) {
console.log("INTERRUPTED:");
for (const interrupt of hitlStream.interrupts) {
for (const request of interrupt.payload.actionRequests) {
console.log(request.description);
}
}
}...
INTERRUPTED:
Tool execution pending approval
Tool: execute_sql
Args: {'query': 'SELECT g.Name AS Genre, AVG(t.Milliseconds) AS AvgTrackLength FROM Track t JOIN Genre g ON t.GenreId = g.GenreId GROUP BY g.Name ORDER BY AvgTrackLength DESC LIMIT 1;'}我们可以使用 Command 恢复执行,在本例中即接受该查询:
ts
import { Command } from "@langchain/langgraph";
const resumeStream = await agent.streamEvents(
new Command({ resume: { decisions: [{ type: "approve" }] } }),
{ ...config, version: "v3" },
);
await Promise.all([
(async () => {
for await (const message of resumeStream.messages) {
for await (const token of message.text) {
process.stdout.write(token);
}
}
})(),
(async () => {
for await (const call of resumeStream.toolCalls) {
console.log(`\nTool call: ${call.name}(${JSON.stringify(call.input)})`);
}
})(),
]);
if (resumeStream.interrupted) {
console.log("INTERRUPTED:");
for (const interrupt of resumeStream.interrupts) {
for (const request of interrupt.payload.actionRequests) {
console.log(request.description);
}
}
}================================== Ai Message ==================================
Tool Calls:
execute_sql (call_7oz86Epg7lYRqi9rQHbZPS1U)
Call ID: call_7oz86Epg7lYRqi9rQHbZPS1U
Args:
query: SELECT Genre.Name, AVG(Track.Milliseconds) AS AvgDuration FROM Track JOIN Genre ON Track.GenreId = Genre.GenreId GROUP BY Genre.Name ORDER BY AvgDuration DESC LIMIT 5;
================================= Tool Message =================================
Name: execute_sql
[('Sci Fi & Fantasy', 2911783.0384615385), ('Science Fiction', 2625549.076923077), ('Drama', 2575283.78125), ('TV Shows', 2145041.0215053763), ('Comedy', 1585263.705882353)]
================================== Ai Message ==================================
The genre with the longest average track length is "Sci Fi & Fantasy" with an average duration of about 2,911,783 milliseconds, followed by "Science Fiction" and "Drama."有关详细信息,请参阅人在回路指南。
后续步骤
如需更深入的定制,请查看本教程,了解如何使用 LangGraph 原语直接实现 SQL 智能体。