跳到主要內容

Kinetica 語言轉 SQL 聊天模型

本筆記本示範如何使用 Kinetica 將自然語言轉換為 SQL,並簡化資料檢索的流程。此示範旨在展示建立和使用鏈的機制,而不是 LLM 的功能。

總覽

透過 Kinetica LLM 工作流程,您可以在資料庫中建立 LLM 環境,以提供推論所需的資訊,包括表格、註解、規則和範例。呼叫 ChatKinetica.load_messages_from_context() 將從資料庫中檢索環境資訊,以便可用於建立聊天提示。

聊天提示包含 SystemMessage 和成對的 HumanMessage/AIMessage,其中包含問題/SQL 配對的範例。您可以將成對的範例附加到此清單,但其目的不是為了促進典型的自然語言對話。

當您從聊天提示建立鏈並執行它時,Kinetica LLM 將從輸入中產生 SQL。您可以選擇使用 KineticaSqlOutputParser 執行 SQL 並將結果以資料框架的形式傳回。

目前,SQL 產生支援 2 個 LLM

  1. Kinetica SQL-GPT:此 LLM 基於 OpenAI ChatGPT API。
  2. Kinetica SqlAssist:此 LLM 專為與 Kinetica 資料庫整合而建置,可以在安全的客戶場所中執行。

在此示範中,我們將使用 SqlAssist。如需更多資訊,請參閱 Kinetica 文件網站

先決條件

若要開始使用,您需要 Kinetica DB 執行個體。如果您沒有執行個體,可以取得免費開發執行個體

您需要安裝下列套件...

# Install Langchain community and core packages
%pip install --upgrade --quiet langchain-core langchain-community

# Install Kineitca DB connection package
%pip install --upgrade --quiet 'gpudb>=7.2.0.8' typeguard pandas tqdm

# Install packages needed for this tutorial
%pip install --upgrade --quiet faker ipykernel

資料庫連線

您必須在下列環境變數中設定資料庫連線。如果您使用的是虛擬環境,則可以在專案的 .env 檔案中設定它們

  • KINETICA_URL:資料庫連線 URL
  • KINETICA_USER:資料庫使用者
  • KINETICA_PASSWD:安全密碼。

如果您可以建立 KineticaChatLLM 的執行個體,則表示您已成功連線。

from langchain_community.chat_models.kinetica import ChatKinetica

kinetica_llm = ChatKinetica()

# Test table we will create
table_name = "demo.user_profiles"

# LLM Context we will create
kinetica_ctx = "demo.test_llm_ctx"
API 參考:ChatKinetica

建立測試資料

在我們可以產生 SQL 之前,我們需要建立 Kinetica 表格和可用於推論表格的 LLM 環境。

建立一些虛假使用者設定檔

我們將使用 faker 套件來建立包含 100 個虛假設定檔的資料框架。

from typing import Generator

import pandas as pd
from faker import Faker

Faker.seed(5467)
faker = Faker(locale="en-US")


def profile_gen(count: int) -> Generator:
for id in range(0, count):
rec = dict(id=id, **faker.simple_profile())
rec["birthdate"] = pd.Timestamp(rec["birthdate"])
yield rec


load_df = pd.DataFrame.from_records(data=profile_gen(100), index="id")
print(load_df.head())
         username             name sex  \
id
0 eduardo69 Haley Beck F
1 lbarrera Joshua Stephens M
2 bburton Paula Kaiser F
3 melissa49 Wendy Reese F
4 melissacarter Manuel Rios M

address mail \
id
0 59836 Carla Causeway Suite 939\nPort Eugene, I... meltondenise@yahoo.com
1 3108 Christina Forges\nPort Timothychester, KY... erica80@hotmail.com
2 Unit 7405 Box 3052\nDPO AE 09858 timothypotts@gmail.com
3 6408 Christopher Hill Apt. 459\nNew Benjamin, ... dadams@gmail.com
4 2241 Bell Gardens Suite 723\nScottside, CA 38463 williamayala@gmail.com

birthdate
id
0 1997-12-08
1 1924-08-03
2 1933-12-05
3 1988-10-26
4 1931-03-19

從資料框架建立 Kinetica 表格

from gpudb import GPUdbTable

