MySQL용 Cloud SQL에서 벡터 임베딩 시작하기

1. 소개

이 Codelab에서는 임베딩을 사용한 시맨틱 검색을 위해 MySQL용 Cloud SQL AI 통합을 사용하는 방법과 벡터 데이터의 색인을 사용하여 성능을 개선하는 방법을 알아봅니다.

8aa6ba3bc12a1593.png

기본 요건

  • Google Cloud 및 Google Cloud 콘솔에 대한 기본적인 이해
  • 명령줄 인터페이스 및 Cloud Shell에 대한 기본 경험

학습할 내용

  • MySQL용 Cloud SQL 인스턴스를 배포하는 방법
  • 데이터베이스를 만들고 Cloud SQL AI 통합을 사용 설정하는 방법
  • 데이터베이스에 데이터를 로드하는 방법
  • Cloud SQL Studio 사용 방법
  • Cloud SQL에서 Vertex AI 임베딩 모델을 사용하는 방법
  • Agent Platform Studio 사용 방법
  • Gemini Enterprise Agent Platform 모델을 사용하여 결과를 보강하는 방법
  • 벡터 색인을 사용하여 성능을 개선하는 방법

필요한 항목

  • Google Cloud 계정 및 Google Cloud 프로젝트
  • 웹브라우저(예: Chrome)

2. 설정 및 요구사항

프로젝트 설정

  1. Google Cloud 콘솔에 로그인합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 Google 계정을 만들어야 합니다.

직장 또는 학교 계정 대신 개인 계정을 사용하세요.

  1. 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다. Google Cloud 콘솔에서 새 프로젝트를 만들려면 툴바에서 프로젝트 선택을 클릭합니다.

295004821bab6a87.png

프로젝트 선택 창에서 새 프로젝트 버튼을 누르면 새 프로젝트 대화상자가 열립니다.

37d264871000675d.png

대화상자에서 프로젝트 이름을 입력하고 위치를 선택합니다.

96d86d3d5655cdbe.png

  • 프로젝트 이름은 이 프로젝트 참가자의 표시 이름입니다. 프로젝트 이름은 Google API에서 사용되지 않으며 언제든지 변경할 수 있습니다.
  • 프로젝트 ID는 모든 Google Cloud 프로젝트에서 고유하며, 변경할 수 없습니다 (설정된 후에는 변경할 수 없음). Google Cloud 콘솔은 고유 ID를 자동으로 생성하지만 이를 맞춤설정할 수 있습니다. 생성된 ID가 마음에 들지 않으면 다른 임의 ID를 생성하거나 직접 ID를 입력하여 사용 가능 여부를 확인할 수 있습니다. 대부분의 Codelab에서는 프로젝트 ID를 참조하며, 이는 일반적으로 자리표시자로 식별됩니다.
  • 참고로 세 번째 값은 일부 API에서 사용하는 프로젝트 번호입니다. 이 세 가지 값에 대한 자세한 내용은 프로젝트 만들기 및 관리 문서를 참고하세요.

결제 사용 설정

결제를 사용 설정하는 방법에는 두 가지가 있습니다. 개인 결제 계정을 사용하거나 다음 단계에 따라 크레딧을 사용할 수 있습니다.

Google Cloud 크레딧 사용 (선택사항)

이 워크숍을 실행하려면 크레딧이 있는 결제 계정이 필요합니다. 워크숍 주최자가 제공한 크레딧을 사용하거나 이 Codelab 상단의 배너에 제공된 크레딧을 사용하여 시작하세요. 이미 결제 계정에 연결되어 있는 경우 이 단계를 건너뛰어도 됩니다.

개인 결제 계정 설정

Google Cloud 크레딧을 사용하여 결제를 설정한 경우 이 단계를 건너뛸 수 있습니다.

개인 결제 계정을 설정하려면 Google Cloud Billing 콘솔에서 결제를 사용 설정하세요.

참고:

  • 이 실습을 완료하는 데 드는 Google Cloud 리소스 비용은 5달러 미만입니다.
  • 이 실습이 끝나면 단계에 따라 리소스를 삭제하여 추가 요금이 발생하지 않도록 하세요.
  • 신규 사용자는 $300 상당의 무료 체험판을 사용할 수 있습니다.
  • 신규 및 기존 사용자는 Cloud SQL 무료 체험판 인스턴스를 사용하여 Cloud SQL을 시작할 수 있습니다.

