【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 SQLDatabase

db = 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 os

db_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 os

os.environ["OPENAI_API_KEY"] = getpass.getpass()

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo-0125")
from langchain.chains import create_sql_query_chain

chain = 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, PromptTemplate

example_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.mfbz.cn/a/746578.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ONLYOFFICE 8.1版本桌面编辑器测评:超越想象的办公体验!

在当今数字化办公时代,一个功能强大、操作便捷的办公套件对于提高工作效率至关重要。ONLYOFFICE 8.1作为一款备受瞩目的办公软件,凭借其全面的功能、优异的性能和出色的用户体验,为用户带来了超越想象的办公体验。下面,我们将对ON…

数据资产风险管理与合规性:全面识别、科学评估并有效应对数据风险,确保企业数据资产的安全性与合规性,为企业稳健发展提供坚实保障

一、引言 在数字化时代,数据资产已成为企业运营和决策的核心要素。然而,随着数据量的快速增长和技术的不断演进,数据资产面临的风险也日益增多,如数据泄露、数据篡改、数据滥用等。同时,数据保护法律法规的不断完善&a…

java基于ssm+jsp 社区生活超市管理系统

1前台首页功能模块 社区生活超市管理系统 ,在社区生活超市管理系统可以查看首页、商品信息、我的、跳转到后台等内容,如图1所示。 图1系统首页界面图 用户登录、用户注册,通过注册填写用户账号、密码、用户姓名、性别、用户手机、送货地址等…

教你如何一键高效下载视频号直播视频

在当今视频号直播盛行的时代,错过精彩直播内容再也不是遗憾!地瓜网络技术倾情推出“视频号直播视频下载器”,为您捕捉每一个直播瞬间。本文将简明扼要地指导您如何利用这款神器下载视频号直播与回放视频,让超清MP4视频轻松入库&am…

wget之Win11中安装及使用

wget之Win11中安装及使用 文章目录 wget之Win11中安装及使用1. 下载2. 安装3. 配置环境变量4. 查看及使用1. 查看版本2. 帮助命令3. 基本使用 1. 下载 下载地址:https://eternallybored.org/misc/wget 选择对应的版本进行下载即可 2. 安装 将下载后的wget-1.21.4-w…

OpenCV中掩膜(mask)图像的创建和使用

操作系统:ubuntu22.04OpenCV版本:OpenCV4.9IDE:Visual Studio Code编程语言:C11 功能描述 掩模图像(Mask Image)是一种特殊类型的形象数据,在图像处理和计算机视觉中扮演着重要角色。它通常是一个二维数组…

LabVIEW遇到无法控制国外设备时怎么办

当使用LabVIEW遇到无法控制国外产品的问题时,解决此类问题需要系统化的分析和处理方法。以下是详细的解决思路和具体办法,以及不同方法的分析和比较,包括寻求代理、国外技术支持、国内用过的人请教等内容。 1. 了解产品的通信接口和协议 思路…

修复:cannot execute binary file --- ppc64le 系统架构

前言: 修复node_exporter,引用pprof包,对源码编译后在 Linux 系统下执行程序运行时,发生了报错,报错信息:cannot execute binary file: Exec format error。 开始以为编译有问题,检查发现;该l…

从零入门激光SLAM(十三)——LeGo-LOAM源码超详细解析3

大家好呀,我是一个SLAM方向的在读博士,深知SLAM学习过程一路走来的坎坷,也十分感谢各位大佬的优质文章和源码。随着知识的越来越多,越来越细,我准备整理一个自己的激光SLAM学习笔记专栏,从0带大家快速上手激…

Python3极简教程(一小时学完)上

开始 Python 之旅 本教程基于 Python for you and me 教程翻译制作,其中参考了 Python tutorial 和 _The Python Standard Library_,并对原教程的内容进行了改进与补充。 相关链接地址如下: _Python tutorial_:Python 入门指南…

通过颜色传感器控制机械臂抓物体

目录 1 绪论 2整体设计方案 2.1 系统的介绍 2.2 抓取模块 2.2.1 机械臂的定义 2.2.2 机械臂的分类 2.2.3 机械臂的选用 2.3 颜色识别模块 2.3.1 颜色传感器识别原理 2.3.2 TCS3200简介 2.4 整体控制方案 3 颜色识别抓取系统的硬件设计 3.1 单片机选型及参数 3.2 系…

13.爬虫---PyMongo安装与使用

13.PyMongo安装与使用 1.安装 PyMongo2.使用PyMongo2.1连接数据库和集合2.2增加数据2.3修改数据2.4查询数据2.5删除数据 3.总结 MongoDB 安装可以看这篇文章MongoDB安装配置教程(详细版) 1.安装 PyMongo PyMongo 是Python中用于连接MongoDB数据库的库&a…

适用于 Windows 11 的 5 大数据恢复软件 [免费和付费]

为什么我们需要Windows 11数据恢复软件? 计算机用户经常遇到的一件事就是数据丢失,这种情况随时可能发生。错误地删除重要文件和文件夹可能会非常令人担忧,但幸运的是,有一种方法可以恢复 PC 上丢失的数据。本文将向您展示可用于…

AI引领创意潮流:高效生成图片,参考图助力,一键保存到指定文件夹

在这个数字与创意交融的时代,我们迎来了AI绘画的新纪元。借助先进的AI技术,我们不仅能够高效生成图片,还能在参考图的启发下,激发无限创意,让您的想象力在数字世界中自由翱翔。 首助编辑高手软件中的魔法智能绘图板块&…

路径规划算法--DFS

文章目录 一、DFS二、DFS伪代码三、DFS做全覆盖路径 一、DFS DFS(Depth First Search)为深度优先搜索,是一种用于遍历或搜索树或图的搜索算法。DFS是从当前点出发,沿着一个方向一直搜索,如果搜索完成且未搜索到目标点…

C++系列-String(三)

&#x1f308;个人主页&#xff1a;羽晨同学 &#x1f4ab;个人格言:“成为自己未来的主人~” assign 这个接口的目的是用一个新的值代替之前的那个值 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> #include<list> #include&l…

HTTP协议中的各种请求头、请求类型的作用以及用途

目录 一、http协议介绍二、http协议的请求头三、http协议的请求类型四、http协议中的各种请求头、请求类型的作用以及用途 一、http协议介绍 HTTP&#xff08;HyperText Transfer Protocol&#xff0c;超文本传输协议&#xff09;是一种用于分布式、协作式和超媒体信息系统的应…

计算机组成原理 | CPU子系统(3)MIPS32指令架构

MIPS32架构指令格式 MIPS32架构寻址方式 指令的编码与功能

突破内存限制:Jamba模型的高效文本处理能力

在当今信息爆炸的时代&#xff0c;处理和理解海量文本数据的需求日益增长。自然语言处理&#xff08;NLP&#xff09;领域的研究者们一直在探索如何构建更高效、更强大且更灵活的语言模型来应对这一挑战。然而&#xff0c;现有的大型语言模型&#xff0c;尤其是基于Transformer…

昇思25天学习打卡营第8天|保存与加载

一、简介&#xff1a; 上一章节主要介绍了如何调整超参数&#xff0c;并进行网络模型训练。在训练网络模型的过程中&#xff0c;实际上我们希望保存中间和最后的结果&#xff0c;用于微调&#xff08;fine-tune&#xff09;和后续的模型推理与部署&#xff0c;本章节我们将介绍…
最新文章