将 TypeSafe AI 的 Jev 模型与 AlloyDB AI 函数搭配使用,实现高速 AI 查询

1. 简介

在此 Codelab 中,您将使用 AlloyDB 的原生 AI 函数(ai.if、ai.analyze_sentiment 和 ml_predict_row)将 TypeSafe AI 的 Jev 模型连接到 AlloyDB AI。这样一来,您就可以直接在 AlloyDB 的运营数据上使用 Jev 模型运行高效的批量推理,而无需移动数据或编写复杂的应用端代码。

您将执行的操作

  • 预配专用服务访问通道 (PSA) 以及 AlloyDB for PostgreSQL 集群和主实例
  • 创建允许 Cloudshell 和内部连接的 VPC 防火墙规则
  • 使用 gcloud alloydb clusters import 加载电子商务示例数据集
  • 启用 Google Secret Manager 和 AlloyDB 的 google_ml_integration 扩展程序
  • 在 Secret Manager 中存储 TypeSafe AI API 密钥并授予访问权限
  • 为 Jev 的 noul(布尔值)和 choice(情感)基元创建 PL/pgSQL 输入和输出转换函数
  • 在 AlloyDB 中注册自定义 jev-model 模型端点
  • 直接在 SQL 中运行标量和数组批处理语义查询(ai.if 和 ai.analyze_sentiment)
  • 使用 ai.analyze_sentiment 查询真实客户的商品评价,以进行情绪分类
  • (奖励)注册一个通用端点 (jev-systemone),并使用 Jev 的 score 基元评估持续的客户满意度强度

所需条件

  • 网络浏览器,例如 Chrome
  • 启用了结算功能的 Google Cloud 项目
  • TypeSafe AI API 密钥(来自 TypeSafe AI)

2. 准备工作

选择 Google Cloud 项目

在 Google Cloud 控制台中,选择或创建要使用的 Google Cloud 项目。

启动 Cloud Shell

点击 Google Cloud 控制台右上角的激活 Cloud Shell。

验证您的 Cloud Shell 会话是否已通过身份验证:

gcloud auth list

设置项目 ID 和环境变量:

export PROJECT_ID=$(gcloud config get-value project)
gcloud config set project $PROJECT_ID

export REGION="us-west4"
export ADBCLUSTER="my-alloydb-cluster"
export ADBINSTANCE="my-alloydb-primary"

启用必需的 Google Cloud API

运行以下命令以启用所有必需的 Google Cloud 服务 API:

gcloud services enable \
  alloydb.googleapis.com \
  servicenetworking.googleapis.com \
  secretmanager.googleapis.com \
  compute.googleapis.com

3. 预配 AlloyDB 集群和主实例

在此步骤中,您将在 VPC 网络中分配专用服务访问通道 IP 范围,建立专用对等互连,并预配具有出站互联网访问权限的 AlloyDB 集群和主实例。

1. 创建专用服务访问通道 (PSA) IP 范围

AlloyDB 需要在您的 Virtual Private Cloud (VPC) 网络中分配专用 IP 范围。假设您使用的是 default VPC 网络:

创建专用 IP 范围分配:

gcloud compute addresses create psa-range \
    --global \
    --purpose=VPC_PEERING \
    --prefix-length=24 \
    --description="VPC private service access" \
    --network=default

建立专用 VPC 对等互连连接:

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

2. 创建 AlloyDB 集群

为初始 postgres 管理员用户生成安全的数据库密码:

export PGPASSWORD="$(openssl rand -hex 8)@1aA"
echo "Your generated AlloyDB postgres password is: $PGPASSWORD"

创建 AlloyDB 免费试用集群:

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

3. 创建具有 AI 标志和出站连接的主实例