Cloud Shell 시작

컴퓨터에서 Google Cloud를 원격으로 운영할 수 있지만 이 Codelab에서는 클라우드에서 실행되는 명령줄 환경인 Google Cloud Shell을 사용합니다.

Google Cloud 콘솔의 오른쪽 상단 툴바에 있는 Cloud Shell 아이콘을 클릭합니다.

Cloud Shell 활성화

또는 Google Cloud 콘솔에서 g와 s를 차례로 누르거나 Cloud Shell을 엽니다.

환경을 프로비저닝하고 연결하는 데 몇 분 정도만 걸립니다. 완료되면 연결된 터미널이 표시됩니다.

환경이 연결되었음을 보여주는 Google Cloud Shell 터미널 스크린샷

이 가상 머신은 필요한 개발 도구가 모두 포함되어 로드됩니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 개선됩니다. 이 Codelab의 모든 작업은 브라우저 내에서 수행할 수 있습니다.

3. 시작하기 전에

API 사용 설정

Cloud SQL, Compute Engine, Service Networking, Gemini Enterprise Agent Platform을 사용하려면 Google Cloud 프로젝트에서 각 API를 사용 설정해야 합니다.

Cloud Shell 터미널에서 프로젝트 ID가 설정되어 있는지 확인합니다.

gcloud config get project

빈 문자열을 반환하는 경우 다음을 사용하여 설정합니다.

gcloud config set project [YOUR-PROJECT-ID]

PROJECT_ID 환경 변수를 설정합니다.

PROJECT_ID=$(gcloud config get-value project)

필요한 모든 API를 사용 설정합니다.

gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com

예상 출력

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 sqladmin.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.

사용 설정된 각 API에 대한 자세한 내용은 문서를 참고하세요.

4. Cloud SQL 인스턴스 만들기

Gemini Enterprise Agent Platform 데이터베이스 통합을 사용하여 Cloud SQL 인스턴스를 만듭니다.

데이터베이스 비밀번호 만들기

기본 데이터베이스 사용자의 비밀번호를 정의합니다. 자체 비밀번호를 정의하거나 무작위 함수를 사용하여 비밀번호를 생성할 수 있습니다.

export CLOUDSQL_PASSWORD=`openssl rand -hex 16`

생성된 비밀번호 값을 표시합니다.

echo $CLOUDSQL_PASSWORD

나중에 사용할 수 있도록 생성된 비밀번호를 기록해 둡니다.

MySQL용 Cloud SQL 인스턴스 만들기

Google Cloud 콘솔, Terraform, Google Cloud CLI (gcloud) 등 여러 방법을 사용하여 Cloud SQL 인스턴스를 만들 수 있습니다. 이 Codelab에서는 gcloud를 사용합니다. 다른 도구로 인스턴스를 만드는 방법을 알아보려면 인스턴스 만들기 문서를 참고하세요.

인스턴스를 만들 때 cloudsql_vector 플래그를 사용 설정할 수 있습니다. MySQL 8.0 R20241208.01_00 이상에서 벡터 지원 사용 가능

Cloud Shell 세션에서 다음을 실행합니다.

gcloud sql instances create my-cloudsql-instance \
--database-version=MYSQL_8_4 \
--tier=db-custom-2-8192 \
--region=us-central1 \
--enable-google-ml-integration \
--edition=ENTERPRISE \
--root-password=$CLOUDSQL_PASSWORD

gcloud sql connect를 사용하여 인스턴스에 연결합니다. 메시지가 표시되면 다음 비밀번호를 입력합니다.

gcloud sql connect my-cloudsql-instance --user=root

예상 출력:

$gcloud sql connect my-cloudsql-instance --user=root
Allowlisting your IP for incoming connection for 5 minutes...done.                                                                                                                           
Connecting to database with SQL user [root].Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 71
Server version: 8.4.4-google (Google)

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Ctrl+D를 누르거나 exit를 입력하여 mysql 세션을 종료합니다.

exit

Gemini Enterprise Agent Platform 통합 사용 설정

Gemini Enterprise Agent Platform 통합을 사용 설정하기 위해 Cloud SQL 서비스 계정에 필요한 IAM 역할을 부여합니다.

