本頁內容適用於 Apigee,但不適用於 Apigee Hybrid。
查看
Apigee Edge 說明文件。
本頁說明如何設定及使用 Apigee 語意快取政策,根據語意相似度重複使用合適的既有回覆。在本例中,政策會對部署在私人 (Private Service Connect) 端點的向量搜尋索引執行相似度搜尋。在 Apigee API Proxy 中使用這些政策,可減少不必要的後端 API 呼叫、縮短延遲時間,並降低營運成本。
事前準備
開始之前,請先完成下列工作:
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Compute Engine, AI Platform, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.- 在 Google Cloud 專案中啟用並設定 Vertex AI Text embeddings API。
- 建立 (或存取) 部署在私人 (Private Service Connect) 端點的向量搜尋索引。本教學課程不會重複說明向量搜尋設定步驟,如需 SemanticCacheLookup 的特定需求,以及向量搜尋說明文件的連結,請參閱向量搜尋索引先決條件。
- 確認 Apigee 執行個體中是否有「中繼」或「全方位」環境。 語意快取政策只能部署在「中繼」或「全方位」環境。
- 確認您有環境群組,且該群組具有執行階段主機名稱,可用於將要求傳送至 API Proxy。
必要的角色
如要取得建立及使用語意快取政策所需的權限,請要求管理員在您用來部署 Apigee Proxy 的服務帳戶中,授予 AI Platform 使用者 (roles/aiplatform.user) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
設定環境變數
在包含 Apigee 執行個體的 Google Cloud 專案中,使用下列指令設定環境變數:
export PROJECT_ID=PROJECT_IDexport REGION=REGIONexport RUNTIME_HOSTNAME=RUNTIME_HOSTNAME
其中:
PROJECT_ID是 Apigee 執行個體所屬專案的 ID。REGION是 Apigee 執行個體的 Google Cloud 區域。RUNTIME_HOSTNAME是 Apigee 執行階段的主機名稱。
如要確認環境變數設定正確無誤,請執行下列指令並檢查輸出內容:
echo $PROJECT_ID $REGION $RUNTIME_HOSTNAME
設定專案
在開發環境中設定 Google Cloud 專案:
gcloud auth logingcloud config set project $PROJECT_ID
向量搜尋索引先決條件
本教學課程假設您已在私人 (Private Service Connect) 端點上部署 (或將建立) 向量搜尋索引。Vector Search 指南中已說明如何建立、格式化及部署 Vector Search 索引,因此本教學課程不會重複這些步驟。請按照向量搜尋說明文件操作:
建立索引時,必須符合下列 SemanticCacheLookup 專屬需求:
- 索引必須使用
STREAM_UPDATE("indexUpdateMethod": "STREAM_UPDATE"),這樣 SemanticCachePopulate 政策的upsertDatapoints呼叫才能近乎即時地進行查詢。 - 索引
dimensions必須與您在 SemanticCacheLookup 政策中使用的嵌入模型輸出維度相符。本教學課程使用gemini-embedding-001,根據預設會產生 3072 維度的嵌入。如果將輸出內容截斷為較低的維度 (例如 768 或 1536),請將dimensions設為相同的值。 - 使用符合政策
<DistanceMeasureType>的距離測量值 (distanceMeasureType) 建立索引。SemanticCacheLookup 政策中的<SimilaritySearch><VertexAI><DistanceMeasureType>元素為選用項目,預設為DOT_PRODUCT_DISTANCE,也支援COSINE_DISTANCE。索引距離測量和政策<DistanceMeasureType>必須相同。
下列簡短範例會建立相容的索引。如需完整的要求主體和所有可用選項,請參閱「建立及管理索引」:
ACCESS_TOKEN=$(gcloud auth print-access-token) && curl -X POST \ "https://$REGION-aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/$REGION/indexes" \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "displayName": "semantic-cache-index", "metadata": { "config": { "dimensions": 3072, "distanceMeasureType": "DOT_PRODUCT_DISTANCE" } }, "indexUpdateMethod": "STREAM_UPDATE" }'
請注意回應中傳回的數值 INDEX_ID,您會在 SemanticCachePopulate 政策中使用該值。建立索引後,請建立 Private Service Connect 索引端點,並將索引部署至該端點。
建立 Private Service Connect 索引端點時,必須符合下列 SemanticCacheLookup 專屬需求:
projectAllowlist必須包含啟動連線的 Apigee 專案:- Apigee:使用 Apigee 租戶專案。從 Organizations API (
apigeeProjectId欄位) 取得租戶專案 ID。
projectAllowlist即無法修改。如果允許清單中的專案有誤,請刪除並重新建立索引端點。- Apigee:使用 Apigee 租戶專案。從 Organizations API (
記下索引端點的數值 INDEX_ENDPOINT_ID。
設定 Apigee Proxy 的服務帳戶
Apigee Proxy 會使用服務帳戶進行 Vertex AI REST 呼叫:SemanticCacheLookup 政策中的 Embeddings API、SemanticCachePopulate 政策中的 upsertDatapoints,以及模型目標。將 AI Platform User (roles/aiplatform.user) 角色授予該服務帳戶:
gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:SERVICE_ACCOUNT" \ --role="roles/aiplatform.user"
其中 SERVICE_ACCOUNT 是 Proxy 使用的服務帳戶電子郵件地址。在「步驟 4:匯入及部署 API Proxy」中部署 Proxy 時,您會參照這個服務帳戶。
總覽
Apigee 使用者可透過語意快取政策,以 LLM 模型智慧且有效率地處理相同或語意相似的提示詞,減少後端 API 呼叫次數和資源用量。
SemanticCacheLookup 和 SemanticCachePopulate 政策會分別附加至 Apigee API Proxy 的要求和回應流程。Proxy 收到要求後,SemanticCacheLookup 政策會從要求中擷取使用者提示,並使用 Text Embeddings API 將提示轉換為數值表示法。語意相似度搜尋功能會使用向量搜尋,找出類似的提示詞。如果找到類似的提示資料點,系統會執行快取查閱作業。如果找到快取資料,系統會將快取回應傳回用戶端。
如果相似度搜尋未傳回類似的先前提示,LLM 模型會生成內容來回應使用者提示,並在 Apigee 快取中填入回覆。建立意見回饋迴路,更新向量搜尋索引項目,為日後的要求做準備。
在這個情境中,向量搜尋索引會透過 gRPC 部署在私有 (Private Service Connect) 端點上。如要進一步瞭解 Vector Search Private Service Connect 支援功能,請參閱「查詢私人服務存取或 Private Service Connect 索引」。
下列各節說明建立及設定語意快取政策的步驟:
步驟 1:驗證資源並取得 Apigee 需要的值
設定 Apigee 前,請先確認向量搜尋索引端點已啟用 Private Service Connect,且索引已部署完成。然後讀取 Apigee Proxy 使用的兩個值:服務附件和 DEPLOYED_INDEX_ID。
確認索引已部署,且端點公開 Private Service Connect 服務連結:
gcloud ai index-endpoints describe INDEX_ENDPOINT_ID \ --project=$PROJECT_ID --region=$REGION \ --format="value(deployedIndexes.privateEndpoints.serviceAttachment)"
指令會傳回服務連結資源名稱,格式為 projects/TENANT_PROJECT/regions/REGION/serviceAttachments/SERVICE_ATTACHMENT_NAME。本指南將該值稱為 SERVICE_ATTACHMENT。如果指令傳回空白值,表示索引尚未部署至 Private Service Connect 端點。返回「向量搜尋索引必要條件」,完成索引部署作業,再繼續操作。
讀取部署至端點的索引 DEPLOYED_INDEX_ID:
gcloud ai index-endpoints describe INDEX_ENDPOINT_ID \ --project=$PROJECT_ID --region=$REGION \ --format="value(deployedIndexes.id)"
本指南將該值稱為 DEPLOYED_INDEX_ID。您會在步驟 3:建構 API Proxy 套件的 SemanticCacheLookup 政策中使用這項政策。
如要進一步瞭解如何部署及查詢私人索引端點,請參閱「將索引部署至 Private Service Connect 端點」和「查詢 Private Services Access 或 Private Service Connect 索引」。
步驟 2:連線至服務附件
這個步驟會提供 Proxy 的 <GrpcEndpoint> 呼叫的私有主機。
在 Apigee 中,建立 Apigee 端點連結。端點連結是 Apigee 的 Private Service Connect 消費者端,可連線至向量搜尋服務連結,並提供 Proxy 呼叫的私人主機。
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ -d '{ "location": "'"$REGION"'", "serviceAttachment": "SERVICE_ATTACHMENT" }' \ "https://apigee.googleapis.com/v1/organizations/$PROJECT_ID/endpointAttachments?endpointAttachmentId=ENDPOINT_ATTACHMENT"
輪詢,直到附件的 state 為 ACTIVE 且 connectionState 為 ACCEPTED,然後記下主機:
curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://apigee.googleapis.com/v1/organizations/$PROJECT_ID/endpointAttachments/ENDPOINT_ATTACHMENT"
回覆會在 host 欄位中包含主機。本指南將該值稱為 TARGET_HOST。
如要從 Proxy 連線至 Vector Search 服務附件,可以使用下列任一方式:
- IP 位址:直接使用
host欄位中傳回的 IP 位址做為TARGET_HOST(例如7.0.3.4)。 - 私人 DNS 記錄:如果您在 Google Cloud 專案中設定了私人 Cloud DNS 區域,並透過 DNS 對接連線至 Apigee,則可以在私人區域中建立指向端點連結 IP 位址的 A 記錄,並使用該網域名稱 (例如
vectorsearch.example.com) 做為TARGET_HOST。詳情請參閱「使用 DNS 記錄」和「透過私人 DNS 對接區域連線」。
步驟 3:建構 API Proxy 套件
建立 Proxy 套裝組合
建立下列目錄版面配置:
apiproxy/ ├── PROXY_NAME.xml ├── proxies/default.xml ├── targets/default.xml └── policies/ ├── SCL-1.xml └── SCP-1.xml
policies/SCL-1.xml:SemanticCacheLookup 政策。<SimilaritySearch> 區塊使用 <PrivateServiceConnect><GrpcEndpoint> (沒有 <URL>)。
注意:<GrpcEndpoint>規則:
- 格式為
grpc://TARGET_HOST:PORT,且配置必須為grpc://。這個版本不支援傳輸層安全標準grpcs://(TLS)。 - 向量搜尋的通訊埠為
10000。Private Service Connect 資料平面端點會在 10000 埠上提供 gRPC,因此端點一律為grpc://TARGET_HOST:10000。 TARGET_HOST可以是端點連結 IP 位址 (來自步驟 2),也可以是在私人 DNS 區域中建立的自訂 DNS 記錄。- gRPC 躍點是純文字且未經驗證 (由網路隔離機制保護)。
<SemanticCacheLookup async="false" continueOnError="false" enabled="true" name="SCL-1"> <DisplayName>SCL-1</DisplayName> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <UserPromptSource>{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}</UserPromptSource> <Embeddings> <VertexAI> <URL>https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/publishers/google/models/gemini-embedding-001:predict</URL> </VertexAI> </Embeddings> <SimilaritySearch> <VertexAI> <PrivateServiceConnect> <GrpcEndpoint>grpc://TARGET_HOST:10000</GrpcEndpoint> </PrivateServiceConnect> <DeployedIndexID>DEPLOYED_INDEX_ID</DeployedIndexID> <Threshold>0.95</Threshold> </VertexAI> </SimilaritySearch> </SemanticCacheLookup>
policies/SCP-1.xml:SemanticCachePopulate 政策。「填入」僅適用於 REST,且必須使用 <URL> (部署時會拒絕 <PrivateServiceConnect>):
<SemanticCachePopulate async="false" continueOnError="true" enabled="true" name="SCP-1"> <DisplayName>SCP-1</DisplayName> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> <SimilaritySearch> <VertexAI> <URL>https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/indexes/INDEX_ID:upsertDatapoints</URL> </VertexAI> </SimilaritySearch> <TTLInSeconds>3600</TTLInSeconds> </SemanticCachePopulate>
targets/default.xml:模型目標。目標會呼叫 Google API,因此需要權杖;<GoogleAccessToken> 會使用部署作業的服務帳戶:
<TargetEndpoint name="default"> <PreFlow name="PreFlow"><Request/><Response/></PreFlow> <PostFlow name="PostFlow"><Request/><Response/></PostFlow> <HTTPTargetConnection> <Authentication> <GoogleAccessToken> <Scopes> <Scope>https://www.googleapis.com/auth/cloud-platform</Scope> </Scopes> </GoogleAccessToken> </Authentication> <URL>https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/publishers/google/models/gemini-2.5-flash:generateContent</URL> </HTTPTargetConnection> </TargetEndpoint>
proxies/default.xml:在要求中執行 SemanticCacheLookup 政策,並在回應中執行 SemanticCachePopulate 政策:
<ProxyEndpoint name="default"> <PreFlow name="PreFlow"> <Request><Step><Name>SCL-1</Name></Step></Request> <Response><Step><Name>SCP-1</Name></Step></Response> </PreFlow> <PostFlow name="PostFlow"><Request/><Response/></PostFlow> <HTTPProxyConnection> <BasePath>/PROXY_NAME</BasePath> </HTTPProxyConnection> <RouteRule name="default"> <TargetEndpoint>default</TargetEndpoint> </RouteRule> </ProxyEndpoint>
PROXY_NAME.xml - 套件描述元:
<APIProxy name="PROXY_NAME"> <BasePaths>/PROXY_NAME</BasePaths> <Policies><Policy>SCL-1</Policy><Policy>SCP-1</Policy></Policies> <ProxyEndpoints><ProxyEndpoint>default</ProxyEndpoint></ProxyEndpoints> <TargetEndpoints><TargetEndpoint>default</TargetEndpoint></TargetEndpoints> </APIProxy>
步驟 4:匯入及部署 API Proxy
將套件壓縮成 ZIP 檔案,匯入該檔案來建立新的修訂版本,然後使用服務帳戶部署該修訂版本:
TOKEN=$(gcloud auth print-access-token)(cd BUNDLE_DIR && zip -r ../PROXY_NAME.zip apiproxy)curl -X POST -H "Authorization: Bearer $TOKEN" \ -F "file=@PROXY_NAME.zip" \ "https://apigee.googleapis.com/v1/organizations/$PROJECT_ID/apis?action=import&name=PROXY_NAME"curl -X POST -H "Authorization: Bearer $TOKEN" \ "https://apigee.googleapis.com/v1/organizations/$PROJECT_ID/environments/ENV/apis/PROXY_NAME/revisions/REVISION/deployments?override=true&serviceAccount=SERVICE_ACCOUNT"
其中:
BUNDLE_DIR是包含apiproxy/資料夾的目錄。封存檔的根目錄必須包含apiproxy/資料夾。ENV是您部署 Proxy 的 Apigee 環境。環境必須是「中級」或「全面」環境。REVISION是匯入呼叫傳回的修訂版本號碼。SERVICE_ACCOUNT是您用來部署 Proxy 的服務帳戶電子郵件地址。
等待部署作業回報 READY:
curl -s -H "Authorization: Bearer $TOKEN" \ "https://apigee.googleapis.com/v1/organizations/$PROJECT_ID/environments/ENV/apis/PROXY_NAME/revisions/REVISION/deployments" | jq .state
步驟 5:測試語意快取政策
傳送新提示。這就是快取失敗:系統會呼叫模型並快取答案。
curl -X POST "https://$RUNTIME_HOSTNAME/PROXY_NAME" \ -H "Content-Type: application/json" \ -d '{"contents":[{"role":"user","parts":[{"text":"Explain in one sentence why the sky appears blue."}]}]}'
再次傳送相同的提示。這是快取命中:系統會從快取提供回應,且不會呼叫模型。
curl -i -X POST "https://$RUNTIME_HOSTNAME/PROXY_NAME" \ -H "Content-Type: application/json" \ -d '{"contents":[{"role":"user","parts":[{"text":"Explain in one sentence why the sky appears blue."}]}]}'
如果命中快取,回應會包含 Cached-content: true 標頭、相同答案,以及明顯較低的延遲時間。
您也可以透過偵錯工作階段驗證快取。如果快取命中,SemanticCacheLookup 政策會設定下列流程變數:
| 變數 | 命中次數的值 |
|---|---|
SemanticCacheLookup.SCL-1.dense_embeddings |
提示的嵌入向量。 |
SemanticCacheLookup.SCL-1.is_nearest_neighbor_hit |
true |
SemanticCacheLookup.SCL-1.cache_hit |
true |
SemanticCacheLookup.SCL-1.cached_llm_response |
快取答案。 |
如果快取命中,系統不會叫用模型目標,而是會短路流程並傳回快取的回應。
疑難排解
如需完整的錯誤參考資料,請參閱 SemanticCacheLookup 政策。
後續步驟
- 瞭解如何在 Vector Search 中查詢私人服務存取權或 Private Service Connect 索引。
- 瞭解如何針對公開端點設定語意快取,請參閱開始使用語意快取政策。
- 瞭解如何開始使用 Model Armor 政策。