【LangChain系列——案例分析】【基于SQL+CSV的案例分析】【持续更新中】

目录

  • 前言
  • 一、LangChain介绍
  • 二、在SQL问答时如何更好的提示?
    • 2-1、安装
    • 2-2、SQLite 样例数据
    • 2-3、使用langchain与其进行交互
    • 2-4、查看模型提示语
    • 2-5、提供表定义和示例行
    • 2-6、将表信息插入到Prompt中去
    • 2-7、添加自然语言->SQL示例
    • 2-8、在向量数据库中查找最相关的提示词
  • 总结


前言

LangChain是一个框架,用于开发由大型语言模型(LLM)驱动的应用程序。

一、LangChain介绍

LangChain是一个框架,用于开发由大型语言模型(LLM)驱动的应用程序。

LangChain 简化了 LLM 应用程序生命周期的每个阶段:

  • 开发:使用LangChain的开源构建块和组件构建应用程序。使用第三方集成和模板开始运行。
  • 生产化:使用 LangSmith 检查、监控和评估您的链条,以便您可以自信地持续优化和部署。
  • 部署:使用 LangServe 将任何链转换为 API。

在这里插入图片描述

二、在SQL问答时如何更好的提示?

2-1、安装

pip install --upgrade --quiet  langchain langchain-community langchain-experimental langchain-openai

2-2、SQLite 样例数据

参考:https://database.guide/2-sample-databases-sqlite/

Chinook 数据: 它代表了一个数字媒体商店,包括艺术家、专辑、媒体曲目、发票和客户的信息,以表格形式呈现。

1、创建数据库: 使用sqlite3 命令来创建

sqlite3 Chinook.db

2、sql脚本下载、运行

sql脚本地址: https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql

# 将脚本粘贴到Chinook_Sqlite.sql文件内后,执行以下命令可以创建数据库表。
.read Chinook_Sqlite.sql

2-3、使用langchain与其进行交互

我们可以使用SQLAlchemy驱动的SQLDatabase类与它交互:

from langchain_community.utilities import SQLDatabasedb = SQLDatabase.from_uri("sqlite:///Chinook.db", sample_rows_in_table_info=3)
print(db.dialect)
print(db.get_usable_table_names())
print(db.run("SELECT * FROM Artist LIMIT 10;"))

输出:

sqlite
[‘Album’, ‘Artist’, ‘Customer’, ‘Employee’, ‘Genre’, ‘Invoice’, ‘InvoiceLine’, ‘MediaType’, ‘Playlist’, ‘PlaylistTrack’, ‘Track’]
[(1, ‘AC/DC’), (2, ‘Accept’), (3, ‘Aerosmith’), (4, ‘Alanis Morissette’), (5, ‘Alice In Chains’), (6, ‘Antônio Carlos Jobim’), (7, ‘Apocalyptica’), (8, ‘Audioslave’), (9, ‘BackBeat’), (10, ‘Billy Cobham’)]

优化:

from langchain_community.utilities import SQLDatabase
import osdb_path = os.path.join(os.path.dirname(__file__), 'Chinook.db')
db_full_path = os.path.abspath(db_path)
db = SQLDatabase.from_uri(f"sqlite:///{db_full_path}")

2-4、查看模型提示语

安装:

pip install -qU langchain-openai
import getpass
import osos.environ["OPENAI_API_KEY"] = getpass.getpass()from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo-0125")
from langchain.chains import create_sql_query_chainchain = create_sql_query_chain(llm, db)
chain.get_prompts()[0].pretty_print()

输出:

You are a SQLite expert. Given an input question, first create a syntactically correct SQLite query to run, then look at the results of the query and return the answer to the input question.
Unless the user specifies in the question a specific number of examples to obtain, query for at most 5 results using the LIMIT clause as per SQLite. You can order the results to return the most informative data in the database.
Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in double quotes (") to denote them as delimited identifiers.
Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.
Pay attention to use date(‘now’) function to get the current date, if the question involves “today”.
Use the following format:
Question: Question here
SQLQuery: SQL Query to run
SQLResult: Result of the SQLQuery
Answer: Final answer here
Only use the following tables:
{table_info}
Question: {input}
None

Notice:我这里使用的是阿里的模型,对传入的llm要做一个修改, 使用OpenAI的不需要修改。

from langchain_community.chat_models.tongyi import ChatTongyi# 环境变量设置,模型接口设置
os.environ["LANGCHAIN_TRACING_V2"] = ""
os.environ["LANGCHAIN_API_KEY"] = ""
os.environ["DASHSCOPE_API_KEY"] = ''
model = ChatTongyi(streaming=True,
)

2-5、提供表定义和示例行

概述: 在大多数SQL链中,我们至少需要向模型提供部分数据库大纲。没有这个,它将无法编写有效的查询。我们的数据库提供了一些方便的方法来提供相关的上下文。具体来说,我们可以从每个表中获取表名、表的概要和行示例。

context = db.get_context()
print(list(context))
print(context["table_info"])

输出: 只截取部分。
在这里插入图片描述

2-6、将表信息插入到Prompt中去

prompt_with_context = chain.get_prompts()[0].partial(table_info=context["table_info"])
print(prompt_with_context.pretty_repr()[:1500])

输出:
在这里插入图片描述

2-7、添加自然语言->SQL示例

概述: 在Prompt中包含将自然语言问题转换为针对数据库的有效SQL查询的示例,通常会提高模型性能,特别是对于复杂查询。

examples = [{"input": "List all artists.", "query": "SELECT * FROM Artist;"},{"input": "Find all albums for the artist 'AC/DC'.","query": "SELECT * FROM Album WHERE ArtistId = (SELECT ArtistId FROM Artist WHERE Name = 'AC/DC');",},{"input": "List all tracks in the 'Rock' genre.","query": "SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = 'Rock');",},{"input": "Find the total duration of all tracks.","query": "SELECT SUM(Milliseconds) FROM Track;",},{"input": "List all customers from Canada.","query": "SELECT * FROM Customer WHERE Country = 'Canada';",},{"input": "How many tracks are there in the album with ID 5?","query": "SELECT COUNT(*) FROM Track WHERE AlbumId = 5;",},{"input": "Find the total number of invoices.","query": "SELECT COUNT(*) FROM Invoice;",},{"input": "List all tracks that are longer than 5 minutes.","query": "SELECT * FROM Track WHERE Milliseconds > 300000;",},{"input": "Who are the top 5 customers by total purchase?","query": "SELECT CustomerId, SUM(Total) AS TotalPurchase FROM Invoice GROUP BY CustomerId ORDER BY TotalPurchase DESC LIMIT 5;",},{"input": "Which albums are from the year 2000?","query": "SELECT * FROM Album WHERE strftime('%Y', ReleaseDate) = '2000';",},{"input": "How many employees are there","query": 'SELECT COUNT(*) FROM "Employee"',},
]

构建提示词模板:

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplateexample_prompt = PromptTemplate.from_template("User input: {input}\nSQL query: {query}")
prompt = FewShotPromptTemplate(examples=examples[:5],example_prompt=example_prompt,prefix="You are a SQLite expert. Given an input question, create a syntactically correct SQLite query to run. Unless otherwise specificed, do not return more than {top_k} rows.\n\nHere is the relevant table info: {table_info}\n\nBelow are a number of examples of questions and their corresponding SQL queries.",suffix="User input: {input}\nSQL query: ",input_variables=["input", "top_k", "table_info"],
)
print(prompt.format(input="How many artists are there?", top_k=3, table_info="foo"))

输出:

You are a SQLite expert. Given an input question, create a syntactically correct SQLite query to run. Unless otherwise specificed, do not return more than 3 rows.
Here is the relevant table info: foo
Below are a number of examples of questions and their corresponding SQL queries.
User input: List all artists.
SQL query: SELECT * FROM Artist;
User input: Find all albums for the artist ‘AC/DC’.
SQL query: SELECT * FROM Album WHERE ArtistId = (SELECT ArtistId FROM Artist WHERE Name = ‘AC/DC’);
User input: List all tracks in the ‘Rock’ genre.
SQL query: SELECT * FROM Track WHERE GenreId = (SELECT GenreId FROM Genre WHERE Name = ‘Rock’);
User input: Find the total duration of all tracks.
SQL query: SELECT SUM(Milliseconds) FROM Track;
User input: List all customers from Canada.
SQL query: SELECT * FROM Customer WHERE Country = ‘Canada’;
User input: How many artists are there?
SQL query:

2-8、在向量数据库中查找最相关的提示词


参考文章
userGuide
How to better prompt when doing SQL question-answering
How to do query validation as part of SQL question-answering
How to deal with large databases when doing SQL question-answering

How to do question answering over CSVs
SQL Database

总结

今天是疯狂星期三,我吃了必胜客😍

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/34694.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JAVA开发的一套医院绩效考核系统源码:KPI关键绩效指标的清晰归纳

KPI是关键绩效指标(Key Performance Indicators)的缩写,它是一种用于衡量员工或组织绩效的量化指标。这些指标通常与组织的目标和战略相关,并帮助管理层评估员工和组织的实际表现。KPI还可以为员工提供清晰的方向,使他…

办公软件汇总

1、OCR 1.1 pearOCR pearOCR 是一个免费的免费在线文字提取OCR工具网站。PearOCR界面简洁,所有过程均在网页端完成,无需下载任何软件,点开即用。官方地址:https://pearocr.com/ 参考:9款文字识别(OCR)工具…

Android性能分析工具-Perfetto基本使用

文章目录 一、Perfetto介绍二、抓取方法2.1 手机端直接抓取2.1.1 打开系统跟踪2.1.2 开始录制 2.2 使用 adb 抓取2.3 通过 Perfetto 网页自定义抓取 三、trace分析方法3.1 打开trace文件3.2 查看方法 一、Perfetto介绍 Perfetto 是一个用于性能检测和跟踪分析的生产级开源堆栈。…

Call_once

call_once和once_flag的声明 struct once_flag {constexpr once_flag() noexcept;once_flag(const once_flag&) delete;once_flag& operator(const once_flag&) delete; }; template<class Callable, class ...Args>void call_once(once_flag& flag, …

程序员如何用ChatGPT解决常见编程问题:实例解析

引言 在现代编程的世界中&#xff0c;技术进步日新月异&#xff0c;程序员们面临着各种各样的挑战和问题。解决这些问题的过程中&#xff0c;找到合适的工具至关重要。ChatGPT作为一种先进的人工智能语言模型&#xff0c;能够帮助程序员迅速、高效地解决常见的编程问题。本文将…

windows10/win11截图快捷键 和 剪贴板历史记录 快捷键

后知后觉的我今天又学了两招&#xff1a; windows10/win11截图快捷键 按 Windows 徽标键‌ Shift S。 选择屏幕截图的区域时&#xff0c;桌面将变暗。 默认情况下&#xff0c;选择“矩形模式”。 可以通过在工具栏中选择以下选项之一来更改截图的形状&#xff1a;“矩形模式”…

深度神经网络(dnn)--风格迁移(简单易懂)

概括 深度神经网络&#xff08;DNN&#xff09;在风格迁移领域的应用&#xff0c;实现了将一幅图像的艺术风格迁移到另一幅图像上的目标。该技术基于深度学习模型&#xff0c;特别是卷积神经网络&#xff08;CNN&#xff09;&#xff0c;通过提取内容图像的内容特征和风格图像的…

Python+Pytest+Yaml+Request+Allure+GitLab+Jenkins接口自动化测试框架概解

PythonPytestYamlAllure整体框架目录&#xff08;源代码请等下篇&#xff09; 框架详解 common:公共方法包 –get_path.py:获取文件路径方法 –logger_util.py:输出日志方法 –parameters_until.py&#xff1a;传参方式方法封装 –requests_util.py&#xff1a;请求方式方法封…

星坤Type-A连接器:创新快充技术,引领电子连接!

快速发展的电子时代&#xff0c;消费者对电子设备的性能和便利性有着更高的要求。特别是在充电和数据传输方面&#xff0c;快充技术和高速传输已成为市场的新宠。中国星坤公司推出的Type-A连接器系列&#xff0c;以其卓越的性能和创新的设计&#xff0c;满足了市场对高效、稳定…

天润融通:AI赋能客户体验,推动企业收入和业绩增长

“客户体验已经成为全球企业差异化的关键。人工智能与数据分析等创新技术正在加速推动企业在客户体验计划中取得成功&#xff0c;以保持领先地位”。Customer Insights & Analysis 研究经理Craig Simpson说道。 客户体验 (CX&#xff0c;Customer Experience) 是客户在与企…

charles抓包

1、去官网下载最新版本&#xff0c;避免出现不必要的问题 2、mac 上charles 的菜单栏在最顶上 3、mac 上安装根证书不受信任 双击下不受信任的正证书&#xff0c;点开信任小文字&#xff0c;然后把下面的这些全部设置为始终信任 4、手机上安装证书 先把wifi代理设置好 如果安…

条码二维码读取设备在医疗设备自助服务的重要性

医疗数字信息化建设的深入推进&#xff0c;医疗设备自助服务系统已成为医疗服务领域的一大趋势&#xff0c;条码二维码读取设备作为自助设备的重要组成部分&#xff0c;通过快速、准确地读取条形码二维码信息&#xff0c;不公提升了医疗服务效率&#xff0c;还为患者提供了更加…

深度相机辅助导航避障(三):地面点云滤除

前面的章节介绍了坐标变换,以及如何设置深度相机的坐标变换。那就可以很直观从机器人的坐标系对深度相机扫描到的障碍物点云进行处理。 在实际应用中,机器人正确估计周围地形,对于道路的可通过性、路径规划和障碍物检测等方面都很重要。那么在获取深度相机点云数据后就得准…

绕过命令过滤器:探索UnixLinux中的Bypass技术

前言 在Unix或Linux系统的安全测试和网络防御中&#xff0c;了解如何绕过命令过滤器是非常重要的。今天&#xff0c;我们将探讨几种利用shell命令绕过安全限制的技巧&#xff0c;这些技巧常用于渗透测试中&#xff0c;以检测系统的安全漏洞。 0x00 命令介绍 一般而言&#x…

学生选课管理系统(JAVA课设)PS:有前端界面

1.课设要求描述 实现系统的所有功能&#xff0c;包括但不限于&#xff1a; 学生信息管理&#xff08;增加、删除、修改、查询&#xff09;课程信息管理选课操作成绩管理 2.制作思路及基础讲解 此项目主要是用于完成大二下半学期的JAVA大作业&#xff0c;也可当作课设&…

树莓派pico入坑笔记,uart使用

uart原理自行百度&#xff0c;相关内容很多其他博主写过并且质量很高&#xff0c;这里不再赘述。 调用circuitpy的busio模块来使用uart&#xff0c;除此以外&#xff0c;spi、iic等要需要使用该模块&#xff0c;使用方法见 官方教程 &#xff0c;详细信息见文档 官方的例子简…

文本生成图像综述

本调查回顾了扩散模型在生成任务中广泛流行的背景下文本到图像的扩散模型。作为一份自成一体的作品&#xff0c;本调查首先简要介绍了基本扩散模型如何用于图像合成&#xff0c;然后介绍了条件或指导如何改善学习。基于这一点&#xff0c;我们介绍了文本到图像生成方面的最新方…

# 深入理解 Java 虚拟机 (二)

深入理解 Java 虚拟机 &#xff08;二&#xff09; Java内存模型 主内存与工作内存 所有的变量存储在主内存&#xff08;虚拟机内存的一部分&#xff09;每条线程有自己的工作内存&#xff0c;线程对变量的所有操作&#xff08;读取、赋值&#xff09;都必须在工作内存中进行…

VMware Windows sever 虚拟机互联网连接配置

一、VMware配置 1、虚拟网络编辑 从左上角 编辑→虚拟网络编辑器 进入 2、配置NAT模式 配置的子网IP&#xff0c;在虚拟机中获取到的ip跟子网IP的前三个是一样的 1.配置网关 2.配置DHCP设置 这个主要是分配ip最后一位获取的区间 3、虚拟机配置 二、Windows Server 虚拟机配置…

【Linux】进程 | 控制块pcb | task_struct | 创建子进程fork

目录 Ⅰ. 进程的概念&#xff08;Process&#xff09; 1. 什么是进程&#xff1f; 2. 多进程管理 3. 进程控制块&#xff08;PCB&#xff09; task_struct 的结构 Ⅱ. 进程查看与管理 1. 使用指令查看进程 2. /proc 查看进程信息 3. 获取进程 ID 4. 创建子进程 原因&…