Cloud SQL 서비스 계정 이메일을 가져와 환경 변수로 내보냅니다.

SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL

Cloud SQL 서비스 계정에 roles/aiplatform.user 역할을 부여합니다.

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

인스턴스 생성 및 구성에 대한 자세한 내용은 Cloud SQL 문서 여기를 참고하세요.

5. 데이터베이스 준비

데이터베이스를 만들고 벡터 지원을 사용 설정합니다.

데이터베이스 만들기

quickstart_db라는 데이터베이스를 만듭니다. 데이터베이스 클라이언트 (예: mysql), Google Cloud CLI 또는 Cloud SQL Studio를 사용하여 데이터베이스를 만들 수 있습니다. 이 단계에서는 gcloud를 사용합니다.

Cloud Shell에서 다음 명령어를 실행하여 데이터베이스를 만듭니다.

gcloud sql databases create quickstart_db --instance=my-cloudsql-instance

6. 데이터 로드

데이터베이스에 테이블을 만들고 공개 Cloud Storage 버킷에 CSV 형식으로 저장된 가상의 Cymbal Store 데이터 세트 파일을 사용하여 데이터를 로드합니다.

Cloud Shell은 데이터베이스에 연결하고, 모든 객체를 만들고, 데이터를 로드하는 기본 환경입니다.

Cloud SQL 인스턴스의 승인된 네트워크 목록에 Cloud Shell 공개 IP를 추가합니다.

Cloud Shell에서 다음을 실행합니다.

gcloud sql instances patch my-cloudsql-instance --authorized-networks=$(curl ifconfig.me)

세션이 손실되거나, 재설정되거나, 다른 도구에서 작업하는 경우 CLOUDSQL_PASSWORD 변수를 다시 내보냅니다.

export CLOUDSQL_PASSWORD=...your password defined for the instance...

필요한 데이터베이스 객체를 만듭니다. mysql를 curl와 함께 사용하여 공개 소스에서 스키마를 다운로드하고 적용합니다.

Cloud Shell에서 다음을 실행합니다.

export INSTANCE_IP=$(gcloud sql instances describe my-cloudsql-instance --format="value(ipAddresses.ipAddress)")
curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_mysql_schema.sql | mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

명령어 분석 이전 단계에서는 데이터베이스에 연결하고 SQL 스크립트를 실행하여 테이블, 색인, 시퀀스를 만들었습니다.

다음으로 curl 및 mysql를 실행하여 데이터베이스에 cymbal_products 데이터를 채웁니다.

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_products.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_products FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

cymbal_stores를 계속 사용합니다.

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_stores.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_stores FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

각 매장의 각 제품 수를 나타내는 cymbal_inventory로 완료합니다.

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_inventory.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_inventory FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

선택사항: 자체 샘플 데이터 세트가 있는 경우 Google Cloud 콘솔의 가져오기 도구를 사용하여 호환되는 CSV 파일을 대신 가져올 수 있습니다.

7. 임베딩 만들기

Gemini Enterprise Agent Platform의 text-embedding-005 모델을 사용하여 제품 설명의 임베딩을 빌드하고 벡터 데이터로 저장합니다.

벡터 데이터를 저장하려면 Cloud SQL 인스턴스에서 벡터 기능을 사용 설정해야 합니다.

Cloud Shell에서 다음을 실행합니다.

gcloud sql instances patch my-cloudsql-instance \
--database-flags=cloudsql_vector=on

데이터베이스에 연결합니다.

mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

임베딩 함수를 사용하여 cymbal_products 테이블에 새 열 embedding를 만듭니다. 새 열에는 product_description 열의 텍스트를 기반으로 하는 벡터 임베딩이 저장됩니다.

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) using varbinary;
UPDATE cymbal_products SET embedding = mysql.ml_embedding('text-embedding-005', product_description);

참고: 일반적으로 2,000개 행의 임베딩 생성은 5분 이내에 완료됩니다.

mysql 세션을 종료합니다.

exit

8. 유사성 검색 실행

제품 설명에 대해 계산된 벡터 임베딩을 검색어의 임베딩과 비교하여 유사성 검색을 실행합니다.

