1. Giới thiệu
Trong lớp học lập trình này, bạn sẽ kết nối mô hình Jev của AI TypeSafe với AlloyDB AI bằng các hàm AI gốc của AlloyDB (ai.if, ai.analyze_sentiment và ml_predict_row). Nhờ đó, bạn có thể chạy suy luận theo lô hiệu quả bằng mô hình Jev ngay trên dữ liệu hoạt động của mình trong AlloyDB mà không cần di chuyển dữ liệu hoặc viết mã phức tạp phía ứng dụng.
Bạn sẽ thực hiện
- Cung cấp Quyền truy cập dịch vụ riêng tư (PSA) và một cụm AlloyDB cho PostgreSQL cũng như phiên bản chính
- Tạo một quy tắc tường lửa VPC cho phép Cloud Shell và kết nối nội bộ
- Tải một tập dữ liệu mẫu thương mại điện tử bằng cách sử dụng
gcloud alloydb clusters import - Bật Google Secret Manager và tiện ích
google_ml_integrationcủa AlloyDB - Lưu trữ và cấp quyền truy cập vào khoá API AI TypeSafe trong Secret Manager
- Tạo các hàm chuyển đổi đầu vào và đầu ra PL/pgSQL cho các nguyên hàm
noul(boolean) vàchoice(cảm xúc) của Jev - Đăng ký điểm cuối mô hình
jev-modeltuỳ chỉnh trong AlloyDB - Chạy các truy vấn ngữ nghĩa theo lô mảng và vô hướng (
ai.ifvàai.analyze_sentiment) ngay trong SQL - Truy vấn bài đánh giá sản phẩm thực tế của khách hàng để phân loại cảm xúc bằng cách sử dụng
ai.analyze_sentiment - (Phần thưởng) Đăng ký một điểm cuối chung (
jev-systemone) và đánh giá mức độ hài lòng liên tục của khách hàng bằng cách sử dụng nguyên hàmscorecủa Jev
Bạn cần có
- Một trình duyệt web như Chrome
- Một dự án trên Google Cloud đã bật tính năng thanh toán
- Khoá API AI TypeSafe (từ TypeSafe AI)
2. Trước khi bắt đầu
Chọn dự án trên đám mây của bạn trên Google Cloud
Trong Google Cloud Console, hãy chọn hoặc tạo dự án trên đám mây mà bạn muốn sử dụng.
Khởi động Cloud Shell
Nhấp vào Kích hoạt Cloud Shell ở trên cùng bên phải của Cloud Console.
Xác minh rằng phiên Cloud Shell của bạn đã được xác thực:
gcloud auth list
Đặt mã dự án và các biến môi trường:
export PROJECT_ID=$(gcloud config get-value project)
gcloud config set project $PROJECT_ID
export REGION="us-west4"
export ADBCLUSTER="my-alloydb-cluster"
export ADBINSTANCE="my-alloydb-primary"
Bật các API bắt buộc của Google Cloud
Chạy lệnh này để bật tất cả các API dịch vụ cần thiết của Google Cloud:
gcloud services enable \
alloydb.googleapis.com \
servicenetworking.googleapis.com \
secretmanager.googleapis.com \
compute.googleapis.com
3. Cung cấp Cụm AlloyDB và Phiên bản chính
Trong bước này, bạn sẽ phân bổ một dải IP Quyền truy cập dịch vụ riêng tư trong mạng VPC, thiết lập quan hệ ngang hàng riêng tư và cung cấp cụm AlloyDB cũng như thực thể chính có quyền truy cập Internet đi ra.
1. Tạo dải IP Private Service Access (PSA)
AlloyDB yêu cầu phân bổ dải IP riêng tư trong mạng Virtual Private Cloud (VPC). Giả sử bạn đang sử dụng mạng VPC default:
Tạo chế độ phân bổ dải IP riêng tư:
gcloud compute addresses create psa-range \
--global \
--purpose=VPC_PEERING \
--prefix-length=24 \
--description="VPC private service access" \
--network=default
Thiết lập kết nối VPC Peering riêng tư:
gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=psa-range \
--network=default
2. Tạo Cụm AlloyDB
Tạo mật khẩu cơ sở dữ liệu an toàn cho người dùng có quyền quản trị postgres ban đầu:
export PGPASSWORD="$(openssl rand -hex 8)@1aA"
echo "Your generated AlloyDB postgres password is: $PGPASSWORD"
Tạo một cụm dùng thử miễn phí AlloyDB:
gcloud alloydb clusters create $ADBCLUSTER \
--password=$PGPASSWORD \
--network=default \
--region=$REGION
3. Tạo phiên bản chính bằng Cờ AI và Khả năng kết nối đi
AlloyDB kết nối trực tiếp với điểm cuối SaaS bảo mật của TypeSafe AI (https://api.typesafe.ai/v1/systemone) qua HTTPS đi ra. Do đó, bạn phải chỉ định --outbound-public-ip. Ngoài ra, hãy định cấu hình cờ cơ sở dữ liệu AI của AlloyDB cho môi trường:
gcloud alloydb instances create $ADBINSTANCE \
--instance-type=PRIMARY \
--cpu-count=2 \
--region=$REGION \
--cluster=$ADBCLUSTER \
--outbound-public-ip \
--ssl-mode=ALLOW_UNENCRYPTED_AND_ENCRYPTED \
--database-flags=\
google_ml_integration.enable_model_support=on,\
google_ml_integration.enable_ai_query_engine=on,\
google_ml_integration.enable_ai_function_acceleration=on,\
google_ml_integration.enable_cost_optimized_ai_functions=on,\
parameterized_views.enabled=on,\
password.enforce_complexity=on,\
password.min_uppercase_letters=1,\
password.min_numerical_chars=1,\
password.min_pass_length=10
4. Tải dữ liệu mẫu về thương mại điện tử
Để kiểm thử các truy vấn ngữ nghĩa thực tế, hãy nhập một tập dữ liệu mẫu về thương mại điện tử có chứa danh mục sản phẩm và bài đánh giá của khách hàng ngay từ Cloud Storage:
gcloud alloydb clusters import $ADBCLUSTER \
--region=$REGION \
--project=$PROJECT_ID \
--gcs-uri="gs://sample-data-and-media/ecomm-retail/ecom_generic.sql" \
--sql \
--database=postgres \
--user=postgres
4. Lưu trữ Khoá API TypeSafe AI trong Secret Manager
Tính năng Quản lý điểm cuối mô hình của AlloyDB tích hợp nguyên bản với Google Secret Manager để xác thực các lệnh gọi API bên ngoài mà không để lộ thông tin đăng nhập ở dạng văn bản thuần tuý trong mã cơ sở dữ liệu hoặc nhật ký cấu hình.
1. Tạo mã bí mật
Trong Cloud Shell, hãy tạo một khoá bí mật mới có tên là typesafe-jev-api-key:
gcloud secrets create typesafe-jev-api-key \
--replication-policy="automatic"
Thêm khoá API AI TypeSafe làm phiên bản bí mật:
echo -n "<YOUR_TYPESAFE_API_KEY>" | \
gcloud secrets versions add typesafe-jev-api-key --data-file=-
2. Cấp quyền truy cập cho Tác nhân dịch vụ AlloyDB
AlloyDB sử dụng tác nhân dịch vụ dự án để truy xuất các khoá bí mật trong quá trình thực thi truy vấn. Tìm số dự án của bạn và cấp vai trò Secret Accessor:
PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
ALLOYDB_SA="service-${PROJECT_NUMBER}@gcp-sa-alloydb.iam.gserviceaccount.com"
gcloud secrets add-iam-policy-binding typesafe-jev-api-key \
--member="serviceAccount:${ALLOYDB_SA}" \
--role="roles/secretmanager.secretAccessor"
Bạn sẽ thấy đầu ra xác nhận rằng tác nhân dịch vụ đã nhận được roles/secretmanager.secretAccessor.
5. Kết nối với AlloyDB thông qua AlloyDB Studio và Khởi động các tiện ích cơ sở dữ liệu
Để tương tác trực tiếp với cơ sở dữ liệu AlloyDB từ trình duyệt mà không cần định cấu hình các công cụ máy khách cục bộ hoặc đường hầm proxy, hãy sử dụng AlloyDB Studio trong Google Cloud Console.
1. Mở AlloyDB Studio
- Trong Bảng điều khiển Google Cloud, hãy chuyển đến AlloyDB cho PostgreSQL > Cụm.
- Nhấp vào cụm của bạn (
my-alloydb-cluster). - Trong trình đơn điều hướng bên trái, hãy nhấp vào AlloyDB Studio.
- Xác thực với cơ sở dữ liệu:
- Cơ sở dữ liệu:
postgres - Người dùng:
postgres - Mật khẩu: Nhập
$PGPASSWORDđược tạo trong quá trình tạo cụm (ví dụ: chạyecho $PGPASSWORDtrong Cloud Shell để xem mật khẩu).
- Cơ sở dữ liệu:
- Nhấp vào Xác thực.
Giờ đây, bạn đang ở trong trình chỉnh sửa truy vấn SQL tương tác của AlloyDB Studio.
2. Bật cờ và tiện ích cơ sở dữ liệu
Trong trình chỉnh sửa truy vấn AlloyDB Studio, hãy dán và chạy các câu lệnh sau để bật tiện ích google_ml_integration và định cấu hình chế độ cài đặt thời gian chạy:
-- Enable the AlloyDB AI integration extension
CREATE EXTENSION IF NOT EXISTS google_ml_integration;
-- Enable preview AI functions (ai.analyze_sentiment, ai.classify)
SET google_ml_integration.enable_preview_ai_functions = 'on';
-- Disable async batching for the session to use custom transform functions directly
SET google_ml_integration.enable_async_operation = 'off';
Nhấp vào Run (Chạy) để thực thi truy vấn.
3. Đăng ký Khoá bí mật trong AlloyDB MEM
Cho AlloyDB biết nơi tìm khoá API AI TypeSafe:
CALL google_ml.create_sm_secret(
secret_id => 'jev_api_key',
secret_path => 'projects/<YOUR_PROJECT_ID>/secrets/typesafe-jev-api-key/versions/latest'
);
6. Tạo hàm biến đổi SQL
System One API của TypeSafe AI chấp nhận JSON có cấu trúc với các nguyên tắc suy luận riêng biệt (noul cho các ràng buộc Boolean, choice cho phân loại đa mục).
Tính năng Quản lý điểm cuối mô hình của AlloyDB sử dụng 4 hàm biến đổi (đầu vào vô hướng, đầu ra vô hướng, đầu vào theo lô, đầu ra theo lô) để kết nối các chữ ký hàm ai.* PostgreSQL tiêu chuẩn với định dạng API REST Jev.
1. Biến đổi đầu vào vô hướng
Thêm hàm sau để chuyển đổi các lệnh gọi ai.if và ai.analyze_sentiment một hàng thành tải trọng yêu cầu Jev:
CREATE OR REPLACE FUNCTION public.jev_model_input_transform(
model_id VARCHAR(100),
input_text TEXT,
generation_config JSON,
system_instruction TEXT
) RETURNS JSON
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
full_instruction TEXT;
enum_json JSON;
criteria_obj JSONB := '{}'::JSONB;
elem TEXT;
q_obj JSON;
BEGIN
-- Combine optional system instructions with the input prompt
IF system_instruction IS NOT NULL AND length(trim(system_instruction)) > 0 THEN
full_instruction := system_instruction || E'\n\n' || input_text;
ELSE
full_instruction := input_text;
END IF;
-- Inspect generation_config to determine whether caller expects a multi-class choice or boolean
enum_json := COALESCE(
generation_config->'generationConfig'->'responseSchema'->'enum',
generation_config->'responseSchema'->'enum'
);
IF enum_json IS NOT NULL AND json_typeof(enum_json) = 'array' THEN
-- Multi-class classification (ai.analyze_sentiment) -> Jev choice primitive
FOR elem IN SELECT json_array_elements_text(enum_json) LOOP
criteria_obj := criteria_obj || jsonb_build_object(elem, 'Category: ' || elem);
END LOOP;
q_obj := json_build_object(
'type', 'choice',
'instructions', full_instruction,
'criteria', criteria_obj::JSON
);
ELSE
-- Boolean filtering (ai.if) -> Jev noul primitive
q_obj := json_build_object(
'type', 'noul',
'instructions', full_instruction
);
END IF;
RETURN json_build_object(
'model', 'jev-latest',
'state', COALESCE(generation_config->>'state', 'Evaluate the question accurately based on the provided text.'),
'questions', json_build_object('q_1', q_obj)
);
END;
$$;
2. Biến đổi đầu ra vô hướng
Thêm hàm để giải nén phản hồi JSON của Jev trở lại kết quả TEXT của PostgreSQL:
CREATE OR REPLACE FUNCTION public.jev_model_output_transform(
model_id VARCHAR(100),
response_json JSON
) RETURNS TEXT
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
q_ans JSON := response_json->'answers'->'q_1';
ans_type TEXT := q_ans->>'type';
BEGIN
IF ans_type = 'choice' THEN
RETURN q_ans->>'choice';
ELSIF ans_type = 'noul' THEN
-- Convert probability score (0.00 to 1.00) to boolean text
RETURN CASE WHEN (q_ans->>'noul')::FLOAT >= 0.50 THEN 'true' ELSE 'false' END;
ELSE
RAISE EXCEPTION 'Unexpected Jev response payload: %', response_json::TEXT;
END IF;
END;
$$;
3. Chuyển đổi dữ liệu đầu vào hàng loạt
Jev có thể đánh giá đồng thời hàng chục câu hỏi trong một chuyến khứ hồi HTTP duy nhất mà không làm giảm khả năng tạo nội dung.
Thêm biến đổi đầu vào hàng loạt để chuyển đổi các mảng prompts TEXT[] PostgreSQL thành các câu hỏi q_1 .. q_N Jev song song:
CREATE OR REPLACE FUNCTION public.jev_model_batch_input_transform(
model_id VARCHAR(100),
prompts TEXT[],
generation_config JSON,
system_instructions JSON
) RETURNS JSON
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
questions_obj JSONB := '{}'::JSONB;
enum_json JSON;
criteria_obj JSONB := '{}'::JSONB;
elem TEXT;
is_choice BOOLEAN := FALSE;
i INT;
BEGIN
enum_json := COALESCE(
generation_config->'generationConfig'->'responseSchema'->'items'->'enum',
generation_config->'generationConfig'->'responseSchema'->'enum',
generation_config->'responseSchema'->'items'->'enum',
generation_config->'responseSchema'->'enum'
);
IF enum_json IS NOT NULL AND json_typeof(enum_json) = 'array' THEN
IF NOT (enum_json::JSONB = '["true", "false"]'::JSONB OR enum_json::JSONB = '["false", "true"]'::JSONB) THEN
is_choice := TRUE;
FOR elem IN SELECT json_array_elements_text(enum_json) LOOP
criteria_obj := criteria_obj || jsonb_build_object(elem, 'Category: ' || elem);
END LOOP;
END IF;
END IF;
-- Construct parallel questions for every prompt in the array
FOR i IN 1 .. COALESCE(array_length(prompts, 1), 0) LOOP
IF is_choice THEN
questions_obj := questions_obj || jsonb_build_object(
'q_' || i::TEXT,
jsonb_build_object(
'type', 'choice',
'instructions', prompts[i],
'criteria', criteria_obj
)
);
ELSE
questions_obj := questions_obj || jsonb_build_object(
'q_' || i::TEXT,
jsonb_build_object(
'type', 'noul',
'instructions', prompts[i]
)
);
END IF;
END LOOP;
RETURN json_build_object(
'model', 'jev-latest',
'state', COALESCE(generation_config->>'state', 'Evaluate each question independently based on the record data.'),
'questions', questions_obj::JSON
);
END;
$$;
4. Biến đổi đầu ra hàng loạt
Thêm hàm để trích xuất câu trả lời theo đúng thứ tự chỉ mục mảng 1..N:
CREATE OR REPLACE FUNCTION public.jev_model_batch_output_transform(
model_id VARCHAR(100),
response JSON
) RETURNS TEXT[]
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
results TEXT[] := ARRAY[]::TEXT[];
answers JSON := response->'answers';
i INT := 1;
q_ans JSON;
ans_type TEXT;
BEGIN
LOOP
q_ans := answers->('q_' || i::TEXT);
EXIT WHEN q_ans IS NULL;
ans_type := q_ans->>'type';
IF ans_type = 'choice' THEN
results := array_append(results, q_ans->>'choice');
ELSE
results := array_append(results, CASE WHEN (q_ans->>'noul')::FLOAT >= 0.50 THEN 'true' ELSE 'false' END);
END IF;
i := i + 1;
END LOOP;
RETURN results;
END;
$$;
7. Đăng ký Điểm cuối của mô hình tuỳ chỉnh trong AlloyDB
Bây giờ, bạn sẽ liên kết các hàm biến đổi, thông tin đăng nhập bí mật và điểm cuối REST AI TypeSafe với nhau thành một mô hình đã đăng ký có tên là jev-model.
1. Đăng ký jev-model
Trong trình chỉnh sửa truy vấn AlloyDB Studio, hãy dán và chạy:
-- Drop previous registration if updating
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM google_ml.model_info_view WHERE model_id = 'jev-model') THEN
CALL google_ml.drop_model('jev-model');
END IF;
END $$;
-- Register custom LLM endpoint
CALL google_ml.create_model(
model_id => 'jev-model',
model_request_url => 'https://api.typesafe.ai/v1/systemone',
model_provider => 'custom',
model_type => 'llm',
model_qualified_name => 'jev-latest',
model_auth_type => 'secret_manager',
model_auth_id => 'jev_api_key',
model_in_transform_fn => 'jev_model_input_transform',
model_out_transform_fn => 'jev_model_output_transform',
model_batch_in_transform_fn => 'jev_model_batch_input_transform',
model_batch_out_transform_fn => 'jev_model_batch_output_transform'
);
2. Xác minh yêu cầu đăng ký
Truy vấn chế độ xem sổ đăng ký mô hình để đảm bảo jev-model đang hoạt động và được nhận dạng:
SELECT model_id, model_type, model_provider, model_auth_type
FROM google_ml.model_info_view
WHERE model_id = 'jev-model';
Bạn sẽ thấy kết quả tương tự như sau:
model_id | model_type | model_provider | model_auth_type ----------+------------+----------------+----------------- jev-model | llm | custom | secret_manager (1 row)
8. Chạy các truy vấn kiểm thử đối với Jev
Sau khi đăng ký jev-model, giờ đây, bạn có thể thực hiện các thao tác ngữ nghĩa ngay trong các truy vấn PostgreSQL tiêu chuẩn.
1. Thử nghiệm lọc giá trị vô hướng Boolean (ai.if)
Đánh giá một câu lệnh văn bản bằng cách sử dụng ai.if:
SELECT ai.if(
prompt => 'Is the product "North Face Waterproof Gore-Tex Hiking Jacket ($249)" suitable for rainy outdoor conditions?',
model_id => 'jev-model'
) AS is_suitable;
Bạn sẽ thấy kết quả tương tự như sau:
is_suitable ------------- true (1 row)
2. Thử nghiệm Phân tích cảm xúc theo thang (ai.analyze_sentiment)
Đánh giá ý kiến phản hồi của khách hàng thành một nhãn phân loại (positive, negative hoặc neutral):
SET google_ml_integration.enable_preview_ai_functions = 'on';
SELECT ai.analyze_sentiment(
input => 'The stitching on this jacket tore on the second day and the zipper jammed completely.',
model_id => 'jev-model'
) AS sentiment;
Bạn sẽ thấy kết quả tương tự như sau:
sentiment ----------- negative (1 row)
3. Kiểm thử tính năng Lọc theo lô bằng mảng Boolean
Đánh giá nhiều mục trong một truy vấn bằng cách truyền một mảng câu lệnh:
SET google_ml_integration.enable_async_operation = 'off';
SELECT unnest(prompts) AS product_prompt,
unnest(ai.if(prompts => prompts, model_id => 'jev-model')) AS is_cold_weather
FROM (
SELECT ARRAY[
'Is "Arctic Expedition Down Parka (-30F)" cold-weather winter outerwear?',
'Is "Men''s Boardshorts Beach Swim Trunk" cold-weather winter outerwear?',
'Is "Merino Wool Thermal Base Layer" cold-weather winter outerwear?'
] AS prompts
) b;
Bạn sẽ thấy kết quả tương tự như sau:
product_prompt | is_cold_weather -------------------------------------------------------------------------+----------------- Is "Arctic Expedition Down Parka (-30F)" cold-weather winter outerwear? | true Is "Men's Boardshorts Beach Swim Trunk" cold-weather winter outerwear? | false Is "Merino Wool Thermal Base Layer" cold-weather winter outerwear? | false (3 rows)
4. Kiểm thử truy vấn bảng bằng tính năng nhóm mảng
Giờ đây, hãy truy vấn bảng ecomm.products đã tải trước đó trong quá trình cung cấp cụm, bằng cách sử dụng ai.if trên một lô mặt hàng để kiểm tra xem sản phẩm nào trong danh mục là thiết bị dùng trong thời tiết lạnh.
Để chạy tính năng lọc ngữ nghĩa có thông lượng cao trên dữ liệu bảng (ví dụ: 50 hàng mỗi lô), hãy sử dụng hàm cửa sổ row_number() của PostgreSQL để chia các hàng thành lô:
-- Evaluate a 50-row batch of real catalog items from ecomm.products
WITH numbered AS (
SELECT
id,
name,
category,
product_description,
((row_number() OVER (ORDER BY id) - 1) / 50) AS batch_id
FROM ecomm.products
ORDER BY id DESC
LIMIT 50
),
batched AS (
SELECT
batch_id,
array_agg(id ORDER BY id) AS ids,
array_agg(name ORDER BY id) AS names,
array_agg(category ORDER BY id) AS categories,
array_agg(product_description ORDER BY id) AS descs,
ai.if(
prompts => array_agg('Is "' || name || '" designed for cold weather winter outerwear?' ORDER BY id),
model_id => 'jev-model'
) AS decisions
FROM numbered
GROUP BY batch_id
),
unrolled AS (
SELECT
b.batch_id,
u.id,
u.name,
u.category,
u.product_description,
u.decision AS cold_weather_gear
FROM batched b
CROSS JOIN LATERAL unnest(b.ids, b.names, b.categories, b.descs, b.decisions)
AS u(id, name, category, product_description, decision)
)
SELECT id, name, category, product_description, cold_weather_gear
FROM unrolled
WHERE cold_weather_gear = TRUE
LIMIT 5;
Bạn sẽ thấy kết quả tương tự như sau:
id | name | category | product_description | cold_weather_gear -------+----------------------------------------------------------------------+-------------+--------------------------------------------------------------------------------------------------------------------+------------------- 29071 | Winter Striped Beanie with Pom | Accessories | Brave the chill in style with the SoleStyle Winter Striped Beanie! This cozy beanie adds a pop of personality... | true 29077 | Knit Collegiate Rugby Stripe Winter Scarf & Beanie Hat Set | Accessories | Stay cozy and show off your sporty side with our Knit Collegiate Rugby Stripe Scarf & Beanie Set... | true 29083 | Junction Finds Men's Muscle Wool Blend Trapper Hat | Accessories | Brave the elements in style with the Junction Finds Trapper Hat! This wool-blend hat will keep you warm... | true 29086 | Mens Soft Thermal Insulated Wrist Length Leather Gloves - Black | Accessories | Brave the chill in style with these supple leather gloves from Gavel Goods! Lined with a soft, thermal knit... | true 29090 | Long Beanie-Red W16S24E | Accessories | Stay cozy and stylish all season long with this vibrant red beanie from Enchant! This isn't just any hat... | true (5 rows)
5. Truy vấn bài đánh giá sản phẩm của khách hàng để biết cảm xúc
Giờ đây, hãy phân tích các bài đánh giá của khách hàng trong bảng ecomm.product_reviews bằng cách sử dụng ai.analyze_sentiment được hỗ trợ bởi nguyên tắc cơ bản choice của Jev:
SET google_ml_integration.enable_preview_ai_functions = 'on'
SELECT
r.id,
p.name AS product_name,
r.rating AS customer_star_rating,
substring(r.review_text FROM 1 FOR 70) || '...' AS review_snippet,
ai.analyze_sentiment(
input => r.review_text,
model_id => 'jev-model'
) AS detected_sentiment
FROM ecomm.product_reviews r
JOIN ecomm.products p ON r.product_id = p.id
ORDER BY r.id
LIMIT 5;
Bạn sẽ thấy kết quả tương tự như sau:
id | product_name | customer_star_rating | review_snippet | detected_sentiment ----+------------------------------------------------+----------------------+-------------------------------------------------------------------------+-------------------- 1 | Hugs & Kisses Juniors Peplum Skirt | 1 | This skirt was poorly made and the fabric felt extremely cheap for for...| negative 2 | Bonkers Larry Full Length Pull on Pants | 1 | These pants are way too expensive for the terrible quality you get. Th...| negative 3 | Gifts and Garb Brah Bra Extenders | 3 | These extenders are okay but nothing special. They do add a bit of ext...| neutral 4 | Auto Forge Men's Tall Duck Traditional Coat | 1 | This coat is terribly stiff and heavy, making it very uncomfortable to...| negative 5 | Weaver's Way Men's Shetland Zip Neck Sweater | 2 | This sweater is just okay and not really worth the high price tag. The...| negative (5 rows)
9. Phần thưởng: Tính năng chấm điểm cảm xúc liên tục bằng Jevscore
Mặc dù các hàm AI của AlloyDB như ai.analyze_sentiment trả về các nhóm phân loại (positive, negative, neutral), nhưng nguyên tắc cơ bản score của AI TypeSafe đánh giá sắc thái theo một tiêu chí chấm điểm có thứ tự và trả về một điểm xếp hạng liên tục, có trọng số kỳ vọng từ 0 đến 100.
Vì score trả về siêu dữ liệu dạng số thay vì nhãn phân loại văn bản, nên bạn có thể đăng ký một điểm cuối mô hình generic tuỳ chỉnh (jev-systemone) và gọi điểm cuối đó bằng cách sử dụng google_ml.predict_row.
1. Đăng ký Điểm cuối chung
Trong AlloyDB Studio, hãy đăng ký jev-systemone bằng model_type => 'generic':
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM google_ml.model_info_view WHERE model_id = 'jev-systemone') THEN
CALL google_ml.drop_model('jev-systemone');
END IF;
EXCEPTION WHEN OTHERS THEN
NULL;
END $$;
CALL google_ml.create_model(
model_id => 'jev-systemone',
model_request_url => 'https://api.typesafe.ai/v1/systemone',
model_provider => 'custom',
model_type => 'generic',
model_qualified_name => 'jev-latest',
model_auth_type => 'secret_manager',
model_auth_id => 'jev_api_key'
);
2. Chạy quy trình Đánh giá nhiều tác vụ (Điểm số Boolean + Liên tục)
Đồng thời đánh giá cả chế độ kiểm tra boolean về lỗi (noul) và cường độ cảm xúc liên tục (score) trong một lệnh gọi HTTP duy nhất:
SELECT jsonb_pretty(google_ml.predict_row(
model_id => 'jev-systemone',
request_body => json_build_object(
'model', 'jev-latest',
'state', 'Review for North Face Parka: "The zipper broke on day 3 and customer service refused an exchange, though the fabric itself is very soft."',
'questions', json_build_object(
'has_defect', json_build_object(
'type', 'noul',
'instructions', 'Does this review report a physical product defect or failure?'
),
'satisfaction_score', json_build_object(
'type', 'score',
'instructions', 'Rate the customer sentiment and satisfaction on a 1-5 scale.',
'criteria', json_build_array(
'1: Extremely dissatisfied / defect failure',
'2: Dissatisfied',
'3: Mixed or neutral',
'4: Satisfied',
'5: Delighted'
)
)
)
)
)::jsonb) AS jev_analysis;
Bạn sẽ thấy kết quả tương tự như sau (kết quả của bạn có thể khác):
{
"model": "jev-1.13.0",
"usage": {
"input_tokens": 388,
"output_tokens": 39
},
"answers": {
"has_defect": {
"noul": 0.98,
"type": "noul"
},
"satisfaction_score": {
"type": "score",
"score": 0.11,
"legend": {
"0": "1: Extremely dissatisfied / defect failure",
"1": "2: Dissatisfied",
"2": "3: Mixed or neutral",
"3": "4: Satisfied",
"4": "5: Delighted"
},
"confidence": 0.91,
"probabilities": {
"0": 0.9,
"1": 0.08,
"2": 0.02,
"3": 0.0,
"4": 0.0
}
}
}
}
Xin lưu ý rằng satisfaction_score được đánh giá là 11 / 100, thể hiện chính xác rằng khách hàng có trải nghiệm chủ yếu là tiêu cực mặc dù thừa nhận rằng chất liệu vải mềm!
10. Dọn dẹp
Để tránh bị tính phí liên tục cho các tài nguyên được tạo trong lớp học lập trình này, hãy dọn dẹp các đối tượng bí mật và cơ sở dữ liệu, đồng thời xoá cụm AlloyDB.
1. Xoá tài nguyên Secret Manager
Trong Cloud Shell, hãy xoá khoá bí mật được tạo cho khoá API TypeSafe AI:
gcloud secrets delete typesafe-jev-api-key --quiet
2. Xoá Cụm và phiên bản chính AlloyDB
Trước tiên, hãy xoá phiên bản chính:
gcloud alloydb instances delete $ADBINSTANCE \
--cluster=$ADBCLUSTER \
--region=$REGION \
--quiet
Sau khi xoá xong phiên bản, hãy xoá cụm:
gcloud alloydb clusters delete $ADBCLUSTER \
--region=$REGION \
--quiet
11. Xin chúc mừng
Xin chúc mừng! Bạn đã cung cấp thành công một cụm AlloyDB trên Google Cloud và tích hợp cụm đó với TypeSafe AI System One (Jev).
Kiến thức bạn học được
- Cách thiết lập Private Service Access (PSA) và cung cấp một cụm AlloyDB cho PostgreSQL và thực thể chính.
- Cách bật
--outbound-public-ipđể AlloyDB có thể truy cập vào các API SaaS HTTPS bên ngoài. - Cách lưu trữ thông tin đăng nhập của nhà cung cấp AI bên thứ ba một cách an toàn trong Google Secret Manager và liên kết thông tin đó với AlloyDB.
- Cách viết các hàm biến đổi PL/pgSQL giúp kết nối các hàm AI PostgreSQL tiêu chuẩn (
ai.ifvàai.analyze_sentiment) với các API REST bên ngoài. - Cách đăng ký các điểm cuối LLM tuỳ chỉnh trong AlloyDB bằng
google_ml.create_model. - Cách thực thi cả truy vấn SQL ngữ nghĩa theo lô có tốc độ cao và truy vấn SQL ngữ nghĩa vô hướng ngay trong PostgreSQL.
- Cách phân tích bài đánh giá sản phẩm thực tế của khách hàng để biết cảm xúc theo danh mục.
- Cách đăng ký điểm cuối mô hình chung và đánh giá điểm số liên tục về sự hài lòng của khách hàng (
0..100) thông quagoogle_ml.predict_row.
Các bước tiếp theo
- Tìm hiểu thêm về các chức năng của Hàm AI AlloyDB trong tài liệu về AI AlloyDB.
- Đọc Tài liệu tham khảo về API AI TypeSafe để tìm hiểu thêm về logic ràng buộc của Noul và tính điểm cảm xúc.