gpudb_table = GPUdbTable.from_df(
load_df,
db=kinetica_llm.kdbc,
table_name=table_name,
clear_table=True,
load_data=True,
)

# See the Kinetica column types
print(gpudb_table.type_as_df())
        name    type   properties
0 username string [char32]
1 name string [char32]
2 sex string [char2]
3 address string [char64]
4 mail string [char32]
5 birthdate long [timestamp]

建立 LLM 環境

您可以使用 Kinetica Workbench UI 建立 LLM 環境,也可以使用 CREATE OR REPLACE CONTEXT 語法手動建立。

在這裡,我們從參考我們建立的表格的 SQL 語法建立環境。

from gpudb import GPUdbSamplesClause, GPUdbSqlContext, GPUdbTableClause

table_ctx = GPUdbTableClause(table=table_name, comment="Contains user profiles.")

samples_ctx = GPUdbSamplesClause(
samples=[
(
"How many male users are there?",
f"""
select count(1) as num_users
from {table_name}
where sex = 'M';
""",
)
]
)

context_sql = GPUdbSqlContext(
name=kinetica_ctx, tables=[table_ctx], samples=samples_ctx
).build_sql()

print(context_sql)
count_affected = kinetica_llm.kdbc.execute(context_sql)
count_affected
CREATE OR REPLACE CONTEXT "demo"."test_llm_ctx" (
TABLE = "demo"."user_profiles",
COMMENT = 'Contains user profiles.'
),
(
SAMPLES = (
'How many male users are there?' = 'select count(1) as num_users
from demo.user_profiles
where sex = ''M'';' )
)
1

使用 Langchain 進行推論

在以下範例中,我們將從先前建立的表格和 LLM 環境建立鏈。此鏈將產生 SQL 並將結果資料以資料框架的形式傳回。

從 Kinetica DB 載入聊天提示

load_messages_from_context() 函數將從 DB 檢索環境,並將其轉換為我們用來建立 ChatPromptTemplate 的聊天訊息清單。

from langchain_core.prompts import ChatPromptTemplate

# load the context from the database
ctx_messages = kinetica_llm.load_messages_from_context(kinetica_ctx)

# Add the input prompt. This is where input question will be substituted.
ctx_messages.append(("human", "{input}"))

# Create the prompt template.
prompt_template = ChatPromptTemplate.from_messages(ctx_messages)
prompt_template.pretty_print()
API 參考:ChatPromptTemplate
================================ System Message ================================

CREATE TABLE demo.user_profiles AS
(
username VARCHAR (32) NOT NULL,
name VARCHAR (32) NOT NULL,
sex VARCHAR (2) NOT NULL,
address VARCHAR (64) NOT NULL,
mail VARCHAR (32) NOT NULL,
birthdate TIMESTAMP NOT NULL
);
COMMENT ON TABLE demo.user_profiles IS 'Contains user profiles.';

================================ Human Message =================================

How many male users are there?

================================== Ai Message ==================================

select count(1) as num_users
from demo.user_profiles
where sex = 'M';

================================ Human Message =================================

{input}

建立鏈

此鏈的最後一個元素是 KineticaSqlOutputParser,它將執行 SQL 並傳回資料框架。這是選用的,如果我們省略它,則只會傳回 SQL。

from langchain_community.chat_models.kinetica import (
KineticaSqlOutputParser,
KineticaSqlResponse,
)

chain = prompt_template | kinetica_llm | KineticaSqlOutputParser(kdbc=kinetica_llm.kdbc)

產生 SQL

我們建立的鏈將以問題作為輸入,並傳回包含產生的 SQL 和資料的 KineticaSqlResponse。問題必須與我們用來建立提示的 LLM 環境相關。

# Here you must ask a question relevant to the LLM context provided in the prompt template.
response: KineticaSqlResponse = chain.invoke(
{"input": "What are the female users ordered by username?"}
)

print(f"SQL: {response.sql}")
print(response.dataframe.head())
SQL: SELECT username, name
FROM demo.user_profiles
WHERE sex = 'F'
ORDER BY username;
username name
0 alexander40 Tina Ramirez
1 bburton Paula Kaiser
2 brian12 Stefanie Williams
3 brownanna Jennifer Rowe
4 carl19 Amanda Potts

此頁面是否對您有幫助?