0


LangChain-09 Query SQL DB With RUN GPT 查询数据库 并 执行SQL 返回结果

请添加图片描述

安装依赖

  1. pip install--upgrade--quiet langchain-core langchain-community langchain-openai

编写代码

  1. from langchain_core.prompts import ChatPromptTemplate
  2. from langchain_community.utilities import SQLDatabase
  3. from langchain_core.output_parsers import StrOutputParser
  4. from langchain_core.runnables import RunnablePassthrough
  5. from langchain_openai import ChatOpenAI
  6. template ="""Based on the table schema below, write a SQL query that would answer the user's question:
  7. {schema}
  8. Question: {question}
  9. SQL Query:"""
  10. prompt = ChatPromptTemplate.from_template(template)
  11. db = SQLDatabase.from_uri("sqlite:///./Chinook.db")defget_schema(_):return db.get_table_info()defrun_query(query):return db.run(query)
  12. model = ChatOpenAI(
  13. model="gpt-3.5-turbo",)
  14. sql_response =(
  15. RunnablePassthrough.assign(schema=get_schema)| prompt
  16. | model.bind(stop=["\nSQLResult:"])| StrOutputParser())
  17. template ="""Based on the table schema below, question, sql query, and sql response, write a natural language response:
  18. {schema}
  19. Question: {question}
  20. SQL Query: {query}
  21. SQL Response: {response}"""
  22. prompt_response = ChatPromptTemplate.from_template(template)
  23. full_chain =(
  24. RunnablePassthrough.assign(query=sql_response).assign(
  25. schema=get_schema,
  26. response=lambda x: db.run(x["query"]),)| prompt_response
  27. | model
  28. )
  29. message = full_chain.invoke({"question":"How many employees are there?"})print(f"message: {message}")

运行结果

  1. python3 test09.py
  2. message: content='There are a total of 8 employees in the database.'response_metadata={'finish_reason':'stop', 'logprobs': None}

在这里插入图片描述

标签: langchain sql ai

本文转载自: https://blog.csdn.net/w776341482/article/details/137425252
版权归原作者 武子康 所有, 如有侵权,请联系我们删除。

“LangChain-09 Query SQL DB With RUN GPT 查询数据库 并 执行SQL 返回结果”的评论:

还没有评论