Kubernetes'te Gemma 4 ile AlloyDB Omni ve EmbeddingGemma

1. Giriş

Bu codelab'de, AlloyDB Omni'yi Google Kubernetes Engine'de (GKE) dağıtmayı ve yerleştirmeler ile tahminler için EmbeddingGemma ve Gemma 4 gibi açık modellerle kullanmayı öğreneceksiniz. Hem veritabanını hem de modelleri aynı kümede çalıştırmak, ağ gecikmesini azaltır ve üçüncü taraf hizmet bağımlılıklarını önler. Ayrıca, verileriniz ortamınızdan hiç ayrılmadığı için uyumluluk ve veri yerleşimi gereksinimlerini karşılamanıza da yardımcı olur.

GKE'de AlloyDB Omni ve EmbeddingGemma'nın mimari şeması

Ön koşullar

  • Google Cloud ve Google Cloud Console hakkında temel düzeyde bilgi sahibi olmak
  • Kubernetes ve GKE hakkında temel düzeyde bilgi
  • Komut satırı arayüzü ve Google Cloud Shell hakkında bilgi sahibi olma

Neler öğreneceksiniz?

  • AlloyDB Omni'yi GKE kümesine dağıtma
  • AlloyDB Omni'ye bağlanma
  • AlloyDB Omni'ye veri yükleme
  • Yapay zeka modellerini (yerleştirme ve LLM) GKE'ye dağıtma
  • AlloyDB Omni'de yapay zeka modellerini kaydetme
  • Semantik arama için yerleştirme oluşturma
  • AlloyDB Omni'de semantik arama sorguları çalıştırma
  • AlloyDB Omni'de vektör dizinleri oluşturma ve kullanma

İhtiyacınız olanlar

  • Google Cloud hesabı ve Google Cloud projesi
  • Chrome gibi bir web tarayıcısı

2. Kurulum ve şartlar

Proje ayarlama

  1. Google Cloud Console'da oturum açın. Gmail veya Google Workspace hesabınız yoksa hesap oluşturun. İş veya okul hesabı yerine kişisel hesap kullanıyorsanız.
  1. Yeni bir proje oluşturun veya mevcut bir projeyi seçin. Google Cloud Console başlığında Proje seçin'i, ardından Yeni Proje'yi tıklayın.

Google Cloud Console'da proje seçme iletişim kutusu

Proje seçin penceresinde Yeni Proje'yi tıklayarak proje oluşturma iletişim kutusunu açın.

Yeni proje oluşturma iletişim kutusu

İletişim kutusunda bir proje adı girin ve kuruluşunuzu veya konumunuzu seçin.

Proje ayrıntıları giriş alanları

  • Proje adı, bu projenin katılımcıları için görünen addır. Proje adı, Google API'leri tarafından kullanılmaz ve istediğiniz zaman değiştirilebilir.
  • Proje kimliği, tüm Google Cloud projeleri genelinde benzersizdir ve sabittir (ayarladıktan sonra değiştiremezsiniz). Google Cloud Console otomatik olarak benzersiz bir kimlik oluşturur veya kendi kimliğinizi sağlayabilirsiniz. Bu codelab'de, proje kimliğinizi yer tutucusuyla referans alırsınız.
  • Project Number (Proje numarası), bazı API'ler tarafından kullanılan üçüncü bir tanımlayıcıdır. Daha fazla bilgi için Kaynak Yöneticisi belgelerini inceleyin.

Faturalandırmayı etkinleştir

Faturalandırmayı Google Cloud kredilerini kullanarak ayarladıysanız bu adımı atlayabilirsiniz.

Kişisel faturalandırma hesabı oluşturmak için Google Cloud Console'da faturalandırmayı etkinleştirin.

  • Bu laboratuvarı tamamlamak için 5 ABD dolarından daha az Google Cloud kaynağı kullanılır.
  • Kaynakları silmek ve daha fazla ücret ödememek için bu laboratuvarın sonundaki temizleme adımlarını uygulayın.
  • Yeni kullanıcılar 300 ABD doları değerindeki ücretsiz deneme sürümünden yararlanabilir.

Cloud Shell'i Başlatma

Bu codelab'de, bulutta çalışan bir komut satırı ortamı olan Google Cloud Shell'i kullanacaksınız.

Google Cloud Console'da, sağ üstteki araç çubuğunda Cloud Shell'i etkinleştir simgesini tıklayın:

Cloud Shell'i etkinleştir düğmesi

Alternatif olarak G ve ardından S tuşuna basabilir veya Google Cloud Shell'i doğrudan açabilirsiniz.

Bağlantı kurulduğunda Cloud Shell, terminal istemini gösterir:

Google Cloud Shell terminalinin ekran görüntüsü

Cloud Shell'de kalıcı depolama alanı ve geliştirme araçları bulunur. Bu codelab'deki tüm adımları tarayıcınızdan çalıştırabilirsiniz.

3. API'leri etkinleştir

AlloyDB Omni ve model dağıtımları için Google Kubernetes Engine'i (GKE) kullanmak istiyorsanız Google Cloud projenizde Compute Engine ve GKE API'lerini etkinleştirin.

Cloud Shell'de proje kimliğinizin yapılandırıldığını doğrulayın:

PROJECT_ID=$(gcloud config get-value project)
echo $PROJECT_ID

Proje kimliğiniz tanımlanmamışsa yapılandırın:

export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID

Gerekli API'leri etkinleştirin:

gcloud services enable compute.googleapis.com
gcloud services enable container.googleapis.com

Beklenen çıkış:

student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=test-project-001-402417
student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable compute.googleapis.com
gcloud services enable container.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

Etkinleştirilen her API hakkında bilgi edinmek için belgeleri inceleyebilirsiniz.

4. GKE'de AlloyDB Omni'yi dağıtma

AlloyDB Omni'yi GKE'ye dağıtmak için AlloyDB Omni Operatörü koşullarını uygulayarak bir Kubernetes kümesi hazırlayın.

GKE kümesi oluşturma

AlloyDB Omni'yi, operatörü ve izleme container'larını çalıştırmak için bir Autopilot GKE kümesi dağıtın. Autopilot'u kullanarak dağıtımı basitleştiriyoruz. AlloyDB Omni Operatörü, küme ve diğer bileşenler için tüm kaynaklar otomatik olarak atanır.

Kaynaklarınızı dağıttığınız bölgeyi seçin. Bulunduğunuz yere coğrafi olarak yakın bir bölge seçin:

export LOCATION=<your region>

Dağıtımınız için ortam değişkenlerini ayarlayın:

export PROJECT_ID=$(gcloud config get-value project)
export CLUSTER_NAME=alloydb-ai-gke

