当前位置: 首页 > news >正文

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}

http://www.jsqmd.com/news/212091/

相关文章:

  • Python高效计算斐波那契数列
  • AWS OpenSearch Service TLS 策略升级指南
  • 深度学习毕设项目:基于人工智能深度学习的土豆疾病识别
  • LangChain-08 Query SQL DB 通过GPT自动查询SQL
  • 使用dify搭建爬虫Agent工作流
  • 【课程设计/毕业设计】基于深度学习机器学习的土豆疾病识别
  • 内驱力:点燃自我成长的发动机
  • Katalon平台的集成生态
  • Python代码实现示例解析
  • 深度学习毕设项目:基于python深度学习的苹果和西红柿识别
  • 新手进阶Python:给办公助手加定时功能,自动处理任务不用盯
  • FastAPI 极简教程1
  • 计及电转气协同的含碳捕集与垃圾焚烧虚拟电厂优化调度Matlab代码
  • 数据科学为大数据领域的业务增长赋能
  • 深度学习毕设选题推荐:python基于CNN卷积神经网络对猫狗数据集训练识别
  • 精准编程代码生成指南
  • 基于阶梯碳交易的含P2G-CCS耦合和燃气掺氢的虚拟电厂优化调度Matlab代码
  • 什么是LLDP
  • 深度学习毕设选题推荐:基于python-cnn深度学习的猫的种类识别基于人工智能-cnn深度学习的猫的种类识别
  • 华为OD技术面真题 - 计算机网络 - 1
  • 基于氢储能的热电联供型微电网优化调度方法Matlab代码
  • 编程实战:从原理到代码的完整指南
  • 深度学习毕设选题推荐:基于 python深度学习的罗马数据集训练识别人工智能
  • 深入解析HMAC:消息认证码的核心原理
  • 深度测评8个一键生成论文工具,专科生毕业论文轻松搞定!
  • iir滤波器的理论分析与matlab仿真,对比butter/cheby1/cheby2/ellip/yulewalk
  • java进阶--多线程学习
  • Java进阶教程(一)关键字
  • AI(人工智能)是模拟人类智能行为的技术,如学习、推理、识别
  • C++内存序