template = """Based on the table schema below, write a SQL query that would answer the user's question: {schema} Question: {question} Return SQL Query Only, do not explain:""" prompt = ChatPromptTemplate.from_template(template)
# 测试 user_question = 'how many albums are there in the database?' res = text_2_sql_chain.invoke({"question": user_question}) pass # {"question": user_question} ->{"question": user_question,'schema'='...'}
app = chat_agent_executor.create_tool_calling_executor(model, tools) # inputs = {"messages": [HumanMessage(content="how many album are there in the mojuan database?")]} inputs = {"messages": [HumanMessage(content="how many album are there in the mojuan database? you must check schema of mojuan first")]} for s in app.stream(inputs): print(list(s.values())[0]) print("----") pass
结果
how many album are there in the mojuan database?
→ 直接调用run_query, 生成的sql 命令有错:’SELECT COUNT(*) FROM albums‘
how many album are there in the mojuan database? you must check schema of mojuan first
from langchain_community.utilities import SQLDatabase from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from langchain_openai import ChatOpenAI import jwt, time
template = """Based on the table schema below, write a SQL query that would answer the user's question: {schema} Question: {question} Return SQL Query Only, do not explain:""" prompt = ChatPromptTemplate.from_template(template)
# 选择你要测试的数据库 # 使用sqlite #db = sqlite_db
# 使用mysql db = mysql_db
res = db.run('SELECT COUNT(*) FROM Album;') pass defrun_query(query): global db res = db.run(query) return res
defget_schema(_): global db schema = db.get_table_info() return schema
from langchain import hub from langchain.agents import AgentExecutor from langchain_core.messages import HumanMessage from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI import jwt, time from langchain_core.tools import tool from langgraph.prebuilt import chat_agent_executor from langchain_community.utilities import SQLDatabase
app = chat_agent_executor.create_tool_calling_executor(model, tools) # inputs = {"messages": [HumanMessage(content="how many album are there in the mojuan database?")]} inputs = {"messages": [HumanMessage(content="How many albums are there in the mojuan database? ")]} for s in app.stream(inputs): print(list(s.values())[0]) print("----") pass