Autopilot GKE kümesini oluşturun:

gcloud container clusters create-auto ${CLUSTER_NAME} \
  --project=${PROJECT_ID} \
  --region=${LOCATION}

Beklenen konsol çıkışı:

student@cloudshell:~ (test-project-001-402417)$ export PROJECT_ID=$(gcloud config get project)
export CLUSTER_NAME=alloydb-ai-gke
Your active configuration is: [test-project-001-402417]
student@cloudshell:~ (test-project-001-402417)$ gcloud container clusters create-auto ${CLUSTER_NAME} \
>   --project=${PROJECT_ID} \
>   --region=${LOCATION}
Creating cluster alloydb-ai-gke in us-east4... Cluster is being health-checked.
..⠹
Creating cluster alloydb-ai-gke in us-east4... Cluster is being health-checked
(Kubernetes Control Plane is healthy)...done.
Created [https://container.googleapis.com/v1/projects/gleb-genai-002/zones/us-east4/clusters/alloydb-ai-gke].
To inspect the contents of your cluster, go to: https://console.cloud.google.com/kubernetes/workload_/gcloud/us-east4/alloydb-ai-gke?project=gleb-genai-002
kubeconfig entry generated for alloydb-ai-gke.
NAME            LOCATION  MASTER_VERSION      MASTER_IP      MACHINE_TYPE   NODE_VERSION        NUM_NODES  STATUS   STACK_TYPE
alloydb-ai-gke  us-east4  1.36.4-gke.1391002  34.145.214.51  ek-standard-8  1.36.4-gke.1391002  3          RUNNING  IPV4

Kümeyi hazırlama

Kubernetes için sertifika denetleyicisi olan cert-manager gibi gerekli bileşenleri yükleyin. Ayrıntılar için cert-manager yükleme belgelerine bakın.

Cloud Shell, Kubernetes komut satırı aracı kubectl ve helm'i içerir. gcloud kullanarak küme kimlik bilgilerini alın:

gcloud container clusters get-credentials ${CLUSTER_NAME} --region=${LOCATION}

helm kullanarak cert-manager uygulamasını yükleyin:

helm install \
  cert-manager oci://quay.io/jetstack/charts/cert-manager \
  --version v1.21.2 \
  --namespace cert-manager \
  --create-namespace \
  --set featureGates="ServerSideApply=true" \
  --set global.leaderElection.namespace=cert-manager \
  --set "extraArgs={--certificate-request-minimum-backoff-duration=15s,--certificate-request-maximum-backoff-duration=5m}" \
  --set crds.enabled=true

Beklenen konsol çıkışı (düzenlenmiş):

student@cloudshell:~$ elm install \
>   cert-manager oci://quay.io/jetstack/charts/cert-manager \
>   --version v1.21.2 \
>   --namespace cert-manager \
>   --create-namespace \
>  --set featureGates="ServerSideApply=true" \
>  --set global.leaderElection.namespace=cert-manager \
>  --set "extraArgs={--certificate-request-minimum-backoff-duration=15s,--certificate-request-maximum-backoff-duration=5m}" \
>   --set crds.enabled=true
Pulled: quay.io/jetstack/charts/cert-manager:v1.21.2
Digest: sha256:634dce9c13b56677a2c05e2ab76c312d0be2664022d5dd05815da67e1fd5f610
I1016 12:25:06.128464   30644 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Deployment cert-manager/cert-manager-cainjector: defaulted unspecified 'cpu' resource for containers [cert-manager-cainjector] (see http://g.co/gke/autopilot-defaults)."
I1016 12:25:06.129972   30644 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Deployment cert-manager/cert-manager: defaulted unspecified 'cpu' resource for containers [cert-manager-controller] (see http://g.co/gke/autopilot-defaults)."
I1016 12:25:06.134580   30644 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Deployment cert-manager/cert-manager-webhook: defaulted unspecified 'cpu' resource for containers [cert-manager-webhook] (see http://g.co/gke/autopilot-defaults)."
I1016 12:25:06.250590   30644 warnings.go:107] "Warning: AdmissionWebhookController: mutated namespaceselector of the webhooks to enforce GKE Autopilot policies."
I1016 12:25:09.758249   30644 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Job cert-manager/cert-manager-startupapicheck: defaulted unspecified 'cpu' resource for containers [cert-manager-startupapicheck] (see http://g.co/gke/autopilot-defaults)."
NAME: cert-manager
LAST DEPLOYED: Fri Oct 16 12:24:57 2026
NAMESPACE: cert-manager
STATUS: deployed
REVISION: 1
DESCRIPTION: Install complete
TEST SUITE: None
NOTES:
cert-manager v1.21.2 has been deployed successfully!

AlloyDB Omni Operatörü'nü yükleme

Helm'i kullanarak AlloyDB Omni Operatörü'nü yükleme

AlloyDB Omni Operatörü grafiğini indirip yükleyin:

helm install alloydbomni-operator oci://gcr.io/alloydb-omni/alloydbomni-operator \
--version 1.9.0 \
--create-namespace \
--namespace alloydb-omni-system \
$(helm install --help | grep -q -- '--rollback-on-failure' && echo '--rollback-on-failure' || echo '--atomic') \
--timeout 5m

Beklenen konsol çıkışı (düzenlenmiş):

student@cloudshell:~$ helm install alloydbomni-operator oci://gcr.io/alloydb-omni/alloydbomni-operator \
> --version 1.9.0 \
> --create-namespace \
> --namespace alloydb-omni-system \
> $(helm install --help | grep -q -- '--rollback-on-failure' && echo '--rollback-on-failure' || echo '--atomic') \
> --timeout 5m

Pulled: gcr.io/alloydb-omni/alloydbomni-operator:1.9.0
Digest: sha256:4f6cc3f0c1fbe003ab7d0119afee516e5c67ec950cd2909b418e5a3f6f09d1f6
I1016 12:28:50.088533   30982 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Deployment alloydb-omni-system/fleet-controller-manager: adjusted 'cpu' resource to meet requirements for containers [fleet-manager] (see http://g.co/gke/autopilot-defaults)."
I1016 12:28:50.092917   30982 warnings.go:107] "Warning: autopilot-default-resources-mutator:Autopilot updated Deployment alloydb-omni-system/local-controller-manager: adjusted 'cpu' resource to meet requirements for containers [local-manager] (see http://g.co/gke/autopilot-defaults)."
I1016 12:28:50.229717   30982 warnings.go:107] "Warning: AdmissionWebhookController: mutated namespaceselector of the webhooks to enforce GKE Autopilot policies."
I1016 12:28:50.238578   30982 warnings.go:107] "Warning: AdmissionWebhookController: mutated namespaceselector of the webhooks to enforce GKE Autopilot policies."
NAME: alloydbomni-operator
LAST DEPLOYED: Fri Oct 16 12:28:45 2026
NAMESPACE: alloydb-omni-system
STATUS: deployed
REVISION: 1
DESCRIPTION: Install complete
TEST SUITE: None

Veritabanı kümesini dağıtma

Aşağıdaki manifest, googleMLExtension etkinleştirilmiş ve dahili yük dengeleyiciye sahip bir veritabanı kümesini yapılandırır:

cat << 'EOF' > my-omni.yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-pw-my-omni
type: Opaque
data:
  my-omni: "VmVyeVN0cm9uZ1Bhc3N3b3Jk"
---
apiVersion: alloydbomni.dbadmin.goog/v1
kind: DBCluster
metadata:
  name: my-omni
spec:
  databaseVersion: "18.4.0"
  primarySpec:
    adminUser:
      passwordRef:
        name: db-pw-my-omni
    features:
      googleMLExtension:
        enabled: true
    resources:
      cpu: 1
      memory: 8Gi
      disks:
      - name: DataDisk
        size: 20Gi
    dbLoadBalancerOptions:
      annotations:
        networking.gke.io/load-balancer-type: "internal"
  allowExternalIncomingTraffic: true
EOF

Şifre gizli anahtar değeri, VeryStrongPassword değerinin Base64 gösterimidir. Üretim ortamlarında şifreleri yönetmek için Google Secret Manager'ı kullanın. Ayrıntılar için Secret Manager belgelerine bakın.

Manifest, my-omni.yaml olarak kaydedilir. Cloud Shell'de, terminal penceresinin sağ üst köşesindeki Open Editor'ı (Düzenleyiciyi Aç) tıklayın ve dosyayı okuyun.

Cloud Shell'de düzenleyiciyi açma

my-omni.yaml manifestini okuduktan sonra Open Terminal'i (Terminali Aç) tıklayarak komut istemine dönün.

Cloud Shell'de terminali açma

my-omni.yaml manifest dosyasını uygulayın:

kubectl apply -f my-omni.yaml

Beklenen konsol çıkışı:

secret/db-pw-my-omni created
dbcluster.alloydbomni.dbadmin.goog/my-omni created

my-omni kümesinin durumunu kontrol edin:

kubectl get dbclusters.alloydbomni.dbadmin.goog my-omni -n default

Dağıtım sırasında veritabanı kümesi, DBClusterReady durumuna ulaşana kadar kurulum aşamalarından geçer.

Beklenen konsol çıkışı:

$ kubectl get dbclusters.alloydbomni.dbadmin.goog my-omni -n default
NAME      PRIMARYENDPOINT   PRIMARYPHASE   DBCLUSTERPHASE   HAREADYSTATUS   HAREADYREASON
my-omni   10.131.0.33        Ready          DBClusterReady

İsterseniz kubectl log komutunu kullanarak küme dağıtımını izleyebilirsiniz:

kubectl logs -l alloydbomni.internal.dbadmin.goog/dbcluster=my-omni --all-containers -f

AlloyDB Omni'ye bağlanma

Küme hazır olduğunda PostgreSQL istemcisini (psql) kullanarak veritabanı kapsülüne bağlanın. Şifre, my-omni.yaml içinde tanımlandığı şekilde VeryStrongPassword olur:

DB_CLUSTER_NAME=my-omni
DB_CLUSTER_NAMESPACE=default
DBPOD=`kubectl get pod --selector=alloydbomni.internal.dbadmin.goog/dbcluster=$DB_CLUSTER_NAME,alloydbomni.internal.dbadmin.goog/task-type=database -n $DB_CLUSTER_NAMESPACE -o jsonpath='{.items[0].metadata.name}'`
kubectl exec -ti $DBPOD -n $DB_CLUSTER_NAMESPACE -c database -- psql -h localhost -U postgres

Örnek konsol çıkışı:

DB_CLUSTER_NAME=my-omni
DB_CLUSTER_NAMESPACE=default
DBPOD=`kubectl get pod --selector=alloydbomni.internal.dbadmin.goog/dbcluster=$DB_CLUSTER_NAME,alloydbomni.internal.dbadmin.goog/task-type=database -n $DB_CLUSTER_NAMESPACE -o jsonpath='{.items[0].metadata.name}'`
kubectl exec -ti $DBPOD -n $DB_CLUSTER_NAMESPACE -c database -- psql -h localhost -U postgres
Password for user postgres:
psql (18.4)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_128_GCM_SHA256, compression: off, ALPN: postgresql)
Type "help" for help.

postgres=#

\q yazıp Enter tuşuna basarak psql oturumundan çıkın:

postgres=# \q

5. EmbeddingGemma modelini GKE'de dağıtma

AlloyDB Omni AI'ın yerel modellerle entegrasyonunu test etmek için GKE kümesine bir yerleştirme modeli dağıtın. Bu eğitimde Google'ın EmbeddingGemma modeli kullanılmaktadır.

Hugging Face jetonu alma

Bu eğitimde, Hugging Face'ten EmbeddingGemma modeli dağıtılır. Model ağırlıklarına erişmek için Hugging Face erişim jetonu oluşturun:

  1. Hugging Face'te oturum açın veya hesap oluşturun.
  2. Profiliniz > Erişim Jetonları'na gidin.
  3. Create new token'ı (Yeni jeton oluştur) tıklayın.
  4. Jeton için bir ad girin ve Okuma rolünü seçin.
  5. Create token'ı (Jeton oluştur) tıklayın ve oluşturulan jeton değerini kopyalayın.
  6. Daha önce yapmadıysanız EmbeddingGemma model sayfasında model şartlarını kabul edin.

Cloud Shell'de Hugging Face jetonunuzu içeren bir Kubernetes gizli anahtarı oluşturun (jeton yer tutucusunu kendi jetonunuzla değiştirin):

export HF_TOKEN=<YOUR_HUGGING_FACE_TOKEN>
kubectl create secret generic hf-secret \
  --from-literal=hf_api_token=$HF_TOKEN \
  --dry-run=client -o yaml | kubectl apply -f -

Dağıtım manifestini hazırlama

Modeli dağıtmak için Hugging Face'in Text Embeddings Inference (TEI) kapsayıcı paketini kullanın. Daha fazla bilgi için Hugging Face GKE TEI belgelerine bakın.

Dağıtım deposunu GitHub'dan klonlayın:

git clone https://github.com/huggingface/Google-Cloud-Containers

CPU yapılandırma manifestini inceleyin ve değiştirin:

edit Google-Cloud-Containers/examples/gke/tei-deployment/cpu-config/deployment.yaml

CPU dağıtımı için güncellenen manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tei-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tei-server
  template:
    metadata:
      labels:
        app: tei-server
        hf.co/model: Google--embeddinggemma-300m
        hf.co/task: text-embeddings
    spec:
      containers:
        - name: tei-container
          image: ghcr.io/huggingface/text-embeddings-inference:cpu-latest
          resources:
            requests:
              cpu: "6"
              memory: "24Gi"
            limits:
              cpu: "6"
              memory: "24Gi"
          env:
            - name: MODEL_ID
              value: google/embeddinggemma-300m
            - name: NUM_SHARD
              value: "1"
            - name: PORT
              value: "8080"
            - name: HF_TOKEN
              valueFrom:
                secretKeyRef:
                  name: hf-secret
                  key: hf_api_token
          volumeMounts:
            - mountPath: /tmp
              name: tmp
      volumes:
        - name: tmp
          emptyDir: {}
      nodeSelector:
        cloud.google.com/machine-family: "c3"

ctrl+s tuşuna basarak değişiklikleri kaydedin ve terminale geri dönün.

Modeli dağıtma

TEI sunucusunu dağıtmak için manifest dosyasını uygulayın:

kubectl apply -f Google-Cloud-Containers/examples/gke/tei-deployment/cpu-config

Hazır duruma gelene kadar dağıtımı izleyin:

printf "Waiting for model to load..."; until kubectl logs -l app=tei-server --tail=50 2>/dev/null | grep -q "Ready"; do printf "."; sleep 3; done; printf '\n\033[1;32m========================================\n[SUCCESS] Model is loaded and ready!\nYou can now proceed to the next step.\n========================================\033[0m\n'

tei-service Kubernetes hizmetini kontrol edin:

kubectl get service tei-service

Beklenen çıkış:

student@cloudshell$ kubectl get service tei-service
NAME          TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
tei-service   ClusterIP   34.118.233.48   <none>        8080/TCP   10m

CLUSTER-IP hizmeti, istekleri dahili olarak http://34.118.233.48:8080/embed adresinde sunar.

kubectl port-forward kullanarak model uç noktasını yerel olarak test edin:

kubectl port-forward service/tei-service 8080:8080

Terminalin üst kısmındaki + simgesini tıklayarak ikinci bir Cloud Shell sekmesi açın:

Cloud Shell sekmesi ekle

Yeni sekmede, curl ile yerleştirme oluşturmayı test edin:

curl http://localhost:8080/embed \
  -X POST \
  -d '{"inputs":"Test"}' \
  -H 'Content-Type: application/json'

Beklenen çıkış (vektör dizisi):

curl http://localhost:8080/embed \
>     -X POST \
>     -d '{"inputs":"Test"}' \
>     -H 'Content-Type: application/json'
[[-0.018975832,0.0071419072,0.06347208,0.022992613,0.014205903
...
-0.03677433,0.01636146,0.06731572]]

ctrl+c tuşuna basarak ilk sekmedeki bağlantı noktası yönlendirmeyi durdurun.

6. Yerleştirme modelini AlloyDB Omni'ye kaydetme

Dağıtılan modeli AlloyDB Omni'den kullanmak için bir veritabanı oluşturun, dönüştürme işlevlerini tanımlayın ve model uç noktasını kaydedin.

İstemci sanal makinesi ve veritabanı oluşturma

İstemci geçiş ana makinesi olarak görev yapması için aynı VPC'de bir Compute Engine sanal makine örneği oluşturun:

İstemci sanal makinesini ve AlloyDB Omni'yi gösteren ağ mimarisi şeması

Cloud Shell'de istemci sanal makinesini oluşturun:

export ZONE=${LOCATION}-a
gcloud compute instances create instance-1 \
  --zone=$ZONE

AlloyDB Omni uç nokta IP'sini alın:

echo "INSTANCE_IP=$(kubectl get dbclusters.alloydbomni.dbadmin.goog my-omni -n default -o jsonpath='{.status.primary.endpoint}')"

Beklenen çıkış:

INSTANCE_IP=10.128.0.33

INSTANCE_IP değeri, AlloyDB Omni kümesinin dahili yük dengeleyici IP'sidir. Bu örnekte bu değer 10.131.0.33 şeklindedir.

SSH kullanarak sanal makine örneğine bağlanın:

gcloud compute ssh instance-1 --zone=$ZONE

instance-1 üzerindeki SSH oturumunda PostgreSQL istemcisini yükleyin:

sudo apt-get update && sudo apt-get install --yes postgresql-client 

AlloyDB Omni yük dengeleyici IP'sini dışa aktarın (PRIMARYENDPOINT IP'nizle değiştirin):