명령줄 또는 Cloud SQL Studio에서 SQL 쿼리를 실행할 수 있습니다. Cloud SQL 스튜디오는 출력이 여러 행인 긴 SQL 문을 더 편리하게 수정하고 실행할 수 있는 방법을 제공합니다.

Cloud SQL Studio용 MySQL 사용자 만들기

Cloud SQL Studio를 사용할 수 있는 새 데이터베이스 사용자가 필요합니다. 루트 사용자에 사용한 것과 동일한 비밀번호를 사용하여 기본 제공 유형 사용자 student를 만듭니다.

Cloud Shell에서 다음을 실행합니다.

gcloud sql users create student  --instance=my-cloudsql-instance --password=$CLOUDSQL_PASSWORD --host=%

Cloud SQL Studio 시작

  1. Google Cloud 콘솔에서 Cloud SQL 인스턴스로 이동하여 my-cloudsql-instance를 클릭합니다.

Google Cloud 콘솔의 Cloud SQL 인스턴스 목록

  1. 탐색 메뉴에서 Cloud SQL Studio를 클릭합니다.

Cloud SQL Studio 메뉴 항목

  1. 인증 대화상자에서 데이터베이스 이름과 사용자 인증 정보를 입력합니다.
    • Database: quickstart_db
    • 사용자: student
    • 비밀번호:
  2. 인증을 클릭합니다.

Cloud SQL Studio 인증 대화상자

  1. 제목 없는 쿼리 탭을 클릭하여 SQL 편집기를 엽니다.

Cloud SQL Studio SQL 편집기 탭

쿼리 실행

고객 질문('여기에서 잘 자라는 과일 나무는 뭐야?')과 가장 관련성이 높은 상위 5개 제품을 가져오는 쿼리를 실행합니다.

다음은 cosine_distance 함수를 사용하여 요청에 가장 적합한 상위 5개 항목을 선택하기 위해 실행할 수 있는 쿼리입니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cosine_distance(cp.embedding ,@query_vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

Cloud SQL Studio에서 쿼리를 입력하고 실행을 클릭하거나 sql 세션에서 쿼리를 실행합니다.

Cloud SQL Studio에서 SQL 쿼리 실행

이 쿼리는 코사인 거리로 정렬된 일치하는 제품을 반환합니다.

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.13 sec)

cosine_distance 함수를 사용하면 쿼리 실행 시간은 약 0.13초입니다.

approx_distance 함수를 사용하여 KNN 검색을 사용하는 동일한 쿼리를 실행합니다. 삽입을 위한 ANN 색인이 없으면 백그라운드에서 정확한 검색으로 자동 복귀합니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

다음은 쿼리에서 반환된 제품 목록입니다.

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set, 1 warning (0.12 sec)

쿼리 실행에 걸린 시간은 0.12초에 불과합니다. KNN 정확한 cosine_distance 함수와 동일한 결과를 얻었습니다.

MySQL용 Cloud SQL 문서에서 함수에 대해 자세히 알아보기

9. 검색된 데이터를 사용하여 LLM 응답 개선

Gemini Enterprise Agent Platform 파운데이션 언어 모델에 대한 프롬프트에서 그라운딩된 컨텍스트로 쿼리 결과를 전달하여 클라이언트 애플리케이션에 대한 생성형 AI 응답을 개선합니다.

이 경우 방법은 다음과 같습니다.

  1. Cloud SQL의 벡터 검색 결과에서 JSON 페이로드를 생성합니다.
  2. Agent Platform Studio에서 프롬프트를 테스트합니다.
  3. google_ml 통합을 사용하여 SQL에서 직접 엔드 투 엔드 프롬프트를 실행합니다.

JSON 형식으로 출력 생성

결과를 JSON 형식으로 지정하고 하나의 행을 반환하도록 쿼리를 수정합니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1)
SELECT json_arrayagg(json_object('product_name',product_name,'description',description,'sale_price',sale_price,'zip_code',zip_code,'product_id',product_id)) FROM trees;

예상되는 JSON 출력:

[{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}]

Agent Platform Studio에서 프롬프트 실행

생성된 JSON을 Agent Platform Studio의 생성형 모델에 대한 프롬프트의 컨텍스트로 제공합니다.

  1. Google Cloud 콘솔에서 Agent Platform Studio를 엽니다.

Agent Platform Studio 탐색

  1. Agent Platform Studio에 다음 프롬프트를 입력합니다.

