- 示例工程
- 人工智能
【免费下载链接】500-AI-Agents-Projects
The 500 AI Agents Projects is a curated collection of AI agent use cases across various industries. It showcases practical applications and provides links to open-source projects for implementation, illustrating how AI agents are transforming sectors such as healthcare, finance, education, retail, and more.
本指南以 500-AI-Agents-Projects 仓库中的 SQL Query Agent 为对象,完整讲解其从环境配置、数据库接入、命令行使用到源码原理的全过程。读完本文,你将掌握如何基于 LangChain 的SQLDatabaseToolkit与 ReAct Agent 搭建一个"自然语言 → SQL → 执行 → 自然语言回答"的查询链路,并学会安全地以只读方式对接任意 SQLite 数据库。
一、Agent 概览:它能做什么
SQL Query Agent 的核心能力是:连接任意 SQLite 数据库,通过自然语言提问,自动生成并执行 SQL,最终返回人类可读的答案。它属于 agents/ 目录 中 21 个可独立运行 Agent 的第 04 号实现,定位于数据分析(Data Analytics)行业场景。
从 metadata.yaml 可以看到该 Agent 的官方画像:
- 框架(framework):
langchain - 语言(language):
python - LLM:
gpt-4o-mini - 难度(difficulty):intermediate(中级)
- 标签(tags):
sql、database、natural-language、data-analysis - 入口(entrypoint):
agent.py
该 Agent 不依赖任何 monorepo 结构,目录自包含,可直接进入 agents/04-sql-query-agent/ 运行,是典型的"零成本上手"的数据问答工具。
二、环境准备与配置
2.1 安装依赖
Agent 的 Python 依赖集中在 requirements.txt 中,共 4 个包:
| 包 | 版本 |
|---|---|
| langchain | 0.3.0 |
| langchain-openai | 0.2.0 |
| langchain-community | 0.3.0 |
| python-dotenv | 1.0.1 |
langchain-community提供了SQLDatabase工具类与SQLDatabaseToolkit,langchain-openai提供ChatOpenAI模型封装,python-dotenv负责从.env文件加载环境变量。
安装命令(文档原命令):
pip install -r requirements.txt2.2 配置 API Key
Agent 通过load_dotenv()(见 agent.py)加载环境变量。仓库中已提供环境变量模板 agents/04-sql-query-agent/.env.example,内容为:
OPENAI_API_KEY=your_openai_api_key_here执行文档规定的复制命令,然后把your_openai_api_key_here替换为真实的 OpenAI API Key:
cp .env.example .env注意:
.env是本地私有文件,通常不应提交到版本库;OPENAI_API_KEY是 Agent 调用 GPT-4o-mini 的唯一凭证,缺失时ChatOpenAI初始化会失败。
三、运行方式:三种模式详解
文档给出的运行命令全部收敛在 agent.py 的argparse参数解析逻辑中,共支持三个命令行参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
--db | str | demo.sqlite | SQLite 数据库文件路径 |
--question | str | 无 | 单次提问;省略则进入交互式问答模式 |
--allow-write | flag | 关闭 | 以可写模式打开数据库(默认只读) |
3.1 Demo 模式:自动创建示例电商库
python agent.py当--db未指定且当前目录不存在demo.sqlite时,agent.py 会调用create_demo_database()自动生成一个演示用电商数据库,包含三张表:
- customers(客户):
id、name、email、country、created_at,内置 Alice Johnson、Bob Smith、Carlos Lima、Diana Prince 四位客户; - products(商品):
id、name、category、price、stock,内置 Laptop Pro(1299.99)、Wireless Mouse(29.99)、Python Book(49.99)、Standing Desk(599.99); - orders(订单):
id、customer_id(外键→customers)、product_id(外键→products)、quantity、total、order_date,内置 6 条跨 2024-04 月的订单记录。
表结构定义与种子数据均可直接在 agent.py 中查看,非常适合在无真实数据库时验证 Agent 能力。
3.2 连接自有数据库
python agent.py --db path/to/your/database.sqlite传入任意 SQLite 文件路径即可。运行后终端会依次打印:
📊 Connected to: <db路径>— 已连接数据库;🔒 Mode: read-only / read-write— 当前打开模式;📋 Tables: ...— 通过db.get_table_names()自动探测到的全部表名。
3.3 单次提问与非交互调用
python agent.py --question "What is the total revenue by country?"--question允许一次性传入自然语言问题,Agent 执行后直接打印✅ Answer: ...并退出(见 agent.py)。省略--question则进入交互式对话循环(agent.py),输入quit、exit或q即可退出,非常适合在终端中连续追问。
四、安全边界:默认只读,慎开写权限
文档明确强调:数据库默认以只读模式打开,只有在使用可丢弃的测试数据库、且确实希望 Agent 生成的 SQL 能够修改数据时,才应使用--allow-write。
该安全机制在源码层面有完整实现。build_agent()通过sqlite_uri()构造连接 URI(agent.py):
- 只读模式:
sqlite:///file:<绝对路径>?mode=ro&uri=true,其中quote()对路径进行 URL 编码,mode=ro&uri=true强制 SQLite 以只读方式打开; - 可写模式:退化为普通形式
sqlite:///<绝对路径>。
read_only的取值由--allow-write决定(agent.py):read_only=not args.allow_write。这意味着未加该参数时,LLM 生成的任何INSERT/UPDATE/DELETE都会因只读模式而失败,从根上杜绝了误写生产数据的风险——这是在生产环境使用该 Agent 时必须保留的默认配置。
五、Agent 架构与源码原理
5.1 一图看懂数据流
文档给出了官方架构图,完整继承如下:
Natural Language → LLM (generates SQL) → SQLite → LLM (formats answer) → Response整个过程分四步:用户自然语言问题 → LLM 生成 SQL → 在 SQLite 上执行 → LLM 将查询结果整理为自然语言回答。这与 agent.py 的build_agent()实现一一对应。
5.2 核心组件拆解
build_agent()用四个对象组装出完整 Agent:
SQLDatabase:通过SQLDatabase.from_uri(sqlite_uri(...))接入数据库,负责表结构探测与 SQL 执行;ChatOpenAI(model="gpt-4o-mini", temperature=0):模型固定为gpt-4o-mini,temperature=0保证 SQL 生成尽量确定、稳定,避免同一问题反复给出不同查询;SQLDatabaseToolkit(db=db, llm=llm):LangChain 提供的 SQL 专用工具包,内部封装了查询表结构、校验 SQL 语法、执行查询、查看表信息等子工具,是 Agent 能"看懂"数据库的关键;create_sql_agent(llm, toolkit, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION):以Zero-shot ReAct(Reason + Act)模式组装 Agent——不给任何示例,仅靠工具描述驱动 LLM 推理:先思考拆解问题、选择工具(生成 SQL → 执行 → 校验),再根据工具结果继续推理直至产出最终答案。verbose=False默认关闭中间推理输出,保持终端界面干净。
从源码结构可以推断,这种 ReAct 循环正是架构图中"LLM (generates SQL)"与"LLM (formats answer)"两个阶段之间反复迭代的执行机制:Agent 会先调用 SQL 相关工具获取 schema 与执行结果,再基于结果组织语言回复。
六、典型提问示例
文档内置了 4 条可直接在 Demo 库上验证的示例问题:
- "How many customers do we have in each country?"(按国家统计客户数)
- "What are the top 3 best-selling products?"(销量最高的 3 款商品)
- "What was the total revenue last month?"(上月总收入)
- "Which customer has spent the most?"(消费最高的客户)
这些查询涉及GROUP BY、ORDER BY ... LIMIT、SUM、MAX等常见 SQL 能力,可作为回归测试集,验证 Agent 在多表关联、聚合统计上的表现。
七、在 500-AI-Agents-Projects 中的定位与扩展
SQL Query Agent 是 agents/ 目录下 21 个实战 Agent 之一,与 08-data-analysis-agent(数据分析)同属数据方向,但与后者偏重 pandas 类分析不同,本 Agent 专攻数据库的自然语言问答,适合直接挂接现有业务库做"Chat with your database"。
如需将其嵌入自己的项目,可以直接复用 agent.py 中sqlite_uri()与build_agent()两个函数(注意保持只读默认值),替换数据库路径即可接入新数据源。仓库同时要求每个 Agent 目录必须包含agent.py、requirements.txt、.env.example、README.md、metadata.yaml五个文件(见 agents/README.md),本 Agent 正是该规范的完整实现示例,可作为新增 Agent 的目录结构范本。
八、小结
SQL Query Agent 用不到 200 行代码,演示了 LangChain 生态中一条完整且安全的"文本转 SQL"链路:SQLDatabase负责连接与执行、SQLDatabaseToolkit提供工具、Zero-shot ReAct Agent 驱动推理、temperature=0保证稳定输出,而默认只读的 URI 设计则是最值得借鉴的生产级安全实践。对照 agent.py 逐行阅读,再配合 Demo 库跑通上述示例问题,你就能快速理解并复刻属于自己的 SQL 问答 Agent。
- 示例工程
- 人工智能
【免费下载链接】500-AI-Agents-Projects
The 500 AI Agents Projects is a curated collection of AI agent use cases across various industries. It showcases practical applications and provides links to open-source projects for implementation, illustrating how AI agents are transforming sectors such as healthcare, finance, education, retail, and more.
相关推荐
NL2SQL Tool 实战:让 CrewAI Agent 用自然语言驱动 SQL 查询与数据库写入
NL2SQL Tool 实战:让 CrewAI Agent 用自然语言驱动 SQL 查询与数据库写入 本篇技术指南围绕 CrewAI 生态中 crewai to
人工智能AI AgentAgent 框架多智能体工作流自动化后端使用 langchaingo SQL Database Chain 通过自然语言查询 SQLite 数据库
使用 langchaingo SQL Database Chain 通过自然语言查询 SQLite 数据库 导读 本文围绕 langchaingo https:
人工智能大模型AI AgentRAG后端基于 ReAct 框架的 Oracle 数据库智能查询 Agent:从自然语言到 SQL 的完整实战
基于 ReAct 框架的 Oracle 数据库智能查询 Agent:从自然语言到 SQL 的完整实战 导读 本文围绕 hello agents https://
教程文档AI Agent人工智能大模型
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考