微信扫码
添加专属顾问
我要投稿
欢迎进入一个激动人心的领域:将大型语言模型(LLMs)与表格和 SQL 数据库等结构化数据相结合!想象一下,拥有一个超级智能的助手,可以“听懂”我们的需求并用数据库的“语言”交流,让获取所需信息变得前所未有的轻松。这不仅仅是简单的问答,而是在创造一种神奇般的体验。
在本文中,我们将深入探索这些强大模型如何在多个方面简化我们的工作。例如,它们可以理解我们的问题并自动生成数据库查询,帮助我们构建能够实时从数据库获取信息的聊天机器人,甚至允许我们创建定制化的仪表板来展示最关注的数据。
但这还只是开始——当 LLMs 的“智慧”与结构化数据的精确性相结合时,我们还能发现更多惊喜。因此,请准备好开启新的可能性,让与数据的互动变得更加轻松愉快!
CREATE DATABASE SalesOrderSchema;USE SalesOrderSchema;CREATE TABLE Customer (CustomerID INT AUTO_INCREMENT PRIMARY KEY,FirstName VARCHAR(100),LastName VARCHAR(100),Email VARCHAR(255),Phone VARCHAR(20),BillingAddress TEXT,ShippingAddress TEXT,CustomerSince DATE,IsActive BOOLEAN);CREATE TABLE SalesOrder (SalesOrderID INT AUTO_INCREMENT PRIMARY KEY,CustomerID INT,OrderDate DATE,RequiredDate DATE,ShippedDate DATE,Status VARCHAR(50),Comments TEXT,PaymentMethod VARCHAR(50),IsPaid BOOLEAN,FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID));CREATE TABLE Product (ProductID INT AUTO_INCREMENT PRIMARY KEY,ProductName VARCHAR(255),Description TEXT,UnitPrice DECIMAL(10, 2),StockQuantity INT,ReorderLevel INT,Discontinued BOOLEAN);CREATE TABLE LineItem (LineItemID INT AUTO_INCREMENT PRIMARY KEY,SalesOrderID INT,ProductID INT,Quantity INT,UnitPrice DECIMAL(10, 2),Discount DECIMAL(10, 2),TotalPrice DECIMAL(10, 2),FOREIGN KEY (SalesOrderID) REFERENCES SalesOrder(SalesOrderID),FOREIGN KEY (ProductID) REFERENCES Product(ProductID));CREATE TABLE Employee (EmployeeID INT AUTO_INCREMENT PRIMARY KEY,FirstName VARCHAR(100),LastName VARCHAR(100),Email VARCHAR(255),Phone VARCHAR(20),HireDate DATE,Position VARCHAR(100),Salary DECIMAL(10, 2));CREATE TABLE Supplier (SupplierID INT AUTO_INCREMENT PRIMARY KEY,CompanyName VARCHAR(255),ContactName VARCHAR(100),ContactTitle VARCHAR(50),Address TEXT,Phone VARCHAR(20),Email VARCHAR(255));CREATE TABLE InventoryLog (LogID INT AUTO_INCREMENT PRIMARY KEY,ProductID INT,ChangeDate DATE,QuantityChange INT,Notes TEXT,FOREIGN KEY (ProductID) REFERENCES Product(ProductID));
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SalesOrderSchema' ORDER BY TABLE_NAME, ORDINAL_POSITION;
生成并加载“客户”、“员工”和“产品”等表的数据。
安装和初始化 Faker:通过 pip 安装 Faker,用于生成虚拟数据(例如,姓名、地址、产品详情等),并确保数据逼真。
编写数据插入脚本:使用 Python 编写脚本,借助 mysql-connector-python 或 SQLAlchemy 等库将虚拟数据插入 MySQL 数据库。该脚本适用于数据库的测试和开发填充。
连接到 MySQL 数据库:连接至名为 SalesOrderSchema 的 MySQL 数据库,使用 root 用户并替换成实际密码。
创建游标并执行 SQL 命令:创建游标以执行 SQL 插入操作,生成 100 条客户记录,包括名字、邮箱、电话等。如果电话号码超出 20 个字符,自动截断。账单和送货地址均为生成的同一地址。
提交事务并关闭连接:插入数据后,通过 conn.commit() 提交变更,关闭游标和数据库连接。
#The code for loading data into the customer table#Customer Tableimport mysql.connectorfrom faker import Faker# Initialize Fakerfake = Faker()# Connect to MySQLconn = mysql.connector.connect(host="localhost",user="root",password="Your MySQL Password",database="SalesOrderSchema")cursor = conn.cursor()# Generate and insert datafor _ in range(100):# Let's say we want to generate 100 recordsfirst_name = fake.first_name()last_name = fake.last_name()email = fake.email()phone = fake.phone_number()if len(phone) > 20:# Assuming the 'Phone' column is VARCHAR(20)phone = phone[:20]# Truncate phone number to fit into the columnaddress = fake.address()customer_since = fake.date_between(start_date='-5y', end_date='today')is_active = fake.boolean()# Insert customer datacursor.execute("""INSERT INTO Customer (FirstName, LastName, Email, Phone, BillingAddress, ShippingAddress, CustomerSince, IsActive)VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (first_name, last_name, email, phone, address, address, customer_since, is_active))# Commit the transactionconn.commit()# Close the cursor and connectioncursor.close()conn.close()
#Employee Tableimport mysql.connectorfrom faker import Faker# Initialize Fakerfake = Faker()# Connect to MySQLconn = mysql.connector.connect(host="localhost",user="root",password="Your MySQL Password",database="SalesOrderSchema")cursor = conn.cursor()# Generate and insert 1000 employee recordsfor _ in range(1000):first_name = fake.first_name()last_name = fake.last_name()email = fake.email()phone = fake.phone_number()if len(phone) > 20:# Truncate phone number if necessaryphone = phone[:20]hire_date = fake.date_between(start_date='-5y', end_date='today')position = fake.job()salary = round(fake.random_number(digits=5), 2)# Generate a 5 digit salary# Insert employee datacursor.execute("""INSERT INTO Employee (FirstName, LastName, Email, Phone, HireDate, Position, Salary)VALUES (%s, %s, %s, %s, %s, %s, %s)""", (first_name, last_name, email, phone, hire_date, position, salary))# Commit the transactionconn.commit()# Close the cursor and connectioncursor.close()conn.close()print("1000 employee records inserted successfully.")
代理和 SQL 代理概括,人工智能代理(AI Agent)简介。
定义:AI代理是一种模拟人类智能的计算机程序,可以自主决策、交互环境或解决问题。
能力:
决策:根据数据或预设规则评估情况并做出选择。
解决问题:在复杂场景中实现特定目标或解决问题。
学习:通过数据或经验改进性能,这称为机器学习。
SQL代理概述
能力:
自然语言查询:支持用户通过自然语言与数据库交互,使非技术用户无需掌握SQL语法即可轻松提取信息。
人工智能辅助数据库交互:利用AI增强数据库交互,通过对话界面实现复杂查询、数据分析和洞察提取。
与语言模型集成:将AI语言模型与SQL数据库结合,实现自然语言输入的自动SQL查询生成,并将结果解释给用户。
成分:
语言模型:经过预训练的AI模型,能够理解并生成类似人类的文本。
查询生成:将自然语言请求转化为SQL查询的机制。
结果解释:将SQL查询结果转换成人类可读的格式或摘要。
应用:
数据探索:为非技术用户提供更直观的数据探索和分析方式。
商业智能:通过对话界面生成报告和洞察。
自动化:简化用户与数据库的交互,自动化查询生成和数据提取流程。
接下来,让我们看看如何使用SQL代理并进行文本到SQL的转换。
import osimport streamlit as stfrom langchain_openai import ChatOpenAIfrom langchain_community.utilities import SQLDatabasefrom langchain_community.agent_toolkits import create_sql_agent# Set your OpenAI API key hereos.environ["OPENAI_API_KEY"] = "Your OpenAI API Key"# Directly using database connection detailshost = "localhost"user = "root"password = "Your MySQL Password"database = "SalesOrderSchema"# Setup database connectiondb_uri = f"mysql+mysqlconnector://{user}:{password}@{host}/{database}"db = SQLDatabase.from_uri(db_uri)llm = ChatOpenAI(model="gpt-4", temperature=0)agent_executor = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True)# Streamlit app layoutst.title('SQL Chatbot')# User inputuser_query = st.text_area("Enter your SQL-related query:", "List Top 10 Employees by Salary?")if st.button('Submit'):#try:# Processing user input#response = agent_executor.invoke(user_query)#response = agent_executor.invoke({"query": user_query})#if st.button('Submit'):try:# Processing user inputresponse = agent_executor.invoke({"agent_scratchpad": "",# Assuming this needs to be an empty string if not used"input": user_query# Changed from "query" to "input"})st.write("Response:")st.json(response)# Use st.json to pretty print the response if it's a JSONexcept Exception as e:st.error(f"An error occurred: {e}")
导入库和模块:该脚本首先导入必要的库,例如 os、streamlit(如 st)以及来自 langchain_openai 和 langchain_community 的特定模块,用于创建和管理 SQL 聊天机器人。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2025-10-23
让打工人头疼的 Excel,被 AI 改造后……我居然玩上瘾了
2025-10-14
ChatBI 实体标准查询名优化实战:如何将准确率从 80% 提升到 90%
2025-09-29
大模型幻觉检测在 NL2SQL 任务的应用实践
2025-09-15
AI Agent重塑商业智能:2025技术融合路线图
2025-09-14
滴滴 ChatBl 技术实践:智能数据分析的前沿探索与应用
2025-09-12
AI重塑生产关系:IT部门不会消失,只会进化
2025-09-12
企业知识库构建最佳实践:ChatBI发展中的关键角色
2025-09-06
介绍菜鸟集团ChatBI在物流领域实践及招人
2025-09-15
2025-08-19
2025-08-24
2025-08-28
2025-09-03
2025-09-02
2025-08-23
2025-08-16
2025-09-06
2025-08-14
2025-09-02
2025-08-16
2025-08-14
2025-08-06
2025-07-29
2025-05-27
2025-05-27
2025-05-12