← All posts

An LLM Service on Vertex AI, Now Agent Platform

Most LLM features start as a direct call from application code to one model's API. That works until the second model, the first quota error, the first invoice nobody can explain, or the first request to keep data in one region. At that point the calls need a home: one internal service that every feature goes through, sitting on a managed platform that handles identity, quotas and data governance.

I migrated an AI stack to Google Vertex AI with a custom LLM service on top. This post is a general guide, not a case study: the platform features that matter, how to separate the many kinds of failure, how to retry without making things worse, how to handle open models, generation settings and cost. It was written against the documentation and SDK as of December 2026.

Version notice. In April 2026 Vertex AI became Gemini Enterprise Agent Platform, which the documentation shortens to Agent Platform. The examples use google-genai 3.6.1. Model IDs, prices and limits change often; check the linked pages before relying on a number.

In short

  • Put one LLM service between your features and the models. It owns credentials, routing, retries, generation defaults, output checks and cost records, so features ask for "extract" rather than a model ID.
  • Classify failures in three layers: transport errors from the platform (HTTP status), failures inside a successful response (truncation, safety blocks, invalid JSON), and your own service's errors. Map them to one internal outcome with a "retryable" flag; truncation and safety stops are not worth retrying.
  • Retry in exactly one layer, with capped exponential backoff and jitter. In a local test, google-genai 3.6.1 without retry options sent one request; retries configured in two layers multiply.
  • Track cost from the response's usage metadata (including cached and thinking tokens), not from estimates, and choose capacity deliberately: shared pay-as-you-go, Provisioned Throughput, caching or batch.

Vertex AI, now Agent Platform

Google's announcement of 22 April 2026 describes Gemini Enterprise Agent Platform as "our new developer platform and evolution of Vertex AI". For code, little changed. The API host is still aiplatform.googleapis.com, and the documentation still lives under /vertex-ai/ paths. Two things did change, and both break old code:

  • The SDK. The generative module of the old Vertex AI SDK was deprecated: "The Generative AI module in the Vertex AI SDK is deprecated and will no longer be available after June 24, 2026." Its replacement is the Google Gen AI SDK, google-genai.
  • The client flag. Current samples create the client with genai.Client(enterprise=True, project=..., location=...). Code from before the rename uses vertexai=True; version 3.6.1 accepts both.

Why a service layer

A thin internal service in front of every model keeps the decisions that change often in one place. Features call it with a task name and inputs; the service decides the rest.

Features call one LLM service, which handles identity, routing, retries, generation defaults, output checks and cost, and calls Gemini, partner models or self-deployed open models, sending traces to an observability store Extraction Chat Classification LLM service identity routing and fallback retries and deadlines generation defaults output checks usage and cost records Gemini models shared or provisioned Partner and open managed APIs (MaaS) Self-deployed your endpoint traces to observability (for example Langfuse)
Figure 1. One service between features and models. The model targets on the right can change without touching feature code.
  • Identity. The documentation calls an attached service account "the preferred authentication method for code running on a Google Cloud compute resource", and for anything outside Google Cloud, "The preferred method to set up authentication from outside of Google Cloud is to use workload identity federation." Long-lived API keys disappear from feature code.
  • Routing. A table maps each task to an ordered list of model targets: a preferred model and fallbacks. Swapping a model, or moving a task to a cheaper one after an evaluation, is a configuration change.
  • Defaults. Generation settings, output schemas and timeouts live per task, not scattered across call sites.
  • Records. Every call leaves the same trace: task and route, model and region, attempt number, outcome layer and kind, finish reason, token counts by type (prompt, output, cached, thinking), latency, cost, and the prompt version.

Three layers of failure

"The LLM call failed" covers very different events, and treating them alike is how retry storms and silent data loss happen. It helps to separate three layers and to normalise each into your own error types, so that callers never see a vendor's exception class.

Layer 1: transport errors from the platform. The request did not produce a response. In google-genai, any HTTP error raises an APIError with code, status and message; the source maps 4xx to ClientError and 5xx to ServerError. Note that a 429 is a ClientError even though it is usually transient, so "client error means do not retry" is wrong here.

