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 ChatOpenAItemplate ="""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")defget_schema(_):return db.get_table_info()defrun_query(query):return db.run(query)model = ChatOpenAI(model="gpt-3.5-turbo",)sql_response =(RunnablePassthrough.assign(schema=get_schema)| prompt| model.bind(stop=["\nSQLResult:"])| 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}
前言
上一篇文章,讲解了《肥胖风险的多类别预测》机器学习方面的文章,主要是多分类算法的运用,本文是一个回归的算法,本期是2024年4月份的题目《Regression with an Abalone Dataset》即《鲍鱼年龄预测》,在此分享高手…