Toán tử AI và tính năng xếp hạng lại của AlloyDB

1. Giới thiệu

Lớp học lập trình này cung cấp hướng dẫn về cách triển khai AlloyDB bằng các toán tử AI và sử dụng các toán tử đó cho các tác vụ như tìm kiếm ngữ nghĩa, nối và xếp hạng kết quả.

Điều kiện tiên quyết

  • Có kiến thức cơ bản về Google Cloud, bảng điều khiển
  • Kỹ năng cơ bản về giao diện dòng lệnh và Cloud Shell

Kiến thức bạn sẽ học được

  • Cách triển khai AlloyDB cho Postgres
  • Cách bật toán tử AI AlloyDB
  • Cách sử dụng các toán tử AI AlloyDB
  • Cách sử dụng toán tử AI AlloyDB trong quy trình làm việc RAG

Bạn cần có

  • Tài khoản Google Cloud và dự án trên Google Cloud
  • Một trình duyệt web như Chrome hỗ trợ Google Cloud Console và Cloud Shell

2. Cách thiết lập và các yêu cầu

Thiết lập môi trường theo tốc độ của riêng bạn

  1. Đăng nhập vào Google Cloud Console rồi tạo một dự án mới hoặc sử dụng lại một dự án hiện có. Nếu chưa có tài khoản Gmail hoặc Google Workspace, bạn phải tạo một tài khoản.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • Tên dự án là tên hiển thị cho người tham gia dự án này. Đây là một chuỗi ký tự không được API của Google sử dụng. Bạn luôn có thể cập nhật thông tin này.
  • Mã dự án là duy nhất trên tất cả các dự án trên Google Cloud và không thể thay đổi (không thể thay đổi sau khi đặt). Cloud Console sẽ tự động tạo một chuỗi duy nhất; thường thì bạn không cần quan tâm đến chuỗi này. Trong hầu hết các lớp học lập trình, bạn sẽ cần tham chiếu đến Mã dự án (thường được xác định là PROJECT_ID). Nếu không thích mã được tạo, bạn có thể tạo một mã ngẫu nhiên khác. Ngoài ra, bạn có thể thử dùng email của riêng mình để xem có thể sử dụng hay không. Bạn không thể thay đổi thông tin này sau bước này và thông tin này sẽ được giữ nguyên trong suốt thời gian thực hiện dự án.
  • Xin lưu ý rằng có một giá trị thứ ba là Mã dự án mà một số API sử dụng. Tìm hiểu thêm về cả ba giá trị này trong tài liệu.
  1. Tiếp theo, bạn cần bật tính năng thanh toán trong Cloud Console để sử dụng các tài nguyên/API trên Cloud. Việc tham gia lớp học lập trình này sẽ không tốn kém nhiều chi phí, nếu có. Để tắt các tài nguyên nhằm tránh bị tính phí sau khi hoàn tất hướng dẫn này, bạn có thể xoá các tài nguyên đã tạo hoặc xoá dự án. Người dùng mới của Google Cloud đủ điều kiện tham gia chương trình Dùng thử miễn phí 300 USD.

Khởi động Cloud Shell

Mặc dù có thể điều khiển Google Cloud từ xa trên máy tính xách tay, nhưng trong lớp học lập trình này, bạn sẽ sử dụng Google Cloud Shell, một môi trường dòng lệnh chạy trên đám mây.

Trong Bảng điều khiển Google Cloud, hãy nhấp vào biểu tượng Cloud Shell trên thanh công cụ trên cùng bên phải:

55efc1aaa7a4d3ad.png

Quá trình cấp phép và kết nối với môi trường chỉ mất vài phút. Khi hoàn tất, bạn sẽ thấy như sau:

7ffe5cbb04455448.png

Máy ảo này được tải sẵn tất cả các công cụ phát triển mà bạn cần. Ứng dụng này cung cấp một thư mục gốc 5 GB ổn định và chạy trên Google Cloud, giúp nâng cao đáng kể hiệu suất mạng và xác thực. Bạn có thể thực hiện tất cả công việc trong lớp học lập trình này trong một trình duyệt. Bạn không cần cài đặt gì cả.

3. Trước khi bắt đầu

Bật API

Trong Cloud Shell, hãy đảm bảo bạn đã thiết lập mã dự án:

gcloud config set project [YOUR-PROJECT-ID]

Đặt biến môi trường PROJECT_ID:

PROJECT_ID=$(gcloud config get-value project)

Bật tất cả các dịch vụ cần thiết:

gcloud services enable alloydb.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com \
                       discoveryengine.googleapis.com \
                       secretmanager.googleapis.com

Kết quả dự kiến

student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-14650]
student@cloudshell:~ (test-project-001-402417)$ 
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable alloydb.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

