LangChain 如何安全使用 SQL 结构化数据?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
旧项目可能见到 SQLDatabaseChain 或 SQL Agent。生产优先提供用途明确的只读查询或经过审核的模板,用参数绑定传入数据。应用应约束账号权限、可见字段、结果上限和超时。
讲清原理
模型可以帮助识别用户要查哪个指标以及传哪些条件。应用必须验证参数和身份后再调用固定查询。不要把开放式写入权限交给模型。
例子与易错点
示例在临时 SQLite 库开启只读查询,用会话中已核对的部门标识统计订单数。执行的 SQL 固定,只有绑定参数会变。
import sqlite3
def get_order_count(connection, department_from_session):
row = connection.execute(
"SELECT COUNT(*) FROM orders WHERE department = ?",
(department_from_session,),
).fetchone()
return row[0]
with sqlite3.connect(":memory:") as db:
db.execute("CREATE TABLE orders (department TEXT NOT NULL)")
db.executemany("INSERT INTO orders VALUES (?)", [("north",), ("south",), ("north",)])
db.commit()
db.execute("PRAGMA query_only = ON")
authorized_count = get_order_count(db, "north")
assert authorized_count == 2
assert get_order_count(db, "west") == 0
print(f"north: {authorized_count}")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。