Agent Platform Studio에 프롬프트 입력

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
<JSON_OUTPUT>
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

을 쿼리의 JSON 응답으로 바꿉니다.

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

Agent Platform Studio의 프롬프트

  1. 프롬프트를 실행합니다.

Agent Platform Studio의 프롬프트 결과

답변에는 나무와 위치에 관한 정보를 기반으로 모델이 외부 소스에서 가져온 가격, 설명, 추가 정보가 포함됩니다.

SQL에서 프롬프트 실행

또한 Gemini Enterprise Agent Platform과 Cloud SQL AI 통합을 사용하여 SQL 내에서 직접 생성형 모델의 응답을 받을 수 있습니다.

먼저 모델을 등록합니다.

  1. 응답을 생성하도록 gemini-3.5-flash 모델을 등록합니다 (을 프로젝트 ID로 바꿈).
CALL
  mysql.ml_create_model_registration(
  'gemini-3.5-flash',
  'https://aiplatform.googleapis.com/v1/projects/<PROJECT_ID>/locations/global/publishers/google/models/gemini-3.5-flash:generateContent',
  'google',
  'GENERIC',
  NULL,
  'auth_type_cloudsql_service_agent_iam',
  NULL, NULL, NULL, NULL);

또한 Gemini Enterprise Agent Platform과의 Cloud SQL AI 통합을 사용하여 데이터베이스에서 직접 SQL을 사용하여 생성형 모델로부터 유사한 응답을 얻을 수 있습니다.

이제 JSON 결과와 함께 하위 쿼리에서 생성된 결과를 사용하여 SQL을 통해 생성형 AI 텍스트 모델에 프롬프트의 일부로 제공할 수 있습니다.

