输入“/”快速插入内容

【经验技巧】NL2SQL的几类方案

2024年10月10日修改
1.
SQLAgent
相关资料:SQLAgent股市数据库问答
看一下SQLAgent的提示词,可以发现它核心是基于React框架:
提示词的Prefix部分,定义了Agent的角色信息,包括一些注意事项,如:不要对数据库进行增删改操作(如果数据有备份且不重要的话也可以去掉这一条)、执行SQL之前需要检查、为了防止返回内容过长无法处理不要查全表...
提示词的Format Instructions部分,是经典的React逻辑。
提示词的Suffix部分,构造了初始思路“先看看库中都有哪些表格,然后根据用户问题选择最相关的表格,并获取这些表中都有哪些字段”,所以默认用户输入每个问题都会进行该操作,进而能让模型根据用户的问题自主选择表格并编写SQL语句。
所以一次典型的请求如下图所示:
SQLAgent提示词:
Prefix
代码块
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 have access to tools for interacting with the database.Only use the below tools. Only use the information returned by the below tools to construct your final answer.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.If the question does not seem related to the database, just return "I don't know" as the answer.
Tools
4个工具,分别是执行SQL query、查询某个表内的字段、查询该数据库中有哪些表、检查SQL query语句是否正确
代码块
ql_db_query:
Execute a SQL query against the database and get back the result..
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.
sql_db_schema: Get the schema and sample rows for the specified SQL tables.
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!
Format Instructions
代码块
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Suffix
代码块
Begin!
Question: {input}
Thought: I should look at the tables in the database to see what I can query. Then I should query the schema of the most relevant tables.
{agent_scratchpad}