CodeStatusUsual meaningRetry?
400INVALID_ARGUMENTRequest fails validation, for example a bad schema or an unsupported parameterNo; fix the request
401 / 403UNAUTHENTICATED / PERMISSION_DENIEDCredentials or IAM role missingNo; alert
404NOT_FOUNDTypically a wrong model ID or regionNo; fall back to another route
429RESOURCE_EXHAUSTEDQuota or shared capacity exhaustedYes, with backoff
500 / 503INTERNAL / UNAVAILABLEServer overload or temporary outageYes, with backoff
504DEADLINE_EXCEEDEDDeadline too short for the requestYes, with backoff; if it repeats, raise the deadline

Layer 2: failures inside a successful response. HTTP 200 does not mean usable output. Check the candidate's finish_reason: MAX_TOKENS means the output was cut at max_output_tokens, and a truncated JSON object is a silent data-loss bug if nothing checks it. SAFETY, RECITATION, BLOCKLIST, PROHIBITED_CONTENT and SPII mean generation stopped for policy reasons, and prompt_feedback.block_reason means the prompt itself was blocked. Retrying the same request will usually give the same answer. Then validate the content: parse the JSON and check it against the schema. For extraction pipelines, layered validation is the subject of a separate post.

Layer 3: your own service's errors. A budget exceeded for a feature, a request rejected before it is sent because it is too long, a downstream timeout, a caller's cancellation. These belong to you, and they should never look like a platform outage on a dashboard.

Partner models such as Anthropic's Claude, offered through Model Garden (the platform's model catalogue), use the same platform endpoints but are separate products, so map their errors explicitly rather than assuming they behave like Gemini's. Normalising every source into one internal error type, with a field for the layer and one for "retryable", is what lets the rest of the service stay simple.

In code, this is two small functions that turn whatever came back into one internal outcome. Built on the real google-genai 3.6.1 types:

RETRYABLE_CODES = {408, 429, 500, 502, 503, 504}
POLICY_STOPS = {"SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"}

@dataclass(frozen=True)
class Outcome:
    layer: str      # "platform", "response" or "service"
    kind: str
    retryable: bool

def from_exception(exc: Exception) -> Outcome:
    if isinstance(exc, errors.APIError):  # ClientError (4xx) and ServerError (5xx)
        return Outcome("platform", f"http_{exc.code}_{exc.status}", exc.code in RETRYABLE_CODES)
    if isinstance(exc, TimeoutError):
        return Outcome("service", "deadline", False)
    return Outcome("service", type(exc).__name__, False)

def from_response(resp: types.GenerateContentResponse, required: tuple[str, ...]) -> Outcome:
    if resp.prompt_feedback and resp.prompt_feedback.block_reason:
        return Outcome("response", f"prompt_blocked_{resp.prompt_feedback.block_reason.name}", False)
    if not resp.candidates:
        return Outcome("response", "no_candidates", True)
    reason = resp.candidates[0].finish_reason
    if reason is not None and reason.name == "MAX_TOKENS":
        return Outcome("response", "truncated", False)  # raise the limit or shorten the task
    if reason is not None and reason.name in POLICY_STOPS:
        return Outcome("response", f"stopped_{reason.name}", False)
    try:
        data = json.loads(resp.text or "")
    except json.JSONDecodeError:
        return Outcome("response", "invalid_json", True)
    if any(k not in data for k in required):
        return Outcome("response", "schema_mismatch", True)
    return Outcome("response", "ok", False)

Fed constructed SDK errors and responses, it sorts them like this (classify.py):