export INSTANCE_IP=10.131.0.33

psql komutunu kullanarak AlloyDB Omni'ye bağlanın (şifre: VeryStrongPassword):

psql "host=$INSTANCE_IP user=postgres sslmode=require"

psql oturumunda demo veritabanını oluşturun:

CREATE DATABASE demo;

demo veritabanına geçin:

\c demo

Dönüşüm işlevleri oluşturma

Özel yerleştirme uç noktaları, AlloyDB Omni ile model API'si arasındaki veri biçimlerini uyarlamak için giriş ve çıkış dönüştürme işlevleri gerektirir.

Giriş dönüştürme işlevini oluşturun:

CREATE OR REPLACE FUNCTION tei_text_input_transform(model_id VARCHAR(100), input_text TEXT)
RETURNS JSON
LANGUAGE plpgsql
AS $$
DECLARE
  transformed_input JSON;
BEGIN
  SELECT json_build_object('inputs', input_text, 'truncate', true)::JSON INTO transformed_input;
  RETURN transformed_input;
END;
$$;

Beklenen çıkış:

demo=# CREATE OR REPLACE FUNCTION tei_text_input_transform(model_id VARCHAR(100), input_text TEXT)
RETURNS JSON
LANGUAGE plpgsql
AS $$
DECLARE
  transformed_input JSON;