4. Triển khai AlloyDB

Tạo cụm AlloyDB và thực thể chính. Quy trình sau đây mô tả cách tạo cụm và thực thể AlloyDB bằng SDK Google Cloud. Nếu muốn sử dụng phương pháp bảng điều khiển, bạn có thể làm theo tài liệu tại đây.

Trước khi tạo cụm AlloyDB, chúng ta cần có một dải IP riêng tư có sẵn trong VPC để thực thể AlloyDB trong tương lai sử dụng. Nếu chưa có, chúng ta cần tạo và chỉ định cho các dịch vụ nội bộ của Google sử dụng. Sau đó, chúng ta có thể tạo cụm và thực thể.

Tạo dải IP riêng tư

Chúng ta cần định cấu hình Quyền truy cập vào dịch vụ riêng tư trong VPC cho AlloyDB. Giả sử ở đây là chúng ta có mạng VPC "mặc định" trong dự án và mạng này sẽ được dùng cho tất cả các hành động.

Tạo 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

Tạo kết nối riêng tư bằng dải IP được phân bổ:

gcloud services vpc-peerings connect \
    --service=servicenetworking.googleapis.com \
    --ranges=psa-range \
    --network=default

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-402417)$ gcloud compute addresses create psa-range \
    --global \
    --purpose=VPC_PEERING \
    --prefix-length=24 \
    --description="VPC private service access" \
    --network=default
Created [https://www.googleapis.com/compute/v1/projects/test-project-402417/global/addresses/psa-range].

student@cloudshell:~ (test-project-402417)$ gcloud services vpc-peerings connect \
    --service=servicenetworking.googleapis.com \
    --ranges=psa-range \
    --network=default
Operation "operations/pssn.p24-4470404856-595e209f-19b7-4669-8a71-cbd45de8ba66" finished successfully.

student@cloudshell:~ (test-project-402417)$

Tạo cụm AlloyDB

Trong phần này, chúng ta sẽ tạo một cụm AlloyDB ở khu vực us-central1.

Xác định mật khẩu cho người dùng postgres. Bạn có thể tự xác định mật khẩu hoặc sử dụng hàm ngẫu nhiên để tạo mật khẩu

export PGPASSWORD=`openssl rand -hex 12`

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-402417)$ export PGPASSWORD=`openssl rand -hex 12`

Ghi lại mật khẩu PostgreSQL để sử dụng sau này:

echo $PGPASSWORD

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-402417)$ echo $PGPASSWORD
bbefbfde7601985b0dee5723

Tạo cụm dùng thử miễn phí

Nếu chưa sử dụng AlloyDB, bạn có thể tạo một cụm dùng thử miễn phí:

Xác định khu vực và tên cụm AlloyDB. Chúng ta sẽ sử dụng khu vực us-central1 và alloydb-aip-01 làm tên cụm:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01

Chạy lệnh để tạo cụm:

gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION \
    --subscription-type=TRIAL

Kết quả đầu ra dự kiến trên bảng điều khiển:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION \
    --subscription-type=TRIAL
Operation ID: operation-1697655441138-6080235852277-9e7f04f5-2012fce4
Creating cluster...done.                                                                                                                                                                                                                                                           

Tạo một thực thể chính AlloyDB cho cụm của chúng ta trong cùng một phiên shell trên đám mây. Nếu bị ngắt kết nối, bạn sẽ cần xác định lại biến môi trường tên cụm và khu vực.

gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=8 \
    --region=$REGION \
    --cluster=$ADBCLUSTER

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-402417)$ gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=8 \
    --region=$REGION \
    --availability-type ZONAL \
    --cluster=$ADBCLUSTER
Operation ID: operation-1697659203545-6080315c6e8ee-391805db-25852721
Creating instance...done.                                                                                                                                                                                                                                                     

Tạo cụm AlloyDB Standard

Nếu đây không phải là cụm AlloyDB đầu tiên trong dự án, hãy tiếp tục tạo một cụm chuẩn.

Xác định khu vực và tên cụm AlloyDB. Chúng ta sẽ sử dụng khu vực us-central1 và alloydb-aip-01 làm tên cụm:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01

Chạy lệnh để tạo cụm:

gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION

Kết quả đầu ra dự kiến trên bảng điều khiển:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION 
Operation ID: operation-1697655441138-6080235852277-9e7f04f5-2012fce4
Creating cluster...done.                                                                                                                                                                                                                                                           

Tạo một thực thể chính AlloyDB cho cụm của chúng ta trong cùng một phiên shell trên đám mây. Nếu bị ngắt kết nối, bạn sẽ cần xác định lại biến môi trường tên cụm và khu vực.

gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=2 \
    --region=$REGION \
    --cluster=$ADBCLUSTER

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-402417)$ gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=2 \
    --region=$REGION \
    --availability-type ZONAL \
    --cluster=$ADBCLUSTER
Operation ID: operation-1697659203545-6080315c6e8ee-391805db-25852721
Creating instance...done.                                                                                                                                                                                                                                                     

5. Chuẩn bị cơ sở dữ liệu

Chúng ta cần tạo một cơ sở dữ liệu, bật tính năng tích hợp Vertex AI, tạo các đối tượng cơ sở dữ liệu và nhập dữ liệu.

Cấp các quyền cần thiết cho AlloyDB

Thêm quyền Vertex AI vào tác nhân dịch vụ AlloyDB.

Mở một thẻ Cloud Shell khác bằng dấu "+" ở trên cùng.

4ca978f5142bb6ce.png

Trong thẻ shell trên đám mây mới, hãy thực thi:

PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-11039]
student@cloudshell:~ (test-project-001-402417)$ gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
Updated IAM policy for project [test-project-001-402417].
bindings:
- members:
  - serviceAccount:service-4470404856@gcp-sa-alloydb.iam.gserviceaccount.com
  role: roles/aiplatform.user
- members:
...
etag: BwYIEbe_Z3U=
version: 1
 

Đóng thẻ bằng lệnh thực thi "exit" trong thẻ:

exit

Kết nối với AlloyDB Studio

Trong các chương sau, bạn có thể thực thi tất cả các lệnh SQL yêu cầu kết nối với cơ sở dữ liệu trong AlloyDB Studio. Để chạy lệnh này, bạn cần mở giao diện bảng điều khiển web cho cụm AlloyDB bằng cách nhấp vào thực thể chính.

ef4bfbcf0ed2ef3a.png

Sau đó, hãy nhấp vào AlloyDB Studio ở bên trái:

5c155cbcd7d43a1.png

Chọn cơ sở dữ liệu postgres, người dùng postgres và cung cấp mật khẩu đã ghi lại khi chúng ta tạo cụm. Sau đó, hãy nhấp vào nút "Xác thực".

432613065cac864f.png

Thao tác này sẽ mở giao diện AlloyDB Studio. Để chạy các lệnh trong cơ sở dữ liệu, bạn nhấp vào thẻ "Trình chỉnh sửa 1" ở bên phải.

b36c28f8165119ca.png

Thao tác này sẽ mở ra giao diện mà bạn có thể chạy các lệnh SQL

cf43aa20f292797e.png

Tạo cơ sở dữ liệu

Tạo hướng dẫn bắt đầu nhanh về cơ sở dữ liệu.

Trong AlloyDB Studio Editor, hãy thực thi lệnh sau.

Tạo cơ sở dữ liệu:

CREATE DATABASE quickstart_db

Kết quả đầu ra dự kiến:

Statement executed successfully

Kết nối với quickstart_db

Kết nối lại với studio bằng nút chuyển đổi người dùng/cơ sở dữ liệu.

e826ad973eb23a74.png

Chọn cơ sở dữ liệu quickstart_db mới trong danh sách thả xuống và sử dụng cùng một người dùng và mật khẩu như trước.

1ca70c59b5aea8c1.png

Thao tác này sẽ mở một kết nối mới để bạn có thể làm việc với các đối tượng trong cơ sở dữ liệu quickstart_db.

Xác minh tiện ích google_ml

Kiểm tra phiên bản tiện ích google_ml để đảm bảo phiên bản đó là 1.4.4 trở lên để có thể sử dụng công cụ truy vấn AI.

Trong AlloyDB Studio khi kết nối với quickstart_db, hãy thực thi:

SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';

Kết quả đầu ra dự kiến:

1.4.4

Nếu phiên bản thấp hơn phiên bản bắt buộc, hãy cập nhật tiện ích.

Trong AlloyDB Studio khi kết nối với quickstart_db, hãy thực thi:

CALL google_ml.upgrade_to_preview_version();

Kết quả đầu ra dự kiến:

Statement executed successfully

Sau khi thực thi thành công, hãy xác minh lại phiên bản.

Trong AlloyDB Studio, khi kết nối với quickstart_db, hãy thực thi:

SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';

Kết quả đầu ra dự kiến:

1.4.4

6. Dữ liệu mẫu

Bây giờ, chúng ta cần tạo các đối tượng trong cơ sở dữ liệu và tải dữ liệu. Chúng ta sẽ sử dụng một tập dữ liệu phim hư cấu có một vài hàng.

Sao chép các câu lệnh sau vào Trình chỉnh sửa AlloyDB Studio rồi nhấn nút "Run" (Chạy).