HTTP 429               Outcome(layer='platform', kind='http_429_RESOURCE_EXHAUSTED', retryable=True)
HTTP 400               Outcome(layer='platform', kind='http_400_INVALID_ARGUMENT', retryable=False)
HTTP 503               Outcome(layer='platform', kind='http_503_UNAVAILABLE', retryable=True)
deadline               Outcome(layer='service', kind='deadline', retryable=False)
valid JSON             Outcome(layer='response', kind='ok', retryable=False)
cut at max tokens      Outcome(layer='response', kind='truncated', retryable=False)
safety stop            Outcome(layer='response', kind='stopped_SAFETY', retryable=False)
prompt blocked         Outcome(layer='response', kind='prompt_blocked_PROHIBITED_CONTENT', retryable=False)
missing key            Outcome(layer='response', kind='schema_mismatch', retryable=True)

Every caller now sees the same three fields whatever the source, and the retry loop needs only one question: is it retryable?

Retries without a retry storm

On shared capacity, a 429 is normal. The dynamic shared quota page is explicit: a 429 "doesn't indicate that you've hit a fixed quota. It indicates temporary high contention for a specific shared resource. Implement an exponential backoff retry strategy to handle these errors". It also warns against "sending requests in sharp, second-level spikes".

The SDK can retry for you, but the documentation is not consistent about how. The retry strategy page says the Python SDK "automatically retries transient errors up to four times", while the API errors page recommends "retrying no more than two times". A local test settles what the client does when nothing is configured:

$ python retry_probe.py   # google-genai 3.6.1, local stub server that always answers 429
no retry_options               requests sent: 1  raised ClientError code=429 status=RESOURCE_EXHAUSTED
HttpRetryOptions(attempts=3)   requests sent: 3  raised ClientError code=429 status=RESOURCE_EXHAUSTED

The test used an API-key client pointed at a stub server, so it does not cover every client mode; the point is that the behaviour depends on configuration and version. The safe rule is to configure retries explicitly, in one layer only. If the SDK makes four attempts and the service around it makes four attempts of its own, one user request becomes sixteen calls during an incident, which is exactly when capacity is shortest. Either let the SDK retry, configured as below, or let your own gateway retry, as in the next section, with the SDK's retry options left unset.

from google import genai
from google.genai import types

client = genai.Client(
    enterprise=True, project="my-project", location="global",
    http_options=types.HttpOptions(
        retry_options=types.HttpRetryOptions(
            attempts=3, initial_delay=1.0, max_delay=30.0,
            http_status_codes=[408, 429, 500, 502, 503, 504],
        ),
        timeout=120_000,  # milliseconds
    ),
)
response = client.models.generate_content(
    model="gemini-3.8-flash",  # from configuration, per task
    contents=prompt,
    config=types.GenerateContentConfig(
        max_output_tokens=2048,
        response_mime_type="application/json",
        response_schema=Section,  # a Pydantic model describing the output
        labels={"feature": "extract"},
    ),
)
usage = response.usage_metadata  # prompt_token_count, candidates_token_count,
                                  # cached_content_token_count, thoughts_token_count

The snippet follows the current documentation and was checked against the 3.6.1 type definitions, but not run against the platform. A few more rules make retries safe:

  • Backoff with jitter and a cap. Randomised delays stop many clients retrying in lockstep; a cap stops a single request waiting minutes.
  • A deadline per request. Retries spend the caller's time budget; stop when it is gone rather than when attempts run out.
  • Fallback after retries, not instead of them. When the preferred model keeps failing, move to the next target in the route, and log it.
  • Endpoint choice reduces 429s. The locations page says the global endpoint can "improve overall availability and reduce resource exhausted (429) errors", with a condition covered below under data.

A minimal gateway

The core of such a service fits on a page. Here the gateway owns retries, so the SDK client it wraps has none. The version below routes a task to an ordered list of models, retries quota errors with capped full-jitter backoff, checks that the reply is valid JSON with the required keys, falls back to the next model when one keeps failing, and records tokens and cost per feature. A fake backend scripts the failures so it runs offline; the prices are illustrative.

# abridged: the sleep, rng and log fields and the logging calls are omitted
@dataclass
class Gateway:
    backend: Backend
    ledger: Ledger
    max_attempts: int = 3  # two retries, as the error guide recommends
    base_delay: float = 1.0
    max_delay: float = 30.0

    def _backoff(self, attempt: int) -> float:
        """Full jitter: a random delay up to base * 2**attempt, capped."""
        return self.rng.uniform(0, min(self.max_delay, self.base_delay * 2 ** attempt))

    def _try_model(self, route: Route, model: str, prompt: str) -> dict | None:
        for attempt in range(self.max_attempts):
            try:
                reply = self.backend.generate(model, prompt)
            except QuotaExceeded:
                if attempt == self.max_attempts - 1:
                    break  # no sleep before giving up
                self.sleep(self._backoff(attempt))
                continue
            self.ledger.record(route.feature, model, reply)  # failed parses still cost tokens
            try:
                data = json.loads(reply.text)
            except json.JSONDecodeError:
                continue
            if all(k in data for k in route.required_keys):
                return data
        return None

    def call(self, route: Route, prompt: str) -> dict:
        for model in route.models:
            if (data := self._try_model(route, model, prompt)) is not None:
                return data
        raise RuntimeError(f"{route.feature}: all models failed")

Run against a script in which the fast model answers 429, broken JSON, 429, the log shows each step, and the ledger shows that the broken reply was still billed:

extract: model-fast 429, retry in 0.84s
extract: model-fast returned invalid JSON, retrying
extract: model-fast 429, no attempts left
extract: giving up on model-fast, falling back
extract: model-strong ok on attempt 1
summarise: model-fast ok on attempt 1
extract    in=  1920 out=  80 cost=$0.002138
summarise  in=   960 out=  60 cost=$0.000438

The full file, gateway.py, adds the fake backend, the ledger and logging in about 130 lines of standard-library Python; the SDK test is retry_probe.py. In production the backend wraps the SDK client, the sleep is real, and the ledger writes to your tracing system.

Generation settings

  • max_output_tokens is a budget, not a target. Set it per task from the size of the expected output, and treat MAX_TOKENS as an error for structured output. With thinking models, the reasoning tokens are reported separately as thoughts_token_count; check the pricing page for how they are charged, and budget for them.
  • Temperature depends on the model. The parameters guide gives a range of 0.0 to 2.0 and a default of 1.0, with 1.0 as "the recommended starting value". But for Gemini 3.6 Flash and later, the content generation parameters page warns that custom temperature, topP and topK values "are ignored if set", and that penalty parameters return an error. A temperature of 0 copied from an old configuration no longer means what it did, and determinism has to come from the prompt, the schema and validation instead.
  • Thinking is a setting. ThinkingConfig takes a thinking_budget in tokens for older models or a thinking_level for newer ones. Lower levels cut cost and latency for simple extraction.
  • Structured output needs a schema. Without one, the documentation warns, JSON mode "acts only as a strong hint"; requests need both response_schema and the JSON MIME type for valid JSON. Validation is still needed, because a valid shape can hold wrong values.
  • Keep settings in configuration, per task and per model, versioned with the prompts, so a model change and its settings move together.

Open models

Model Garden offers two ways to run models that are not Gemini, and they behave differently in cost and operations:

OptionWhat you manageHow it is billedGood for
Managed models (MaaS): partner and open models as an APINothing: "Partner models are serverless so there's no need to provision or manage infrastructure."Per use, see the pricing pageSpiky traffic, trying several models
Self-deployed open models on your own endpointThe endpoint: machine type, accelerators, replicas, serving container, scaling"You are charged for the compute resources used to deploy the model to an endpoint", so the endpoint costs money while deployedSteady high volume, fine-tuned weights, models not offered as an API

A self-deployed model is a serving system you own: autoscaling limits, cold starts, upgrades and a bill that runs while idle. The trade-offs of running open models with vLLM yourself are in the posts on vLLM throughput and KServe with vLLM. Behind the service layer, either option is just another route target with its own error mapping and price row.

Capacity and cost

  • Shared pay-as-you-go is the default. Expect 429s under contention and smooth your traffic.
  • Provisioned Throughput is, in the documentation's words, "a fixed-cost, fixed-term subscription available in several term-lengths that reserves throughput", measured in generative AI scale units. Its customers "are prioritized and serviced first before on-demand requests", and traffic above the reservation spills over to pay-as-you-go. It suits steady, latency-sensitive load; idle reservations still cost money.
  • Context caching is on by default in its implicit form: cached input tokens are discounted, by 90 per cent for Gemini 3 and 2.5 models and 95 per cent for Gemini 4 and later, according to the caching overview. Putting the long, stable part of a prompt first (instructions, schemas, reference documents) makes hits more likely.
  • Batch inference "is offered at a 50% discounted rate compared to real-time inference". "Most jobs complete within 24 hours after it starts running", not counting queue time, and incomplete jobs are cancelled after 24 hours. Anything that does not need an answer now, such as backfills or nightly re-scoring, belongs there.
WorkloadUsually the better fit
Interactive, modest or spiky trafficShared pay-as-you-go, global endpoint if processing location allows, smoothed traffic
Interactive, steady and latency-sensitiveProvisioned Throughput sized to the steady load, pay-as-you-go above it
Many calls sharing a long prompt prefixContext caching, with the stable part of the prompt first
Large jobs that can wait a dayBatch inference

For tracking, the source of truth is the response's usage_metadata: prompt, output, cached and thinking token counts. The token counting page is clear that estimates are only estimates: "The accurate usage for billing is only available after execution within the response's usage_metadata."

Langfuse, an open-source LLM observability tool that can be self-hosted, records each model call as a generation inside a trace. Cost can be "Ingested", sent with the generation, or "Inferred", where "Langfuse calculates cost from submitted usage and the generation's model parameter, using a model definition that stores prices per usage type". When both exist, "ingested costs take priority". In practice:

  • send usage from usage_metadata, split by type, including cached and thinking tokens, which are priced differently;
  • add model definitions with your contracted prices for models the built-in list does not know, since "Model definition changes only apply to new generations";
  • tag every generation with the feature and route, so cost per feature and per model falls out of a query;
  • use platform labels as well (the labels field in the request), so the cloud bill can be split the same way.

Cost per successful output is the number that matters. A cheap model that needs three attempts and a fallback is not cheap, and only per-call records show that.

Data, regions and governance

  • Global endpoint or not. The global endpoint improves availability, but the documentation warns: "Don't use the global endpoint if you have ML processing requirements, because you can't control or know which region your ML processing requests are sent to". For EU or US processing there are multi-region endpoints (eu, us) and regional ones. Note also that "Endpoints don't guarantee data residency or in-region ML processing"; residency is a separate set of commitments to check.
  • Training. The data governance page states: "Google won't use your data to train or fine-tune any AI/ML models without your prior permission or instruction."
  • Perimeters and keys. Support for VPC Service Controls and customer-managed encryption keys varies by model and feature; the security controls page has the table. Check each feature you use before promising either.

A migration checklist

  1. Inventory every call site: which feature, which model, which settings, what output shape.
  2. Route everything through the service first, still pointing at the old provider, so the switch is a configuration change.
  3. Build a held-out evaluation set per task and score old and new models on it before switching. Recording runs reproducibly is covered in the MLflow evaluation post.
  4. Adapt prompts and settings per model rather than copying them; temperature and token limits do not transfer.
  5. Compare tokens and cost on the same inputs: tokenisers differ, so the same prompt costs differently.
  6. Shadow, then cut over per task, keeping the old route as a fallback until error and quality metrics are stable.
  7. Move long, multi-step jobs into a workflow engine so a retry resumes a step instead of repeating a whole document; see the Temporal post.
  8. Watch model retirement dates. The model versions page lists them, and a retired model stops serving requests, so routes need a planned successor.

What this does not cover

  • Agents, tools and the Agent Development Kit; this post is about calling models reliably.
  • Tuning and fine-tuning, and grounding with search or retrieval.
  • Exact prices: the pricing page changes, and introductory prices expire.
  • The SDK retry test covers one client mode against a stub server, not the platform itself. The gateway runs against a fake backend, and the classifier against constructed SDK objects.

Sources