<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Artur Pacan on Medium]]></title>
        <description><![CDATA[Stories by Artur Pacan on Medium]]></description>
        <link>https://medium.com/@arturpacan?source=rss-b96b4eea63f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VmJ2uKrFDInTaIk2</url>
            <title>Stories by Artur Pacan on Medium</title>
            <link>https://medium.com/@arturpacan?source=rss-b96b4eea63f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:27:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arturpacan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The endpoint your AI gateway can’t reach]]></title>
            <link>https://medium.com/google-cloud/the-endpoint-your-ai-gateway-cant-reach-22c8cef420dc?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/22c8cef420dc</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[apigee]]></category>
            <category><![CDATA[api-management]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 10:39:19 GMT</pubDate>
            <atom:updated>2026-11-12T11:02:26.419Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What changes when an Apigee AI gateway moves into a private network with VPC Service Controls, and a relay pattern for the regional endpoints that Apigee can’t reach directly.</em></p><blockquote>Part 6 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>The example projects in this series are built to get you started quickly, and their network choices show it. Both call Gemini Enterprise Agent Platform, formerly Vertex AI, on its global endpoint: <strong>aiplatform.googleapis.com</strong> with location <strong>global</strong>. Both can send requests straight to providers on the internet, such as OpenAI at <strong>api.openai.com</strong>. And gsjurseth’s semantic cache queries Vector Search on a public endpoint. For a demo, that’s exactly right.</p><p>Production tends to add requirements that a template can’t know about. Three come up again and again:</p><ul><li>clients reach the gateway only from internal networks</li><li>the gateway reaches models and services without touching the public internet</li><li>data stays in a region, for example the EU</li></ul><p>Each requirement has a well-documented answer. Put together, they hide a problem that’s easy to miss on paper.</p><h3>Switching off the internet</h3><p>Apigee’s runtime lives in a Google-managed tenant project that’s peered with your VPC. To use <a href="https://docs.cloud.google.com/apigee/docs/api-platform/security/vpc-sc">VPC Service Controls with Apigee</a>, you enable them on that peering:</p><pre>gcloud services vpc-peerings enable-vpc-service-controls \<br>  --network=SHARED_VPC_NETWORK --project=PROJECT_ID</pre><p>The documentation is blunt about the effect: the Apigee runtime “will no longer communicate with any public internet target.” The <a href="https://docs.cloud.google.com/sdk/gcloud/reference/services/vpc-peerings/enable-vpc-service-controls">command reference</a> explains how. The command removes the default internet route from the runtime’s network, adds a route to the restricted VIP range <strong>199.36.153.4/30</strong>, and creates private DNS zones that resolve Google API hostnames, such as those under <strong>googleapis.com</strong>, to that range. The same page warns that routes you export from your own VPC can bring a default route back, so treat the command as one part of a perimeter design, not as an internet switch on its own.</p><p>Clients are the easy half. They reach the gateway through an internal load balancer whose backend points at the Apigee instance over Private Service Connect, the <a href="https://docs.cloud.google.com/apigee/docs/api-platform/system-administration/northbound-networking-psc">northbound PSC pattern</a>. The interesting half is everything the gateway calls.</p><h3>Sort every backend</h3><p>List every host the gateway calls. Each one lands in one of four groups:</p><ul><li><strong>Google APIs that support VPC Service Controls</strong>, on classic hostnames such as <strong>dlp.googleapis.com</strong> and <strong>REGION-aiplatform.googleapis.com</strong>, keep working through the restricted VIP. Masking (Part 3) and the cache’s embeddings and writes (Part 5) use this path.</li><li><strong>Vector Search queries</strong> go through an Apigee endpoint attachment over Private Service Connect (Part 5).</li><li><strong>Internet targets</strong> stop working, and that includes model providers’ own APIs. Agent Platform hosts Claude and open models as well as Gemini, which keeps most model traffic on Google APIs. For anything else, an environment-level <a href="https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/environments-overview">forward proxy</a> that you run is the documented way out.</li><li><strong>Regional endpoints</strong>, on <strong>*.rep.googleapis.com</strong> hostnames, have nowhere to go.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Si6lH8J0DEmhQwljsMrHiw.png" /><figcaption><em>Figure 1 — The Apigee runtime has no internet route. Each kind of backend is reached through a different private path.</em></figcaption></figure><h3>Two backends with nowhere to go</h3><p>Data residency often points straight at regional endpoints. Agent Platform serves the EU multi-region from <strong>aiplatform.eu.rep.googleapis.com</strong> (see <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations">locations</a>), and Model Armor serves each region from a hostname like <strong>modelarmor.REGION.rep.googleapis.com</strong>.</p><p>Inside a VPC, the documented answer is a <a href="https://docs.cloud.google.com/vpc/docs/access-regional-google-apis-endpoints">Private Service Connect endpoint for regional Google APIs</a>: an internal IP address in your subnet that forwards to the regional service. For Model Armor it isn’t optional. Its <a href="https://docs.cloud.google.com/model-armor/overview">overview</a> says you must create one to reach the regional endpoints from a VPC network, to prevent certificate errors with Private Google Access or VPC Service Controls.</p><p>Then look at the compatibility table on the <a href="https://docs.cloud.google.com/vpc/docs/about-accessing-regional-google-apis-endpoints">concepts page</a>: access through VPC Network Peering isn’t supported. The how-to page puts it plainly: “Clients in peered VPC networks cannot reach endpoints.”</p><p>Apigee isn’t in your VPC. It reaches your network over a peering. The documented fix gives you an IP address that your gateway can’t reach.</p><h3>A relay Apigee can reach</h3><p>What Apigee <em>can</em> reach over the peering is an internal load balancer. That suggests a small relay in front of each regional endpoint, built from documented pieces:</p><ul><li>An <a href="https://docs.cloud.google.com/load-balancing/docs/tcp/internal-proxy">internal proxy Network Load Balancer</a>, a regional TCP proxy with an internal IP address.</li><li>A <a href="https://docs.cloud.google.com/load-balancing/docs/negs/hybrid-neg-concepts">hybrid network endpoint group</a> of type <strong>NON_GCP_PRIVATE_IP_PORT</strong>, whose only member is the PSC endpoint’s IP address on port 443.</li><li>A private DNS zone for the exact regional hostname, pointing at the load balancer.</li><li>A peered DNS domain, so that the Apigee runtime sends lookups for that hostname to your VPC’s private zones. DNS peering with service producers is part of <a href="https://docs.cloud.google.com/vpc/docs/configure-private-services-access">private services access</a>.</li></ul><p>The DNS piece is one command. The suffix is the full hostname, including the final dot:</p><pre>gcloud services peered-dns-domains create aiplatform-eu \<br>  --network=VPC_NETWORK \<br>  --dns-suffix=aiplatform.eu.rep.googleapis.com.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J37PCqcb8xpJ15HKJ5WFJw.png" /><figcaption><em>Figure 2 — Apigee resolves the regional hostname to the load balancer, and the load balancer relays the TCP connection to the PSC endpoint. TLS is never terminated along the way.</em></figcaption></figure><p>The best part is what you don’t have to do. The load balancer only forwards TCP, so TLS stays end to end. Apigee connects to <strong>aiplatform.eu.rep.googleapis.com</strong>, receives Google’s certificate for that name and validates it as usual. There are no custom truststores, no certificate overrides and no host-header tricks, and targets keep using the real hostname.</p><p>Treat this as a pattern, not a product feature. Each piece is documented, but the combination isn’t a documented Apigee setup, so test it end to end in your environment, including what happens when DNS or the endpoint changes. The forward proxy is the alternative. It means running proxy VMs, but it’s a documented Apigee feature, and recent versions route the Model Armor and semantic cache policies’ calls through it too.</p><h3>Things that bite</h3><ul><li><strong>The PSC endpoint needs a regular subnet.</strong> Its address can’t come from a proxy-only or PSC NAT subnet.</li><li><strong>The TCP proxy needs a proxy-only subnet</strong> in its region.</li><li><strong>Mind the regions.</strong> A PSC endpoint for a regional API must be in that API’s region, and by default it only accepts clients from its own region, which includes the relay’s proxies. Keep them together, or enable global access on the endpoint.</li><li><strong>An endpoint only helps if something calls its exact hostname.</strong> The semantic cache configurations in the docs and in gsjurseth’s feature call REGION-aiplatform.googleapis.com, not the EU endpoint, so a relay for aiplatform.eu.rep.googleapis.com changes nothing for them.</li><li><strong>Keep locations straight.</strong> Inference, Model Armor templates, Sensitive Data Protection and the Vector Search index can each have their own location. Write them down in one place.</li></ul><h3>Looking back</h3><p>Here’s one lesson from each part of this series:</p><ul><li><a href="https://medium.com/google-cloud/stop-building-one-proxy-per-model-6a05ea63a6f5"><strong>Part 1</strong></a><strong>:</strong> Choose one API contract first, and build the gateway from small features whose order you review like code.</li><li><a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009"><strong>Part 2</strong></a><strong>:</strong> A compatibility promise covers requests, streams and errors. Errors are the part teams forget.</li><li><a href="https://medium.com/google-cloud/my-favorite-guardrail-test-is-a-polite-trap-58b8ae84a2f1"><strong>Part 3</strong></a><strong>:</strong> Guardrails protect only the paths they cover, so write down the paths they don’t.</li><li><a href="https://medium.com/google-cloud/never-let-a-request-decide-who-pays-1090ee69fa1e"><strong>Part 4</strong></a><strong>:</strong> Never let a request decide who it is, which plan it’s on or how big it is.</li><li><a href="https://medium.com/google-cloud/a-semantic-cache-is-easy-to-demo-and-hard-to-trust-873e0fa159d8"><strong>Part 5</strong></a><strong>:</strong> Cache only what the embedded text fully describes, and check which way your threshold points.</li><li><strong>Part 6:</strong> In a private network, list every backend and give each one a path you’ve tested.</li></ul><p>None of these problems is exotic. They’re what happens when a good demo meets production requirements, and Apigee has an answer for each of them. If you’re building an AI gateway, start from <a href="https://github.com/tyayers/apigee-completions-template">tyayers/apigee-completions-template</a>, browse <a href="https://github.com/gsjurseth/apigee-yaml-configs">gsjurseth/apigee-yaml-configs</a> for patterns that arrive one stage at a time, and compose your own features with <a href="https://github.com/apigee/apigee-templater">apigee-templater</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22c8cef420dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/the-endpoint-your-ai-gateway-cant-reach-22c8cef420dc">The endpoint your AI gateway can’t reach</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A semantic cache is easy to demo and hard to trust]]></title>
            <link>https://medium.com/google-cloud/a-semantic-cache-is-easy-to-demo-and-hard-to-trust-873e0fa159d8?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/873e0fa159d8</guid>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[apigee]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 08:32:10 GMT</pubDate>
            <atom:updated>2026-11-12T10:43:03.724Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Apigee’s semantic cache policies answer repeated questions without calling the model. Here’s what decides whether a hit is the right answer, and how the cache reaches Vector Search in a private network.</em></p><blockquote>Part 5 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>The demo always works. Ask “How do I reset my password?”, then ask “I forgot my password, what now?”, and the second answer comes back faster, with one extra response header:</p><pre>HTTP/1.1 200 OK<br>Cached-Content: true</pre><p>Users ask the same things in different words, and paying a model to write the same answer twice is waste. A semantic cache matches requests by meaning instead of exact text. It’s one of the most satisfying features to demo in an AI gateway, and the one I’d treat most carefully in production. A cache that hits on the wrong question doesn’t fail. It returns a fast, confident answer to a question nobody asked.</p><h3>How it works</h3><p>Apigee has two policies for this, <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-lookup-policy">SemanticCacheLookup</a> and <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-populate-policy">SemanticCachePopulate</a>, backed by <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/overview">Vector Search</a> on Gemini Enterprise Agent Platform, formerly Vertex AI. The lookup embeds the prompt with an embedding model such as <strong>gemini-embedding-001</strong> and asks Vector Search for the nearest stored prompt. If it’s close enough, Apigee returns the stored answer without calling the model. On a miss, the populate policy stores the model’s answer after it replies, for as long as its TTL allows.</p><p>Stage 3 of <a href="https://github.com/gsjurseth/apigee-yaml-configs">gsjurseth’s</a> progressive gateway adds both policies with one feature. The flows are the interesting part:</p><pre>defaultEndpoint:<br>  name: default<br>  flows:<br>    - name: PreFlow<br>      mode: Request<br>      steps:<br>        - name: SCLLookup<br>    - name: PostFlow<br>      mode: Response<br>      steps:<br>        - name: SCPPopulate<br>          condition: &quot;&#39;SemanticCacheLookup.llm-semantic-cache-SCLLookup.cache_hit&#39; is false&quot;</pre><p>Two details are worth copying. The populate step runs only on a miss, so hits don’t write themselves back into the cache. And the condition puts the variable name in quotes. When the template compiles, each policy name gets the feature’s name as a prefix, as the <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/api-proxy-yaml-configuration-reference">YAML reference</a> explains, so <strong>SCLLookup</strong> becomes <strong>llm-semantic-cache-SCLLookup</strong>. Without the quotes, Apigee’s condition parser would read the hyphens as minus signs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjL15iXKajpfsHdpBNk2HA.png" /><figcaption><em>Figure 1 — The prompt is embedded and its nearest neighbor looked up. On a hit, the cached answer is returned. On a miss, the model answers and the response is stored for the TTL.</em></figcaption></figure><h3>A threshold has a direction</h3><p>The lookup’s <strong>Threshold</strong> decides how close is close enough, and what it means depends on how your index measures distance. The <strong>SemanticCacheLookup</strong> reference is explicit: dot product is a similarity, so a larger value means a closer match, while cosine, squared L2 and L1 are distances, where a smaller value does. The policy’s <strong>DistanceMeasureType</strong> element sets the direction of the comparison. It defaults to dot product, and the default threshold, 0.9, suits dot product.</p><p>Here’s how that goes wrong. Build the index with <strong>COSINE_DISTANCE</strong>, set <strong>DistanceMeasureType</strong> to match, and keep the threshold at 0.9. A hit now means a distance of 0.9 or less, which almost every stored prompt passes. The cache answers everything.</p><p>Older runtimes add a twist. Before Apigee <strong>1–18–0-apigee-4</strong> and <strong>hybrid 1.17.0</strong>, the element is accepted and silently ignored, and the threshold is always compared as a dot product. On a cosine index, that turns the comparison upside down: close matches miss, and only very different prompts can hit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JflZkZEq18FHKEEw31PbEg.png" /><figcaption><em>Figure 2 — With dot product, bigger means closer. With cosine distance, smaller means closer, and a dot-product threshold lets everything through. Illustrative values.</em></figcaption></figure><p>The simplest fix is to avoid the mismatch. Vector Search’s <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/configuring-indexes">index configuration guide</a> strongly suggests <strong>DOT_PRODUCT_DISTANCE</strong> with <strong>UNIT_L2_NORM</strong> instead of <strong>COSINE_DISTANCE</strong>, and dot product is what the policy assumes by default. gsjurseth’s feature describes its 0.9 as a cosine similarity, which agrees with that setup: for normalized vectors, such as those <strong>gemini-embedding-001</strong> returns, the dot product is the cosine similarity.</p><p>A short checklist keeps you honest:</p><ul><li>Read the measure your index was built with: run <strong>gcloud ai indexes describe INDEX_ID — region=REGION</strong> and check <strong>distanceMeasureType</strong>.</li><li>Set <strong>DistanceMeasureType</strong> to match, then tune the threshold for that measure.</li><li>Confirm it in a debug session. Send the same request twice and check <strong>semanticcache.lookup.POLICY_NAME.measure_type</strong> and <strong>semanticcache.lookup.POLICY_NAME.nearest_neighbor_measure</strong>.</li><li>Start strict. A false hit, the right answer to a different question, costs more than a miss.</li><li>Retune whenever you change the embedding model.</li></ul><h3>The cache key is whatever you embed</h3><p>The lookup embeds one thing: the text that <strong>UserPromptSource</strong> points at. In gsjurseth’s feature, that’s <strong>llm.prompt</strong>, the content of the last message. Everything else in the request is invisible to the cache: the system prompt, the conversation history, the tools and even the model name. Two requests that end with the same question can deserve very different answers.</p><p>So cache only when the last message is the whole story. A conservative rule:</p><ul><li>one user message, with no system prompt and no history</li><li>text only, with no tools and no structured output format</li><li>no streaming, which the cache policies don’t support anyway (more below)</li><li>a generic question, not a personal one</li></ul><p>You can express a rule like this as a condition on both cache steps, so that requests that don’t qualify skip the cache entirely.</p><p>The policies don’t scope entries per caller, so everyone whose requests reach the same index shares one cache. That’s what makes it effective, and it’s also why it suits generic questions rather than personal ones. Apigee’s <a href="https://docs.cloud.google.com/apigee/docs/api-platform/tutorials/using-semantic-caching-policies">semantic caching tutorial</a> suggests TTLs that follow the same logic: a long TTL, such as an hour, for generic answers, no caching or about five minutes for user-specific ones, and about five minutes for anything time-sensitive. If you don’t set one, entries expire after 60 seconds.</p><p>Finally, put the cache behind your guardrails. In gsjurseth’s stage 4, Model Armor runs before the cache, so blocked prompts never reach it. If you mask personal data (<a href="https://medium.com/google-cloud/my-favorite-guardrail-test-is-a-polite-trap-58b8ae84a2f1">Part 3</a>), mask before the lookup too, so the cache only ever stores masked text.</p><h3>Two policies, two transports</h3><p>The tutorial queries Vector Search through a public endpoint on <strong>*.vdb.vertexai.goog</strong>, and so does gsjurseth’s feature. That’s fine until the gateway runs in a private network without internet egress (<a href="https://medium.com/@arturpacan/the-endpoint-your-ai-gateway-cant-reach-22c8cef420dc">Part 6</a>), because the public endpoint is an internet target.</p><p>Vector Search index endpoints can use <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/private-service-connect">Private Service Connect</a> instead, and here the two policies differ:</p><ul><li><strong>SemanticCacheLookup</strong> can query Vector Search over Private Service Connect, using gRPC.</li><li><strong>SemanticCachePopulate</strong> is REST-only. It writes with <strong>upsertDatapoints</strong> on <strong>REGION-aiplatform.googleapis.com</strong> and rejects a Private Service Connect configuration at deployment time. It doesn’t need one, because that hostname is a Google API, which stays reachable inside a VPC Service Controls perimeter.</li></ul><p>The embedding call goes to <strong>REGION-aiplatform.googleapis.com</strong> too. Only the similarity search needs the private path:</p><pre>&lt;SimilaritySearch&gt;<br>  &lt;VertexAI&gt;<br>    &lt;PrivateServiceConnect&gt;<br>      &lt;GrpcEndpoint&gt;grpc://{TARGET_HOST}:10000&lt;/GrpcEndpoint&gt;<br>    &lt;/PrivateServiceConnect&gt;<br>    &lt;Threshold&gt;0.9&lt;/Threshold&gt;<br>    &lt;DeployedIndexID&gt;{DEPLOYED_INDEX_ID}&lt;/DeployedIndexID&gt;<br>    &lt;DistanceMeasureType&gt;DOT_PRODUCT_DISTANCE&lt;/DistanceMeasureType&gt;<br>  &lt;/VertexAI&gt;<br>&lt;/SimilaritySearch&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1tEaA-7LMYWfFuaNlPWkQ.png" /><figcaption><em>Figure 3 — Lookup reaches Vector Search over Private Service Connect and gRPC. Embedding calls and upserts use the Agent Platform REST API on REGION-aiplatform.googleapis.com.</em></figcaption></figure><p>Apigee’s tutorial for <a href="https://docs.cloud.google.com/apigee/docs/api-platform/tutorials/using-semantic-caching-policies-psc">semantic caching with a Private Service Connect endpoint</a> walks through the setup. Three things in it are easy to miss:</p><ul><li><strong>Allowlist the Apigee tenant project, not your own.</strong> The connection comes from the Apigee-managed project, whose ID is the <strong>apigeeProjectId</strong> field in the Organizations API. The allowlist can’t be changed after the index endpoint is created, so a wrong project means re-creating the endpoint.</li><li><strong>The gRPC hop is plaintext.</strong> <strong>GrpcEndpoint</strong> accepts only <strong>grpc://</strong> on port 10000 and relies on network isolation for its security.</li><li><strong>Vector Search isn’t available in every region.</strong> Your index endpoint may have to live in a different region from your Apigee organization.</li></ul><h3>The fine print</h3><ul><li><strong>Streaming:</strong> the semantic caching policies aren’t supported in proxies that use EventFlows to stream server-sent events. If your gateway streams, serve cached and streamed traffic from separate proxies.</li><li><strong>Limits:</strong> cacheable text is capped at 256 KB, and Apigee ignores Cache-Control headers from the model.</li><li><strong>Latency:</strong> every lookup pays for an embedding and a vector query, and the tutorial warns this can add hundreds of milliseconds. Measure your hit rate before you celebrate.</li></ul><h3>What I’d tell you</h3><ul><li>Cache only when the embedded text fully describes the request, and treat false hits as bugs.</li><li>Check which way your threshold points. Match <strong>DistanceMeasureType</strong> to your index and confirm it in a debug session.</li><li>Put the cache behind masking and screening, and choose TTLs by how personal and how fresh the answers are.</li><li>Check which transports each policy supports before you design your network around them.</li></ul><p>A semantic cache earns trust the way people do: by being right when it’s confident. Configure it to miss more than it hits, and let the evidence loosen it.</p><p><strong>Next — </strong><a href="https://medium.com/@arturpacan/the-endpoint-your-ai-gateway-cant-reach-22c8cef420dc"><strong>Part 6</strong></a><strong>:</strong> The endpoint your AI gateway can’t reach. What changes when the gateway moves into a private network, and a relay pattern for regional endpoints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873e0fa159d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/a-semantic-cache-is-easy-to-demo-and-hard-to-trust-873e0fa159d8">A semantic cache is easy to demo and hard to trust</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never let a request decide who pays]]></title>
            <link>https://medium.com/google-cloud/never-let-a-request-decide-who-pays-1090ee69fa1e?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1090ee69fa1e</guid>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[apigee]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 09:10:48 GMT</pubDate>
            <atom:updated>2026-10-28T08:33:15.332Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Token quotas, API products and cost reports in an Apigee AI gateway, and the one rule that keeps them honest: only the credential decides.</em></p><blockquote>Part 4 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>Here’s a test I like to run against an AI gateway. It sends a free-plan API key, a large prompt and three extra headers:</p><pre>curl &quot;https://$GATEWAY_HOST/v1/chat/completions&quot; \<br>  -H &quot;x-api-key: $FREE_PLAN_KEY&quot; \<br>  -H &quot;x-user-id: someone-else&quot; \<br>  -H &quot;x-tier: enterprise&quot; \<br>  -H &quot;x-requested-tokens: 1&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d @large-prompt.json</pre><p>The test passes only if the gateway ignores all three. The usage must land on the key’s own app and developer, the free plan’s limits must apply, and the gateway must measure the prompt itself.</p><p>Each header is a tempting shortcut: a quick way to test plans, a hook to force a 429 in a test, a fallback for clients that don’t send an ID. Each one also lets the caller decide who pays. If a header can name the user, anyone can put someone else’s name on the bill. If it can choose the plan, everyone is on the biggest one. And if a fresh ID on every request means a fresh quota, nobody ever runs out.</p><h3>Why tokens</h3><p>For LLM traffic, two requests can differ in cost by a factor of a thousand. A requests-per-minute limit protects the gateway, but it does little for your budget, and model providers enforce their own token quotas anyway. So an AI gateway counts tokens per consumer, and consumers get plans: a small one for experiments, bigger ones for production apps.</p><p>The limits are rarely the hard part. The hard part is deciding who the consumer is and which plan they’re on.</p><h3>Only the credential decides</h3><p>Apigee’s AI policies are deliberately flexible. Their elements accept references to flow variables, and the LLMTokenQuota reference lists headers and query parameters as possible sources, next to API products, apps, developers and key-value maps. That flexibility is useful, but it means a policy can’t tell a header the caller typed from an attribute your platform team set. That choice is yours, and there’s one safe answer:</p><ul><li><strong>Identity</strong> comes from the credential. <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/verify-api-key-policy">VerifyAPIKey</a> maps the key to an app, its developer and the API products it may use.</li><li><strong>Plan</strong> comes from the API product, or from custom attributes on the app or developer that only the platform team can change.</li><li><strong>Size</strong> is measured by the gateway: prompt tokens before the call, and actual usage from the model’s response after it.</li></ul><p>The <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy">LLMTokenQuota</a> reference shows the pattern with per-developer attributes. Here it is as an enforcement policy:</p><pre>&lt;LLMTokenQuota name=&quot;LTQ-Enforce&quot; type=&quot;rollingwindow&quot;&gt;<br>  &lt;SharedName&gt;developer-tokens&lt;/SharedName&gt;<br>  &lt;EnforceOnly&gt;true&lt;/EnforceOnly&gt;<br>  &lt;Identifier ref=&quot;verifyapikey.verify-api-key.client_id&quot;/&gt;<br>  &lt;Interval ref=&quot;verifyapikey.verify-api-key.developer.timeInterval&quot;&gt;1&lt;/Interval&gt;<br>  &lt;TimeUnit ref=&quot;verifyapikey.verify-api-key.developer.timeUnit&quot;&gt;minute&lt;/TimeUnit&gt;<br>  &lt;Allow count=&quot;10000&quot; countRef=&quot;verifyapikey.verify-api-key.developer.limit&quot;/&gt;<br>&lt;/LLMTokenQuota&gt;</pre><p>Each app gets its own counter, keyed on the verified client ID, and the limits come from the developer’s attributes. The values inside the elements are fallbacks. When a reference doesn’t resolve, Apigee uses the value instead, so a developer without attributes gets the smallest plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXpC2HJrZopYS3jl6A77Og.png" /><figcaption><em>Figure 1 — Headers are ignored. The verified key decides identity and plan, and the gateway measures the tokens itself.</em></figcaption></figure><h3>Plans belong in API products</h3><p>Attributes work, but the natural home for a plan is an <a href="https://docs.cloud.google.com/apigee/docs/api-platform/publish/create-api-products">API product</a>. Products have LLM operations, which list the proxies, paths and models a plan may use, each with an optional token quota. VerifyAPIKey matches the key to its product and exposes the product’s LLM quota settings as flow variables. LLMTokenQuota reads them through references such as <strong>verifyapikey.verify-api-key.apiproduct.developer.llmQuota.limit</strong>, or all at once with <strong>UseQuotaConfigInAPIProduct</strong>.</p><p>Plans are configuration, so keep them in version control next to the gateway. apigee-templater has a YAML format for products (trimmed):</p><pre>name: ai-standard-plan<br>displayName: AI Standard Plan<br>type: product<br>approvalType: manual<br>environments:<br>  - prod<br>proxies:<br>  - llm-gateway<br>llmOperations:<br>  - apiSource: llm-gateway<br>    operations:<br>      - name: /chat/completions<br>        model: google/gemini-3.8-flash<br>        methods:<br>          - POST</pre><p>Two details are worth a second look. With <strong>approvalType: manual</strong>, someone on the platform team approves every key request for the plan, so nobody upgrades themselves. And LLMTokenQuota reads the <strong>model</strong> from the request’s model field by default and matches it against the product’s LLM operations, so make sure the names agree, especially if the gateway resolves aliases (<a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009">Part 2</a>). apigee-templater can also export existing products to YAML and deploy products together with a template, which makes plan changes as reviewable as code.</p><h3>Enforce before, count after</h3><p>Three policies cover three jobs:</p><ul><li><a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/prompt-token-limit-policy">PromptTokenLimit</a> works like SpikeArrest for prompt tokens. It stops a burst of huge prompts before they reach the model.</li><li>LLMTokenQuota holds the budget per minute, day or month.</li><li>A classic <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/quota-policy">Quota</a> policy still caps requests, which protects the gateway itself.</li></ul><p>You can’t know how many tokens a model will produce until it has produced them, so LLMTokenQuota runs twice on one shared counter. In the request flow, <strong>EnforceOnly</strong> rejects a request when the budget is spent, but never adds to the counter. In the response flow, <strong>CountOnly</strong> adds the tokens the model actually used, but never rejects. SharedName ties the two together. Point the counting policy’s <strong>LLMTokenUsageSource</strong> at the response’s usage data: the reference examples read Gemini’s native <strong>usageMetadata</strong>, while an OpenAI-compatible gateway reads <strong>usage</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjWip2OYjKy338aM7nbrcw.png" /><figcaption><em>Figure 2 — Requests are admitted while budget remains, and actual usage is added afterwards. A consumer can overshoot once within a window and is then blocked until the window moves on.</em></figcaption></figure><p>One large answer can push a consumer past the limit, and the next request has to wait. That’s a reasonable trade-off. Reserving the worst-case output for every request would waste most of the budget.</p><p>Two more details:</p><ul><li><strong>Streams.</strong> Put the counting policy in the EventFlow. It counts when an event carries usage data and does nothing for the others, so make sure your streams include usage.</li><li><strong>The 429.</strong> Both token policies answer a violation with a 429. Map it to OpenAI’s <strong>rate_limit_exceeded</strong> with a <strong>Retry-After</strong> header (<a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009">Part 2</a>), so SDK retry logic works unchanged.</li></ul><h3>Telling finance</h3><p>Limits protect the budget. Reports explain it. <a href="https://github.com/tyayers/apigee-completions-template">tyayers’ template</a> turns usage into money after every response. A JavaScript step reads the token counts from the response, or from whichever stream event carries them, and multiplies them by per-model prices from a key-value map. Then a <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/data-capture-policy">DataCapture</a> policy writes the results to custom data collectors (trimmed):</p><pre>- name: DC-TokenAnalytics<br>  type: DataCapture<br>  content:<br>    DataCapture:<br>      Capture:<br>        - Collect:<br>            metadata:<br>              ref: ai.model<br>              default: unknown<br>          DataCollector: dc_ai_model<br>        - Collect:<br>            metadata:<br>              ref: ai.totalTokenCount<br>              default: &quot;0&quot;<br>          DataCollector: dc_ai_total_token_count<br>        - Collect:<br>            metadata:<br>              ref: ai.totalCost<br>              default: &quot;0&quot;<br>          DataCollector: dc_ai_total_cost</pre><p>The template’s <strong>initialize.sh</strong> creates data collectors and three <a href="https://docs.cloud.google.com/apigee/docs/api-platform/analytics/create-custom-reports">custom reports</a>. The cost report sums cost by two dimensions, <strong>dc_ai_model</strong> and <strong>developer_email</strong>.</p><p><strong>developer_email</strong> is the interesting one, because no client sends it. According to the <a href="https://docs.cloud.google.com/apigee/docs/api-platform/analytics/analytics-reference">analytics reference</a>, Apigee fills it in only when the proxy checks an API key or OAuth token for an app in an API product. Otherwise every row says <strong>(not set)</strong>. The template’s README treats API key verification as optional, which is the right call for a quick start. Turn it on before you show anyone a cost report. It’s the difference between cost per developer and one big total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3qS044rxKK6MlJS9q65PQ.png" /><figcaption><em>Figure 3 — Token counts and prices become cost figures in custom reports. The verified key supplies the developer dimension.</em></figcaption></figure><p>Two caveats. These figures are estimates, not invoices: prices change, and a price list doesn’t know about discounts, so reconcile them with Cloud Billing. And streams report usage at the end, if at all, so check that each provider you route to actually sends it.</p><h3>What I’d tell you</h3><ul><li>Take identity, plan and size from the verified credential and the gateway’s own measurements, never from the request.</li><li>Keep plans in API products, review them like code, and make upgrades a human decision.</li><li>Enforce before the call and count after it, on one shared counter.</li><li>Turn on API key verification before you build a single cost report.</li></ul><p>Every header is a suggestion from the caller. Budgets, limits and invoices deserve more than suggestions.</p><p><strong>Next — </strong><a href="https://medium.com/@arturpacan/a-semantic-cache-is-easy-to-demo-and-hard-to-trust-873e0fa159d8"><strong>Part 5</strong></a><strong>:</strong> A semantic cache is easy to demo and hard to trust. What the cache key really is, why a threshold has a direction, and how the two cache policies reach Vector Search.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1090ee69fa1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/never-let-a-request-decide-who-pays-1090ee69fa1e">Never let a request decide who pays</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My favorite guardrail test is a polite trap]]></title>
            <link>https://medium.com/google-cloud/my-favorite-guardrail-test-is-a-polite-trap-58b8ae84a2f1?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/58b8ae84a2f1</guid>
            <category><![CDATA[apigee]]></category>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 08:19:14 GMT</pubDate>
            <atom:updated>2026-10-28T08:33:43.024Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One harmless-looking request shows how Sensitive Data Protection and Apigee’s Model Armor policies fit together in an AI gateway, and where their blind spots are.</em></p><blockquote>Part 3 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>The first test I write for any AI gateway sends one very polite message:</p><pre>{<br>  &quot;model&quot;: &quot;google/gemini-3.8-flash&quot;,<br>  &quot;messages&quot;: [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;My email is test.user@example.com. Please confirm receipt of my message.&quot;}<br>  ]<br>}</pre><p>It’s a trap. Helpful models like to confirm things by repeating them back, so the easiest way to leak an address is to ask the model to acknowledge it. The test passes only if the answer doesn’t contain <strong>test.user@example.com</strong>.</p><p>I like it because it checks the outcome a user cares about: what goes in shouldn’t come back out. It’s also the clearest way I know to explain what an AI gateway’s guardrails do, and what they can’t do.</p><h3>Two risks, two services</h3><p>Teams usually ask for guardrails against two different risks:</p><ul><li><strong>Data leakage</strong> means personal data in prompts leaving your control, or coming back in answers. <a href="https://docs.cloud.google.com/sensitive-data-protection/docs/deidentify-sensitive-data">Sensitive Data Protection</a> finds that data and masks it.</li><li><strong>Unsafe content and attacks</strong> means hate speech, dangerous instructions, prompt injection, jailbreaks and malicious links. That’s what <a href="https://docs.cloud.google.com/model-armor/overview">Model Armor</a> screens for.</li></ul><p>One naming trap while we’re here: Cloud Armor and Model Armor are different products. Cloud Armor is Google Cloud’s web application firewall, and it protects the gateway’s front door from web attacks. Model Armor inspects what’s said to and by the model. Many gateways need both, and neither replaces the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04FUEP89qUNtQddpudGdfQ.png" /><figcaption><em>Figure 1 — Personal data is masked first, then Model Armor screens the masked prompt. The answer can go through the same two checks on its way back.</em></figcaption></figure><h3>Screening: configuration, not code</h3><p>Apigee has native Model Armor policies. <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-user-prompt-policy">SanitizeUserPrompt</a> screens the prompt, and <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy">SanitizeModelResponse</a> screens the answer. Stage 2 of <a href="https://github.com/gsjurseth/apigee-yaml-configs">gsjurseth’s</a> progressive gateway adds both with one feature (trimmed):</p><pre>defaultEndpoint:<br>  flows:<br>    - name: PreFlow<br>      mode: Request<br>      steps:<br>        - name: MA-SanitizeUserPrompt<br>    - name: PostFlow<br>      mode: Response<br>      steps:<br>        - name: MA-SanitizeModelResponse<br>policies:<br>  - name: MA-SanitizeUserPrompt<br>    type: SanitizeUserPrompt<br>    content:<br>      SanitizeUserPrompt:<br>        ModelArmor:<br>          TemplateName:<br>            _text: &quot;{MA_TEMPLATE_PATH}&quot;<br>        UserPromptSource:<br>          _text: &quot;{llm.prompt}&quot;</pre><p>Three details matter more than the YAML suggests:</p><ul><li><strong>Tell the policies where the text is.</strong> SanitizeUserPrompt’s default <strong>UserPromptSource</strong> expects Gemini’s native request format, so an OpenAI-compatible gateway has to point it at the prompt. Here it reads <strong>llm.prompt</strong>, which the format feature fills from <strong>$.messages[-1].content</strong>, the last message. The response policy in the same feature reads the answer from <strong>$.choices[-1].message.content</strong>.</li><li><strong>The filters live in a Model Armor template</strong>, not in the proxy. The template sets responsible AI categories (hate speech, harassment, sexually explicit and dangerous content), each with its own confidence level, plus prompt injection and jailbreak detection and malicious URL detection. Prompt injection and jailbreak detection has its own setting, separate from the responsible AI filters, so it’s easy to turn one on and forget the other. Check both.</li><li><strong>A match is a 400.</strong> When a prompt trips a filter, SanitizeUserPrompt raises <strong>FilterMatched</strong>, and Apigee answers with a 400 in its own error format. <a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009">Part 2</a> shows how to turn that into an error OpenAI clients understand.</li></ul><h3>Masking: the model only sees asterisks</h3><p>Screening decides whether a request may continue. Masking changes the request so that it can continue safely. A gateway can call the Sensitive Data Protection <strong>content:deidentify</strong> method from a <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/service-callout-policy">ServiceCallout</a> policy, authenticated with the proxy’s service account, and write the result back into the prompt. A minimal request body looks like this:</p><pre>{<br>  &quot;item&quot;: {&quot;value&quot;: &quot;My email is test.user@example.com. Please confirm receipt of my message.&quot;},<br>  &quot;inspectConfig&quot;: {&quot;infoTypes&quot;: [{&quot;name&quot;: &quot;EMAIL_ADDRESS&quot;}, {&quot;name&quot;: &quot;PERSON_NAME&quot;}]},<br>  &quot;deidentifyConfig&quot;: {<br>    &quot;infoTypeTransformations&quot;: {<br>      &quot;transformations&quot;: [{<br>        &quot;infoTypes&quot;: [{&quot;name&quot;: &quot;EMAIL_ADDRESS&quot;}, {&quot;name&quot;: &quot;PERSON_NAME&quot;}],<br>        &quot;primitiveTransformation&quot;: {&quot;characterMaskConfig&quot;: {&quot;maskingCharacter&quot;: &quot;*&quot;}}<br>      }]<br>    }<br>  }<br>}</pre><p>With the prompt masked, the model receives this:</p><pre>My email is *********************. Please confirm receipt of my message.</pre><p>Twenty-one characters, twenty-one asterisks. The model can confirm receipt all it likes. There’s nothing left to repeat.</p><p>A few choices are worth making on purpose:</p><ul><li><strong>Pick infoTypes for your users.</strong> Start from the <a href="https://docs.cloud.google.com/sensitive-data-protection/docs/infotypes-reference">infoTypes reference</a> and choose what actually shows up in your traffic.</li><li><strong>Keep some context.</strong> Full masking also removes meaning. Replacing each finding with its infoType name (<strong>replaceWithInfoTypeConfig</strong>) keeps the prompt readable for the model.</li><li><strong>Mask first.</strong> Run masking before Model Armor and before the semantic cache, so every later step, including the cache in <a href="https://medium.com/@arturpacan/a-semantic-cache-is-easy-to-demo-and-hard-to-trust-873e0fa159d8">Part 5</a>, only ever sees masked text.</li></ul><p>Model Armor templates can run Sensitive Data Protection checks too. That’s a good fit for blocking prompts that contain personal data. Masking the data and letting the request continue is a different job, and a direct de-identify call keeps it explicit.</p><h3>What the polite test can’t tell you</h3><p>Here’s the catch: the polite test passes even if the response checks never run. Prompt masking removes the address before the model sees it, so the model can’t repeat it. The test proves the outcome, not that every layer works.</p><p>That’s fine as long as you know it. Response checks exist for what prompt checks can’t cover, such as personal data from an earlier turn or from a document the model was given. If a layer matters, give it its own test. My second test is the opposite of polite: it asks for step-by-step instructions for something dangerous, and it passes only if the gateway refuses with a 400 before the model is ever called.</p><h3>The fine print</h3><p>Guardrails only protect the paths they cover. Write down the paths they don’t:</p><ul><li><strong>Decide how each check fails.</strong> With <strong>continueOnError</strong> set to <strong>false</strong>, as in the example, a Model Armor outage fails the request with a 500, so the gateway fails closed. A masking callout can go either way. Failing open keeps the gateway up, but prompts go through unmasked until the service recovers. Either can be right. Choose on purpose, and alert on the fail-open path.</li><li><strong>Know which messages are inspected.</strong> The example screens the last message. Earlier turns, system prompts and tool results reach the model as sent unless you extract and check them too. For agents, tool results matter most. SanitizeUserPrompt has a <strong>FunctionResponseSource</strong> element for them, which also defaults to Gemini’s format.</li><li><strong>Streamed answers are hard to screen.</strong> SanitizeModelResponse reads the whole answer from the response body. A streamed answer passes through as events and is never held in full, so decide whether streaming is allowed where response screening is required.</li><li><strong>A cache hit is only as safe as what was stored.</strong> Put the cache behind masking and screening, so it only stores what passed both.</li><li><strong>Logs are a path too.</strong> If an analytics or logging step captures the prompt before masking runs, your logs keep what the model never saw. Log after the guardrails, or log the masked values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOeWdOjE0yg6_wvTTHqjvg.png" /><figcaption><em>Figure 2 — Prompt checks run on every request. Full-answer checks need a buffered answer, and a cache hit returns what was checked when it was stored.</em></figcaption></figure><h3>What I’d tell you</h3><ul><li>Use Sensitive Data Protection for data and Model Armor for content. They solve different problems.</li><li>Mask first, so every later step, including your cache and your logs, only sees masked data.</li><li>Write tests that bait the model, and give each layer its own test.</li><li>Decide how each guardrail fails, and write down the paths it doesn’t cover.</li></ul><p>Guardrails are only as strong as the paths they cover. The polite trap is a good place to start, because it tests the one thing users will notice: whether what they told you comes back out.</p><p><strong>Next — </strong><a href="https://medium.com/@arturpacan/never-let-a-request-decide-who-pays-1090ee69fa1e"><strong>Part 4</strong></a><strong>:</strong> Never let a request decide who pays. Token quotas, API products and cost reports, and the one rule that keeps them honest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58b8ae84a2f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/my-favorite-guardrail-test-is-a-polite-trap-58b8ae84a2f1">My favorite guardrail test is a polite trap</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switching models should take one string]]></title>
            <link>https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/213b15578009</guid>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[apigee]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 07:30:39 GMT</pubDate>
            <atom:updated>2026-10-22T08:20:36.244Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Routing, aliases, translation, fallback and errors: what an Apigee AI gateway does so that clients can swap Gemini for Claude by changing the model field.</em></p><blockquote>Part 2 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>Here’s the promise an AI gateway makes to developers: write your code against one API, and switch models by changing one string.</p><pre>curl &quot;https://$GATEWAY_HOST/v1/chat/completions&quot; \<br>  -H &quot;x-api-key: $API_KEY&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>        &quot;model&quot;: &quot;google/gemini-flash-latest&quot;,<br>        &quot;stream&quot;: true,<br>        &quot;messages&quot;: [<br>          {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Summarize our refund policy in three bullets.&quot;}<br>        ]<br>      }&#39;</pre><p>Swap <strong>google/gemini-flash-latest</strong> for <strong>anthropic/claude-sonnet-5–5</strong> and nothing else in the request changes. Behind that one field, the gateway has to work out which model the client means, which provider serves it and how to speak that provider’s API. And it has to keep the promise when something fails.</p><p>The promise is easy to make and surprisingly easy to break. Here’s where it bends, and how the two example projects keep it.</p><h3>Routing as code</h3><p>The simplest router is a set of route rules. The <strong>llm-routing</strong> feature in <a href="https://github.com/gsjurseth/apigee-yaml-configs">gsjurseth/apigee-yaml-configs</a> sends anything that starts with <strong>google/</strong> to Gemini and everything else to OpenAI:</p><pre>endpoints:<br>  - name: default<br>    basePath: &quot;{BASE_PATH}&quot;<br>    routes:<br>      - name: gemini<br>        condition: llm.model StartsWith &quot;google/&quot;<br>        target: gemini-target<br>      - name: openai<br>        target: openai-target</pre><p>Apigee uses the first route rule that matches. The interesting part is the default, and the feature’s description tells a story worth learning from. An earlier version matched <strong>gpt-</strong> for OpenAI, which silently sent every other OpenAI model family, such as <strong>o1-*</strong> and <strong>chatgpt-*</strong>, to Gemini, where the requests failed. Inverting the default means new model families work without a change, as long as Gemini requests carry the <strong>google/</strong> prefix.</p><p>That’s a good habit in general: make the rules you control specific, and let the default absorb other people’s naming decisions.</p><h3>Routing as data</h3><p>Route rules need a redeploy for every change. <a href="https://github.com/tyayers/apigee-completions-template">tyayers/apigee-completions-template</a> moves the decision into data. A <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/key-value-map-operations-policy">key-value map</a> (KVM) policy reads one entry, <strong>ModelRoutingText</strong>, and a JavaScript step turns it into a <strong>target.route</strong> variable that the route rules match on:</p><pre>{<br>  &quot;models&quot;: {<br>    &quot;google/&quot;: &quot;googlecloud-oai&quot;,<br>    &quot;anthropic/&quot;: &quot;googlecloud&quot;,<br>    &quot;openai/&quot;: &quot;openai&quot;<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;google/gemini-flash-latest&quot;: &quot;google/gemini-3.8-flash&quot;<br>  }<br>}</pre><p>models maps a provider prefix to a route family. mappings holds aliases: clients ask for gemini-flash-latest, and the platform team decides what that points to this month. The template caches the entry for ten seconds, so moving an alias to a new model version takes effect almost immediately, with no redeploy and no client change. That’s the platform team’s version of changing one string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoBcOHRo4snliuV8AQzhKw.png" /><figcaption><em>Figure 1 — The alias resolves to a concrete model, the provider prefix picks a route family, and a route rule picks the target.</em></figcaption></figure><h3>Speaking Claude</h3><p>Gemini is the easy case. The <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/openai">OpenAI-compatible endpoint</a> of Gemini Enterprise Agent Platform, formerly Vertex AI, accepts the client’s request as it is, apart from the model name.</p><p><a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/partner-models/claude">Claude on Agent Platform</a> speaks Anthropic’s Messages API through the <strong>rawPredict</strong> and <strong>streamRawPredict</strong> methods, so the gateway has to translate. tyayers’ template is a good reference. Its Claude target URL ends in <strong>publishers/{ai.provider}/models/{ai.model}:{ai.method}</strong>, and a JavaScript step sets <strong>ai.method</strong> to <strong>streamRawPredict</strong> or <strong>rawPredict</strong>, depending on whether the client asked for a stream.</p><p>On the way in, the translation moves system messages into Anthropic’s top-level <strong>system</strong> field, adds <strong>anthropic_version</strong>, fills in <strong>max_tokens</strong> (Anthropic requires it) and turns image data URLs into base64 image blocks. On the way out, it rebuilds an OpenAI <strong>chat.completion</strong>.</p><p>Streams are the interesting part. Anthropic sends typed events such as <strong>message_start</strong>, <strong>content_block_delta</strong> and <strong>message_stop</strong>, while OpenAI clients expect <strong>chat.completion.chunk</strong> objects and a final <strong>data: [DONE]</strong>. Apigee’s <a href="https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events">EventFlow</a> runs policies on each server-sent event as it arrives, so the gateway can rewrite every event without buffering the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtrxuWqUIS-vX2rI6JutiA.png" /><figcaption><em>Figure 2 — Each Anthropic event becomes the OpenAI chunk the client expects, as soon as it arrives.</em></figcaption></figure><p>Write down what your translation covers. Tool calls are the usual gap: if OpenAI-style <strong>tools</strong> aren’t mapped to Anthropic’s format, an agent that relies on them quietly gets plain text back. A clear 400 is kinder than a silent downgrade.</p><h3>When a provider fails</h3><p>One string also implies that the gateway, not the client, deals with a provider having a bad minute. Stage 4 of gsjurseth’s example adds cross-provider fallback with one feature. When the primary target answers with a 4xx or 5xx, the target’s <strong>DefaultFaultRule</strong> sends the prompt to the other provider through a <a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/service-callout-policy">ServiceCallout</a> and returns that answer, with an <strong>x-apigee-fallback</strong> header so callers can tell (trimmed to the Gemini target):</p><pre>targets:<br>  - name: gemini-target<br>    flows:<br>      - name: PostFlow<br>        mode: Response<br>        steps:<br>          - name: RF-TargetErrorToFault<br>            condition: response.status.code &gt;= 400<br>    defaultFaultRule:<br>      name: FallbackToOpenAI<br>      steps:<br>        - name: KVM-GetOpenAIKey<br>        - name: AM-BuildOpenAIFallbackRequest<br>        - name: SC-FallbackToOpenAI<br>        - name: AM-CopyOpenAIFallbackResponse</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjbLZEsHf-URgAYQM2Q3eg.png" /><figcaption><em>Figure 3 — An error from the primary model raises a fault. The fault rule calls the other provider and returns its answer, marked with a header.</em></figcaption></figure><p>It’s a teaching example, and its own comments say what production needs: translate the model name with a mapping instead of hard-coding the fallback model. I’d add two more refinements. Carry the whole conversation, not just the last prompt. And fall back only on errors another provider can fix, such as 429s, 5xx responses and timeouts. A malformed request fails at the second provider too, and you pay twice.</p><h3>Errors are part of the contract</h3><p>Everything the gateway can’t recover from still has to fail in a way OpenAI clients understand. By default, Apigee reports policy errors in its own envelope. A prompt blocked by Model Armor comes back as a 400 with a body like this:</p><pre>{&quot;fault&quot;: {&quot;faultstring&quot;: &quot;...&quot;, &quot;detail&quot;: {&quot;errorcode&quot;: &quot;steps.sanitize.user.prompt.response.FilterMatched&quot;}}}</pre><p>An OpenAI SDK looks for <strong>error.message</strong>, <strong>error.type</strong> and <strong>error.code</strong>, and finds none of them. So the last feature in the chain should rewrite every error, whether it comes from upstream, from an Apigee policy or from the gateway itself, into OpenAI’s error envelope with a stable string code. For example:</p><ul><li><strong>invalid_api_key</strong> for a 401</li><li><strong>model_not_found</strong> for a model the gateway doesn’t know</li><li><strong>rate_limit_exceeded</strong> for a 429, with a <strong>Retry-After</strong> header</li><li><strong>content_policy_violation</strong> when Model Armor blocks a prompt, with a neutral message</li></ul><p>Then test the shape of your failures, not only their status codes. One <strong>jq</strong> check in every negative test catches most regressions:</p><pre>jq -e &#39;.error | (.message | type == &quot;string&quot;) and has(&quot;type&quot;) and has(&quot;code&quot;)&#39;</pre><h3>What I’d tell you</h3><ul><li>Keep aliases and provider routing in data, with a short cache, so model changes don’t need a redeploy.</li><li>Make the routing rules you control specific, and let the default absorb new model names.</li><li>A compatibility promise covers requests, streams and errors. Errors are the part teams forget.</li><li>Fall back on errors another provider can fix, and say so in a header.</li></ul><p>One string for the client means careful plumbing in the gateway. That’s exactly where it belongs.</p><p><strong>Next — </strong><a href="https://medium.com/@arturpacan/my-favorite-guardrail-test-is-a-polite-trap-58b8ae84a2f1"><strong>Part 3</strong></a><strong>:</strong> My favorite guardrail test is a polite trap. What it catches, what it can’t, and how masking and Model Armor fit together in Apigee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213b15578009" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009">Switching models should take one string</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop building one proxy per model]]></title>
            <link>https://medium.com/google-cloud/stop-building-one-proxy-per-model-6a05ea63a6f5?source=rss-b96b4eea63f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a05ea63a6f5</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[apigee]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[api-management]]></category>
            <dc:creator><![CDATA[Artur Pacan]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 15:15:49 GMT</pubDate>
            <atom:updated>2026-11-12T10:43:37.026Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How one OpenAI-compatible endpoint, assembled from small Apigee feature templates, gives every app and agent the same front door to every model.</em></p><blockquote>Part 1 of 6 in <em>Apigee as an AI gateway</em>: common problems teams hit when they put LLMs into production, and how to solve them with Apigee, using open-source templates as examples.</blockquote><p>Most LLM platforms I see start the same way. One team needs Gemini, so someone builds a proxy for it. A second team wants Claude and gets a second proxy, with its own key and its own limits. Then an open model arrives, and a third proxy with it.</p><p>Each proxy works. Together they make it hard to answer the questions that matter once LLMs reach production: who is calling which model, what it costs, and whether the same safety checks run everywhere. Every new model means another proxy to secure, another product to manage and another client configuration to change.</p><p>This series is about the alternative: one AI gateway on Apigee that every app and agent goes through. Each part takes a problem you’re likely to meet and solves it with Apigee features, using three open-source projects as working examples: <a href="https://github.com/tyayers/apigee-completions-template">tyayers/apigee-completions-template</a>, <a href="https://github.com/gsjurseth/apigee-yaml-configs">gsjurseth/apigee-yaml-configs</a> and <a href="https://github.com/apigee/apigee-templater">apigee-templater</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnNGVDTj-wuPSo82v54gKg.png" /><figcaption><em>Figure 1 — A proxy per model multiplies keys, limits and dashboards. One OpenAI-compatible front door gives every client the same API and every model the same policies.</em></figcaption></figure><h3>Choose the contract first</h3><p>The fix starts with a decision, not a tool. Pick one API contract for every model:</p><ul><li>one endpoint, <strong>POST /v1/chat/completions</strong>, compatible with the OpenAI Chat Completions API that most SDKs and agent frameworks already speak</li><li>one credential per app, an Apigee API key</li><li>one place for policy, where identity, token limits, safety checks, caching and cost all live</li></ul><p>Clients choose a model with the <strong>model</strong> field. Which provider serves it, and how to talk to that provider, is the gateway’s problem. <a href="https://medium.com/google-cloud/switching-models-should-take-one-string-213b15578009">Part 2</a> is about keeping that promise.</p><p>The contract is cheaper than it sounds. Gemini Enterprise Agent Platform (<a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/vertex-ai-name-changes">formerly Vertex AI</a>) has an <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/openai">OpenAI-compatible endpoint</a> for Gemini, so the gateway can forward those requests almost unchanged.</p><h3>A proxy is a list of features</h3><p>Apigee can <a href="https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/configure-proxy-with-yaml">build proxies from YAML</a>. A template lists features. Each feature is a self-contained file with its own policies, flow steps, targets and parameters, and the gcloud CLI compiles the list into a standard proxy bundle. The documentation names this use case directly: a standardized way to put an Apigee gateway in front of a model backend. Its <a href="https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/configure-proxy-with-yaml-example">step-by-step example</a> even ends with a small AI gateway for Gemini.</p><p>The best illustration I know is the progressive AI gateway in the <a href="https://github.com/gsjurseth/apigee-yaml-configs/tree/main/llm-routing">llm-routing folder of gsjurseth/apigee-yaml-configs</a>. Stage 1 is a working proxy that takes OpenAI-format requests and sends them to Gemini (trimmed, comments mine):</p><pre>gateway: apigee<br>schemaVersion: 1.0.0<br>name: aft-demo-01-hello-llm<br>features:<br>  - llm-base.yaml              # endpoint at /v1/chat/completions<br>  - llm-openai-format.yaml     # extract the model and the prompt<br>  - target-vertex-gemini.yaml  # Gemini, OpenAI-compatible endpoint</pre><p>Stage 4 is a complete gateway with Model Armor, routing across two providers, a semantic cache and fallback. The feature list grows by five lines:</p><pre>features:<br>  - llm-base.yaml<br>  - llm-openai-format.yaml<br>  - target-vertex-gemini.yaml<br>  - llm-model-armor.yaml       # stage 2: screen prompts and answers<br>  - target-openai-gpt.yaml     # stage 3: a second provider,<br>  - llm-routing.yaml           #   chosen by model prefix,<br>  - llm-semantic-cache.yaml    #   behind a semantic cache<br>  - llm-fallback.yaml          # stage 4: fail over between providers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMSqjG9NVI6J7ekZJtFZwg.png" /><figcaption><em>Figure 2 — Each stage of the example adds one to three features to the same feature list, plus the parameters those features need.</em></figcaption></figure><p><a href="https://github.com/tyayers/apigee-completions-template">tyayers/apigee-completions-template</a> uses the same format for a more production-shaped gateway. Its template has three features: one validates the request and picks a route, one defines the endpoint and the targets, and one captures token counts, cost and latency. Parts 2 and 4 look inside.</p><h3>Two rules that keep features composable</h3><p>Composition only works if features don’t step on each other. Two rules help.</p><p><strong>Features share variables, not code.</strong> In gsjurseth’s example, one feature extracts the model and the prompt into <strong>llm.model</strong> and <strong>llm.prompt</strong>, and Model Armor, routing and the cache simply read them. apigee-templater documents a common vocabulary for AI features, such as <strong>ai.model</strong>, <strong>ai.user</strong>, <strong>ai.requestPrompt</strong> and the token counts, and tyayers’ template follows it. Agree on names once, and new features plug in without extra wiring.</p><p><strong>Order is behavior.</strong> Features are applied in order when the template compiles, and a feature’s <strong>priority</strong> field can move it (<a href="https://docs.cloud.google.com/apigee/docs/api-platform/reference/api-proxy-yaml-configuration-reference">reference</a>). In stage 4, the Model Armor feature is listed before the cache, so a blocked prompt never reaches a cache lookup. Moving one line can change your security posture, so review the feature list as carefully as code. When in doubt, look at the generated proxy: the Apigee UI shows the compiled XML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pI2Gl0KalkWt9NWVxos0-A.png" /><figcaption><em>Figure 3 — The gateway this series builds: one endpoint, a chain of features, models on Agent Platform and a few supporting services.</em></figcaption></figure><h3>Shipping it</h3><p>Importing compiles the template on your machine and creates a proxy revision. It doesn’t deploy it:</p><pre>gcloud beta apigee apis import REST-AI-Completions \<br>  --from-template=REST-AI-Completions.yaml \<br>  --organization=&quot;$ORG&quot;</pre><p>One deployment detail is easy to miss. Targets that call Agent Platform authenticate with a Google access token, so the proxy must be deployed with a service account. As the documented example notes, <strong>gcloud apigee apis deploy</strong> doesn’t accept one, so use the Apigee UI or the deployments API. gsjurseth’s deploy.sh does the latter:</p><pre>curl -X POST -H &quot;Authorization: Bearer $(gcloud auth print-access-token)&quot; \<br>  &quot;https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV/apis/$API/revisions/$REV/deployments?serviceAccount=$SA_EMAIL&quot;</pre><p>A few more things are worth knowing before your first import:</p><ul><li><strong>Features are local files.</strong> gcloud only resolves features that sit in the same directory as the template. apigee-templater (aft), the open-source CLI aligned with the same YAML schema, can also pull features from a shared repository.</li><li><strong>Parameters resolve to their defaults.</strong> There’s no flag to override them at import time. A template can set defaults for its features in its own <strong>parameters</strong> block, which is how gsjurseth’s stages give each stage its own base path.</li><li><strong>AI policies need the right environment.</strong> LLMTokenQuota, PromptTokenLimit and the Model Armor and semantic cache policies are extensible policies. A Base environment rejects them, so deploy to an Intermediate or Comprehensive environment.</li></ul><h3>Where Agent Gateway fits</h3><p>If you’re building this today, you’ll also come across <a href="https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/agent-gateway-overview">Agent Gateway</a>, the network entry and exit point for agent traffic on Gemini Enterprise Agent Platform. I see it as a neighbor, not a replacement. Agent Gateway governs agent connectivity: which agent is calling, and which tools, MCP servers and other agents it may reach. The gateway in this series governs model consumption for any client, with one OpenAI-compatible API, API keys, token quotas, cost analytics, masking and caching. The two also connect. An agent on Agent Runtime can <a href="https://docs.cloud.google.com/apigee/docs/api-platform/system-administration/private-access-from-agent-runtime">reach Apigee privately</a>, and an Agent Gateway can <a href="https://docs.cloud.google.com/apigee/docs/api-platform/service-extensions/extension-processor-agent-gateway">send each request to Apigee for a verdict</a>, so Apigee policies apply to an agent’s model and tool calls without changing the agent.</p><h3>What I’d tell you</h3><ul><li>Choose the API contract first. Routing, safety and limits all get easier when every client speaks the same API.</li><li>Build the gateway from small features that share variables, and review their order like code.</li><li>Start from a working example. gsjurseth’s stages show each capability arriving on its own, and tyayers’ template shows the production details.</li></ul><p>A proxy per model feels faster on the first day. One front door is what lets you say, months later, who used which model, what it cost and which checks it passed.</p><p><strong>Next — </strong><a href="https://medium.com/@arturpacan/switching-models-should-take-one-string-213b15578009"><strong>Part 2</strong></a><strong>:</strong> Switching models should take one string. Here’s what the gateway does to keep that promise across Gemini and Claude, including when a provider fails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a05ea63a6f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/stop-building-one-proxy-per-model-6a05ea63a6f5">Stop building one proxy per model</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>