AlloyDB 通过出站 HTTPS 直接连接到 TypeSafe AI 的安全 SaaS 端点 (https://api.typesafe.ai/v1/systemone)。因此,您必须指定 --outbound-public-ip。此外,还需为环境配置 AlloyDB AI 数据库标志:

gcloud alloydb instances create $ADBINSTANCE \
    --instance-type=PRIMARY \
    --cpu-count=2 \
    --region=$REGION \
    --cluster=$ADBCLUSTER \
    --outbound-public-ip \
    --ssl-mode=ALLOW_UNENCRYPTED_AND_ENCRYPTED \
    --database-flags=\
google_ml_integration.enable_model_support=on,\
google_ml_integration.enable_ai_query_engine=on,\
google_ml_integration.enable_ai_function_acceleration=on,\
google_ml_integration.enable_cost_optimized_ai_functions=on,\
parameterized_views.enabled=on,\
password.enforce_complexity=on,\
password.min_uppercase_letters=1,\
password.min_numerical_chars=1,\
password.min_pass_length=10

4. 加载电子商务示例数据

如需测试真实的语义查询,请直接从 Cloud Storage 导入包含商品目录和客户评价的电子商务示例数据集:

gcloud alloydb clusters import $ADBCLUSTER \
    --region=$REGION \
    --project=$PROJECT_ID \
    --gcs-uri="gs://sample-data-and-media/ecomm-retail/ecom_generic.sql" \
    --sql \
    --database=postgres \
    --user=postgres

4. 将 TypeSafe AI API 密钥存储在 Secret Manager 中

AlloyDB 的模型端点管理功能与 Google Secret Manager 原生集成,可在不对数据库代码或配置日志中的明文凭据进行公开的情况下,对外部 API 调用进行身份验证。

1. 创建 Secret

在 Cloud Shell 中,创建一个名为 typesafe-jev-api-key 的新 Secret:

gcloud secrets create typesafe-jev-api-key \
  --replication-policy="automatic"

以 Secret 版本形式添加您的 TypeSafe AI API 密钥:

echo -n "<YOUR_TYPESAFE_API_KEY>" | \
  gcloud secrets versions add typesafe-jev-api-key --data-file=-

2. 授予对 AlloyDB 服务代理的访问权限

AlloyDB 会使用其项目服务代理在查询执行期间检索 Secret。查找您的项目编号并授予 Secret Accessor 角色:

PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
ALLOYDB_SA="service-${PROJECT_NUMBER}@gcp-sa-alloydb.iam.gserviceaccount.com"

gcloud secrets add-iam-policy-binding typesafe-jev-api-key \
  --member="serviceAccount:${ALLOYDB_SA}" \
  --role="roles/secretmanager.secretAccessor"

您应该会看到输出信息,确认服务代理已收到 roles/secretmanager.secretAccessor。

5. 通过 AlloyDB Studio 连接到 AlloyDB 并初始化数据库扩展程序

如需直接通过浏览器与 AlloyDB 数据库互动,而无需配置本地客户端工具或代理隧道,请使用 Google Cloud 控制台中的 AlloyDB Studio。

1. 打开 AlloyDB Studio

  1. 在 Google Cloud 控制台中,依次前往 AlloyDB for PostgreSQL > 集群。
  2. 点击您的集群 (my-alloydb-cluster)。
  3. 在左侧导航菜单中,点击 AlloyDB Studio。
  4. 向数据库进行身份验证:
    • 数据库:postgres
    • 用户:postgres
    • 密码:输入集群创建期间生成的 $PGPASSWORD(例如,在 Cloud Shell 中运行 echo $PGPASSWORD 即可查看)。
  5. 点击身份验证。

您现在位于 AlloyDB Studio 交互式 SQL 查询编辑器中。

2. 启用数据库扩展程序和标志

在 AlloyDB Studio 查询编辑器中,粘贴并运行以下语句,以启用 google_ml_integration 扩展程序并配置运行时设置:

-- Enable the AlloyDB AI integration extension
CREATE EXTENSION IF NOT EXISTS google_ml_integration;

-- Enable preview AI functions (ai.analyze_sentiment, ai.classify)
SET google_ml_integration.enable_preview_ai_functions = 'on';

-- Disable async batching for the session to use custom transform functions directly
SET google_ml_integration.enable_async_operation = 'off';

点击运行以执行查询。

3. 在 AlloyDB MEM 中注册 Secret

告知 AlloyDB 在何处查找您的 TypeSafe AI API 密钥:

CALL google_ml.create_sm_secret(
    secret_id => 'jev_api_key',
    secret_path => 'projects/<YOUR_PROJECT_ID>/secrets/typesafe-jev-api-key/versions/latest'
);

6. 创建 SQL 转换函数

TypeSafe AI 的 System One API 接受具有不同推理原语(noul 用于布尔值约束,choice 用于多类别分类)的结构化 JSON。

AlloyDB 的模型端点管理功能使用四种转换函数(标量输入、标量输出、批量输入、批量输出)将标准 PostgreSQL ai.* 函数签名转换为 Jev REST API 格式。

1. 标量输入转换

添加以下函数,以将单行 ai.if 和 ai.analyze_sentiment 调用转换为 Jev 请求载荷:

CREATE OR REPLACE FUNCTION public.jev_model_input_transform(
    model_id VARCHAR(100),
    input_text TEXT,
    generation_config JSON,
    system_instruction TEXT
) RETURNS JSON
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
    full_instruction TEXT;
    enum_json JSON;
    criteria_obj JSONB := '{}'::JSONB;
    elem TEXT;
    q_obj JSON;
BEGIN
    -- Combine optional system instructions with the input prompt
    IF system_instruction IS NOT NULL AND length(trim(system_instruction)) > 0 THEN
        full_instruction := system_instruction || E'\n\n' || input_text;
    ELSE
        full_instruction := input_text;
    END IF;

    -- Inspect generation_config to determine whether caller expects a multi-class choice or boolean
    enum_json := COALESCE(
        generation_config->'generationConfig'->'responseSchema'->'enum',
        generation_config->'responseSchema'->'enum'
    );

    IF enum_json IS NOT NULL AND json_typeof(enum_json) = 'array' THEN
        -- Multi-class classification (ai.analyze_sentiment) -> Jev choice primitive
        FOR elem IN SELECT json_array_elements_text(enum_json) LOOP
            criteria_obj := criteria_obj || jsonb_build_object(elem, 'Category: ' || elem);
        END LOOP;
        q_obj := json_build_object(
            'type', 'choice',
            'instructions', full_instruction,
            'criteria', criteria_obj::JSON
        );
    ELSE
        -- Boolean filtering (ai.if) -> Jev noul primitive
        q_obj := json_build_object(
            'type', 'noul',
            'instructions', full_instruction
        );
    END IF;

    RETURN json_build_object(
        'model', 'jev-latest',
        'state', COALESCE(generation_config->>'state', 'Evaluate the question accurately based on the provided text.'),
        'questions', json_build_object('q_1', q_obj)
    );
END;
$$;

2. 标量输出转换

添加函数以将 Jev 的 JSON 响应解压缩回 PostgreSQL TEXT 结果:

CREATE OR REPLACE FUNCTION public.jev_model_output_transform(
    model_id VARCHAR(100),
    response_json JSON
) RETURNS TEXT
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
    q_ans JSON := response_json->'answers'->'q_1';
    ans_type TEXT := q_ans->>'type';
BEGIN
    IF ans_type = 'choice' THEN
        RETURN q_ans->>'choice';
    ELSIF ans_type = 'noul' THEN
        -- Convert probability score (0.00 to 1.00) to boolean text
        RETURN CASE WHEN (q_ans->>'noul')::FLOAT >= 0.50 THEN 'true' ELSE 'false' END;
    ELSE
        RAISE EXCEPTION 'Unexpected Jev response payload: %', response_json::TEXT;
    END IF;
END;
$$;

3. 批量输入转换

Jev 可以在一次 HTTP 往返中同时评估数十个问题,而不会出现生成质量下降的情况。

添加批输入转换,以将 PostgreSQL prompts TEXT[] 数组转换为并行 q_1 .. q_N Jev 问题:

CREATE OR REPLACE FUNCTION public.jev_model_batch_input_transform(
    model_id VARCHAR(100),
    prompts TEXT[],
    generation_config JSON,
    system_instructions JSON
) RETURNS JSON
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
    questions_obj JSONB := '{}'::JSONB;
    enum_json JSON;
    criteria_obj JSONB := '{}'::JSONB;
    elem TEXT;
    is_choice BOOLEAN := FALSE;
    i INT;
BEGIN
    enum_json := COALESCE(
        generation_config->'generationConfig'->'responseSchema'->'items'->'enum',
        generation_config->'generationConfig'->'responseSchema'->'enum',
        generation_config->'responseSchema'->'items'->'enum',
        generation_config->'responseSchema'->'enum'
    );

    IF enum_json IS NOT NULL AND json_typeof(enum_json) = 'array' THEN
        IF NOT (enum_json::JSONB = '["true", "false"]'::JSONB OR enum_json::JSONB = '["false", "true"]'::JSONB) THEN
            is_choice := TRUE;
            FOR elem IN SELECT json_array_elements_text(enum_json) LOOP
                criteria_obj := criteria_obj || jsonb_build_object(elem, 'Category: ' || elem);
            END LOOP;
        END IF;
    END IF;

    -- Construct parallel questions for every prompt in the array
    FOR i IN 1 .. COALESCE(array_length(prompts, 1), 0) LOOP
        IF is_choice THEN
            questions_obj := questions_obj || jsonb_build_object(
                'q_' || i::TEXT,
                jsonb_build_object(
                    'type', 'choice',
                    'instructions', prompts[i],
                    'criteria', criteria_obj
                )
            );
        ELSE
            questions_obj := questions_obj || jsonb_build_object(
                'q_' || i::TEXT,
                jsonb_build_object(
                    'type', 'noul',
                    'instructions', prompts[i]
                )
            );
        END IF;
    END LOOP;

    RETURN json_build_object(
        'model', 'jev-latest',
        'state', COALESCE(generation_config->>'state', 'Evaluate each question independently based on the record data.'),
        'questions', questions_obj::JSON
    );
END;
$$;

4. 批量输出转换

添加函数以按正确的 1..N 数组索引顺序提取答案:

CREATE OR REPLACE FUNCTION public.jev_model_batch_output_transform(
    model_id VARCHAR(100),
    response JSON
) RETURNS TEXT[]
LANGUAGE plpgsql IMMUTABLE AS $$
DECLARE
    results TEXT[] := ARRAY[]::TEXT[];
    answers JSON := response->'answers';
    i INT := 1;
    q_ans JSON;
    ans_type TEXT;
BEGIN
    LOOP
        q_ans := answers->('q_' || i::TEXT);
        EXIT WHEN q_ans IS NULL;
        ans_type := q_ans->>'type';
        IF ans_type = 'choice' THEN
            results := array_append(results, q_ans->>'choice');
        ELSE
            results := array_append(results, CASE WHEN (q_ans->>'noul')::FLOAT >= 0.50 THEN 'true' ELSE 'false' END);
        END IF;
        i := i + 1;
    END LOOP;
    RETURN results;
END;
$$;

7. 在 AlloyDB 中注册自定义模型端点

现在,您将转换函数、Secret 凭据和 TypeSafe AI REST 端点绑定在一起,形成一个名为 jev-model 的已注册模型。

1. 注册 jev-model

在 AlloyDB Studio 查询编辑器中,粘贴并运行以下查询:

-- Drop previous registration if updating
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM google_ml.model_info_view WHERE model_id = 'jev-model') THEN
        CALL google_ml.drop_model('jev-model');
    END IF;