BEGIN
  SELECT json_build_object('inputs', input_text, 'truncate', true)::JSON INTO transformed_input;
  RETURN transformed_input;
END;
$$;
CREATE FUNCTION
demo=#

Vektör dizisi yanıtını ayrıştırmak için çıkış dönüştürme işlevini oluşturun:

CREATE OR REPLACE FUNCTION tei_text_output_transform(model_id VARCHAR(100), response_json JSON)
RETURNS REAL[]
LANGUAGE plpgsql
AS $$
DECLARE
  transformed_output REAL[];
BEGIN
  SELECT ARRAY(SELECT json_array_elements_text(response_json->0)) INTO transformed_output;
  RETURN transformed_output;
END;
$$;

Beklenen çıkış:

demo=# CREATE OR REPLACE FUNCTION tei_text_output_transform(model_id VARCHAR(100), response_json JSON)
RETURNS REAL[]
LANGUAGE plpgsql
AS $$
DECLARE
  transformed_output REAL[];
BEGIN
  SELECT ARRAY(SELECT json_array_elements_text(response_json->0)) INTO transformed_output;
  RETURN transformed_output;
END;
$$;
CREATE FUNCTION
demo=#

Modeli kaydetme

google_ml.create_model prosedürünü kullanarak modeli AlloyDB Omni'ye kaydedin. İstekleri Kubernetes küme hizmetine yönlendirmek için model_request_url olarak http://tei-service:8080/embed değerini belirtin:

CALL
  google_ml.create_model(
    model_id => 'embeddinggemma',
    model_request_url => 'http://tei-service:8080/embed',
    model_provider => 'custom',
    model_type => 'text_embedding',
    model_in_transform_fn => 'tei_text_input_transform',
    model_out_transform_fn => 'tei_text_output_transform');

Beklenen çıkış:

demo=# CALL
  google_ml.create_model(
    model_id => 'embeddinggemma',
    model_request_url => 'http://tei-service:8080/embed',
    model_provider => 'custom',
    model_type => 'text_embedding',
    model_in_transform_fn => 'tei_text_input_transform',
    model_out_transform_fn => 'tei_text_output_transform');
CALL
demo=#

Kayıtlı modeli örnek bir SQL sorgusuyla test edin:

SELECT google_ml.embedding('embeddinggemma', 'What is AlloyDB Omni?');

İşlev, GKE'de çalışan yerel EmbeddingGemma modeli tarafından oluşturulan gerçek sayı dizisi temsilini döndürür.

psql oturum istemine dönmek için q tuşuna basın.

psql oturumundan çıkın:

\q

7. Modeli örneklenmiş verilerle test etme

Örnek verileri yükleme

Bu eğitimde, vektör benzerlik aramasını göstermek için Cymbal perakende veri kümesi kullanılır. AlloyDB Omni'ye veri aktarmak için Google Cloud SDK'yı ve PostgreSQL istemcisini kullanacaksınız.

instance-1 üzerindeki SSH oturumunda demo veritabanına bağlanın ve vector uzantısını etkinleştirin:

psql "host=$INSTANCE_IP user=postgres sslmode=require dbname=demo"

psql oturumunda:

CREATE EXTENSION IF NOT EXISTS vector;

psql oturumundan çıkın:

\q

demo veritabanında tablo oluşturmak için şemayı indirip uygulayın:

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql |psql "host=$INSTANCE_IP user=postgres dbname=demo"

Beklenen çıkış:

student@cloudshell:~$ gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql |psql "host=$INSTANCE_IP user=postgres dbname=demo"
Password for user postgres:
SET
SET
SET
SET
SET
 set_config
------------

(1 row)

SET
SET
SET
SET
SET
SET
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE SEQUENCE
ALTER TABLE
ALTER SEQUENCE
ALTER TABLE
ALTER TABLE
ALTER TABLE
student@cloudshell:~$

Oluşturulan tabloları doğrulayın:

psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\dt+"

Beklenen çıkış:

student@cloudshell:~$ psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\dt+"
Password for user postgres: 
                                           List of relations
 Schema |       Name       | Type  |  Owner   | Persistence | Access method |    Size    | Description 
--------+------------------+-------+----------+-------------+---------------+------------+-------------
 public | cymbal_embedding | table | postgres | permanent   | heap          | 8192 bytes | 
 public | cymbal_inventory | table | postgres | permanent   | heap          | 8192 bytes | 
 public | cymbal_products  | table | postgres | permanent   | heap          | 8192 bytes | 
 public | cymbal_stores    | table | postgres | permanent   | heap          | 8192 bytes | 
(4 rows)

cymbal_products tablosuna veri yükleyin:

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_products from stdin csv header"

Beklenen çıkış:

student@cloudshell:~$ gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_products from stdin csv header"
COPY 941
student@cloudshell:~$ 

cymbal_products tablosundan birkaç satırlık bir örnek aşağıda verilmiştir.

psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT uniq_id,left(product_name,30),left(product_description,50),sale_price FROM cymbal_products limit 3"

Beklenen çıkış:

student@cloudshell:~$ psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT uniq_id,left(product_name,30),left(product_description,50),sale_price FROM cymbal_products limit 3"
Password for user postgres: 
             uniq_id              |              left              |                        left                        | sale_price 
----------------------------------+--------------------------------+----------------------------------------------------+------------
 a73d5f754f225ecb9fdc64232a57bc37 | Laundry Tub Strainer Cup       |   Laundry tub strainer cup Chrome For 1-.50, drain |      11.74
 41b8993891aa7d39352f092ace8f3a86 | LED Starry Star Night Light La |  LED Starry Star Night Light Laser Projector 3D Oc |      46.97
 ed4a5c1b02990a1bebec908d416fe801 | Surya Horizon HRZ-1060 Area Ru |  The 100% polypropylene construction of the Surya  |       77.4
(3 rows)
student@cloudshell:~$ 

cymbal_inventory tablosuna veri yükleyin:

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_inventory from stdin csv header"

Beklenen çıkış:

student@cloudshell:~$ gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_inventory from stdin csv header"
Password for user postgres: 
COPY 263861
student@cloudshell:~$ 

cymbal_inventory tablosundan birkaç satırlık bir örnek aşağıda verilmiştir.

psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT * FROM cymbal_inventory LIMIT 3"

Çıkış:

student@cloudshell:~$ psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT * FROM cymbal_inventory LIMIT 3"
Password for user postgres: 
 store_id |             uniq_id              | inventory 
----------+----------------------------------+-----------
     1583 | adc4964a6138d1148b1d98c557546695 |         5
     1490 | adc4964a6138d1148b1d98c557546695 |         4
     1492 | adc4964a6138d1148b1d98c557546695 |         3
(3 rows)
student@cloudshell:~$ 

cymbal_stores tablosuna veri yükleyin:

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_stores from stdin csv header"

Beklenen konsol çıkışı:

student@cloudshell:~$ gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv |psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "\copy cymbal_stores from stdin csv header"
Password for user postgres: 
COPY 4654
student@cloudshell:~$

cymbal_stores tablosundan birkaç satırlık bir örnek aşağıda verilmiştir.

psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT store_id, name, zip_code FROM cymbal_stores limit 3"

Çıkış:

student@cloudshell:~$ psql "host=$INSTANCE_IP user=postgres dbname=demo" -c "SELECT store_id, name, zip_code FROM cymbal_stores limit 3"
Password for user postgres: 
 store_id |       name        | zip_code 
