ai newsMi., 25. Nov.
EilmeldungCan Claude’s storage webhooks miss an hour-long outage?

Build a Production LLM Integration for Customer Support on GCP

A single mis-configured retrieval request can flood your GCP bill and return irrelevant answers, turning a promising support bot into a costly liability. An LLM integration that respects latency, cost, and data-privacy constraints is therefore the only viable path for a production-grade customer-su

dev.toDienstag 05:30 · 24.11.13 Min. Lesezeit
Bild: dev.to

A single mis-configured retrieval request can flood your GCP bill and return irrelevant answers, turning a promising support bot into a costly liability. An LLM integration that respects latency, cost, and data-privacy constraints is therefore the only viable path for a production-grade customer-support assistant.

In this guide you’ll build a end-to-end support bot that safely consumes your knowledge base, serves accurate answers, and stays within budget. We start with a full-stack architecture map that ties Vertex AI, Cloud Storage, and Cloud Run together. Next, you’ll assemble a scalable pipeline that crawls documents, creates vector embeddings, and populates a managed vector store. We then cover model hosting, retrieval, and a CI/CD workflow that automates model refreshes and API deployments. Finally, you’ll learn concrete cost-control tactics, monitoring dashboards, and a production-ops checklist that lets you scale the bot without surprise outages.

With these pieces wired together, you have a production-grade, GCP-native stack that isolates data, scales retrieval, and serves LLM-driven answers with minimal operational friction.

import apache_beam as beam from apache_beam. io. gcp. pubsub import ReadFromPubSub from apache_beam. io. fileio import MatchFiles, ReadMatches from apache_beam. options. pipeline_options import PipelineOptions options = PipelineOptions ( streaming = True, project = 'my-gcp-project', temp_location = 'gs://tmp-bucket/temp', region = 'us-central1' ) with beam. Pipeline ( options = options ) as p: ( p | 'ReadPubSub' >> ReadFromPubSub ( topic = 'projects/my-gcp-project/topics/support-ingest' ) | 'ParsePath' >> beam. Map ( lambda msg: msg. decode ( 'utf-8' ) ) | 'MatchFiles' >> MatchFiles ( 'gs://support-docs/**' ) | 'ReadFiles' >> ReadMatches ( ) | 'ExtractText' >> beam.

ParDo ( ExtractTextFn ( ) ) ) # Tika-based parser Enter fullscreen mode Exit fullscreen mode Gotcha: Beam’s default ReadAllFromText cannot handle binary PDFs; use Apache Tika (or pdfminer.six ) inside a DoFn to pull out clean text for all three formats.

import sentencepiece as spm sp = spm. SentencePieceProcessor ( ) sp. Load ( 'gs://models/spm_unigram.model' ) def chunk ( text, size = 200, overlap = 30 ): ids = sp.

EncodeAsIds ( text ) for i in range ( 0, len ( ids ), size - overlap ): yield sp. DecodeIds ( ids [ i: i + size ] ) Enter fullscreen mode Exit fullscreen mode Embedding each chunk on Vertex AI Deploy your fine-tuned embedding model to Vertex AI as an online prediction endpoint ( projects/.../locations/us-central1/endpoints/12345 ). In the Beam pipeline, call the endpoint via the Vertex AI SDK inside a ParDo.

Batch up to 64 chunks per request to stay within latency budgets and reduce RPC overhead. from google. cloud import aiplatform endpoint = aiplatform. Endpoint ( '12345' ) def embed ( chunk ): response = endpoint. predict ( instances = [ { 'content': chunk } ] ) return response. predictions [ 0 ] [ 'embedding' ] Enter fullscreen mode Exit fullscreen mode Persisting vectors and traceability Destination Purpose Write method Vertex AI Matching Engine Fast nearest-neighbor lookup for support queries IndexServiceClient.upsert_datapoints (batch up to 1000) Cloud SQL (PostgreSQL) Auditable metadata – source file, chunk offset, processing timestamps JDBC sink ( beam.io.jdbc.WriteToJdbc ) Include columns like doc_id, chunk_index, embedding_id, ingest_ts. Use a composite primary key ( doc_id, chunk_index ) so re-processing the same file simply overwrites existing rows without duplication.

gcloud functions deploy trigger_ingest \ --runtime python311 \ --trigger-http \ --entry-point run_ingest \ --set-env-vars BUCKET = support-docs,TOPIC=support-ingest Enter fullscreen mode Exit fullscreen mode Key gotchas

With these pieces wired together, new support documents become searchable vector representations within minutes, and the pipeline scales automatically as your knowledge base grows.

### 1️⃣ Upload the model artifact (if you have a custom checkpoint) gcloud ai models upload \ --region=us-central1 \ --display-name= "gemini-1.5-flash" \ --container-image-uri= "us-docker.pkg.dev/vertex-ai/prediction/gemini-1.5-flash:latest" ### 2️⃣ Create an endpoint gcloud ai endpoints create \ --region=us-central1 \ --display-name= "support-bot-endpoint" ### 3️⃣ Deploy with autoscaling (min=0 allows cold-start, max=5 caps cost) gcloud ai endpoints deploy-model us-central1 \ --endpoint=SUPPORT_BOT_ENDPOINT_ID \ --model=GEMINI_MODEL_ID \ --display-name= "gemini-prod" \ --machine-type=n1-standard-4 \ --min-replica-count=0 \ --max-replica-count=5 \ --traffic-split=0=100 Enter fullscreen mode Exit fullscreen mode Why min = 0? Vertex AI spins the pod down when idle, saving compute dollars. Expect a 1-2 s warm-up on the first request after a lull; mitigate by sending a lightweight “ping” from a Cloud Scheduler job every 5 min.

When a newer model version (e.g., a fine-tuned Gemini-Flash) is ready, you can route a fraction of traffic without redeploying the whole endpoint:

gcloud ai endpoints update-traffic-split us-central1 \ --endpoint=SUPPORT_BOT_ENDPOINT_ID \ --traffic-split=0=90,1=10 # 10 % to model version 1 (canary) Enter fullscreen mode Exit fullscreen mode Gotcha: The split works per-request, not per-client. If you need user-level canary, embed a custom header ( X-Canary: true ) and let your front-end decide which model ID to call via the Vertex AI SDK’s predict method.

from vertexai. preview import matching_engine, language_models ### 1️⃣ Initialise the Matching Engine index index = matching_engine. MatchServiceClient ( ). index_path ( project = "my-project", location = "us-central1", index = "support-docs-index" ) def retrieve_chunks ( query: str, k: int = 5 ): # Encode query with the same embedding model used for indexing embed = language_models. TextEmbeddingModel. from_pretrained ( "textembedding-gecko@001" ) query_vec = embed. embed_text ( [ query ] ) [ 0 ] # Perform ANN search response = matching_engine.

MatchServiceClient ( ). find_neighbors ( request = { "index": index, "queries": [ { "embedding": query_vec, "neighbor_count": k } ] } ) # Return raw text chunks return [ neighbor. datapoint. restricts [ 0 ]. value for neighbor in response. neighbors [ 0 ]. neighbors ] def generate_answer ( question: str ): context = "\n". join ( retrieve_chunks ( question ) ) prompt = f """Context:\n{context}\n\nQuestion: {question}\nAnswer:""" llm = language_models. TextGenerationModel. from_pretrained ( "gemini-1.5-flash" ) return llm. predict ( prompt ) Enter fullscreen mode Exit fullscreen mode The retrieval call runs before each LLM generation, ensuring the prompt stays under token limits while still grounding the answer.

OAuth2 client-ID – Create a confidential OAuth client in Cloud Identity, then grant the aiplatform.endpoints.predict permission to its service account. In your API gateway (e.g., Cloud Endpoints or API Gateway), enforce audience = <client-id> and validate the bearer token before forwarding to the Vertex endpoint.

VPC Service Controls (VPC-SC) – Add the Vertex AI service to the same service perimeter as your data stores. Then define an egress rule that only allows traffic to aiplatform.googleapis.com over private Google Access:

gcloud access-context-manager perimeters update my-perimeter \ --add-egress-policies= '{"egressFrom":{"identities":["serviceAccount:my-service@my-project.iam.gserviceaccount.com"]},"egressTo":{"resources":["//aiplatform.googleapis.com/projects/my-project/locations/us-central1"]}}' Enter fullscreen mode Exit fullscreen mode Gotcha: VPC-SC blocks public internet calls; ensure your Matching Engine index resides in the same perimeter, otherwise the retrieval step will fail with a permission error.

By combining autoscaled Vertex endpoints, request-level traffic splitting, on-the-fly retrieval, and strict OAuth/VPC-SC controls, you get a production-grade LLM integration that can evolve safely while keeping costs predictable.

Connect Cloud Build to GitHub – In the Cloud Console, create a trigger that watches the main and release/* branches. Set the trigger event to Push to branch and select the repository that holds both the API code and the model-artifact manifest ( model.yaml ).

Run static checks first – The trigger invokes a Cloud Build step that runs:

Integration test against a staging Vertex AI endpoint – After the unit phase, Cloud Build spins up a temporary staging endpoint ( staging-support-bot ) and executes a small suite of end-to-end queries. The test harness reads the staging endpoint URL from the substitution variable $STAGING_ENDPOINT. If any request fails, the build aborts and no deployment proceeds.

Gotcha: Vertex AI may take 1–2 minutes to spin up a new endpoint. Include a retry loop in the integration step to avoid false negatives.

Cloud Run supports traffic splitting, which we use for zero-downtime releases:

- name: 'gcr.io/cloud-builders/gcloud' args: - run - services - update - support-bot-api - --image=gcr.io/$PROJECT_ID/support-bot-api:$COMMIT_SHA - --platform=managed - --region=us-central1 - --no-traffic - name: 'gcr.io/cloud-builders/gcloud' args: - run - services - update-traffic - support-bot-api - --to-revisions=latest=10 - --platform=managed - --region=us-central1 Enter fullscreen mode Exit fullscreen mode The first step creates a new revision without routing traffic. The second step shifts 10 % of live traffic to the new revision; you can increase the percentage in a follow-up manual approval step. If monitoring shows no errors, promote the revision to 100 % and retire the old one.

Model updates are treated as separate artifacts stored in Artifact Registry ( model-artifacts ). After the integration tests pass, a dedicated Cloud Build step promotes the candidate model:

- name: 'gcr.io/cloud-builders/gcloud' id: promote-model waitFor: [ '-' ] args: - ai - models - upload - --region=us-central1 - --display-name=customer-support-v2 - --artifact-uri=gs://my-bucket/models/$MODEL_SHA - name: 'gcr.io/cloud-builders/gcloud' args: - ai - endpoints - deploy - --region=us-central1 - --model=projects/$PROJECT_ID/locations/us-central1/models/$MODEL_SHA - --endpoint=projects/$PROJECT_ID/locations/us-central1/endpoints/PROD_ENDPOINT_ID - --traffic-split=100 Enter fullscreen mode Exit fullscreen mode The first command registers the new model version; the second swaps the production Vertex AI endpoint to point at it. Because the endpoint is already serving traffic, the switch is instantaneous and does not disrupt existing requests.

By wiring these three pieces—Git-triggered tests, blue-green Cloud Run deployments, and atomic model promotion—your support bot can iterate on both code and AI improvements without ever taking the service offline.

Gotcha: Token-per-second estimates must include both prompt and completion tokens. Over-provisioning a GPU for a workload that rarely exceeds 150 tps can waste > 80 % of the budget.

Deploy the endpoint with a Vertex AI Model Deployment that references an autoscaling policy:

### vertex_autoscale.yaml autoscaling: minReplicaCount: 0 # scale to zero when idle maxReplicaCount: 8 metric: type: custom.googleapis.com/vertex_ai/throughput target: 250 # tokens per second per replica Enter fullscreen mode Exit fullscreen mode Attach the YAML to the model via gcloud beta ai endpoints deploy-model. Verify the metric name ( throughput ) exists by publishing a custom metric from your inference code. Set minReplicaCount: 0 only if your SLA tolerates a cold-start latency of a few seconds; otherwise use 1. Pitfall: Cloud Run-for-Containers (if you wrap the model in a container) does not support GPU scaling to zero—use Vertex AI directly.

When you create resources (datasets, pipelines, endpoints), add a cost tag:

gcloud beta ai endpoints update ENDPOINT_ID \ --update-labels=stage=embedding,pipeline=doc_ingest Enter fullscreen mode Exit fullscreen mode In the Billing > Cost Table, filter by stage or pipeline to see:

This granularity lets you spot a runaway cost in the retrieval layer before it balloons.

Use the built-in vertex_ai_endpoint_request_latency metric and a budget alert tied to the billing project.

Note: Latency spikes often correlate with cold-starts after scaling to zero; consider a warm-up cron that sends a dummy request every 5 min.

Pick the pattern that matches your SLA and budget horizon, then instrument the relevant metrics so you can verify the expected savings.

A lightweight Cloud Scheduler job (e.g., a Cloud Function) should run every 24 h and exit with a non-zero status if any check fails. Example in Python:

import requests, google. cloud. logging as glog, sys from google. cloud import aiplatform, storage PROJECT = "my-gcp-project" REGION = "us-central1" ENDPOINT_ID = "1234567890123456789" VECTOR_BUCKET = "support-vectors" INDEX_ID = "matching-engine-idx" def check_vectors ( ): client = storage. Client ( ) blobs = list ( client. list_blobs ( VECTOR_BUCKET, prefix = "2023/" ) ) # assume daily batch creates a manifest file; its timestamp must be within 48 h latest = max ( b. time_created for b in blobs ) if ( now ( ) - latest ). total_seconds ( ) > 48 * 3600: raise RuntimeError ( "Stale vector store" ) def check_endpoint ( ): endpoint = aiplatform. Endpoint ( endpoint_name = ENDPOINT_ID, project = PROJECT, location = REGION ) if endpoint. state!= aiplatform. gapic.

Endpoint. State. READY: raise RuntimeError ( f "Endpoint not ready: {endpoint.state}" ) def check_cloudrun ( ): url = "https://support-bot-xyz.run.app/health" r = requests. get ( url, timeout = 5 ) if r. status_code!= 200: raise RuntimeError ( f "Cloud Run health check failed: {r.status_code}" ) if __name__ == "__main__": try: check_vectors ( ) check_endpoint ( ) check_cloudrun ( ) except Exception as e: glog. get_logger ( ). error ( e ) sys. exit ( 1 ) glog. get_logger ( ). info ( "All checks passed" ) Enter fullscreen mode Exit fullscreen mode Why: Vector freshness guarantees that new FAQs are searchable; endpoint health catches model crashes; Cloud Run response codes surface routing or quota issues.

Gotchas: Cloud Scheduler’s default retry policy may mask transient failures—set retry_count=0 and let the script surface the error to Cloud Monitoring alerts.

When the support bot calls the Vertex AI endpoint, throttling (HTTP 429) can cascade under load. Wrap the call with a retry library (e.g., tenacity ) and a simple circuit-breaker:

from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type import time class CircuitBreaker: def __init__ ( self, failures = 5, reset_sec = 300 ): self. failures, self. reset_sec = failures, reset_sec self. _counter, self. _opened_at = 0, None def call ( self, fn, * a, ** kw ): if self. _opened_at and time. time ( ) - self. _opened_at < self. _reset_sec: raise RuntimeError ( "Circuit open" ) try: return fn ( * a, ** kw ) except Exception: self. _counter += 1 if self. _counter >= self. failures: self. _opened_at = time. time ( ) raise cb = CircuitBreaker ( ) @retry ( wait = wait_exponential ( multiplier = 1, min = 2, max = 30 ), stop = stop_after_attempt ( 5 ), retry = retry_if_exception_type ( requests. exceptions. HTTPError ) ) def predict ( payload ): return cb. call ( requests. post, endpoint_url, json = payload ) Enter fullscreen mode Exit fullscreen mode Why: Exponential back-off reduces burst pressure on the endpoint; the circuit-breaker prevents endless retries that would exhaust Cloud Run CPU quotas. Gotchas: Do not set max too low; otherwise legitimate spikes get dropped.

Log every circuit-open event for capacity planning.

Why: A zone outage isolates to a single replica; the load balancer automatically routes traffic to the surviving region. Gotchas: Cross-region latency can surface in the vector similarity step; keep the index replicas in the same region as the serving endpoint to avoid extra network hops.

Document these steps in a version-controlled ops repo, tag each rollback with the associated Git SHA, and trigger an alert on every rollback so that post-mortems are mandatory.

Store document embeddings in a Matching Engine index. When a user query arrives, call the index via its REST API to retrieve the top-k vectors, fetch the corresponding raw text from Cloud Storage or Firestore, and concatenate it into a prompt. Send that prompt to your LLM hosted on Vertex AI Prediction (or a custom endpoint) and return the generated answer. The flow is: query → vector search → context fetch → LLM inference.

Deploy the model on Vertex AI Serverless endpoints using custom machine types sized just enough for your token throughput, and enable GPU-based preemptible instances for batch inference. Combine this with model quantization (e.g., 8-bit) to reduce compute demand. Cache frequent retrieval results in Memorystore, and use autoscaling to spin down resources during idle periods. This balances cost and sub-second response times.

Yes. Configure a Cloud Build trigger on your model repository. The pipeline runs unit and integration tests, builds a Docker image (if using custom serving), and uses Terraform or gcloud commands to register the new model version in Vertex AI. After a successful canary validation, the pipeline updates traffic splitting to promote the new version to 100 % production. All steps are version-controlled and repeatable.

Create a Cloud Billing budget for the project and set alert thresholds (e.g., 50 %, 80 %, 100 %). Export detailed cost data to BigQuery daily and build a dashboard in Looker Studio that breaks spend by service (Vertex AI, Dataflow, Cloud Run). Use Cloud Monitoring to track usage metrics (requests, GPU hours) and set alerting policies that trigger Cloud Functions to throttle or pause pipelines when thresholds are approached.

You now have a concrete blueprint for a production-grade LLM-powered support bot on GCP, from data ingestion to continuous delivery and cost control. The next step is to spin up a minimal proof-of-concept using the outlined services, validate latency and accuracy, then iterate toward full rollout. If you’d like an experienced partner to accelerate this journey, talk to Cloudesign’s engineering team.

Quelle: dev.to (dev.to). Original öffnen