LangChain实战:利用LangChain SQL Agent和GPT进行文档分析和交互

img

我最近接触到一个非常有趣的挑战,涉及到人工智能数字化大量文件的能力,并使用户可以在这些文件上提出复杂的与数据相关的问题,比如:

  • 数据检索问题: 涉及从数据库中获取特定数据点或数据集,例如“电子产品类别中有多少产品?” 或 “2021年第四季度总销售额是多少?”
  • 汇总查询: 需要对数据进行总结的问题,如计算平均值、求和、计数等,例如“所有已上架产品的平均价格是多少?”或“每个地区客户的总人数是多少?”
  • 数据关系探索: 探究不同数据实体之间关系的问题,比如"哪些客户购买了三种以上不同的产品?" 或 “列出上个月没有交付任何产品的所有供应商。”
  • 条件查询: 涉及条件或筛选器,比如“列出2022年发生在超过500美元交易额以上的所有交易” 或 “展示所有缺货商品。”

这些不是你可以仅通过使用RAG来解决的典型问题。相反,我们将利用LangChainSQLAgent从人类文本中生成复杂的数据库查询。

文档应包含具有大量规格说明的数据,以及更多流畅、自然语言描述等。

我们将执行以下步骤,最终能够提出关于大量文档的复杂问题:

  • 阅读所有PDF文档
  • 使用GPT分析每个文档的内容,将其解析为JSON对象。
  • 将这些对象写入SQLite获取其他数据库中,分布在多个表中。
  • 使用LangChain SQL代理程序通过自动生成SQL语句来提出问题。

备注:本文涵盖了涉及人工智能和数据处理的概念。为了获得最大价值,您应具备对Python编程能力、GPT模型接入能力、嵌入式技术了解、向量搜索和SQL数据库的基础理解以及使用能力。

使用 Python、LangChain 和 GPT 分析文档

我们将使用PythonLangChain来读取和分析PDF文档。我使用的 PythonPython 3.11

首先,我们安装环境所需要的依赖包:

shell复制代码 %pip install pypdf
 %pip install langchain
 %pip install langchain_openai
 %pip install sqlite3
python复制代码 # 导入 pdf 阅读器
 from pypdf import PdfReader
 # 导入langchain 的消息类型
 from langchain_core.messages import HumanMessage, SystemMessage
 # 导入 openAI
 from langchain_openai import ChatOpenAI

现在,让我们来深入研究 PDF 解析。我们的目标是使用 visitor_text 提取有意义的内容,同时忽略不太有用的信息,例如空行、页眉和页脚。

python复制代码 document_content = None
 
 def visitor_body(text, cm, tm, fontDict, fontSize):
     y = tm[5]
     if text and 35 < y < 770:
         page_contents.append(text)
 
 with open(f'./documents/ZMP_55852_XBO_1000_W_HS_OFR.pdf', 'rb') as file:
     pdf_reader = PdfReader(file)
     page_contents = []
     for page in pdf_reader.pages:
        # 提取PDF每页文本的内容
         page.extract_text(visitor_text=visitor_body)
     document_content = "\n".join(page_contents)
 
 print(document_content)

让我们查看解析后的文档:

python复制代码 Product family benefits
 _
 Short arc with very high luminance for brighter screen illumination
 _
 Constant color temperature of 6,000 K throughout the entire lamp lifetime
 _
 Easy to maintain
 _
 High arc stability
 _
 Instant light on screen thanks to hot restart function
 _
 Wide dimming range
 Product family features
 _
 Color temperature: approx. 6,000 K (Daylight)
 _
 Wattage: 45010,000 W
 _
 Very good color rendering index: Ra >
 Product datasheet
 
 
  
 XBO 1000 W/HS OFR
 XBO for cinema projection | Xenon short-arc lamps 45010,000 W
 
 [..] 
 
 Packaging unit
 
 (Pieces/Unit)
 Dimensions (length
 
 x width x height)
 Volume
 Gross weight
 4008321082114
 XBO 1000 W/HS OFR
 Shipping carton box
 
 1
 410 mm x 184 mm x
 
 180 mm
 13.58 dm³
 819.00 g
 
 [..]

在解析的内容中,显而易见地发现它缺乏结构 — 表格不连贯,相关实体分散。