----------+-------------------+----------
     1990 | Mayaguez Store    |      680
     2267 | Ware Supercenter  |     1082
     4359 | Ponce Supercenter |      780
(3 rows)
student@cloudshell:~$ 

Yerleştirmeler oluşturma

psql kullanarak demo veritabanına bağlanın ve cymbal_products tablosunda açıklanan ürünler için ürün açıklamalarına göre yerleştirmeler oluşturun.

Demo veritabanına bağlanma:

psql "host=$INSTANCE_IP user=postgres sslmode=require dbname=demo"

Ürün açıklamaları için oluşturulan metin yerleştirmelerini depolamak üzere vector türündeki embedding sütununu kullanın.

Sorgu zamanlamasını etkinleştirme:

\timing

Her ürün açıklaması için yerleştirme oluşturun ve bunları cymbal_embedding tablosunda depolayın:

INSERT INTO cymbal_embedding (uniq_id, embedding)
SELECT uniq_id, google_ml.embedding('embeddinggemma', product_description)::vector
FROM cymbal_products;

Beklenen çıkış:

demo=# INSERT INTO cymbal_embedding(uniq_id,embedding)  SELECT uniq_id, google_ml.embedding('embeddinggemma',product_description)::vector FROM cymbal_products;
INSERT 0 941
Time: 497878.136 ms (08:17.878)
demo=#

Semantik arama sorguları çalıştırma

psql oturumunda, kosinüs uzaklığını (<=>) kullanarak "What kind of fruit trees grow well here?" sorusuyla eşleşen en iyi beş ürünü bulun:

SELECT
    cp.product_name,
    left(cp.product_description, 80) AS description,
    cp.sale_price,
    cs.zip_code,
    (ce.embedding <=> google_ml.embedding('embeddinggemma', 'What kind of fruit trees grow well here?')::vector) AS distance
FROM
    cymbal_products cp
JOIN cymbal_embedding ce ON ce.uniq_id = cp.uniq_id
JOIN cymbal_inventory ci ON ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON cs.store_id = ci.store_id
WHERE
    ci.inventory > 0
    AND cs.store_id = 1583
ORDER BY
    distance ASC
LIMIT 5;

Beklenen çıkış:

demo=# SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (ce.embedding <=> google_ml.embedding('embeddinggemma','What kind of fruit trees grow well here?')::vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_embedding ce on ce.uniq_id=cp.uniq_id
JOIN cymbal_inventory ci on ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on cs.store_id=ci.store_id
WHERE
    ci.inventory > 0
    AND cs.store_id = 1583
ORDER BY
    distance ASC
LIMIT 5;
     product_name      |                                   description                                    | sale_price | zip_code |      distance
-----------------------+----------------------------------------------------------------------------------+------------+----------+--------------------
 Cherry Tree           | This is a beautiful cherry tree that will produce delicious cherries. It is an d |      75.00 |    93230 | 0.5210549378080666
 California Lilac      | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d |       5.00 |    93230 | 0.5639421771781971
 Toyon                 | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 | 0.5670010914504852
 Rose Bush             | This is a beautiful rose bush that will produce fragrant roses. It is a perennia |      50.00 |    93230 | 0.5731542622882957
 California Peppertree | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e |      25.00 |    93230 | 0.5750934653011995
(5 rows)

Time: 83.610 ms
demo=#

Sorgu 83 milisaniye boyunca çalıştı ve cymbal_products tablosundan istekle eşleşen ve 1583 numaralı mağazada envanteri bulunan ağaçların listesini döndürdü.

ANN dizini oluşturma

Küçük bir veri kümesinde, tüm yerleştirmeleri tarayan tam arama özelliğini kullanmak kolaydır. Ancak veri kümesi büyüdükçe yükleme ve yanıt süresi de artar. Performansı artırmak için yerleştirme verilerinizde dizinler oluşturabilirsiniz. Vektör verileri için Google ScaNN dizinini kullanarak bunu nasıl yapacağınızı gösteren bir örnek aşağıda verilmiştir.

Bağlantıyı kaybettiyseniz demo veritabanına yeniden bağlanın:

psql "host=$INSTANCE_IP user=postgres sslmode=require dbname=demo"

alloydb_scann uzantısını etkinleştirin:

CREATE EXTENSION IF NOT EXISTS alloydb_scann;

embedding sütununda ScaNN dizini oluşturun:

CREATE INDEX cymbal_products_embeddings_scann ON cymbal_embedding
  USING scann (embedding cosine)
  WITH (num_leaves=10, max_num_levels = 1);

Yürütme performansını karşılaştırmak için semantik arama sorgusunu yeniden çalıştırın:

SELECT
    cp.product_name,
    left(cp.product_description, 80) AS description,
    cp.sale_price,
    cs.zip_code,
    (ce.embedding <=> google_ml.embedding('embeddinggemma', 'What kind of fruit trees grow well here?')::vector) AS distance
FROM
    cymbal_products cp
JOIN cymbal_embedding ce ON ce.uniq_id = cp.uniq_id
JOIN cymbal_inventory ci ON ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON cs.store_id = ci.store_id
WHERE
    ci.inventory > 0
    AND cs.store_id = 1583
ORDER BY
    distance ASC
LIMIT 5;

Beklenen çıkış:

demo=# SELECT
    cp.product_name,
    left(cp.product_description,80) as description,
    cp.sale_price,
    cs.zip_code,
    (ce.embedding <=> google_ml.embedding('embeddinggemma', 'What kind of fruit trees grow well here?')::vector) AS distance
FROM
    cymbal_products cp
JOIN cymbal_embedding ce ON ce.uniq_id = cp.uniq_id
JOIN cymbal_inventory ci ON ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON cs.store_id = ci.store_id
WHERE
    ci.inventory > 0
    AND cs.store_id = 1583
ORDER BY
    distance ASC
LIMIT 5;
     product_name      |                                   description                                    | sale_price | zip_code |      distance
-----------------------+----------------------------------------------------------------------------------+------------+----------+--------------------
 Cherry Tree           | This is a beautiful cherry tree that will produce delicious cherries. It is an d |      75.00 |    93230 | 0.5210549378080666
 California Lilac      | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d |       5.00 |    93230 | 0.5639421771781971
 Toyon                 | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 | 0.5670010914504852
 Rose Bush             | This is a beautiful rose bush that will produce fragrant roses. It is a perennia |      50.00 |    93230 | 0.5731542622882957
 California Peppertree | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e |      25.00 |    93230 | 0.5750934653011995
(5 rows)

Time: 64.783 ms