-- Drop tables if they exist to prevent errors on re-running the script
DROP TABLE IF EXISTS movie_reviews;
DROP TABLE IF EXISTS movies;

-- Create the 'movies' table
-- This table stores information about each movie.
CREATE TABLE movies (
    id BIGINT PRIMARY KEY,              -- Unique identifier for the movie
    title TEXT NOT NULL,               -- Title of the movie
    description TEXT,                  -- A brief description or synopsis of the movie
    genres TEXT,                       -- Comma-separated list of genres (e.g., "Action, Adventure, Sci-Fi")
    actors TEXT                        -- Comma-separated list of main actors
);

-- Create the 'movie_reviews' table
-- This table stores reviews for the movies.
CREATE TABLE movie_reviews (
    review_id BIGINT PRIMARY KEY,      -- Unique identifier for the review
    movie_id BIGINT NOT NULL,          -- Foreign key referencing the movie being reviewed
    reviewer_name TEXT,                -- Name of the person who wrote the review
    rating INT CHECK (rating >= 1 AND rating <= 5), -- Rating from 1 to 5 stars
    review_text TEXT,                  -- The content of the review
    review_date DATE DEFAULT CURRENT_DATE, -- Date when the review was submitted
    FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE -- Ensures referential integrity; if a movie is deleted, its reviews are also deleted.
);

