您现在的位置是:首页 >技术教程 >LangChain-09 Query SQL DB With RUN GPT 查询数据库 并 执行SQL 返回结果网站首页技术教程
LangChain-09 Query SQL DB With RUN GPT 查询数据库 并 执行SQL 返回结果
简介LangChain-09 Query SQL DB With RUN GPT 查询数据库 并 执行SQL 返回结果

安装依赖
pip install --upgrade --quiet langchain-core langchain-community langchain-openai
编写代码
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.utilities import SQLDatabase
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
template = """Based on the table schema below, write a SQL query that would answer the user's question:
{schema}
Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)
db = SQLDatabase.from_uri("sqlite:///./Chinook.db")
def get_schema(_):
return db.get_table_info()
def run_query(query):
return db.run(query)
model = ChatOpenAI(
model="gpt-3.5-turbo",
)
sql_response = (
RunnablePassthrough.assign(schema=get_schema)
| prompt
| model.bind(stop=["
SQLResult:"])
| StrOutputParser()
)
template = """Based on the table schema below, question, sql query, and sql response, write a natural language response:
{schema}
Question: {question}
SQL Query: {query}
SQL Response: {response}"""
prompt_response = ChatPromptTemplate.from_template(template)
full_chain = (
RunnablePassthrough.assign(query=sql_response).assign(
schema=get_schema,
response=lambda x: db.run(x["query"]),
)
| prompt_response
| model
)
message = full_chain.invoke({"question": "How many employees are there?"})
print(f"message: {message}")
运行结果
? python3 test09.py
message: content='There are a total of 8 employees in the database.' response_metadata={'finish_reason': 'stop', 'logprobs': None}

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。





QT多线程的5种用法,通过使用线程解决UI主界面的耗时操作代码,防止界面卡死。...
U8W/U8W-Mini使用与常见问题解决
stm32使用HAL库配置串口中断收发数据(保姆级教程)
分享几个国内免费的ChatGPT镜像网址(亲测有效)
Allegro16.6差分等长设置及走线总结