END $$;

-- Register custom LLM endpoint
CALL google_ml.create_model(
    model_id => 'jev-model',
    model_request_url => 'https://api.typesafe.ai/v1/systemone',
    model_provider => 'custom',
    model_type => 'llm',
    model_qualified_name => 'jev-latest',
    model_auth_type => 'secret_manager',
    model_auth_id => 'jev_api_key',
    model_in_transform_fn => 'jev_model_input_transform',
    model_out_transform_fn => 'jev_model_output_transform',
    model_batch_in_transform_fn => 'jev_model_batch_input_transform',
    model_batch_out_transform_fn => 'jev_model_batch_output_transform'
);

2. 验证注册

查询模型注册表视图,确保 jev-model 处于有效状态且已被识别:

SELECT model_id, model_type, model_provider, model_auth_type 
FROM google_ml.model_info_view 
WHERE model_id = 'jev-model';

您看到的输出结果应该类似于以下内容:

 model_id | model_type | model_provider | model_auth_type 
----------+------------+----------------+-----------------
 jev-model  | llm        | custom         | secret_manager
(1 row)

8. 针对 Jev 运行测试查询

注册 jev-model 后,您现在可以直接在标准 PostgreSQL 查询中执行语义操作。

1. 测试标量布尔值过滤 (ai.if)