Sorgu yürütme süresi biraz azaldı ve daha büyük veri kümelerinde bu fark daha belirgin olacaktır. Döndürülen veriler, dizin olmadan aldığımız verilerle aynı veya çok benzer olmalıdır.

Diğer sorguları deneyin ve vektör dizinini optimize etme hakkında daha fazla bilgiyi belgelerde okuyun.

psql oturumundan çıkın:

\q

CTRL+D tuşlarına basarak veya exit yazarak instance-1 ssh oturumunun bağlantısını kesin ve Google Cloud Shell'e dönün.

8. Gemma'yı vLLM ile dağıtma

Gemma için düğüm havuzu ekleme

Öncelikle bölgenizde hangi düğüm türlerinin kullanılabildiğini kontrol edin:

gcloud compute accelerator-types list --filter="zone:${LOCATION}"

nvidia-l4 hızlandırıcısı da dahil olmak üzere kullanılabilir hızlandırıcı türlerinin listesini görürsünüz.

vLLM kullanarak Google Gemini 4 12B modeli için bir dağıtım manifesti oluşturun:

cat << 'EOF' > gemma-12b-gpu-vllm-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gemma-12b-gpu-vllm-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: gemma-12b-gpu-vllm
  template:
    metadata:
      labels:
        app: gemma-12b-gpu-vllm
        ai.gke.io/model: gemma-4-12b-it
        ai.gke.io/inference-server: vllm
        examples.ai.gke.io/source: user-guide
    spec:
      containers:
      - name: inference-server
        image: us-docker.pkg.dev/vertex-ai/vertex-vision-model-garden-dockers/pytorch-vllm-serve:latest
        resources:
          requests:
            cpu: "4"
            memory: "16Gi"
            ephemeral-storage: "30Gi"
            nvidia.com/gpu: "1"
          limits:
            cpu: "8"
            memory: "24Gi"
            ephemeral-storage: "30Gi"
            nvidia.com/gpu: "1"
        command: ["python3", "-m", "vllm.entrypoints.api_server"]
        args:
          - --model=$(MODEL_ID)
          - --host=0.0.0.0
          - --port=8000
          - --tensor-parallel-size=1
          - --enable-log-requests
          - --enable-chunked-prefill
          - --enable-prefix-caching
          - --enable-auto-tool-choice
          - --generation-config=auto
          - --tool-call-parser=gemma4
          - --dtype=bfloat16
          - --max-num-seqs=16
          - --max-model-len=32768
          - --gpu-memory-utilization=0.95
          - --reasoning-parser=gemma4
          - --trust-remote-code
          - --quantization=fp8
        env:
        - name: LD_LIBRARY_PATH
          value: ${LD_LIBRARY_PATH}:/usr/local/nvidia/lib64
        - name: MODEL_ID
          value: google/gemma-4-12b-it
        - name: HF_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-secret
              key: hf_api_token
        volumeMounts:
        - mountPath: /dev/shm
          name: dshm
      volumes:
      - name: dshm
        emptyDir:
            medium: Memory
      nodeSelector:
        cloud.google.com/gke-accelerator: nvidia-l4
        cloud.google.com/gke-gpu-driver-version: latest
---
apiVersion: v1
kind: Service
metadata:
  name: gemma-12b-gpu-vllm-service
spec:
  selector:
    app: gemma-12b-gpu-vllm
  type: ClusterIP
  ports:
    - protocol: TCP
      port: 8000
      targetPort: 8000
EOF

Kayıtlı gemma-12b-gpu-vllm-deployment.yaml dağıtımını uygulayın:

kubectl apply -f gemma-12b-gpu-vllm-deployment.yaml

Beklenen çıkış:

$ kubectl apply -f gemma-12b-gpu-vllm-deployment.yaml
deployment.apps/gemma-12b-gpu-vllm-deployment created
service/gemma-12b-gpu-vllm-service created

Dağıtım tamamlanana ve model yüklenene kadar bekleyin. Bu işlem birkaç dakika sürebilir.

printf "Waiting for model to load..."; until kubectl logs -l app=gemma-12b-gpu-vllm --tail=50 2>/dev/null | grep -q "Application startup complete"; do printf "."; sleep 3; done; printf '\n\033[1;32m========================================\n[SUCCESS] Model is loaded and ready!\nYou can now proceed to the next step.\n========================================\033[0m\n'

Beklenen çıkış:

Waiting for model to load...
========================================
[SUCCESS] Model is loaded and ready!
You can now proceed to the next step.
========================================

Modeli test etme Modele erişmek için bağlantı noktası yönlendirmeyi etkinleştirin:

kubectl port-forward svc/gemma-12b-gpu-vllm-service 8090:8000

Başka bir terminal penceresinde, modele istem göndermek için curl'ü kullanın:

curl http://localhost:8090/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "system", "content": "You are a helpful assistant running on GKE."},
      {"role": "user", "content": "What is AlloyDB Omni."}
    ],
    "temperature": 0.7
  }' | jq -r '.choices[0].message.content'

Beklenen çıkış:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  3957  100  3761  100   196     85      4  0:00:49  0:00:43  0:00:06   830
**AlloyDB Omni** is a fully managed, PostgreSQL-compatible database engine from Google Cloud that can be run **on-premises, in other clouds, or in your own data centers.**

To understand it simply: It allows you to run the high-performance, enterprise-grade capabilities of Google's **AlloyDB** (a cloud-native database) on your own infrastructure.

Here is a breakdown of what makes it significant:

### 1. The "Best of Both Worlds" Architecture
Normally, you have to choose between:
*   **Managed Cloud Databases:** Easy to scale and manage, but you are locked into the cloud provider's infrastructure.
*   **Self-Managed Databases:** You have full control over the hardware/location, but you are responsible for scaling, patching, and high availability.

**AlloyDB Omni** bridges this gap. It provides the advanced features of a cloud-native database (like intelligent indexing, high availability, and massive scalability) while allowing you to run it anywhere.

Ctrl+C tuşuna basarak ilk terminaldeki bağlantı noktası yönlendirmeyi durdurun (hâlâ çalışıyorsa).

9. Gemma 4 modelini AlloyDB Omni'ye kaydetme

google_ml.create_model prosedürünü kullanarak Gemma 12B modelini AlloyDB Omni'ye kaydedin. İstekleri Kubernetes küme hizmetine yönlendirmek için model_request_url olarak http://gemma-12b-gpu-vllm-service:8000/v1/chat/completions değerini belirtin:

AlloyDB Omni uç nokta IP'sini alın:

echo "INSTANCE_IP=$(kubectl get dbclusters.alloydbomni.dbadmin.goog my-omni -n default -o jsonpath='{.status.primary.endpoint}')"

SSH kullanarak sanal makine örneğine bağlanın:

gcloud compute ssh instance-1 --zone=$ZONE

Sanal makineye bağlandıktan sonra önceki adımda elde ettiğiniz INSTANCE_IP değişkenini dışa aktarın (10.128.0.33 değeri örnek olarak verilmiştir, bu değeri kendi IP'nizle değiştirin):

export INSTANCE_IP=10.128.0.33

AlloyDB şifresini dışa aktarın:

export PGPASSWORD=VeryStrongPassword

demo veritabanına bağlanın:

psql "host=$INSTANCE_IP user=postgres sslmode=require dbname=demo"

psql oturumunda modeli kaydedin:

CALL
  google_ml.create_model(
    model_id => 'gemma-12b-gpu',
    model_request_url => 'http://gemma-12b-gpu-vllm-service:8000/v1/chat/completions',
    model_provider => 'custom',
    model_type => 'llm');

Modeli örnek bir SQL sorgusuyla test edin:

SELECT google_ml.predict_row(
  model_id => 'gemma-12b-gpu',
  request_body => json_build_object(
    'messages', json_build_array(
      json_build_object('role', 'user', 'content', 'What is AlloyDB Omni?'))))->'choices'->0->'message'->'content';

Sonuç penceresinden çıkıp psql istemine dönmek için q tuşuna basın.

AlloyDB Omni'de vektör aramasını LLM RAG ile birleştirme

LLM ile RAG'yi (almayla artırılmış üretim) göstermek için LLM isteğiyle vektör aramasını kullanma

SQL sorgusunu plsql'de çalıştırın:

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_embedding ce ON ce.uniq_id = cp.uniq_id
JOIN cymbal_inventory ci ON ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON cs.store_id = ci.store_id
WHERE
        ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (ce.embedding <=> embedding('embeddinggemma',
        'What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1),
prompt AS (
SELECT
        '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_agg(trees) || '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
        google_ml.predict_row(
          model_id =>'gemma-12b-gpu',
          request_body => json_build_object(
            'messages', json_build_array(
              json_build_object('role', 'user', 'content',prompt_text)
            )))->'choices'->0->'message'->'content' AS resp
FROM
        prompt)
SELECT
REPLACE(resp::text, '\n', CHR(10))
FROM
        response;

Beklenen çıkış:

----------------------------------------------------------------------------------------------------------------------------------------------
 "Hello there! I'd be happy to help you find the perfect tree for your garden.                                                               +
                                                                                                                                             +
 Based on your location, we have a wonderful option that would grow beautifully in your area:                                                +
                                                                                                                                             +
 **Cherry Tree**                                                                                                                             +
 *   **Price:** $75.00                                                                                                                       +
 *   **Description:** This is a stunning deciduous tree that not only provides a beautiful landscape but also produces delicious cherries.   +
 *   **Supplemental Information:**                                                                                                           +
     *   **Growth:** It grows to about 15 feet tall.                                                                                         +
     *   **Appearance:** You can look forward to dark green leaves in the summer that transform into a vibrant red in the fall.              +
     *   **Benefits:** It's a great choice if you're looking for both fruit and extra shade or privacy in your yard.                         +
     *   **Care Tips:** It performs best in a cool, moist climate with sandy soil. Since you are in a suitable zone, it should thrive nicely!+
                                                                                                                                             +
 Would you like more details on how to plant this, or would you like to proceed with an order?"
(1 row)

Sorgu, LLM'ye gönderilen istemi vektör arama sonuçlarıyla destekler.

Diğer sorguları deneyin ve RAG kalıplarıyla denemeler yapın. Sunulan mimarinin avantajı, tamamen kendi kendine yetebilmesidir. Veriler kümenizin dışına gönderilmez ve tamamen izole edilmiş ortamlarda çalıştırılabilir.

psql oturumundan çıkın:

\q

Sanal makineyle SSH oturumunun bağlantısını kesin:

exit

AlloyDB Omni'nin daha fazla özelliği ve laboratuvarı olduğunu unutmayın.

10. Ortamı temizleme

Google Cloud hesabınızda sürekli ücretlendirme olmaması için bu codelab'de oluşturulan kaynakları silin.

GKE kümesini silme

Cloud Shell'de GKE kümesini silin:

export PROJECT_ID=$(gcloud config get-value project)
export CLUSTER_NAME=alloydb-ai-gke
gcloud container clusters delete ${CLUSTER_NAME} \
  --project=${PROJECT_ID} \
  --region=${LOCATION}

Beklenen çıkış:

student@cloudshell:~$ gcloud container clusters delete ${CLUSTER_NAME} \
>   --project=${PROJECT_ID} \
>   --region=${LOCATION}
The following clusters will be deleted.
 - [alloydb-ai-gke] in [us-east4]

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

Deleting cluster alloydb-ai-gke...done.
Deleted

İstemci sanal makinesini silme

Cloud Shell'de Compute Engine örneğini silin:

export PROJECT_ID=$(gcloud config get-value project)
gcloud compute instances delete instance-1 \
  --project=${PROJECT_ID} \
  --zone=${ZONE}

Beklenen çıkış:

student@cloudshell:~$ export PROJECT_ID=$(gcloud config get project)
export ZONE=us-east4-a
gcloud compute instances delete instance-1 \
  --project=${PROJECT_ID} \
  --zone=${ZONE}
Your active configuration is: [cloudshell-5399]
The following instances will be deleted. Any attached disks configured to be auto-deleted will be deleted unless they are attached to any other instances or the `--keep-disks` flag is given and specifies them for keeping. Deleting a disk 
is irreversible and any data on the disk will be lost.
 - [instance-1] in [us-east4-a]

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

Deleted

Bu codelab için yeni bir proje oluşturduysanız dilerseniz projenin tamamını Google Cloud Resource Manager'dan silebilirsiniz.

11. Tebrikler

Codelab'i tamamladığınız için tebrikler.

İşlediğiniz konular

  • AlloyDB Omni'yi GKE kümesine dağıtma
  • AlloyDB Omni'ye bağlanma
  • AlloyDB Omni'ye veri yükleme
  • Yapay zeka modellerini (yerleştirme ve LLM) GKE'ye dağıtma
  • AlloyDB Omni'de yapay zeka modellerini kaydetme
  • Semantik arama için yerleştirme oluşturma
  • AlloyDB Omni'de semantik arama sorguları çalıştırma
  • AlloyDB Omni'de vektör dizinleri oluşturma ve kullanma

AlloyDB Omni'de yapay zeka ile çalışma hakkında daha fazla bilgiyi belgelerde bulabilirsiniz.

Anket

Çıkış:

Bu eğitimden nasıl yararlanacaksınız?

Yalnızca okuyun Okuyun ve alıştırmaları tamamlayın