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 TypeSafe AI với AlloyDB AI bằng các chức năng 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 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 và thực thể chính
- Tạo quy tắc tường lửa VPC cho phép Cloudshell và kết nối nội bộ
- Tải tập dữ liệu mẫu về thương mại điện tử bằng
gcloud alloydb clusters import - Bật tiện ích
google_ml_integrationcủa Google Secret Manager và AlloyDB - Lưu trữ và cấp quyền truy cập vào khoá API TypeSafe AI trong Secret Manager
- Tạo các hàm biến đổi đầu vào và đầu ra PL/pgSQL cho các kiểu dữ liệu gốc
noul(boolean) vàchoice(sentiment) 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 vô hướng và theo lô mảng (
ai.ifvàai.analyze_sentiment) trực tiếp trong SQL - Truy vấn bài đánh giá sản phẩm của khách hàng thực tế để phân loại cảm xúc bằng
ai.analyze_sentiment - (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 dữ liệu gốcscorecủa Jev
Bạn cần có
- Một trình duyệt web, chẳng hạn như Chrome
- Một dự án trên Google Cloud đã bật tính năng thanh toán
- Khoá API TypeSafe AI (từ TypeSafe AI)
2. Trước khi bắt đầu
Chọn dự án Google Cloud của bạn
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.
Bắt đầu Cloud Shell
Nhấp vào Activate Cloud Shell (Kích hoạt Cloud Shell) ở trên cùng bên phải của Google 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à 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 Google Cloud bắt buộc
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 của Quyền truy cập dịch vụ riêng tư trong mạng VPC, thiết lập kết nối ngang hàng riêng tư, đồng thời cung cấp cụm AlloyDB và thực thể chính có quyền truy cập Internet ra bên ngoài.
1. Tạo dải IP cho Quyền truy cập dịch vụ riêng tư (PSA)
AlloyDB yêu cầu phân bổ dải IP riêng tư trong mạng Đám mây riêng ảo (VPC). Giả sử bạn đang sử dụng mạng VPC default:
Tạo dải IP riêng tư được phân bổ:
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 ngang hàng VPC 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 có cờ AI và kết nối ra bên ngoà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 gửi đi. 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 thương mại điện tử mẫu
Để thử nghiệm các truy vấn ngữ nghĩa thực tế, hãy nhập một tập dữ liệu thương mại điện tử mẫu 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 sẵn với Trình quản lý mật khẩu của Google để xác thực các lệnh gọi API bên ngoài mà không làm lộ thông tin xác thực dạng văn bản thô trong mã cơ sở dữ liệu hoặc nhật ký cấu hình.
1. Tạo mật khẩu
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á TypeSafe AI API của bạn dưới dạng 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 thông tin mật trong quá trình thực thi truy vấn. Tìm số dự án và cấp vai trò Người truy cập bí mật:
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 kết quả 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 chạy các tiện ích cơ sở dữ liệu
Để tương tác với cơ sở dữ liệu AlloyDB ngay trên trình duyệt mà không cần định cấu hình công cụ ứng dụng 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.
Bây giờ, bạn đang ở trong trình soạn thảo 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 soạn thảo truy vấn của 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 TypeSafe AI:
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 dữ liệu gốc suy luận riêng biệt (noul cho các quy tắc ràng buộc boolean, choice cho việc 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 chữ ký hàm ai.* PostgreSQL tiêu chuẩn với định dạng API REST của Jev.
1. Chuyển đổi dữ liệu đầ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. Chuyể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 thành 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. Biến đổi dữ liệu đầu vào theo lô
Jev có thể đánh giá hàng chục câu hỏi cùng lúc trong một lượt khứ hồi HTTP mà không làm giảm chất lượng tạo sinh.
Thêm phép biến đổi dữ liệu đầu vào theo lô để chuyển đổi mảng prompts TEXT[] của PostgreSQL thành các câu hỏi Jev q_1 .. q_N 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 kết quả theo lô
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 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 xác thực bí mật và điểm cuối REST của TypeSafe AI 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 soạn thảo truy vấn của 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 đơn đăng ký
Truy vấn chế độ xem Model Registry để đả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 truy vấn thử nghiệm đối với Jev
Sau khi đăng ký jev-model, giờ đây, bạn có thể thực thi các thao tác ngữ nghĩa ngay trong các truy vấn PostgreSQL tiêu chuẩn.
1. Thử nghiệm tính năng lọc boolean vô hướng (ai.if)
Đánh giá một câu lệnh văn bản bằ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. Phân tích cảm xúc theo thang đo thử nghiệm (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. Thử nghiệm tính năng lọc boolean theo lô mảng
Đá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. Truy vấn bảng kiểm thử bằng tính năng gom theo lô mảng
Bây giờ, hãy truy vấn bảng ecomm.products đã tải trước đó trong quá trình cấp phép cụm, 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à đồ dùng cho thời tiết lạnh.
Để chạy tính năng lọc ngữ nghĩa có công suất 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 các 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 để phân tích cảm xúc
Bây giờ, hãy phân tích 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 dựa trên dữ liệu gốc 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: Điểm cảm nhận liên tục với điểm Jev
Trong khi các chức năng AI của AlloyDB như ai.analyze_sentiment trả về các nhóm phân loại (positive, negative, neutral), thì hàm gốc score của TypeSafe AI đánh giá sắc thái theo một tiêu chí chấm điểm có thứ tự và trả về đ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 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 nhiệm vụ (Boolean + Điểm liên tục)
Đánh giá đồng thời cả kết quả 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
}
}
}
}
Hãy lưu ý rằng satisfaction_score được đánh giá là 11 / 100, phản ánh 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 vải mềm!
10. Dọn dẹp
Để tránh phát sinh 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 của Trình quản lý mật khẩu
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á phiên bản chính và cụm 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 thực thể, 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 đã cấp thành công một cụm Google Cloud AlloyDB 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 Quyền truy cập dịch vụ riêng tư (PSA) và 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ể kết nối với các API SaaS HTTPS bên ngoài. - Cách lưu trữ thông tin xác thực của nhà cung cấp AI bên thứ ba một cách an toàn trong Trình quản lý bí mật của Google và liên kết thông tin xác thực đó với AlloyDB.
- Cách viết các hàm biến đổi PL/pgSQL để kết nối các chức năng AI chuẩn của PostgreSQL (
ai.ifvàai.analyze_sentiment) với các API REST bên ngoài. - Cách đăng ký đ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 vô hướng và truy vấn SQL ngữ nghĩa theo lô có thông lượng cao ngay trong PostgreSQL.
- Cách phân tích bài đánh giá sản phẩm của khách hàng thực tế để xác định cảm xúc theo danh mục.
- Cách đăng ký một điểm cuối mô hình chung và đánh giá điểm sự hài lòng của khách hàng liên tục (
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 của AlloyDB trong tài liệu về AI của AlloyDB.
- Đọc Tài liệu tham khảo API TypeSafe AI để tìm hiểu thêm về logic ràng buộc Noul và cách tính điểm cảm xúc.