我们使用 GPT 重新帮我们整理文档的内容:

  • 我们将指示GPT将解析的数据格式化为一个结构化JSON对象。
  • 通过提供一份解析数据的示例,以及在前面加上<<<的提示,我们可以引导GPT理解并整理文档。
  • 利用OpenAI Chat API,我们将请求GPT从一组新的解析产品数据中生成一个JSON对象。

让我们构建一条深思熟虑的系统消息来启动这个过程。我们将以清晰的指令为GPT开头,接着呈现解析后的数据作为背景,并夹杂目标性提示来完善输出:

认真观察我们如何整合各种提示来塑造我们所需的精确JSON输出。

txt复制代码 你会分析产品描述,将其导出为 JSON 格式。我会向您展示一个产品数据表,并用 <<< 描述各个 JSON 对象和属性。然后您可以从另一个产品数据表中创建一个 JSON 对象。
 
 >>> Example product:
 
 Product family benefits <<< benefits (string[])
 _
 Short arc with very high luminance for brighter screen illumination <<< benefits.[*]
 _
 Constant color temperature of 6,000 K throughout the entire lamp lifetime <<< benefits.[*]
 
 [..]
 
 _
 Wide dimming range <<< benefits.[*]
 Product family features <<< product_family (object)
 _
 Color temperature: approx. 6,000 K (Daylight) <<< product_family.temperature = 6000
 _
 Wattage: 450…10,000 W <<< product_family.watts_min = 450, product_family.watts_max = 10000
 _
 Very good color rendering index: Ra >
 Product datasheet
 
 
  
 XBO 1000 W/HS OFR <<< name
 XBO for cinema projection | Xenon short-arc lamps 450…10,000 W <<< description
 
 [..]
 
 Technical data
 Electrical data <<< technical_data (object)
 Nominal current
 50 A <<< technical_data.nominal_current = 50.00
 Current control range
 30…55 A <<< technical_data.control_range = 30, technical_data.control_range = 55
 Nominal wattage
 1000.00 W <<< technical_data.nominal_wattage = 1000.00
 Nominal voltage
 19.0 V <<< technical_data.nominal_voltage = 19.0
 Dimensions & weight <<< dimensions (object)
 
 [..]
 
 Safe Use Instruction
 The identification of the Candidate List substance is <<< environmental_information.safe_use (beginning of string)
 
 sufficient to allow safe use of the article. <<< environmental_information.safe_use (end of string)
 Declaration No. in SCIP database
 22b5c075-11fc-41b0-ad60-dec034d8f30c <<< environmental_information.scip_declaration_number (single string!)
 Country specific information
 
 [..]
 
 Shipping carton box
 
 1
 410 mm x 184 mm x <<< packaging_unity.length = 410, packaging_unit.width = 184
 
 180 mm <<< packaging_unit.height = 180
 
 [..]
 """

我的 prompt 是不同方法的集合:

  • <<< benefits(字符串[])— 这里开始了一个字符串列表。
  • <<< benefits.[*] — 这行属于字符串列表。
  • <<< product_family(对象)— 这里开始了一个对象。
  • <<< product_family.temperature = 6000 — 这行是对象的整数属性
  • <<< product_family.watts_min = 450,product_family.watts_max = 1000 — 这一行是两个整数属性(例如,当有类似功率:450…10,000 W 的语句时)

在这里你可以完全发挥创意,尝试任何对你有意义的东西。而且需要多次调试 prompt 的内容以适应你的应用场景。

注意: 这里 prompt 最好还是英文的好, 最好不要中文和英文夹着来。

请将以下文本翻译成中文:

要翻译的文字:

  • <<< 将其翻译成另一种语言。
  • <<< 提供摘要或提供项目符号下的整个句子。
  • <<< 将数据拆分为名字和姓名。

测试 prompt

现在我们是时候测试一下 GPT 了,看看它是否能够完美地将我们混乱的 PDF 文本转换成一个整洁的 JSON 对象。

GPT-3.5-Turbo的0125版本在以JSON等请求格式响应时具有更高的准确性,这非常适合我们的情况! 我们已经准备好了system_message,并将其与document_content配对作为输入:

python复制代码 # 初始化 OpenAI Model
 chat = ChatOpenAI(model_name='gpt-3.5-turbo-0125', temperature=0)
 
 def convert_to_json(document_content):
     messages = [
         # 这里是系统的角色设定
         SystemMessage(
             content=system_message
         ),
         # 这里是我们的输入内容
         HumanMessage(
             content=document_content
         )
     ]
     # 构建 langchain 的链式
     answer = chat.invoke(messages)
     return answer.content
 
 json = convert_to_json(document_content)
 # json 就是 OpenAI Model 返回的内容:
 print(json)

一切就绪,我们看一下我们得到的JSON输出了:

json复制代码 {
     "name": "XBO 1000 W/HS OFR",
     "description": "XBO for cinema projection | Xenon short-arc lamps 450…10,000 W",
     "applications": [
         "Classic 35 mm film projection",
         "Digital film and video projection",
         "Architectural and effect light (“Light Finger”)",
         "Sunlight simulation"
     ],
     "technical_data": {
         "nominal_current": 50.00,
         "control_range_min": 30,
         "control_range_max": 55,
         "nominal_wattage": 1000.00,
         "nominal_voltage": 19.0
     },
     "dimensions": {
         "diameter": 40.0,
         "length": 235.0,
         "length_base": 205.00,
         "light_center_length": 95.0,
         "electrode_gap": 3.6,
         "weight": 255.00
     },
     "operating_conditions": {
         "max_temp": 230,
         "lifespan": 2000,
         "service_lifetime": 3000
     },
     "additional_data": {
         "base_anode": "SFa27-11",
         "base_cathode": "SFcX27-8",
         "product_remark": "OFR = Ozone-free version/H = Suitable for horizontal burning position/S = Short"
     },
     "capabilities": {
         "cooling": "Forced",
         "burning_position": "s20/p20"
     },
     "environmental_information": {
         "declaration_date": "10-03-2023",
         "primary_product_number": "4008321082114 | 4050300933566",
         "candidate_list_substance": "Lead",
         "cas_number": "7439-92-1",
         "safe_use": "The identification of the Candidate List substance is sufficient to allow safe use of the article.",
         "scip_declaration_number": "22b5c075-11fc-41b0-ad60-dec034d8f30c"
     },
     "logistical_data": {
         "product_code": "4008321082114",
         "product_name": "XBO 1000 W/HS OFR",
         "packaging_unit": {
             "product_code": "4008321082114",
             "product_name": "XBO 1000 W/HS OFR",
             "length": 410,
             "width": 184,
             "height": 180,
             "volume": 13.58,
             "weight": 819.00
         }
     }
 }

从结果看还是相当不错的。它找到的对象和属性是准确无误。

然而,有一个明显BUG:GPT忽略了一些关键元素,比如利益和产品系列

那么,我们的如何做呢?转向使用 GPT-4 看看效果,它提供增强功能但成本更高且响应时间较慢,还是调整策略以包括函数调用来优化资源同时保持效率?

通过提供一个 JSON Schema 来改善 prompt

在使用 GPT 时,function call 是我最喜欢的功能。它允许我们指定不仅 GPT 可执行的函数本身,还可以指定我们自己的函数所需的 JSON 参数。

下面是一个 function call 的示例:

python复制代码 "function": {
     "name": "get_current_weather",
     "description": "Get the current weather in a given location",
     "parameters": {
         "type": "object",
         "properties": {
             "location": {
                 "type": "string",
                 "description": "The city and state, e.g. beijing",
             },
             "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
         },
         "required": ["location"],
     },
 }

最新的模型gpt-3.5-turbo-0125gpt-4-turbo-preview经过训练,能够检测何时启动功能调用,并生成与指定函数签名相符的JSON输出.

为了充分利用这一点,我们优化我们的提示,以包含我们期望返回的 JSON 模式。

python复制代码You analyze product descriptions to export them into a JSON format. I will present you with a product data sheet and describe the individual JSON objects and properties with <<<. You then create a JSON object from another product data sheet.

>>> Example product:

Product family benefits <<< benefits (string[])

[..]

-----

Provide your JSON in the following schema:

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "applications": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "benefits": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "product_family": {
      "type": "object",
      "properties": {
        "temperature": {
          "type": "number"
        },
        "watts_min": {
          "type": "number"
        },
        "watts_max": {
          "type": "number"
        }
      }
    },
    "technical_data": {
      "type": "object",
      "properties": {
        "nominal_current": {
          "type": "number"
        },
        "control_range_min": {
          "type": "number"
        },
        "control_range_max": {
          "type": "number"
        },
        "nominal_wattage": {
          "type": "number"
        },
        "nominal_voltage": {
          "type": "number"
        }
      }
    },
    "dimensions": {
      "type": "object",
      "properties": {
        "diameter": {
          "type": "number"
        },
        "length": {
          "type": "number"
        },
        "length_base": {
          "type": "number"
        },
        "light_center_length": {
          "type": "number"
        },
        "electrode_gap": {
          "type": "number"
        },
        "weight": {
          "type": "number"
        }
      }
    },
    "operating_conditions": {
      "type": "object",
      "properties": {
        "max_temp": {
          "type": "string"
        },
        "lifespan": {
          "type": "number"
        },
        "service_lifetime": {
          "type": "number"
        }
      }
    },
    "logistical_data": {
      "type": "object",
      "properties": {
        "product_code": {
          "type": "string"
        },
        "product_name": {
          "type": "string"
        },
        "packaging_unit": {
          "type": "object",
          "properties": {
            "product_code": {
              "type": "string"
            },
            "product_name": {
              "type": "string"
            },
            "length": {
              "type": "number"
            },
            "width": {
              "type": "number"
            },
            "height": {
              "type": "number"
            },
            "volume": {
              "type": "number"
            },
            "weight": {
              "type": "number"
            }
          }
        }
      }
    }
  }
}

调整我们的方法后,让我们来看一下新的输出:

json复制代码{
  "name": "XBO 1000 W/HS OFR",
  "description": "XBO for cinema projection | Xenon short-arc lamps 450…10,000 W",
  "applications": [
    "Classic 35 mm film projection",
    "Digital film and video projection",
    "Architectural and effect light (“Light Finger”)",
    "Sunlight simulation"
  ],
  "benefits": [
    "Short arc with very high luminance for brighter screen illumination",
    "Constant color temperature of 6,000 K throughout the entire lamp lifetime",
    "Easy to maintain",
    "High arc stability",
    "Instant light on screen thanks to hot restart function",
    "Wide dimming range"
  ],
  "product_family": {
    "temperature": 6000,
    "watts_min": 450,
    "watts_max": 10000
  },
  "technical_data": {
    "nominal_current": 50,
    "control_range_min": 30,
    "control_range_max": 55,
    "nominal_wattage": 1000.00,
    "nominal_voltage": 19.0
  },
  "dimensions": {
    "diameter": 40.0,
    "length": 235.0,
    "length_base": 205.00,
    "light_center_length": 95.0,
    "electrode_gap": 3.6,
    "weight": 255.00
  },
  "operating_conditions": {
    "max_temp": "230 °C",
    "lifespan": 2000,
    "service_lifetime": 3000
  },
  "logistical_data": {
    "product_code": "4008321082114",
    "product_name": "XBO 1000 W/HS OFR",
    "packaging_unit": {
      "product_code": "4008321082114",
      "product_name": "XBO 1000 W/HS OFR",
      "length": 410,
      "width": 184,
      "height": 180,
      "volume": 13.58,
      "weight": 819.00
    }
  }
}

这个结果很美丽哦😯。

输出完整地映射了名称和描述,将应用分类为字符串列表,并使用最小值和最大值区分范围 — 所有这些都与我们的 JSON 模式期望完美对齐。

探索 LangChain 的QA能力

虽然幕墙我们主要关注 PDF 分析和 SQL Agent,但如果你已经想继续探索的话,可以尝试使用 LangChain Q&ARAG,尤其是因为它与我们更广泛的目标相契合。

我将提供一些代码和输出,这样我们就能迅速转入真正的内容领域了。

让我们先收集更多产品数据. 下载一些额外随机的PDF文档,并将它们存储在指定的文档文件夹中。接下来,我们需要添加一些代码:

python复制代码import os

# 导入 langchain 的问答链
from langchain.chains.question_answering import load_qa_chain
# 导入 OpenAI 包
from langchain_openai import OpenAIEmbeddings
# 导入向量数据库 FAISS
from langchain.vectorstores import FAISS

下一步涉及阅读和转换所有已下载的PDF文档,然后将它们的JSON输出汇总到一个数组中。

python复制代码# 从文件夹中获取所有的 pdf 文件
pdf_files = [f for f in os.listdir('./documents') if f.endswith('.pdf')]

json_documents = []

for pdf_file in pdf_files:
    with open(f'./documents/{pdf_file}', 'rb') as file:
        # 读取文件的内容
        pdf_reader = PdfReader(file)

        page_contents = []

        for page in pdf_reader.pages:
            page.extract_text(visitor_text=visitor_body)

        json = convert_to_json("\n".join(page_contents))

        json_documents.append(json)

此外,我们将整合FAISS相似性搜索库,并将其与我们的文档内容和嵌入模型对齐,以便实现内容向量化。

如果你喜欢使用其他的向量数据库也可以。应该使用哪个向量数据库?选择最适合您需求的一款

FAISS是由 Facebook 于2017年开发的,作为 Azure 人工智能搜索服务中 Azure 机器学习的开源替代方案——在比较嵌入向量方面表现相当不错。

python复制代码# 加载向量化模型
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
# 将上面的文本向量化到向量数据库中
docsearch = FAISS.from_texts(documents, embeddings)

提出问题:

python复制代码chain = load_qa_chain(chat, chain_type="stuff", verbose=True)
# 输入我们的问题
query = "我可以将XBO 1000 W/HS OFR放入长350毫米,宽200毫米的盒子中吗?"
# 向量相似性搜索
docs = docsearch.similarity_search(query)
# 将查到相似的内容做为LLM的内容
chain.run(input_documents=docs, question=query)

观察以最相关的文件内容为基础的回复。

不能,XBO 1000 W/HS OFR 的尺寸为长410毫米,宽184毫米,比盒子的尺寸大,后者为长350毫米,宽200毫米。

目前进展还是不错的。 现在让我们深入研究更高级的应用程序。

SQLight 和 LangChain SQL 代理

RAG 是一个已建立的技术,使用户能够与他们自己的数据进行交流。对于需要一些内部、无结构信息的情况来说,它非常强大。

虽然 RAG 在导航无结构信息方面表现出色,但如何询问与数据相关得多的信息呢? 比如,请给我所有至少有 4000 瓦特的产品。或者提供足够容纳所有产品的运输纸箱尺寸?

当涉及数据中心查询时,SQL 的精准性和结构就会发挥作用。

在SQLite数据库中管理我们的数据

为了管理我们的数据,需要在数据库中对其进行系统化处理。这里直观的步骤包括将数据结构化为SQLite中的关系表,以便执行一些更复杂的查询。

虽然不是强制性要求,但我建议添加以下备用步骤:定义映射我们 JSON 输出结构的类。

通过在数据库插入前集成这些,我们不仅简化了数据验证过程,还确保我们的数据符合预期格式。

如果解析后的 JSON 字典缺少未标记为可选项的必要属性,则可能有错误发生。

python复制代码import json

from typing import Any, List, Optional
from dataclasses import dataclass, field
@dataclass
class ProductFamily:
    watts_min: int
    watts_max: int
    temperature: Optional[int] = field(default=0)

    @staticmethod
    def from_dict(obj: Any) -> 'ProductFamily':
        _watts_min = int(obj.get("watts_min"))
        _watts_max = int(obj.get("watts_max"))
        _temperature = obj.get("temperature")
        return ProductFamily(_watts_min, _watts_max, _temperature)


@dataclass
class Product:
    name: str
    description: str
    benefits: List[str]
    product_family: ProductFamily

    @staticmethod
    def from_dict(obj: Any) -> 'Product':
        _name = str(obj.get("name"))
        _description = str(obj.get("description"))
        _benefits = obj.get("benefits")
        _product_family = ProductFamily.from_dict(obj.get("product_family"))
        return Product(_name, _description, _benefits, _product_family)

建立这些类之后,我们重新查看我们的PDF文档。

这一次我们将它们转换为JSON格式,并创建Product对象的实例。此外,我将所有处理过的文档移动到一个processed文件夹中。

python复制代码import traceback

pdf_files = [f for f in os.listdir('./documents') if f.endswith('.pdf')]
products = []

for pdf_file in pdf_files:
    json_content = None
    try:
        with open(f'./documents/{pdf_file}', 'rb') as file:
            pdf_reader = PdfReader(file)

            page_contents = []

            for page in pdf_reader.pages:
                page.extract_text(visitor_text=visitor_body)

            document_content = "\n".join(page_contents)

            json_content = convert_to_json(document_content)
            json_data = json.loads(json_content)

            product = Product.from_dict(json_data)
            products.append(product)
    except Exception as e:
        print("{filename} has a problem: {e}".format(filename=pdf_file, e=e))
        print(traceback.format_exc())
        print(json_content)
    else:
        os.rename(f'./documents/{pdf_file}', f'./processed/{pdf_file}')

上面的代码太简单了,就不做注释了。

现在我们已经编写了一个强大的产品实例列表,准备插入数据库表中。

对于我们的目前的功能来说,SQLite数据库就足够了。我们会创建三张表来存放我们的数据集:

  • 产品 — 产品的基本规格(名称,描述,长度)。
  • 产品应用 — 与特定产品相关联的应用程序列表。
  • 产品优势 — 与特定产品相关联的优势列表。

我们将执行以下步骤:

  • 初始化数据库并创建表格。
  • 为每个表格创建包含相关产品数据的元组。
  • 执行数据插入过程。

启动数据库并创建表格:

python复制代码import sqlite3
if(os.path.exists('./db') == False):
    os.makedirs('./db')

db_file = './db/products.db'

db_connection = sqlite3.connect(db_file)
db_cursor = db_connection.cursor()

db_cursor.execute('''CREATE TABLE IF NOT EXISTS Product
    (name TEXT PRIMARY KEY,
    description TEXT,
    temperature INTEGER,
    watts_min INTEGER,
    watts_max INTEGER,
    dimension_diameter REAL,
    dimension_length REAL,
    dimension_weight REAL,
    packaging_length INTEGER,
    packaging_width INTEGER,
    packaging_height INTEGER,
    packaging_weight REAL) WITHOUT ROWID
''')

db_cursor.execute('''
CREATE TABLE IF NOT EXISTS ProductApplication (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product TEXT,
    text TEXT NOT NULL,
    FOREIGN KEY (product) REFERENCES Product(name)
)
''')

db_cursor.execute('''
CREATE TABLE IF NOT EXISTS ProductBenefit (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    product TEXT,
    text TEXT NOT NULL,
    FOREIGN KEY (product) REFERENCES Product(name)
)
''')

db_connection.commit()

继续创建元组:

python复制代码products_sql_tuples = [(
    p.name,
    p.description,
    p.product_family.temperature,
    p.product_family.watts_min,
    p.product_family.watts_max,
    p.dimensions.diameter,
    p.dimensions.length,
    p.dimensions.weight,
    p.logistical_data.packaging_unit.length,
    p.logistical_data.packaging_unit.width,
    p.logistical_data.packaging_unit.height,
    p.logistical_data.packaging_unit.weight,) for p in products]

applications_sql_tuples = []
for product in products:
    applications_sql_tuples.extend([(product.name, application) for application in product.applications])

benefits_sql_tuples = []
for product in products:
    benefits_sql_tuples.extend([(product.name, benefit) for benefit in product.benefits])

最后插入数据:

python复制代码db_cursor.executemany('''
    REPLACE INTO Product (name, description, temperature, watts_min, watts_max, dimension_diameter, dimension_length, dimension_weight, packaging_length, packaging_width, packaging_height, packaging_weight)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', products_sql_tuples)

db_cursor.executemany('''
    REPLACE INTO ProductApplication (product, text)
    VALUES (?, ?)
''', applications_sql_tuples)

db_cursor.executemany('''
    REPLACE INTO ProductBenefit (product, text)
    VALUES (?, ?)
''', benefits_sql_tuples)

db_connection.commit()

不要忘记关闭光标和连接。

python复制代码db_cursor.close()
db_connection.close()

让我们来查看一下我们的数据库表格。这里和那里有些字段是NULL,只是因为产品数据表上没有相应的信息。所以没关系。

但所有重要信息都已解析并成功转换。所以我对结果非常满意!

img

使用 LangChain SQL Agent 查询信息

LangChain SQL Agent 提问!

LangChainSQL代理提供了一种动态与SQL数据库进行交互的方式。它擅长解释表结构并根据用户提示生成SQL查询。

使用SQL代理的主要优势包括:

  • 它可以根据数据库模式或内容(如描述特定表)来回答问题。
  • 它能通过运行生成的查询、捕获溯源并正确地再生来从错误中恢复。
  • 它可以根据需要多次查询数据库以回答用户的问题。
  • 只检索相关表的模式,从而节省token。

正如你所期待的那样,LangChain的代码非常清晰,即使在执行复杂操作时也是如此。

对于使用SQL Agent进行查询,这次我想要利用GPT-4。与需要导入大量文档并进行广泛处理相比,数据量较小且可控。

python复制代码from langchain_community.utilities import SQLDatabase
from langchain.chains import create_sql_query_chain
from langchain_openai import ChatOpenAI
from langchain_community.agent_toolkits import create_sql_agent

db = SQLDatabase.from_uri("sqlite:///db/products.db")
llm = ChatOpenAI(model="gpt-4-0125-preview", temperature=0)

agent_executor = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)

一切就绪。我们提出一些比较简单的问题,比如我们目前有多少种产品。

python复制代码prompt = "How many products do you have?"

result = agent_executor.invoke({"input": prompt})

它给出了一个完全正确的答案,包括 SQL 语句:

Invoking: sql_db_query with SELECT COUNT(\*) AS NumberOfProducts FROM Product [(20,)]

There are 20 products in the database .

虽然看起来很简单,SQL代理的能力不仅在于制定SQL查询,还包括识别现有的表格.

现在,让我们增加一些复杂性。我想找到一个适用于所有产品的包装尺寸。

python复制代码prompt = "I need to find a packaging size that works for all products. What size would that package have?"

result = agent_executor.invoke({"input": prompt})

To accommodate all products, the packaging size would need to have the following dimensions:

Length: 605 mm

Width: 420 mm

Height: 900 mm

Weight: 7177.0 grams

This size would work for all products in the database.

这是 SQL 代理设计的查询,用于检索所需信息:

sql_db_querywithSELECT MAX(packaging_length) AS max_length, MAX(packaging_width) AS max_width, MAX(packaging_height) AS max_height, MAX(packaging_weight) AS max_weight FROM Product

现在我们想得到更多信息!让我们询问具有最高可能温度及其用途的产品。

这些信息存储在另一个表中:

python复制代码prompt = "Provide the product with the highest possible temperature and it's applications."

result = agent_executor.invoke({"input": prompt})

完美,“SharXS 1500W Brilliant” 绝对是拥有最高可能温度的产品:

img

SQL Agent甚至聪明地找到了ProductApplication表上的引用:

img

总结:

GPT版本0125 可以完美地提供 JSON 格式的数据。OpenAI 致力于增强函数调用,并确保它符合用于创建可供计算机读取格式的标准用例。

如果设计目标正是针对这种情况,并且仅供企业内部员工使用,那么我会使用 SQL Agent 来处理企业数据库!

但是我觉得允许LLM模型自主执行查询依然风险太大了。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费
  • 14
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给出以下解答: 1. 情感分析 情感分析是一种通过自然语言处理技术来分析文本中所蕴含的情感信息的方法。通常情感分析会将文本分为积极、消极或中性三种情感类别。在对评论的txt文档进行情感分析时,我们可以使用机器学习算法或深度学习模型来实现。 常用的机器学习算法包括朴素贝叶斯、支持向量机和随机森林等,这些算法可以通过对大量已标注情感类别的文本数据进行训练,来预测新的文本的情感类别。 而深度学习模型则是通过构建多层神经网络来实现情感分析,比如目前比较流行的BERT、GPT模型。 2. 动态分析 动态分析是一种对软件或应用程序进行测试和评估的方法,通过模拟用户的使用行为来发现软件或应用程序的缺陷和问题。在对评论的txt文档进行动态分析时,我们可以使用自动化测试工具来模拟用户的行为,并观察软件或应用程序的响应情况。 自动化测试工具可以模拟用户的点击、滑动、输入等行为,通过对软件或应用程序的界面进行截图和分析,来发现潜在的问题和缺陷。同时,自动化测试工具还可以生成测试报告和日志,用于后续的分析和优化。 总之,对评论的txt文档进行情感分析和动态分析都是非常重要的,可以帮助我们了解用户的需求和反馈,同时也可以帮助我们优化软件或应用程序的性能和用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值