-- Insert sample data into the 'movies' table (20 rows)
INSERT INTO movies (id, title, description, genres, actors) VALUES
(1, 'Inception', 'A thief who steals information by entering people''s dreams.', 'Sci-Fi, Thriller, Action', 'Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page'),
(2, 'The Matrix', 'A computer hacker learns about the true nature of his reality.', 'Sci-Fi, Action', 'Keanu Reeves, Laurence Fishburne, Carrie-Anne Moss'),
(3, 'Interstellar', 'A team of explorers journey through a cosmic passage beyond our world in an attempt to ensure humanity''s survival.', 'Sci-Fi, Drama, Adventure', 'Matthew McConaughey, Anne Hathaway, Jessica Chastain'), -- Updated description
(4, 'The Dark Knight', 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.', 'Action, Crime, Drama', 'Christian Bale, Heath Ledger, Aaron Eckhart'),
(5, 'Pulp Fiction', 'The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', 'Crime, Drama', 'John Travolta, Uma Thurman, Samuel L. Jackson'),
(6, 'Forrest Gump', 'The presidencies of Kennedy and Johnson, the Vietnam War, the Watergate scandal and other historical events unfold from the perspective of an Alabama man with an IQ of 75.', 'Drama, Romance', 'Tom Hanks, Robin Wright, Gary Sinise'),
(7, 'The Shawshank Redemption', 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', 'Drama', 'Tim Robbins, Morgan Freeman, Bob Gunton'),
(8, 'Gladiator', 'A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery.', 'Action, Adventure, Drama', 'Russell Crowe, Joaquin Phoenix, Connie Nielsen'),
(9, 'Fight Club', 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more.', 'Drama', 'Brad Pitt, Edward Norton, Meat Loaf'),
(10, 'The Lord of the Rings: The Return of the King', 'Gandalf and Aragorn lead the World of Men against Sauron''s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', 'Action, Adventure, Drama', 'Elijah Wood, Viggo Mortensen, Ian McKellen'),
(11, 'Spirited Away', 'During her family''s move to the suburbs, a sullen 10-year-old girl wanders into a world ruled by gods, witches, and spirits, and where humans are changed into beasts.', 'Animation, Adventure, Family', 'Daveigh Chase, Suzanne Pleshette, Miyu Irino'),
(12, 'Parasite', 'Greed and class discrimination threaten the newly formed symbiotic relationship between the wealthy Park family and the destitute Kim clan.', 'Comedy, Drama, Thriller', 'Song Kang-ho, Lee Sun-kyun, Cho Yeo-jeong'),
(13, 'The Godfather', 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', 'Crime, Drama', 'Marlon Brando, Al Pacino, James Caan'),
(14, 'Avengers: Endgame', 'After the devastating events of Avengers: Infinity War, the universe is in ruins. With the help of remaining allies, the Avengers assemble once more in order to reverse Thanos'' actions and restore balance to the universe.', 'Action, Adventure, Drama', 'Robert Downey Jr., Chris Evans, Mark Ruffalo'),
(15, 'Joker', 'In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime.', 'Crime, Drama, Thriller', 'Joaquin Phoenix, Robert De Niro, Zazie Beetz'),
(16, 'Mad Max: Fury Road', 'In a post-apocalyptic wasteland, a woman rebels against a tyrannical ruler in search for her homeland with the help of a group of female prisoners, a psychotic worshiper, and a drifter named Max.', 'Action, Adventure, Sci-Fi', 'Tom Hardy, Charlize Theron, Nicholas Hoult'),
(17, 'Coco', 'Aspiring musician Miguel, confronted with his family''s ancestral ban on music, enters the Land of the Dead to find his great-great-grandfather, a legendary singer.', 'Animation, Adventure, Family', 'Anthony Gonzalez, Gael García Bernal, Benjamin Bratt'),
(18, 'Whiplash', 'A promising young drummer enrolls at a cut-throat music conservatory where his dreams of greatness are mentored by an instructor who will stop at nothing to realize a student''s potential.', 'Drama, Music', 'Miles Teller, J.K. Simmons, Paul Reiser'),
(19, 'The Grand Budapest Hotel', 'The adventures of Gustave H, a legendary concierge at a famous hotel from the fictional Republic of Zubrowka between the first and second World Wars, and Zero Moustafa, the lobby boy who becomes his most trusted friend.', 'Adventure, Comedy, Drama', 'Ralph Fiennes, F. Murray Abraham, Mathieu Amalric'),
(20, 'Blade Runner 2049', 'Young Blade Runner K''s discovery of a long-buried secret leads him to track down former Blade Runner Rick Deckard, who''s been missing for thirty years.', 'Action, Drama, Mystery', 'Ryan Gosling, Harrison Ford, Ana de Armas');

-- Insert sample data into the 'movie_reviews' table (30 rows)
-- Reviews are linked to movies via movie_id. Includes a mix of positive and negative reviews.
-- Movie title is prepended to the review text.
INSERT INTO movie_reviews (review_id, movie_id, reviewer_name, rating, review_text) VALUES
(1, 1, 'Alice Wonderland', 5, 'Inception: Absolutely mind-bending! A masterpiece of sci-fi.'),
(2, 1, 'Bob The Critic', 2, 'Inception: Too confusing and pretentious. Didn''t enjoy it.'),
(3, 2, 'Charlie Reviewer', 5, 'The Matrix: Revolutionary visuals and a compelling story.'),
(4, 3, 'Diana Prince', 5, 'Interstellar: Visually stunning and emotionally powerful. A must-see.'),
(5, 3, 'Edward Nigma', 4, 'Interstellar: Long, but worth it for the spectacle and ideas.'),
(6, 4, 'Fiona Glenanne', 5, 'The Dark Knight: Heath Ledger''s Joker is iconic. Dark and thrilling.'),
(7, 5, 'George Costanza', 5, 'Pulp Fiction: Quirky, violent, and endlessly quotable.'),
(8, 5, 'Hannah Montana', 1, 'Pulp Fiction: Way too violent and the timeline was confusing. Hated it.'),
(9, 6, 'Ian Malcolm', 4, 'Forrest Gump: A heartwarming story with a great performance by Hanks.'),
(10, 7, 'Jane Doe', 5, 'The Shawshank Redemption: An uplifting story of hope and friendship. Perfect.'),
(11, 7, 'John Smith', 5, 'The Shawshank Redemption: Morgan Freeman is amazing. Truly a classic.'),
(12, 8, 'Kyle Broflovski', 2, 'Gladiator: Generic plot and boring action scenes. Overrated.'),
(13, 9, 'Laura Palmer', 5, 'Fight Club: Provocative and thought-provoking. Norton and Pitt are fantastic.'),
(14, 10, 'Michael Scott', 5, 'The Lord of the Rings: The Return of the King: A fitting and epic conclusion to a legendary trilogy.'),
(15, 11, 'Nancy Drew', 5, 'Spirited Away: Beautiful animation and a magical story for all ages.'),
(16, 12, 'Oscar Martinez', 5, 'Parasite: A brilliant satire with unexpected twists. Loved it!'),
(17, 12, 'Pam Beesly', 4, 'Parasite: Very intense, but incredibly well-directed and acted.'),
(18, 13, 'Quentin Coldwater', 5, 'The Godfather: A cinematic masterpiece. Brando is unforgettable.'),
(19, 14, 'Rachel Green', 3, 'Avengers: Endgame: It was okay, but felt bloated and had too many characters.'),
(20, 14, 'Steve Rogers', 5, 'Avengers: Endgame: The culmination of a decade of storytelling. Perfect ending.'),
(21, 15, 'Tony Stark', 4, 'Joker: A dark and disturbing character study. Phoenix is mesmerizing.'),
(22, 16, 'Uma Thurman', 5, 'Mad Max: Fury Road: Non-stop action and incredible practical effects. What a ride!'),
(23, 17, 'Victor Frankenstein', 5, 'Coco: A heartwarming and visually stunning celebration of family and culture.'),
(24, 18, 'Walter White', 5, 'Whiplash: Intense and gripping. J.K. Simmons is terrifyingly good.'),
(25, 19, 'Xena Warrior', 2, 'The Grand Budapest Hotel: Too quirky for its own good. Style over substance.'),
(26, 20, 'Ygritte Snow', 5, 'Blade Runner 2049: A worthy sequel that expands on the original in meaningful ways. Visually breathtaking.'),
(27, 1, 'Zack Morris', 4, 'Inception: Kept me on the edge of my seat. Very clever.'),
(28, 4, 'Buffy Summers', 5, 'The Dark Knight: The best superhero movie ever made. Ledger is a legend.'),
(29, 8, 'Clark Kent', 3, 'Gladiator: Decent action, but the story felt predictable and dragged a bit.'),
(30, 15, 'Diana Troy', 3, 'Joker: Hard to watch at times, but a powerful performance. Felt it was a bit one-note though.');

Nếu có dữ liệu mẫu và tệp CSV tương thích với công cụ nhập Cloud SQL có trong bảng điều khiển Cloud, bạn có thể sử dụng công cụ này thay vì phương pháp được trình bày.

7. Sử dụng toán tử IF

Trước tiên, hãy thử tìm kiếm kiểu cũ bằng các phương pháp PostgreSQL tiêu chuẩn.

Nếu muốn tìm kiếm một bộ phim về cuộc phiêu lưu trong không gian, chúng ta có thể thử truy vấn sau

SELECT title,description AS movies_about_space
    FROM movies
    WHERE description like '%space%' OR title like '%space%';

Không có kết quả nào được trả về. Nhưng tôi chắc chắn rằng chúng tôi có ít nhất một bộ phim thuộc danh mục đó. Chúng ta có thể thử sử dụng phương pháp tìm kiếm toàn văn bản.

SELECT title,description
FROM movies
WHERE to_tsvector('english', description) @@ to_tsquery('english', 'space');

Và có thể chúng ta sẽ không nhận được kết quả nào. Vì vậy, chúng ta cần biết một số từ khoá hoặc cụm từ để có thể sử dụng các kỹ thuật "cổ điển" của tính năng tìm kiếm PostgreSQL.

Bây giờ, chúng ta có thể thử sử dụng tính năng lọc ngữ nghĩa dựa trên AI bằng hàm google_ml.if. Công cụ này sẽ sử dụng AI ở chế độ nền để lọc ngữ nghĩa dựa trên yêu cầu bằng ngôn ngữ tự nhiên của chúng ta.

SELECT title,description AS movies_about_space
    FROM movies
    WHERE
      google_ml.if(
        prompt => 'Here are descriptions of movies, can you return the ones about space adventures:  '||description);

Chúng tôi sẽ tìm phim "Interstellar" dựa trên ý nghĩa ngữ nghĩa của yêu cầu, ngay cả khi phim không có cụm từ "không gian" trong tiêu đề hoặc nội dung mô tả. Như bạn đã nhận thấy, chúng ta cũng không tạo trước bất kỳ nội dung nào và chỉ dựa vào các hàm tích hợp tự động.

8. Sử dụng toán tử JOIN với toán tử IF

Nếu chúng ta muốn kết hợp hai bảng bằng cách sử dụng tính năng lọc ngữ nghĩa do AI điều khiển thì sao? Ví dụ: chúng ta có thể cố gắng so khớp bài đánh giá của người dùng với các bộ phim dựa trên bài đánh giá của người dùng nếu bộ phim được đề cập trong bài đánh giá.

Chạy trong thẻ trình soạn thảo AlloyDB Studio mới:

SELECT title, rating, movie_reviews 
    FROM movies
    JOIN
    movie_reviews ON 
      google_ml.if(
        prompt => 'Does the following reviews talk about a movie mentioned? The review: ' || review_text||' and the movie title is: '||title)
    AND
    title='Interstellar';

Và chúng ta nhận được 2 bài đánh giá khớp với yêu cầu của mình dựa trên tên của bộ phim được đề cập trong tiêu đề. Và chúng ta có thể đơn giản hoá yêu cầu này hơn nữa:

SELECT title, rating, movie_reviews 
    FROM movies
    JOIN
    movie_reviews ON 
      google_ml.if(
        prompt => 'Do we have the movie in the review?: ' || review_text||' and the movie title is: '||title)
    AND
    title='Interstellar';

9. Kết quả tính điểm dựa trên nội dung

Bảng movie_reviews có điểm xếp hạng cho các bộ phim, nhưng nếu muốn triển khai điểm xếp hạng của riêng mình, chúng ta có thể sử dụng hàm google_ml.rank. Chúng ta có thể tính điểm cho bài đánh giá dựa trên các điều kiện do ngôn ngữ tự nhiên xác định, chẳng hạn như lấy 5 bài đánh giá hàng đầu cho phim và hiển thị điểm xếp hạng ban đầu để so sánh.

SELECT rating,review_text AS top_five
    FROM movie_reviews
    ORDER BY google_ml.rank('Score of 7 to 10 if the review says the movie was really good, 3 to 6 if the review says it''s alright is and 1 to 2 if the review says it was not worth of time. Review: ' || review_text) DESC
    LIMIT 5;

Nếu muốn hiển thị điểm xếp hạng mới bên cạnh điểm xếp hạng ban đầu, chúng ta có thể thêm điểm xếp hạng mới vào danh sách cột.

SELECT rating,
    google_ml.rank('Score of 7 to 10 if the review says the movie was really good, 3 to 6 if the review says it''s alright is and 1 to 2 if the review says it was not worth of time. Review: ' || review_text) AS ml_rank,
    review_text AS top_five
    FROM movie_reviews
    ORDER BY ml_rank DESC
    LIMIT 5;

Sau đây là 5 bài đánh giá hàng đầu.

 rating | ml_rank |                               top_five
--------+---------+-----------------------------------------------------------------------
      5 |       9 | The Dark Knight: Heath Ledger's Joker is iconic. Dark and thrilling.
      5 |       9 | The Matrix: Revolutionary visuals and a compelling story.
      5 |       9 | Interstellar: Visually stunning and emotionally powerful. A must-see.
      5 |       9 | Inception: Absolutely mind-bending! A masterpiece of sci-fi.
      5 |       9 | Pulp Fiction: Quirky, violent, and endlessly quotable.
(5 rows)
5 rows in set (0.13 sec)

Điểm xếp hạng được chọn là 9/10 cho các bài đánh giá hàng đầu.

10. Cải thiện tính năng Tìm kiếm ngữ nghĩa bằng cách sử dụng thứ hạng

Chúng ta có thể kết hợp tính năng tìm kiếm ngữ nghĩa với thứ hạng để có được kết quả chính xác hơn.

Đăng ký mô hình xếp hạng lại

Mở một thẻ Cloud Shell khác bằng dấu "+" ở trên cùng.

4ca978f5142bb6ce.png

Trong thẻ shell trên đám mây mới, hãy thực thi:

export PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts create aip-reranking
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/discoveryengine.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
gcloud iam service-accounts add-iam-policy-binding aip-reranking@$PROJECT_ID.iam.gserviceaccount.com \
    --member="user:$(gcloud auth list --filter=status:ACTIVE --format="value(account)")" --role="roles/iam.serviceAccountTokenCreator"
gcloud iam service-accounts add-iam-policy-binding aip-reranking@$PROJECT_ID.iam.gserviceaccount.com \
    --member="user:$(gcloud auth list --filter=status:ACTIVE --format="value(account)")" --role="roles/iam.serviceAccountUser"

Tạo mã thông báo truy cập và thêm mã đó dưới dạng khoá bí mật có tên "rerank-secret":

echo -n $(gcloud auth print-access-token \
  --impersonate-service-account="aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --lifetime=3600) | gcloud secrets create rerank-secret \
    --replication-policy="automatic" \
    --data-file=-
gcloud secrets add-iam-policy-binding 'rerank-secret' \
      --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
      --role="roles/secretmanager.secretAccessor"

Trong ví dụ này, mã xác thực sẽ có hiệu lực trong một giờ và sau đó sẽ được cập nhật bằng cách tạo một phiên bản mới. Ví dụ:

echo -n $(gcloud auth print-access-token \
--impersonate-service-account="aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --lifetime=3600) | gcloud secrets versions add rerank-secret \
    --data-file=-

Bây giờ, chúng ta cần chuyển sang AlloyDB Studio và tạo một khoá bí mật để truy cập vào mô hình xếp hạng lại.

Trong bảng điều khiển AlloyDB Studio, hãy thực thi sau khi thay đổi $PROJECT_ID theo dự án của bạn:

CALL
  google_ml.create_sm_secret(
    secret_id => 'rerank-secret',
    secret_path => 'projects/PROJECT_ID/secrets/rerank-secret/versions/latest');

Sau đó, hãy đăng ký mô hình trong cùng một phiên Studio sau khi thay đổi PROJECT_ID theo dự án của bạn:

CALL
google_ml.create_model(
  model_id => 'semantic-ranker-512-002',
  model_type => 'reranking',
  model_provider => 'custom',
  model_request_url =>
    'https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/rankingConfigs/default_ranking_config:rank',
  model_qualified_name => 'semantic-ranker-512@002',
  model_auth_type => 'secret_manager',
  model_auth_id => 'rerank-secret',
  model_in_transform_fn => 'google_ml.vertexai_reranking_input_transform',
  model_out_transform_fn => 'google_ml.vertexai_reranking_output_transform');

Sử dụng Mô hình xếp hạng lại

Giờ đây, chúng ta có thể sử dụng mô hình xếp hạng lại trong các cụm từ tìm kiếm để cải thiện kết quả tìm kiếm ngữ nghĩa, giúp kết quả trở nên cụ thể hơn và chọn các lựa chọn tốt nhất.

Hãy tìm phim hành động rồi xếp hạng các phim đó bằng cách sử dụng điều kiện "máy tính và tương lai".

WITH
  action_movies AS (
    SELECT
      title,
      description,
      ROW_NUMBER() OVER (ORDER BY title, description) AS ref_number
    FROM
      movies
    WHERE
      google_ml.if(
        prompt => 'The following movies are action movies. The movie title: ' || title || ' and the description is: ' || description
      ) 
  ),
  ranked_documents_array AS (
    SELECT
      ARRAY_AGG(description ORDER BY ref_number) AS docs
    FROM
      action_movies
  ),
  reranked_results AS (
    SELECT
      r.index,
      r.score
    FROM
      ranked_documents_array,
      ai.rank(
        model_id => 'semantic-ranker-512-002',
        search_string => 'Computers and future',
        documents => ranked_documents_array.docs
      ) AS r 
  )
SELECT
  am.title,
  left(am.description,80) as description,
  rr.score
FROM
  action_movies am
JOIN
  reranked_results rr ON am.ref_number = rr.index 
ORDER BY
  rr.score DESC;

Kết quả sẽ liệt kê các bộ phim hành động, hy vọng là các bộ phim về tương lai và máy tính sẽ đứng đầu.

title                     |                                   description                                    | score
-----------------------------------------------+----------------------------------------------------------------------------------+--------
 The Matrix                                    | A computer hacker learns about the true nature of his reality.                   | 0.0145
 Mad Max: Fury Road                            | In a post-apocalyptic wasteland, a woman rebels against a tyrannical ruler in se |  0.002
 Avengers: Endgame                             | After the devastating events of Avengers: Infinity War, the universe is in ruins | 0.0018
 Blade Runner 2049                             | Young Blade Runner K's discovery of a long-buried secret leads him to track down | 0.0004
 The Lord of the Rings: The Return of the King | Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze |  1e-05
 The Dark Knight                               | When the menace known as the Joker wreaks havoc and chaos on the people of Gotha |  1e-05
 Inception                                     | A thief who steals information by entering people's dreams.                      |  1e-05
 Gladiator                                     | A former Roman General sets out to exact vengeance against the corrupt emperor w |  1e-05
(8 rows)

Hãy thử với nhiều điều kiện khác nhau và xem thứ hạng ảnh hưởng như thế nào đến thứ tự đầu ra.

11. Dọn dẹp môi trường

Huỷ bỏ các phiên bản AlloyDB và cụm khi bạn hoàn tất lớp học lập trình

Xoá cụm AlloyDB và tất cả các phiên bản

Cụm này bị huỷ bằng tuỳ chọn buộc, đồng thời xoá tất cả các thực thể thuộc cụm.

Trong màn hình shell trên đám mây, hãy xác định biến dự án và biến môi trường nếu bạn đã bị ngắt kết nối và tất cả các chế độ cài đặt trước đó đều bị mất:

gcloud config set project <your project id>
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
export PROJECT_ID=$(gcloud config get-value project)

Xoá cụm:

gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-001-402417)$ gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force
All of the cluster data will be lost when the cluster is deleted.

Do you want to continue (Y/n)?  Y

Operation ID: operation-1697820178429-6082890a0b570-4a72f7e4-4c5df36f
Deleting cluster...done.   

Xoá bản sao lưu AlloyDB

Xoá tất cả bản sao lưu AlloyDB cho cụm:

for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done

Kết quả đầu ra dự kiến trên bảng điều khiển:

student@cloudshell:~ (test-project-001-402417)$ for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done
Operation ID: operation-1697826266108-60829fb7b5258-7f99dc0b-99f3c35f
Deleting backup...done.                                                                                                                                                                                                                                                            

12. Xin chúc mừng

Chúc mừng bạn đã hoàn thành lớp học lập trình.

Nội dung đã đề cập

  • Cách triển khai AlloyDB cho Postgres
  • Cách bật toán tử AI AlloyDB
  • Cách sử dụng các toán tử AI AlloyDB
  • Cách sử dụng toán tử AI AlloyDB trong quy trình làm việc RAG

13. Khảo sát

Kết quả:

Bạn sẽ sử dụng hướng dẫn này như thế nào?

Chỉ đọc qua Đọc và hoàn thành bài tập