使用 ai.if 评估单个文本陈述:

SELECT ai.if(
    prompt => 'Is the product "North Face Waterproof Gore-Tex Hiking Jacket ($249)" suitable for rainy outdoor conditions?',
    model_id => 'jev-model'
) AS is_suitable;

您看到的输出结果应该类似于以下内容:

 is_suitable 
-------------
 true
(1 row)

2. 测试标量情感分析 (ai.analyze_sentiment)

将客户反馈评估为类别标签(positive、negative 或 neutral):

SET google_ml_integration.enable_preview_ai_functions = 'on';
SELECT ai.analyze_sentiment(
    input => 'The stitching on this jacket tore on the second day and the zipper jammed completely.',
    model_id => 'jev-model'
) AS sentiment;

您看到的输出结果应该类似于以下内容:

 sentiment 
-----------
 negative
(1 row)

3. 测试了数组批处理布尔值过滤

通过传递提示数组,在单个查询中评估多个项:

SET google_ml_integration.enable_async_operation = 'off';
SELECT unnest(prompts) AS product_prompt,
       unnest(ai.if(prompts => prompts, model_id => 'jev-model')) AS is_cold_weather
FROM (
    SELECT ARRAY[
        'Is "Arctic Expedition Down Parka (-30F)" cold-weather winter outerwear?',
        'Is "Men''s Boardshorts Beach Swim Trunk" cold-weather winter outerwear?',
        'Is "Merino Wool Thermal Base Layer" cold-weather winter outerwear?'
    ] AS prompts
) b;