데이터베이스에 대한 mysql 또는 Cloud SQL Studio 세션에서 다음 쿼리를 실행합니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees AS (
SELECT
        cp.product_name,
        cp.product_description AS description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id AS product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci ON
        ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON
        cs.store_id = ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
         (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1),
prompt AS (
SELECT
       CONCAT( 'You are a friendly advisor helping to find a product based on the customer''s needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","product_description":"some description","sale_price":10}
Here is the list of products:', json_arrayagg(json_object('product_name',trees.product_name,'description',trees.description,'sale_price',trees.sale_price,'zip_code',trees.zip_code,'product_id',trees.product_id)) , 'The customer asked "What kind of fruit trees grow well here?"
You should give information about the product, price and some supplemental information') AS prompt_text
FROM
        trees),
response AS (
SELECT
       mysql.ML_PREDICT_ROW('gemini-3.5-flash',
        json_object('contents',
        json_object('role',
        'user',
        'parts',
        json_array(
        json_object('text',
        prompt_text))))) AS resp
FROM
        prompt)
SELECT
JSON_EXTRACT(resp, '$.candidates[0].content.parts[0].text')
FROM
        response;

샘플 출력은 다음과 같습니다. 모델 버전과 매개변수에 따라 출력이 다를 수 있습니다.

"Hello there! I'd be happy to help you find the perfect fruit tree for your space. \n\nBased on your area, a wonderful option we currently have in stock is the **Malus Domestica** (the classic Apple Tree)!\n\nHere are the key details:\n\n* **Product Name:** Malus Domestica (Classic Apple Tree)\n* **Price:** $100.00\n\n### Why it's a great choice:\n* **Beautiful Seasonal Foliage:** It features vibrant green leaves during the summer that turn into gorgeous shades of red, orange, and yellow in the autumn. \n* **Shade & Size:** It grows to approximately 30 feet tall, making it a strong, durable tree that offers excellent shade for your yard alongside delicious fresh fruit.\n* **Growing Conditions:** It thrives best in cool, moist climates with well-draining, loamy soil and is ideal for USDA Hardiness Zones 4–8.\n\n### Supplemental Care Tips:\n* **Planting Location:** Choose a spot that gets full sunlight (at least 6 hours a day) to ensure maximum fruit production.\n* **Soil:** Make sure the soil is rich and loamy with good drainage so the roots stay healthy.\n* **Cross-Pollination:** Apple trees often produce a higher yield when planted near another compatible apple tree variety, so if you have extra space, adding a companion tree in the future can boost your harvest!\n\nLet me know if you have any questions about planting or care, or if you'd like help adding this to your cart!"

출력은 마크다운 형식으로 제공됩니다.

10. 최근접 이웃 색인 만들기

수백만 개의 벡터가 포함된 대규모 데이터 세트의 경우 벡터 검색에 상당한 컴퓨팅 리소스가 필요할 수 있습니다. 쿼리 성능을 개선하려면 벡터 임베딩에 색인을 만드세요.

ScaNN 색인 만들기

테스트에서는 ScaNN 색인 유형을 사용해 보겠습니다.

임베딩 열의 색인을 빌드하려면 임베딩 열의 거리 측정항목을 정의해야 합니다. 매개변수에 관한 자세한 내용은 문서를 참고하세요.

CREATE VECTOR INDEX cymbal_products_embedding_idx ON cymbal_products(embedding) USING SCANN DISTANCE_MEASURE=COSINE;

대답 비교

벡터 검색 쿼리를 다시 실행하고 결과를 확인합니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

예상 출력:

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.08 sec)

성능 개선은 약간의 차이만 있지만 이렇게 작은 데이터 세트에서는 예상되는 결과입니다. 수백만 개의 벡터가 있는 대규모 데이터 세트의 경우 훨씬 더 눈에 띕니다.

EXPLAIN 명령어를 사용하여 실행 계획을 확인합니다.

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
EXPLAIN ANALYZE SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

실행 계획 (발췌):

...
-> Nested loop inner join  (cost=443 rows=5) (actual time=1.14..1.18 rows=5 loops=1)
                                -> Vector index scan on cp  (cost=441 rows=5) (actual time=1.1..1.1 rows=5 loops=1)
                                -> Single-row index lookup on cp using PRIMARY (uniq_id=cp.uniq_id)  (cost=0.25 rows=1) (actual time=0.0152..0.0152 rows=1 loops=5)

...

cp 테이블(cymbal_products 테이블의 별칭)에서 벡터 색인 검색을 보여줍니다.

자체 데이터를 사용해 보거나 다양한 검색어를 테스트하여 MySQL에서 시맨틱 검색이 어떻게 작동하는지 확인하세요.

11. 환경 정리

Cloud SQL 인스턴스를 삭제합니다.

실습을 마치면 Cloud SQL 인스턴스를 폐기합니다.

연결이 끊어지고 이전 설정이 모두 손실된 경우 Cloud Shell에서 프로젝트와 환경 변수를 정의합니다.

export INSTANCE_NAME=my-cloudsql-instance
export PROJECT_ID=$(gcloud config get-value project)

인스턴스를 삭제합니다.

gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID

예상되는 콘솔 출력:

student@cloudshell:~$ gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID
All of the instance data will be lost when the instance is deleted.

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

Deleting Cloud SQL instance...done.                                                                                                                
Deleted [https://sandbox.googleapis.com/v1beta4/projects/test-project-001-402417/instances/my-cloudsql-instance].

12. 축하합니다

축하합니다. Codelab을 완료했습니다.

Google Cloud 학습 과정

이 실습은 Google Cloud를 사용한 프로덕션 레디 AI 학습 과정의 일부입니다.

  • 전체 교육과정을 살펴보고 프로토타입과 프로덕션 간의 격차를 해소하세요.
  • #ProductionReadyAI 해시태그를 사용하여 진행 상황을 공유하세요.

학습한 내용

  • MySQL용 Cloud SQL 인스턴스를 배포하는 방법
  • 데이터베이스를 만들고 Cloud SQL AI 통합을 사용 설정하는 방법
  • 데이터베이스에 데이터를 로드하는 방법
  • Cloud SQL Studio 사용 방법
  • Cloud SQL에서 Vertex AI 임베딩 모델을 사용하는 방법
  • Agent Platform Studio 사용 방법
  • Gemini Enterprise Agent Platform 모델을 사용하여 결과를 보강하는 방법
  • 벡터 색인을 사용하여 성능을 개선하는 방법

AlloyDB Codelab 또는 Postgres용 Cloud SQL Codelab을 사용해 보세요.

설문조사

결과:

본 튜토리얼을 어떻게 사용하실 계획인가요?

읽기만 할 계획입니다. 읽은 다음 연습 활동을 완료할 계획입니다.