【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还可以为员工提供清晰的方向,使他…

python读取mp4视频,读取摄像头代码

python读取mp4视频 import cv2# 读取视频文件 video_path path_to_your_video.mp4 # 将此处替换为你的MP4文件路径 cap cv2.VideoCapture(video_path)# 检查视频是否成功打开 if not cap.isOpened():print("Error: Could not open video.")exit()# 播放视频 whil…

ASP.NET Core 6.0 使用 资源过滤器和行为过滤器

1.AOP 面向切面编程 概念 AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,旨在通过预定义的模式(即“切面”)对程序的横切关注点进行模块化。横切关注点是一个在多个应用模块中出现的概念,例如日志记录、事务管理、安全检查等。AOP允许开发者定义“切面”…

办公软件汇总

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

JS签名库jSignature增加回退事件, 支持导入svgbase64等

原始插件下载地址: https://github.com/Smile-lrn/jSignature 用倒是挺好用的, 但是存在几个问题: 1. 插件自身未提供回退事件(需要通过别的插件js实现回退, 但是样式, 位置不是我想要的) 2. getData方法可以支持svgbase64导出, 但是setData方法不支持这种格式的导入(= =) …

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 是一个用于性能检测和跟踪分析的生产级开源堆栈。…

适合java程序员的桌面开发的技术栈

JavaFX: JavaFX是Oracle官方支持的用于构建富客户端应用程序的Java库,提供了现代的UI控件、图形和媒体功能。它支持跨平台(Windows、macOS、Linux)开发,并且与Java SE紧密结合。JavaFX适合开发具有复杂用户界面和多媒体…

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;能够帮助程序员迅速、高效地解决常见的编程问题。本文将…

Android 自定义按键关机

Android 自定义按键关机 最近收到客户需求&#xff0c;需要设备实现自定义按键关机功能&#xff0c;具体修改参照如下&#xff1a; /frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java public int interceptKeyBeforeQueueing(KeyEvent…

Vue3自定义指令基本使用(1)

#方式一 定义ref绑定到input中, 调用focus <template> <div class"app"><input type"text" ref"inputRef"></div> </template><script setup> // 1.方式一: 定义ref绑定到input中, 调用focus import useI…

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;满足了市场对高效、稳定…

map和set关联式容器特性(课堂笔记)

map和set都是关联式容器&#xff0c;它们有一些共同的特性&#xff1a; 1. 存储方式&#xff1a;map和set都是基于红黑树&#xff08;Red-Black Tree&#xff09;实现的&#xff0c;这使得它们内部的元素是有序的&#xff0c;根据特定的排序准则进行排列。 2. 唯一性&#xf…

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

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

Unity在非继承自MonoBehaviour的脚本启动协程

在Unity中&#xff0c;协程通常是通过MonoBehaviour的StartCoroutine方法来启动的。很多时候&#xff0c;我们写逻辑层代码的时候也希望能够调用协程&#xff0c;例如网络通讯等功能&#xff0c;这就需要一个中介来帮你做这件事。这个中介通常是一个继承自MonoBehaviour的管理类…

charles抓包

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

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

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