您看到的输出结果应该类似于以下内容:

                             product_prompt                              | is_cold_weather 
-------------------------------------------------------------------------+-----------------
 Is "Arctic Expedition Down Parka (-30F)" cold-weather winter outerwear? | true
 Is "Men's Boardshorts Beach Swim Trunk" cold-weather winter outerwear?  | false
 Is "Merino Wool Thermal Base Layer" cold-weather winter outerwear?      | false
(3 rows)

4. 使用数组批处理测试表格查询

现在,查询在集群配置期间加载的 ecomm.products 表,对一批商品使用 ai.if,以检查目录中的哪些商品是寒冷天气装备。

如需对表数据运行高吞吐量语义过滤(例如,每批 50 行),请使用 PostgreSQL 的 row_number() 窗口函数将行分批:

-- Evaluate a 50-row batch of real catalog items from ecomm.products
WITH numbered AS (
    SELECT 
        id, 
        name, 
        category,
        product_description,
        ((row_number() OVER (ORDER BY id) - 1) / 50) AS batch_id
    FROM ecomm.products
    ORDER BY id DESC
    LIMIT 50
),
batched AS (
    SELECT 
        batch_id,
        array_agg(id ORDER BY id) AS ids,
        array_agg(name ORDER BY id) AS names,
        array_agg(category ORDER BY id) AS categories,
        array_agg(product_description ORDER BY id) AS descs,
        ai.if(
            prompts => array_agg('Is "' || name || '" designed for cold weather winter outerwear?' ORDER BY id),
            model_id => 'jev-model'
        ) AS decisions
    FROM numbered
    GROUP BY batch_id
),
unrolled AS (
    SELECT 
        b.batch_id,
        u.id,
        u.name,
        u.category,
        u.product_description,
        u.decision AS cold_weather_gear
    FROM batched b
    CROSS JOIN LATERAL unnest(b.ids, b.names, b.categories, b.descs, b.decisions) 
      AS u(id, name, category, product_description, decision)
)
SELECT id, name, category, product_description, cold_weather_gear
FROM unrolled
WHERE cold_weather_gear = TRUE
LIMIT 5;

您看到的输出结果应该类似于以下内容:

  id   |                                 name                                 |  category   |                                                product_description                                                 | cold_weather_gear 
-------+----------------------------------------------------------------------+-------------+--------------------------------------------------------------------------------------------------------------------+-------------------
 29071 | Winter Striped Beanie with Pom                                       | Accessories | Brave the chill in style with the SoleStyle Winter Striped Beanie! This cozy beanie adds a pop of personality...  | true
 29077 | Knit Collegiate Rugby Stripe Winter Scarf & Beanie Hat Set           | Accessories | Stay cozy and show off your sporty side with our Knit Collegiate Rugby Stripe Scarf & Beanie Set...               | true
 29083 | Junction Finds Men's Muscle Wool Blend Trapper Hat                   | Accessories | Brave the elements in style with the Junction Finds Trapper Hat! This wool-blend hat will keep you warm...        | true
 29086 | Mens Soft Thermal Insulated Wrist Length Leather Gloves - Black      | Accessories | Brave the chill in style with these supple leather gloves from Gavel Goods! Lined with a soft, thermal knit...    | true
 29090 | Long Beanie-Red W16S24E                                              | Accessories | Stay cozy and stylish all season long with this vibrant red beanie from Enchant! This isn't just any hat...       | true
(5 rows)

5. 查询客户商品评价的情感倾向

现在,使用由 Jev 的 choice 原语支持的 ai.analyze_sentiment 分析 ecomm.product_reviews 表中的客户评价:

SET google_ml_integration.enable_preview_ai_functions = 'on'
SELECT 
    r.id,
    p.name AS product_name,
    r.rating AS customer_star_rating,
    substring(r.review_text FROM 1 FOR 70) || '...' AS review_snippet,
    ai.analyze_sentiment(
        input => r.review_text,
        model_id => 'jev-model'
    ) AS detected_sentiment
FROM ecomm.product_reviews r
JOIN ecomm.products p ON r.product_id = p.id
ORDER BY r.id
LIMIT 5;

您看到的输出结果应该类似于以下内容:

 id |                  product_name                  | customer_star_rating |                             review_snippet                              | detected_sentiment 
----+------------------------------------------------+----------------------+-------------------------------------------------------------------------+--------------------
  1 | Hugs & Kisses Juniors Peplum Skirt             |                    1 | This skirt was poorly made and the fabric felt extremely cheap for for...| negative
  2 | Bonkers Larry Full Length Pull on Pants        |                    1 | These pants are way too expensive for the terrible quality you get. Th...| negative
  3 | Gifts and Garb Brah Bra Extenders              |                    3 | These extenders are okay but nothing special. They do add a bit of ext...| neutral
  4 | Auto Forge Men's Tall Duck Traditional Coat    |                    1 | This coat is terribly stiff and heavy, making it very uncomfortable to...| negative
  5 | Weaver's Way Men's Shetland Zip Neck Sweater   |                    2 | This sweater is just okay and not really worth the high price tag. The...| negative
(5 rows)

9. 奖励:使用 Jev 进行持续情感评分 score

虽然 AlloyDB 的 AI 函数(例如 ai.analyze_sentiment)会返回类别分桶(positive、negative、neutral),但 TypeSafe AI 的 score 基元会根据有序的评分准则评估细微差别,并返回介于 0 到 100 之间的连续的期望加权评分。

由于 score 返回的是数值元数据,而不是文本分类标签,因此您可以注册自定义 generic 模型端点 (jev-systemone),并使用 google_ml.predict_row 调用该端点。

1. 注册通用端点

在 AlloyDB Studio 中,使用 model_type => 'generic' 注册 jev-systemone:

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM google_ml.model_info_view WHERE model_id = 'jev-systemone') THEN
        CALL google_ml.drop_model('jev-systemone');
    END IF;
EXCEPTION WHEN OTHERS THEN
    NULL;
END $$;

