概述
在本教程中,您将学习如何使用 LangChain 智能体构建可以回答有关 SQL 数据库的问题的智能体。 在高层次上,智能体将:1
从数据库获取可用的表和模式
2
决定哪些表与问题相关
3
获取相关表的模式
4
基于问题和模式中的信息生成查询
5
使用 LLM 仔细检查查询中的常见错误
6
执行查询并返回结果
7
纠正数据库引擎发现的错误,直到查询成功
8
基于结果制定响应
概念
我们将涵盖以下概念:设置
安装
LangSmith
设置 LangSmith 以检查链或智能体内部发生的情况。然后设置以下环境变量:1. 选择 LLM
选择支持工具调用的模型:- OpenAI
- Anthropic
- Azure
- Google Gemini
- AWS Bedrock
2. 配置数据库
您将为本教程创建一个 SQLite 数据库。SQLite 是一个轻量级数据库,易于设置和使用。我们将加载chinook 数据库,这是一个代表数字媒体商店的示例数据库。
为方便起见,我们已将数据库(Chinook.db)托管在公共 GCS 存储桶上。
langchain_community 包中提供的便捷 SQL 数据库包装器与数据库交互。该包装器提供了一个简单的接口来执行 SQL 查询并获取结果:
3. Add tools for database interactions
使用langchain_community 包中提供的 SQLDatabase 包装器与数据库交互。该包装器提供了一个简单的接口来执行 SQL 查询并获取结果:
5. Use create_agent
Use create_agent to build a ReAct agent with minimal code. The agent will interpret the request and generate a SQL command, which the tools will execute. If the command has an error, the error message is returned to the model. The model can then examine the original request and the new error message and generate a new command. This can continue until the LLM generates the command successfully or reaches an end count. This pattern of providing a model with feedback - error messages in this case - is very powerful.
Initialize the agent with a descriptive system prompt to customize its behavior:
6. Run the agent
Run the agent on a sample query and observe its behavior:You can inspect all aspects of the above run, including steps taken, tools invoked, what prompts were seen by the LLM, and more in the LangSmith trace.
(Optional) Use Studio
Studio provides a “client side” loop as well as memory so you can run this as a chat interface and query the database. You can ask questions like “Tell me the scheme of the database” or “Show me the invoices for the 5 top customers”. You will see the SQL command that is generated and the resulting output. The details of how to get that started are below.Run your agent in Studio
Run your agent in Studio
In addition to the previously mentioned packages, you will need to:In directory you will run in, you will need a Create a file
langgraph.json file with the following contents:sql_agent.py and insert this:6. Implement human-in-the-loop review
It can be prudent to check the agent’s SQL queries before they are executed for any unintended actions or inefficiencies. LangChain agents feature support for built-in human-in-the-loop middleware to add oversight to agent tool calls. Let’s configure the agent to pause for human review on calling thesql_db_query tool:
We’ve added a checkpointer to our agent to allow execution to be paused and resumed. See the human-in-the-loop guide for detalis on this as well as available middleware configurations.
sql_db_query tool: