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.
| Service | Role in the support bot | Typical IAM role (least-privilege) |
|---|---|---|
| Cloud Storage | Stores the original knowledge-base PDFs, HTML, or markdown files. Acts as the source bucket for the ETL pipeline. | roles/storage.objectViewer on the bucket |
| Dataflow | Executes a Beam pipeline that extracts text, cleans it, creates embeddings (via Vertex AI’s embedding model), and writes vectors to Matching Engine. Also writes the raw chunks to a Firestore collection for debugging. | roles/dataflow.worker ,roles/vertexai.viewer |
| Vertex AI Matching Engine | Persistent vector index (≈ 10-100 M vectors) used for fast nearest-neighbor lookup during retrieval. | roles/aiplatform.matchingEngineAdmin |
| Vertex AI (LLM endpoint) | Hosts the generative model (e.g., PaLM-2 or a fine-tuned T5). Provides two endpoints: predict for generation andembed for query embeddings. |
roles/aiplatform.modelViewer ,roles/aiplatform.endpointUser |
| Cloud Run (API layer) | Stateless HTTP front-end that receives user queries, orchestrates retrieval, calls the LLM, and returns the answer. Deployed in a fully managed VPC-connected service. | roles/run.invoker for internal callers,roles/run.serviceAgent for the service itself |
| Cloud SQL / Firestore | Persists session context (e.g., last 3 user turns) and audit logs. Firestore is preferred for low-latency key-value access; Cloud SQL can host relational metadata if needed. | roles/cloudsql.client orroles/datastore.user |
dataflow-sa@project.iam.gserviceaccount.com, run-sa@project.iam.gserviceaccount.com) and enforce 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.
gs://support-docs) and enable support-ingest).
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
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.
spm_unigram.model) inside the same DoFn.
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])
projects/.../locations/us-central1/endpoints/12345).
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']
| 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.
.processed). For each missing marker, it publishes the object path to
gcloud functions deploy trigger_ingest \
--runtime python311 \
--trigger-http \
--entry-point run_ingest \
--set-env-vars BUCKET=support-docs,TOPIC=support-ingest
Key gotchas
gs://support-docs/<path>.processed) after successful upserts; the Cloud Function checks this flag before republishing.
beam.transforms.util.Reshuffle and exponential back-off on ResourceExhausted errors.
index_v1, index_v2) and keep the old index read-only for rollback.
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
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)
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):
embed = language_models.TextEmbeddingModel.from_pretrained("textembedding-gecko@001")
query_vec = embed.embed_text([query])[0]
response = matching_engine.MatchServiceClient().find_neighbors(
request={
"index": index,
"queries": [{"embedding": query_vec, "neighbor_count": k}]
}
)
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)
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"]}}'
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:
pylint (or eslint for Node) to enforce coding standards.pytest --junitxml=unit.xml to produce a machine-readable test report.flake8 (or equivalent) for style compliance.
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
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
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.
| Step | Artifact | Destination |
|---|---|---|
| 1️⃣ | API container image | Cloud Run (new revision) |
| 2️⃣ | Model checkpoint ( .tar.gz ) |
Artifact Registry |
| 3️⃣ | Model version | Vertex AI production endpoint |
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.
| Token throughput (tokens / sec) | Recommended instance | Why it matters |
|---|---|---|
| ≤ 200 tps | n2-standard (CPU) | CPUs handle low-throughput inference at ~ $0.04 / hour, avoiding the $0.70 / hour GPU surcharge. |
| 200 – 800 tps | a2-highgpu-1 (GPU) | A single A100 delivers ~ 300 tps for 7B-parameter models; cost per token drops sharply once you cross the CPU ceiling. |
| > 800 tps | a2-highgpu-4 (GPU) +autoscaling | Multiple GPUs keep latency < 2 s while spreading the workload; you pay only for the active replicas. |
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
gcloud beta ai endpoints deploy-model. throughput) exists by publishing a custom metric from your inference code.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
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.
Create two alert policies:
| Condition | Threshold | Notification channel |
|---|---|---|
| Request latency (p95) | > 2 s | Slack / PagerDuty |
| Weekly spend increase | > 20 % vs. prior week | Email to finance lead |
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.
| Pattern | When to use | Trade-offs |
|---|---|---|
| Scale-to-zero CPU endpoint | Low traffic (< 200 tps) and tolerant of ~ 2 s cold start | Minimal cost, higher latency on first request |
| GPU burst with max-replica cap | Variable traffic, occasional peaks > 800 tps | Predictable max spend, may queue requests during spikes |
| Hybrid CPU-GPU routing | Mixed workloads: cheap text-only queries + occasional generation | Complexity in routing logic; requires separate endpoints and a request router (e.g., Cloud Functions) |
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/"))
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")
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)
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.
us-central1-a and us-central1-b). Use the --replica-count=2 flag in gcloud beta ai indexes create.
prod-us).
backend_service that includes both regions) to the Cloud Run service.
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.
| Artifact | Rollback trigger | Steps |
|---|---|---|
| Model version | New version degrades latency or quality | 1. Call gcloud ai endpoints undeploy-model --endpoint=ENDPOINT_ID --deployed-model=NEW_ID 2. Deploy the previous model ID withgcloud ai endpoints deploy-model |
| API code (Cloud Run) | Health-check script reports failure after deploy | 1. gcloud run revisions list --service=support-bot --platform=managed 2. Identify the last known-good revision 3.gcloud run services update-traffic --to-revisions=REVISION=100 |
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 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.