CALL google_ml.create_model(
    model_id => 'jev-systemone',
    model_request_url => 'https://api.typesafe.ai/v1/systemone',
    model_provider => 'custom',
    model_type => 'generic',
    model_qualified_name => 'jev-latest',
    model_auth_type => 'secret_manager',
    model_auth_id => 'jev_api_key'
);

2. 运行多任务评估(布尔值 + 连续分数)

在一次 HTTP 调用中同时评估缺陷布尔值检查 (noul) 和连续情感强度 (score):

SELECT jsonb_pretty(google_ml.predict_row(
    model_id => 'jev-systemone',
    request_body => json_build_object(
        'model', 'jev-latest',
        'state', 'Review for North Face Parka: "The zipper broke on day 3 and customer service refused an exchange, though the fabric itself is very soft."',
        'questions', json_build_object(
            'has_defect', json_build_object(
                'type', 'noul',
                'instructions', 'Does this review report a physical product defect or failure?'
            ),
            'satisfaction_score', json_build_object(
                'type', 'score',
                'instructions', 'Rate the customer sentiment and satisfaction on a 1-5 scale.',
                'criteria', json_build_array(
                    '1: Extremely dissatisfied / defect failure',
                    '2: Dissatisfied',
                    '3: Mixed or neutral',
                    '4: Satisfied',
                    '5: Delighted'
                )
            )
        )
    )
)::jsonb) AS jev_analysis;

您应该会看到类似如下所示的输出(您的结果可能会有所不同):

{
  "model": "jev-1.13.0",
  "usage": {
    "input_tokens": 388,
    "output_tokens": 39
  },
  "answers": {
    "has_defect": {
      "noul": 0.98,
      "type": "noul"
    },
    "satisfaction_score": {
      "type": "score",
      "score": 0.11,
      "legend": {
        "0": "1: Extremely dissatisfied / defect failure",
        "1": "2: Dissatisfied",
        "2": "3: Mixed or neutral",
        "3": "4: Satisfied",
        "4": "5: Delighted"
      },
      "confidence": 0.91,
      "probabilities": {
        "0": 0.9,
        "1": 0.08,
        "2": 0.02,
        "3": 0.0,
        "4": 0.0
      }
    }
  }
}

请注意,satisfaction_score 的评估结果为 11 / 100,准确地反映了客户的体验总体上是负面的,尽管客户承认面料很柔软!

10. 清理

为避免因在本 Codelab 中创建的资源而持续产生费用,请清理 Secret 和数据库对象,并删除 AlloyDB 集群。

1. 删除 Secret Manager 资源

在 Cloud Shell 中,删除为 TypeSafe AI API 密钥创建的 Secret:

gcloud secrets delete typesafe-jev-api-key --quiet

2. 删除 AlloyDB 主实例和集群

先删除主实例:

gcloud alloydb instances delete $ADBINSTANCE \
  --cluster=$ADBCLUSTER \
  --region=$REGION \
  --quiet

实例删除完成后,删除集群:

gcloud alloydb clusters delete $ADBCLUSTER \
  --region=$REGION \
  --quiet

11. 恭喜

恭喜!您已成功预配 Google Cloud AlloyDB 集群,并将其与 TypeSafe AI System One (Jev) 集成。

您学到的内容

  • 如何建立专用服务访问通道 (PSA),以及如何预配 AlloyDB for PostgreSQL 集群和主实例。
  • 如何启用 --outbound-public-ip,以便 AlloyDB 可以访问外部 HTTPS SaaS API。
  • 如何在 Google Secret Manager 中安全地存储第三方 AI 提供商凭据,并将其绑定到 AlloyDB。
  • 如何编写 PL/pgSQL 转换函数,将标准 PostgreSQL AI 函数(ai.if 和 ai.analyze_sentiment)桥接到外部 REST API。
  • 如何使用 google_ml.create_model 在 AlloyDB 中注册自定义 LLM 端点。
  • 如何在 PostgreSQL 中直接执行标量和高吞吐量批处理语义 SQL 查询。
  • 如何分析真实客户的商品评价,以了解分类情绪。
  • 如何注册通用模型端点,以及如何通过 google_ml.predict_row 评估持续的客户满意度得分 (0..100)。

后续步骤

参考文档