This tutorial shows you how to connect Customer Experience Agent Studio (CX Agent Studio), part of
Gemini Enterprise for Customer Experience, to private API servers hosted in an on-premises data center
without traversing the public internet.

By default, CX Agent Studio runs in a Google-managed tenant project and routes
outbound tool requests over the public internet. To reach private APIs hosted
on-premises, you bridge the Google-managed tenant project to your
Virtual Private Cloud (VPC) network using Service Directory private network access, and then route
traffic through a regional internal Application Load Balancer over Cloud VPN or
Cloud Interconnect. This tutorial is intended for platform engineers, network
architects, and agent developers who manage hybrid Google Cloud connectivity.

## Objectives

- Grant Identity and Access Management (IAM) roles to the Customer Engagement Suite service agent for Service Directory private network access.
- Configure a custom-mode VPC network with a load balancer subnet and a regional managed proxy-only subnet.
- Configure custom route advertisements on Cloud Router and set up Google Cloud and on-premises firewall rules.
- Deploy a hybrid connectivity network endpoint group (NEG) or a regional internet NEG behind a regional internal Application Load Balancer, and register the load balancer in Service Directory.
- Configure an OpenAPI tool in CX Agent Studio to call the on-premises API server and verify the connection in the simulator.

## Costs

In this tutorial, you use the following billable components of
Google Cloud:

- [CX Agent Studio](https://cloud.google.com/products/gemini-enterprise-for-customer-experience/cx-agent-studio/pricing)
- [Cloud Load Balancing](https://cloud.google.com/vpc/network-pricing#cloud-load-balancing)
- [Service Directory](https://cloud.google.com/service-directory/pricing)
- [Cloud VPN](https://cloud.google.com/network-connectivity/docs/vpn/pricing) or [Cloud Interconnect](https://cloud.google.com/network-connectivity/docs/interconnect/pricing)
- [Cloud DNS](https://cloud.google.com/dns/pricing) (required only if you use a regional internet NEG)
- [VPC](https://cloud.google.com/vpc/network-pricing#virtual-private-cloud)

To generate a cost estimate based on your projected usage, use the
[pricing calculator](https://cloud.google.com/products/calculator).

## Architecture

The following diagram shows the end-to-end private outbound networking flow from
CX Agent Studio to an on-premises API server:

![Architecture routing traffic from CX Agent Studio through Service Directory, an internal load balancer, and hybrid connectivity to an on-premises API.](https://docs.cloud.google.com/static/gemini-enterprise-cx/cx-agent-studio/images/network-outbound-on-premises.png)

The request flow operates across the following components:

1. **CX Agent Studio and OpenAPI tool**: When an agent invokes an OpenAPI tool configured with Service Directory, CX Agent Studio intercepts the outbound call instead of routing it to the public internet.
2. **Service Directory private network access**: Service Directory resolves the target service to the internal virtual IP (VIP) address of your regional internal Application Load Balancer inside your VPC network and sends traffic over a private point-to-point connection.
3. **Regional internal Application Load Balancer**: Although you can configure Service Directory per OpenAPI tool or toolset in CX Agent Studio to point directly to an on-premises endpoint, placing a regional internal Application Load Balancer behind Service Directory is recommended as a best practice. It provides a unified entry point that centralizes TLS termination, distributed Envoy health checks, and URL map host and path routing across multiple backend services.
4. **Hybrid connectivity NEG or regional internet NEG** : The load balancer's Envoy proxies (running in the regional proxy-only subnet) forward requests to your on-premises endpoints defined in either a [hybrid connectivity NEG](https://docs.cloud.google.com/load-balancing/docs/negs/hybrid-neg-concepts.md.txt) or a [regional internet NEG](https://docs.cloud.google.com/load-balancing/docs/negs/internet-neg-concepts.md.txt).
5. **Cloud Router and hybrid connectivity**: Cloud Router advertises the regional proxy-only subnet to your on-premises router over Border Gateway Protocol (BGP) and routes traffic across Cloud VPN or Cloud Interconnect to your on-premises API server.

## Choose a network endpoint group type

When configuring the regional internal Application Load Balancer to forward traffic to on-premises
API servers, you can define your backend endpoints using either a hybrid
connectivity NEG or a regional internet NEG.

Although regional internet NEGs are commonly used to reach external backends
over the internet, managed Envoy proxies in a regional internal Application Load Balancer can also
route regional internet NEG traffic over private VPC routes
learned from Cloud Router (Cloud VPN or
Cloud Interconnect) when the configured fully qualified domain name
(FQDN) resolves to a private on-premises IP address through Cloud DNS.

The following table compares hybrid connectivity NEGs and regional internet NEGs
for on-premises connectivity:

| Feature | Hybrid connectivity NEG | Regional internet NEG |
|---|---|---|
| API endpoint type | `NON_GCP_PRIVATE_IP_PORT` | `INTERNET_FQDN_PORT` or `INTERNET_IP_PORT` |
| Resource scope | Zonal (`--zone`). Must be created in a specific zone within the region. | Regional (`--region`). Operates across the entire region without a single-zone dependency. |
| Target addressing | Static private IPv4 address and port (`IP:Port`), such as `10.10.100.2:443`. | FQDN and port (`FQDN:Port`), such as `api.onprem.example.com:443`, or public `IP:Port`. |
| DNS requirement | None. Traffic routes directly to the configured IP address using BGP routes. | Requires Cloud DNS (private zone or DNS forwarding zone to on-premises DNS) to resolve private FQDNs to RFC 1918 IP addresses. |
| TLS SNI to backend | Doesn't populate the TLS `HostName` Server Name Indication (SNI) field when connecting to IP literals. | Automatically sends the configured FQDN in the TLS ClientHello SNI extension during the backend TLS handshake. |
| Health checks | Distributed Envoy health checks originating from the regional proxy-only subnet. | Distributed Envoy health checks originating from the regional proxy-only subnet. |
| Backend balancing mode | Uses `RATE` balancing mode (`--balancing-mode=RATE` and `--max-rate-per-endpoint`). | Pools resolved endpoints and distributes traffic using Envoy locality policies, such as `ROUND_ROBIN`. |

### When to use a hybrid connectivity NEG

Choose a hybrid connectivity NEG (`NON_GCP_PRIVATE_IP_PORT`) in the following
scenarios:

- **Static private IP addressing** : Your on-premises API servers or internal load balancers have fixed RFC 1918 IP addresses, and you want to route directly to `IP:Port` combinations without maintaining Cloud DNS private zones or DNS forwarding rules.
- **Rate-based load balancing across multiple IPs** : You want to configure explicit request-rate targets (`--max-rate-per-endpoint`) across multiple on-premises server IP addresses, or mix Google Cloud zonal NEGs (`GCE_VM_IP_PORT`) and on-premises endpoints in the same backend service during cloud migrations.
- **No backend SNI requirement**: Your on-premises backend server doesn't require a hostname in the TLS SNI extension during the backend handshake.

### When to use a regional internet NEG

Choose a regional internet NEG (`INTERNET_FQDN_PORT`) in the following
scenarios:

- **Regional high availability without zonal dependency** : Because hybrid connectivity NEGs are zonal resources, Google Cloud recommends using a regional internet NEG with `INTERNET_FQDN_PORT` and a private Cloud DNS zone when you want to avoid a single zonal configuration dependency.
- **Dynamic DNS resolution**: Your on-premises API sits behind an on-premises load balancer, Kubernetes ingress controller, or API gateway whose IP addresses change dynamically in DNS. Envoy periodically re-resolves the FQDN based on the DNS time to live (TTL).
- **Backend TLS SNI requirement**: Your on-premises HTTPS server or API gateway hosts multiple virtual domains on the same IP address and requires the load balancer to send the target hostname in the TLS SNI extension during the backend handshake.
- **Private access to Google APIs (`*.googleapis.com`) under
  VPC Service Controls** : When VPC Service Controls blocks direct public egress from CX Agent Studio, a regional internet NEG (`INTERNET_FQDN_PORT`) can also route tool calls to Google APIs through your VPC network. The Envoy proxies resolve the FQDN by using your VPC network's Cloud DNS configuration and send it in the TLS SNI extension and `Host` header. Because proxy-only subnets don't support Private Google Access, choose one of the following egress paths:
  - **Private Service Connect endpoint for Google APIs** : Create a Private Service Connect endpoint with the `vpc-sc` API bundle (an internal VPC IP address that is equivalent to `restricted.googleapis.com`) and a private Cloud DNS zone that resolves `*.googleapis.com` to that address. Traffic to the endpoint stays inside your VPC network, so you don't need a route to the default internet gateway.
  - **Private Google Access VIPs with Cloud NAT** : Resolve `*.googleapis.com` to `restricted.googleapis.com` (`199.36.153.4/30`) or `private.googleapis.com` (`199.36.153.8/30`), add a route for that range to the default internet gateway, and configure a Cloud NAT gateway for the proxy-only subnet (endpoint type `ENDPOINT_TYPE_MANAGED_PROXY_LB`).
  - **For both paths** : Don't attach a health check to the backend service because an unauthenticated probe to `GET /` on `*.googleapis.com` returns a `4xx` response and marks the endpoint unhealthy. Keep the VPC network project, the CX Agent Studio project, and the target Google API resources in the same service perimeter, and configure authentication on the OpenAPI tool.

## Before you begin

Verify that you have the following prerequisites in place:

- **Hybrid connectivity to on-premises** : An active HA VPN tunnel or Cloud Interconnect VLAN attachment connecting your Google Cloud project to your on-premises network in your target region (for example, `us-central1`), managed by a Cloud Router.
- **On-premises API server** : An HTTP or HTTPS API server running on-premises (for example, `10.10.100.2` listening on port `443`) that is reachable from your on-premises router. If you don't have an API server ready for testing, see [Deploy a sample on-premises API server
  (optional)](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises#deploy-sample-on-premises-server).
- **Command-line tools** : Cloud Shell or a local terminal with the Google Cloud CLI and `openssl` installed.

### Required roles


To get the permissions that
you need to complete this tutorial,

ask your administrator to grant you the
following IAM roles on your project:

- [Compute Network Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/compute.md.txt#compute.networkAdmin) (`roles/compute.networkAdmin`)
- [Compute Load Balancer Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/compute.md.txt#compute.loadBalancerAdmin) (`roles/compute.loadBalancerAdmin`)
- [Compute Security Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/compute.md.txt#compute.securityAdmin) (`roles/compute.securityAdmin`)
- [Service Directory Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/servicedirectory.md.txt#servicedirectory.editor) (`roles/servicedirectory.editor`)
- [Service Directory Network Attacher](https://docs.cloud.google.com/iam/docs/roles-permissions/servicedirectory.md.txt#servicedirectory.networkAttacher) (`roles/servicedirectory.networkAttacher`)
- [Project IAM Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/resourcemanager.md.txt#resourcemanager.projectIamAdmin) (`roles/resourcemanager.projectIamAdmin`)
- [Service Usage Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageAdmin) (`roles/serviceusage.serviceUsageAdmin`)
- [Gemini Enterprise for Customer Experience Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/ces.md.txt#ces.admin) (`roles/ces.admin`)
- Configure Cloud DNS for a regional internet NEG: [DNS Administrator](https://docs.cloud.google.com/iam/docs/roles-permissions/dns.md.txt#dns.admin) (`roles/dns.admin`)


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

> [!NOTE]
> **Note:** If you use a Shared VPC network, grant the Service Directory Network Attacher (`roles/servicedirectory.networkAttacher`) role on the Shared VPC host project.

## Prepare the environment

1. In the Google Cloud console, activate Cloud Shell or open a local
   terminal with the gcloud CLI installed.

2. Set the environment variables for your deployment:

   ```bash
   export PROJECT_ID="PROJECT_ID"
   export REGION="us-central1"
   export ZONE="us-central1-a"

   # Networking and Cloud Router variables
   export NETWORK_NAME="gecx-hybrid-vpc"
   export LB_SUBNET_NAME="gecx-lb-subnet"
   export LB_SUBNET_RANGE="10.0.1.0/24"
   export PROXY_ONLY_SUBNET_NAME="gecx-proxy-only-subnet"
   export PROXY_ONLY_SUBNET_RANGE="10.0.2.0/24"
   export ROUTER_NAME="CLOUD_ROUTER_NAME"

   # On-premises target variables
   export ON_PREM_CIDR="10.10.100.0/24"
   export ON_PREM_API_IP="10.10.100.2"
   export ON_PREM_API_PORT="443"
   export FQDN="api.onprem.example.com"

   # Load balancer and Service Directory variables
   export HYBRID_NEG_NAME="onprem-hybrid-neg"
   export INTERNET_NEG_NAME="onprem-regional-internet-neg"
   export HEALTH_CHECK_NAME="onprem-api-hc"
   export BACKEND_SERVICE_NAME="onprem-api-backend"
   export URL_MAP_NAME="onprem-api-url-map"
   export CERTIFICATE_NAME="onprem-api-cert"
   export TARGET_PROXY_NAME="onprem-api-https-proxy"
   export ADDRESS_NAME="onprem-alb-vip"
   export FORWARDING_RULE_NAME="onprem-alb-forwarding-rule"
   export NAMESPACE_NAME="gecx-onprem-ns"
   export SERVICE_NAME="onprem-api-service"
   export ENDPOINT_NAME="onprem-alb-endpoint"
   ```

   Replace the following:
   - `PROJECT_ID`: your Google Cloud project ID
   - `CLOUD_ROUTER_NAME`: the name of the Cloud Router in `REGION` that manages your Cloud VPN tunnel or Cloud Interconnect attachment
3. Configure the gcloud CLI to use your project and retrieve your
   project number:

   ```bash
   gcloud config set project "${PROJECT_ID}"
   export PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" \
       --format="value(projectNumber)")
   ```
4. Enable the required Google Cloud APIs:

   ```bash
   gcloud services enable \
       compute.googleapis.com \
       servicedirectory.googleapis.com \
       ces.googleapis.com \
       dialogflow.googleapis.com \
       dns.googleapis.com \
       --project="${PROJECT_ID}"
   ```

## Deploy a sample on-premises API server (optional)

If you already have an on-premises API server to test with, skip to
[Grant IAM roles to the Customer Engagement Suite service
agent](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises#grant-service-agent-roles).

This section deploys a sample Python FastAPI Order Status API server on your
on-premises Linux host (for example, `10.10.100.2:443`). The server listens over
HTTPS on port `443` and exposes two endpoints:

- `GET /`: Responds with HTTP `200 OK` (`{"status": "healthy"}`) to satisfy the regional internal Application Load Balancer's Envoy health check probes.
- `GET /order/{order_number}`: Returns an order fulfillment status (`pending`, `processing`, `shipped`, `delivered`, or `cancelled`) matching the `OrderStatus` OpenAPI 3.0 schema configured later in CX Agent Studio.

### Generate a TLS certificate for port 443

On your on-premises Linux host (`10.10.100.2`), create a directory for the
service and generate a self-signed TLS certificate:

```bash
mkdir -p ~/order-status-api && cd ~/order-status-api

openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout onprem.key \
    -out onprem.crt \
    -subj "/CN=api.onprem.example.com" \
    -addext "subjectAltName=DNS:api.onprem.example.com,IP:10.10.100.2"
```

> [!NOTE]
> **Note:** When the regional internal Application Load Balancer connects to an HTTPS backend (`--protocol=HTTPS`), its managed Envoy proxies encrypt traffic to the backend without validating the backend server's TLS certificate chain. A self-signed certificate on the on-premises server is sufficient for backend encryption.

### Create the FastAPI application

Create a `main.py` file inside `~/order-status-api`:

```python
from typing import Literal
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(
    title="On-Premises Order Status API",
    description="Retrieves order fulfillment status from the on-premises API server.",
    version="1.0.0",
)


class OrderStatus(BaseModel):
    order_number: str
    status: Literal["pending", "processing", "shipped", "delivered", "cancelled"]


# Sample in-memory order database
SAMPLE_ORDERS: dict[
    str, Literal["pending", "processing", "shipped", "delivered", "cancelled"]
] = {
    "10042": "shipped",
    "10043": "processing",
    "10044": "delivered",
    "10045": "pending",
    "10046": "cancelled",
}


@app.get("/")
def health_check() -> dict[str, str]:
    """Health check endpoint for Google Cloud Envoy load balancer probes."""
    return {"status": "healthy"}


@app.get(
    "/order/{order_number}",
    response_model=OrderStatus,
    operation_id="getOrderStatus",
)
def get_order_status(order_number: str) -> OrderStatus:
    """Returns the current fulfillment status for a specific order number."""
    order_state = SAMPLE_ORDERS.get(order_number, "processing")
    return OrderStatus(order_number=order_number, status=order_state)
```

### Start the HTTPS server

Start the server using either Python and Uvicorn or Docker:

#### Option A: Run with Python and Uvicorn

1. Create a Python virtual environment and install `fastapi` and `uvicorn`:

   ```bash
   python3 -m venv venv
   ./venv/bin/pip install --upgrade pip fastapi uvicorn
   ```
2. Start `uvicorn` listening on `0.0.0.0:443` with TLS enabled:

   ```bash
   sudo ./venv/bin/uvicorn main:app \
       --host 0.0.0.0 \
       --port 443 \
       --ssl-keyfile onprem.key \
       --ssl-certfile onprem.crt
   ```
3. Optional: To run the service persistently in the background using `systemd`,
   create `/etc/systemd/system/order-status-api.service` and start the service:

   ```bash
   sudo tee /etc/systemd/system/order-status-api.service > /dev/null <<EOF
   [Unit]
   Description=On-Premises Order Status FastAPI Server
   After=network.target

   [Service]
   WorkingDirectory=${HOME}/order-status-api
   ExecStart=${HOME}/order-status-api/venv/bin/uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile onprem.key --ssl-certfile onprem.crt
   Restart=always
   RestartSec=3

   [Install]
   WantedBy=multi-user.target
   EOF

   sudo systemctl daemon-reload
   sudo systemctl enable --now order-status-api
   ```

#### Option B: Run as a Docker container

1. Create a `Dockerfile` inside `~/order-status-api`:

   ```bash
   cat << 'EOF' > Dockerfile
   FROM python:3.11-slim
   WORKDIR /app
   RUN pip install --no-cache-dir fastapi uvicorn
   COPY main.py onprem.key onprem.crt ./
   EXPOSE 443
   CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "443", "--ssl-keyfile", "onprem.key", "--ssl-certfile", "onprem.crt"]
   EOF
   ```
2. Build and start the container on port `443`:

   ```bash
   docker build -t order-status-api .
   docker run -d --name order-status-api --restart unless-stopped -p 443:443 order-status-api
   ```

### Verify the server locally

From your on-premises host, verify that the health check endpoint (`/`), the
order lookup endpoint (`/order/10042`), and the OpenAPI schema endpoint
(`/openapi.json`) respond over HTTPS:

1. Test the Envoy health check endpoint:

   ```bash
   curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/
   ```

   The output is `{"status":"healthy"}`.
2. Test the OpenAPI tool endpoint:

   ```bash
   curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/order/10042
   ```

   The output is `{"order_number":"10042","status":"shipped"}`.
3. Verify the auto-generated OpenAPI 3.0 schema:

   ```bash
   curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/openapi.json
   ```

## Grant IAM roles to the Customer Engagement Suite service agent

CX Agent Studio uses the Customer Engagement Suite
[service agent](https://docs.cloud.google.com/iam/docs/service-agents.md.txt) to resolve Service Directory services
and send traffic into your VPC network over private network access.

1. Make sure that the Customer Engagement Suite service agent exists in your
   project:

   ```bash
   gcloud beta services identity create \
       --service=ces.googleapis.com \
       --project="${PROJECT_ID}"
   ```

   The command returns a service account in the format
   `service-PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com`.
2. Grant the Service Directory Viewer (`roles/servicedirectory.viewer`) and
   Private Service Connect Authorized Service
   (`roles/servicedirectory.pscAuthorizedService`) roles to the service agent:

   ```bash
   for ROLE in \
       roles/servicedirectory.viewer \
       roles/servicedirectory.pscAuthorizedService; do
     gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
         --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com" \
         --role="${ROLE}"
   done
   ```

## Configure the VPC network and subnets

A regional internal Application Load Balancer requires two subnets in the same region as your
Cloud VPN tunnel or Cloud Interconnect attachment:

- A standard load balancer subnet to host the load balancer's internal forwarding rule VIP address.
- A regional managed proxy-only subnet (`REGIONAL_MANAGED_PROXY`) where Google Cloud allocates IP addresses for the Envoy proxies that terminate client connections and initiate backend connections to your on-premises server.

> [!IMPORTANT]
> **Important:** Hybrid load balancing requires your VPC network's dynamic routing mode to be set to `GLOBAL` so that Cloud Router can program learned on-premises routes for the load balancer. Verify that your VPC subnet CIDR ranges don't overlap with your on-premises CIDR ranges.

1. If you are creating a new custom-mode VPC network, run the
   following command:

   ```bash
   gcloud compute networks create "${NETWORK_NAME}" \
       --subnet-mode=custom \
       --bgp-routing-mode=global \
       --project="${PROJECT_ID}"
   ```

   If you are using an existing VPC network that already has
   Cloud VPN or Cloud Interconnect attached, update its
   dynamic routing mode to `GLOBAL` instead:

   ```bash
   gcloud compute networks update "${NETWORK_NAME}" \
       --bgp-routing-mode=global \
       --project="${PROJECT_ID}"
   ```
2. Create the load balancer subnet in your target region:

   ```bash
   gcloud compute networks subnets create "${LB_SUBNET_NAME}" \
       --network="${NETWORK_NAME}" \
       --region="${REGION}" \
       --range="${LB_SUBNET_RANGE}" \
       --project="${PROJECT_ID}"
   ```
3. Create the regional managed proxy-only subnet in the same region:

   ```bash
   gcloud compute networks subnets create "${PROXY_ONLY_SUBNET_NAME}" \
       --purpose=REGIONAL_MANAGED_PROXY \
       --role=ACTIVE \
       --network="${NETWORK_NAME}" \
       --region="${REGION}" \
       --range="${PROXY_ONLY_SUBNET_RANGE}" \
       --project="${PROJECT_ID}"
   ```

## Configure custom route advertisements on Cloud Router

When the regional internal Application Load Balancer forwards tool requests or sends distributed
Envoy health check probes to your on-premises API server, the packets originate
from IP addresses in the regional proxy-only subnet (`PROXY_ONLY_SUBNET_RANGE`).

By default, Cloud Router advertises only standard VPC
subnets (`ALL_SUBNETS`) and doesn't advertise `REGIONAL_MANAGED_PROXY` subnets.
You must configure
[custom route advertisements](https://docs.cloud.google.com/network-connectivity/docs/router/how-to/advertising-custom-ip.md.txt)
on your Cloud Router so that your on-premises router learns the route
back to the proxy-only subnet.

1. Update your Cloud Router to advertise all visible
   VPC subnets along with the custom IP range of your regional
   proxy-only subnet:

   ```bash
   gcloud compute routers update "${ROUTER_NAME}" \
       --region="${REGION}" \
       --advertisement-mode=CUSTOM \
       --set-advertisement-groups=ALL_SUBNETS \
       --set-advertisement-ranges="${PROXY_ONLY_SUBNET_RANGE}" \
       --project="${PROJECT_ID}"
   ```

   > [!NOTE]
   > **Note:** If you plan to use a regional internet NEG with Cloud DNS forwarding to an on-premises DNS server, also include the Cloud DNS egress range (`35.199.192.0/19`) in `--set-advertisement-ranges`: `--set-advertisement-ranges="${PROXY_ONLY_SUBNET_RANGE},35.199.192.0/19"`.

2. Verify that Cloud Router is advertising the proxy-only subnet
   range:

   ```bash
   gcloud compute routers describe "${ROUTER_NAME}" \
       --region="${REGION}" \
       --format="yaml(bgp)" \
       --project="${PROJECT_ID}"
   ```

## Configure firewall policies and on-premises firewall rules

To let traffic flow between the regional internal Application Load Balancer and your on-premises API
server, configure both your Google Cloud VPC network
firewall policy and your on-premises network firewall.

### Configure the Google Cloud VPC network firewall policy

Service Directory private network access sends traffic from `35.199.192.0/19` directly to
the forwarding rule VIP of the regional internal Application Load Balancer, which accepts traffic on
its configured port automatically without requiring a VPC
ingress firewall rule. Because Google Cloud VPC firewall
rules are stateful and distributed Envoy health check probes originate from the
regional proxy-only subnet (`PROXY_ONLY_SUBNET_RANGE`) toward your on-premises
network, you only need an egress allow rule in your VPC network
firewall policy:

1. Create a global network firewall policy and associate it with your
   VPC network:

   ```bash
   gcloud compute network-firewall-policies create gecx-onprem-fw-policy \
       --global \
       --project="${PROJECT_ID}"

   gcloud compute network-firewall-policies associations create \
       --firewall-policy=gecx-onprem-fw-policy \
       --name="network-${NETWORK_NAME}" \
       --network="${NETWORK_NAME}" \
       --global-firewall-policy \
       --project="${PROJECT_ID}"
   ```
2. Add an egress allow rule permitting outbound requests and distributed Envoy
   health check probes from the VPC network (including the
   proxy-only subnet) to your on-premises API subnet:

   ```bash
   gcloud compute network-firewall-policies rules create 1000 \
       --firewall-policy=gecx-onprem-fw-policy \
       --global-firewall-policy \
       --direction=EGRESS \
       --action=allow \
       --dest-ip-ranges="${ON_PREM_CIDR}" \
       --layer4-configs="tcp:${ON_PREM_API_PORT}" \
       --description="Allow egress from Envoy proxies to on-premises API servers" \
       --project="${PROJECT_ID}"
   ```

### Configure on-premises firewall rules

Work with your on-premises network administrator to confirm that your
on-premises firewall permits the following inbound traffic to your on-premises
API server (`ON_PREM_API_IP` on port `ON_PREM_API_PORT`) and DNS infrastructure:

- **Source IP range** : `PROXY_ONLY_SUBNET_RANGE` (for example, `10.0.2.0/24`). Both load-balanced API requests and distributed Envoy health check probes originate from this range.
- **Centralized health check ranges (optional)** : `35.191.0.0/16` and `130.211.0.0/22`, if any centralized Google Cloud health checks are used.
- **Cloud DNS outbound forwarding range (if using a Cloud DNS
  forwarding zone in Option B)** : Permit inbound UDP and TCP port `53` from `35.199.192.0/19` to your on-premises DNS servers so that Cloud DNS can forward queries for your on-premises domain.
- **Service Directory private network access range (if routing directly without an
  internal Application Load Balancer)** : If you register an on-premises IP address directly as a Service Directory endpoint instead of routing through a regional internal Application Load Balancer, permit inbound TCP traffic on `ON_PREM_API_PORT` from `35.199.192.0/19` and advertise `35.199.192.0/19` using Cloud Router custom route advertisements.

## Create the network endpoint group

Complete either Option A (hybrid connectivity NEG) or Option B (regional
internet NEG) based on the architectural requirements in
[Choose a network endpoint group type](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises.md.txt#choose-neg-type).

### Option A: Create a hybrid connectivity NEG

Use this option when routing directly to static on-premises private IP addresses
(`NON_GCP_PRIVATE_IP_PORT`).

1. Create the hybrid connectivity NEG in a zone within the same region as your
   Cloud VPN tunnel or Cloud Interconnect attachment:

   ```bash
   gcloud compute network-endpoint-groups create "${HYBRID_NEG_NAME}" \
       --network-endpoint-type=NON_GCP_PRIVATE_IP_PORT \
       --zone="${ZONE}" \
       --network="${NETWORK_NAME}" \
       --project="${PROJECT_ID}"
   ```
2. Add your on-premises API server's private IP address and port to the hybrid
   connectivity NEG:

   ```bash
   gcloud compute network-endpoint-groups update "${HYBRID_NEG_NAME}" \
       --zone="${ZONE}" \
       --add-endpoint="ip=${ON_PREM_API_IP},port=${ON_PREM_API_PORT}" \
       --project="${PROJECT_ID}"
   ```

### Option B: Create a regional internet NEG

Use this option when you require regional NEG availability without a single-zone
dependency, dynamic DNS resolution, or TLS SNI sent to your on-premises backend
(`INTERNET_FQDN_PORT`).

1. Create the regional internet NEG in your target region:

   ```bash
   gcloud compute network-endpoint-groups create "${INTERNET_NEG_NAME}" \
       --network-endpoint-type=INTERNET_FQDN_PORT \
       --default-port="${ON_PREM_API_PORT}" \
       --network="${NETWORK_NAME}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}"
   ```
2. Add the FQDN and port of your on-premises API server to the regional
   internet NEG:

   ```bash
   gcloud compute network-endpoint-groups update "${INTERNET_NEG_NAME}" \
       --region="${REGION}" \
       --add-endpoint="fqdn=${FQDN},port=${ON_PREM_API_PORT}" \
       --project="${PROJECT_ID}"
   ```
3. Configure a [Cloud DNS private zone](https://docs.cloud.google.com/dns/docs/zones.md.txt) associated
   with your VPC network so that the Envoy proxies can resolve
   `FQDN` (`api.onprem.example.com`) to your on-premises private IP address
   (`10.10.100.2`):

   ```bash
   # Create a private Cloud DNS zone visible to your VPC network
   gcloud dns managed-zones create onprem-private-zone \
       --dns-name="onprem.example.com." \
       --description="Private zone for on-premises API endpoints" \
       --visibility=private \
       --networks="${NETWORK_NAME}" \
       --project="${PROJECT_ID}"

   # Add an A record mapping the FQDN to the on-premises API server IP
   gcloud dns record-sets create "${FQDN}." \
       --zone=onprem-private-zone \
       --type=A \
       --ttl=60 \
       --rrdatas="${ON_PREM_API_IP}" \
       --project="${PROJECT_ID}"
   ```

   > [!TIP]
   > **Tip:** If your on-premises environment already runs an internal DNS server that resolves `onprem.example.com`, you can configure a Cloud DNS forwarding zone (`--forwarding-targets=ON_PREM_DNS_IP`, where `ON_PREM_DNS_IP` is the IP address of your on-premises DNS server) instead of creating static `A` records.

## Configure the regional internal Application Load Balancer

Provision the regional internal Application Load Balancer (`INTERNAL_MANAGED`) that sits in front of
your NEG and exposes an internal HTTPS endpoint to Service Directory.

### Create the health check and backend service

1. Create a regional HTTPS health check (use `http` if your on-premises API
   server listens over unencrypted HTTP):

   ```bash
   gcloud compute health-checks create https "${HEALTH_CHECK_NAME}" \
       --region="${REGION}" \
       --use-serving-port \
       --enable-logging \
       --project="${PROJECT_ID}"
   ```
2. Create the regional internal managed backend service:

   ```bash
   gcloud compute backend-services create "${BACKEND_SERVICE_NAME}" \
       --load-balancing-scheme=INTERNAL_MANAGED \
       --protocol=HTTPS \
       --health-checks="${HEALTH_CHECK_NAME}" \
       --health-checks-region="${REGION}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}"
   ```
3. Attach your NEG to the backend service depending on which option you chose
   in [Create the network endpoint group](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises.md.txt#create-neg):

   - If you created a hybrid connectivity NEG (Option A):

     ```bash
     gcloud compute backend-services add-backend "${BACKEND_SERVICE_NAME}" \
         --region="${REGION}" \
         --balancing-mode=RATE \
         --max-rate-per-endpoint=100 \
         --network-endpoint-group="${HYBRID_NEG_NAME}" \
         --network-endpoint-group-zone="${ZONE}" \
         --project="${PROJECT_ID}"
     ```
   - If you created a regional internet NEG (Option B):

     ```bash
     gcloud compute backend-services add-backend "${BACKEND_SERVICE_NAME}" \
         --region="${REGION}" \
         --network-endpoint-group="${INTERNET_NEG_NAME}" \
         --network-endpoint-group-region="${REGION}" \
         --project="${PROJECT_ID}"
     ```

### Create the URL map, TLS certificate, and target HTTPS proxy

CX Agent Studio OpenAPI tools require HTTPS when communicating with a custom TLS
certificate over Service Directory.

1. Create a regional URL map that routes incoming requests to your backend
   service:

   ```bash
   gcloud compute url-maps create "${URL_MAP_NAME}" \
       --default-service="${BACKEND_SERVICE_NAME}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}"
   ```
2. Generate a private key and self-signed TLS certificate for `FQDN`
   (`api.onprem.example.com`), and convert the certificate to DER format
   (`server.der`) so that you can upload it to CX Agent Studio:

   ```bash
   openssl genrsa -out server.key 2048

   openssl req -nodes -new -sha256 \
       -key server.key \
       -subj "/CN=${FQDN}" \
       -out server.csr

   openssl x509 -req -days 3650 -sha256 \
       -in server.csr \
       -signkey server.key \
       -out server.crt \
       -extfile <(printf "subjectAltName=DNS:%s\n" "${FQDN}")

   openssl x509 -in server.crt -out server.der -outform DER
   ```

   > [!NOTE]
   > **Note:** In a production environment, use a certificate issued by your organization's Certificate Authority (CA) or Certificate Authority Service, and convert the root or intermediate CA certificate to DER format for CX Agent Studio.

3. Create a regional
   [self-managed SSL certificate](https://docs.cloud.google.com/load-balancing/docs/ssl-certificates/self-managed-certs.md.txt)
   resource in Google Cloud:

   ```bash
   gcloud compute ssl-certificates create "${CERTIFICATE_NAME}" \
       --certificate=server.crt \
       --private-key=server.key \
       --region="${REGION}" \
       --project="${PROJECT_ID}"
   ```
4. Create the regional target HTTPS proxy and attach the SSL certificate and
   URL map:

   ```bash
   gcloud compute target-https-proxies create "${TARGET_PROXY_NAME}" \
       --ssl-certificates="${CERTIFICATE_NAME}" \
       --url-map="${URL_MAP_NAME}" \
       --url-map-region="${REGION}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}"
   ```

### Reserve an internal IP address and create the forwarding rule

1. Reserve a static internal IPv4 address from your load balancer subnet
   (`LB_SUBNET_NAME`):

   ```bash
   gcloud compute addresses create "${ADDRESS_NAME}" \
       --region="${REGION}" \
       --subnet="${LB_SUBNET_NAME}" \
       --project="${PROJECT_ID}"
   ```
2. Store the allocated internal IP address in an environment variable:

   ```bash
   export LB_VIP=$(gcloud compute addresses describe "${ADDRESS_NAME}" \
       --region="${REGION}" \
       --format="value(address)" \
       --project="${PROJECT_ID}")
   echo "Load Balancer Internal VIP: ${LB_VIP}"
   ```
3. Create the regional forwarding rule on port `443`:

   ```bash
   gcloud compute forwarding-rules create "${FORWARDING_RULE_NAME}" \
       --load-balancing-scheme=INTERNAL_MANAGED \
       --network="${NETWORK_NAME}" \
       --subnet="${LB_SUBNET_NAME}" \
       --address="${ADDRESS_NAME}" \
       --ports=443 \
       --region="${REGION}" \
       --target-https-proxy="${TARGET_PROXY_NAME}" \
       --target-https-proxy-region="${REGION}" \
       --allow-global-access \
       --project="${PROJECT_ID}"
   ```

## Register the internal load balancer in Service Directory

Register the regional internal Application Load Balancer's VIP (`LB_VIP`) in Service Directory so
that CX Agent Studio can discover and route to it over private network access.

1. Create a Service Directory namespace in the same region as your load
   balancer:

   ```bash
   gcloud service-directory namespaces create "${NAMESPACE_NAME}" \
       --location="${REGION}" \
       --project="${PROJECT_ID}"
   ```
2. Create a Service Directory service inside the namespace:

   ```bash
   gcloud service-directory services create "${SERVICE_NAME}" \
       --namespace="${NAMESPACE_NAME}" \
       --location="${REGION}" \
       --project="${PROJECT_ID}"
   ```
3. Create a Service Directory endpoint pointing to your load balancer's
   internal IP address (`LB_VIP`) and associated with your VPC
   network:

   ```bash
   gcloud service-directory endpoints create "${ENDPOINT_NAME}" \
       --location="${REGION}" \
       --namespace="${NAMESPACE_NAME}" \
       --service="${SERVICE_NAME}" \
       --address="${LB_VIP}" \
       --port=443 \
       --network="projects/${PROJECT_NUMBER}/locations/global/networks/${NETWORK_NAME}" \
       --project="${PROJECT_ID}"
   ```

   > [!IMPORTANT]
   > **Important:** In the `--network` flag for Service Directory endpoints, you must specify the project number (`PROJECT_NUMBER`) rather than the project ID, and use the format `projects/PROJECT_NUMBER/locations/global/networks/NETWORK_NAME`.

   > [!NOTE]
   > **Note:** Keep the following Service Directory behaviors in
   > mind when configuring endpoints for CX Agent Studio:
   > - **Shared VPC network path** : In a Shared VPC architecture, specify the Shared VPC host project number in `--network` (`projects/HOST_PROJECT_NUMBER/locations/global/networks/NETWORK_NAME`).
   > - **Endpoint `--port` is ignored at runtime** : Although `--port` is required when creating a Service Directory endpoint, CX Agent Studio ignores the endpoint's `--port` value and instead connects to the port derived from the `servers.url` field in your OpenAPI specification (`443` for `https://`, `80` for `http://`, or an explicit `:PORT` in the URL).
   > - **Single endpoint selection**: If you create multiple endpoints inside a single Service Directory service, CX Agent Studio routes only to the first endpoint. Use the regional internal Application Load Balancer to distribute traffic across multiple backend instances.
   > - **Runtime resolution caching**: CX Agent Studio caches Service Directory endpoint lookups at runtime. If you modify an existing endpoint's IP address in place, the update can take several minutes to take effect. Creating a new Service Directory service and endpoint avoids stale cache delays during testing.

4. Print the fully qualified Service Directory service path to use in the next
   section:

   ```bash
   echo "projects/${PROJECT_ID}/locations/${REGION}/namespaces/${NAMESPACE_NAME}/services/${SERVICE_NAME}"
   ```

## Configure CX Agent Studio and the OpenAPI tool

With the Google Cloud networking infrastructure and Service Directory
endpoint in place, configure your CX Agent Studio agent and
[OpenAPI tool](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/tool/open-api.md.txt).

### Create an agent

1. Open the [CX Agent Studio console](https://ces.cloud.google.com/).
2. Select your Google Cloud project (`PROJECT_ID`).
3. Click **Create agent** , enter `Order_Status_Agent` as the agent name, and click **Create**.

### Create the OpenAPI tool

1. In the agent builder navigation bar, click **Tools** , and then click **+ (Create)** to add a tool.
2. Select **OpenAPI** as the tool type.
3. In the **Name** field, enter `order_status_api`.
4. In the **Schema (YAML)** editor, paste the following OpenAPI 3.0
   specification, replacing `api.onprem.example.com` with your `FQDN` value if
   you used a different domain in your TLS certificate:

   ```yaml
   openapi: 3.0.0
   info:
     title: On-Premises Order Status API
     description: Retrieves order fulfillment status from the on-premises API server.
     version: 1.0.0
   servers:
     - url: https://api.onprem.example.com
       description: On-premises production API server through regional internal ALB
   paths:
     /order/{order_number}:
       get:
         summary: Get Order Status
         description: Returns the current fulfillment status for a specific order number.
         operationId: getOrderStatus
         parameters:
           - name: order_number
             in: path
             required: true
             description: The unique identifier for the order.
             schema:
               type: string
         responses:
           '200':
             description: Successful response
             content:
               application/json:
                 schema:
                   type: object
                   properties:
                     order_number:
                       type: string
                     status:
                       type: string
                       enum:
                         - pending
                         - processing
                         - shipped
                         - delivered
                         - cancelled
   ```
5. Expand the **Advanced** settings section and configure the private
   networking fields:

   1. **Custom TLS certificate authorities** : Upload the `server.der` file that you generated in [Create the URL map, TLS certificate, and target HTTPS
      proxy](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises#create-url-map-and-proxy).
   2. **Service Directory** : Enter the fully qualified Service Directory
      service path from
      [Register the internal load balancer in
      Service Directory](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises#register-service-directory):

          projects/PROJECT_ID/locations/REGION/namespaces/NAMESPACE_NAME/services/SERVICE_NAME

      Replace the following:
      - `PROJECT_ID`: your Google Cloud project ID
      - `REGION`: the region of your Service Directory namespace (for example, `us-central1`)
      - `NAMESPACE_NAME`: your Service Directory namespace name (for example, `gecx-onprem-ns`)
      - `SERVICE_NAME`: your Service Directory service name (for example, `onprem-api-service`)
6. Click **Create**.

### Attach the tool and configure instructions

1. Open the root agent in the agent builder.
2. In the **Tools** section of the agent, click **+ Add tool** and select `order_status_api`.
3. In the **Instructions** section of the root agent, enter the following
   [instructions](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/instruction.md.txt) to invoke
   the OpenAPI tool when a user asks for an order status:

   ```xml
   <role>An order support agent that retrieves real-time order statuses from an on-premises system.</role>
   <persona>
     <primary_goal>Ask the user for their order number, invoke the on-premises Order Status tool, and return the status clearly.</primary_goal>
   </persona>
   <taskflow>
     <subtask name="Check Order Status">
       <step name="Prompt for Order Number">
         <trigger>User asks to check an order status without providing an order number</trigger>
         <action>Politely ask the user to provide their order number.</action>
       </step>
       <step name="Run On-Premises Lookup">
         <trigger>User provides an order number</trigger>
         <action>
           Immediately call {@TOOL: order_status_api_getOrderStatus} with the provided `order_number`.
           Return the `order_number` and `status` fields from the JSON payload to the user.
         </action>
       </step>
     </subtask>
   </taskflow>
   ```
4. Click **Save**.

## Test the agent in the simulator

Verify the end-to-end private connection using the built-in
[simulator](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/simulator.md.txt) in CX Agent Studio:

1. In the CX Agent Studio console, click **Preview agent** to open the simulator pane.
2. Enter `Check my order status` and press `Enter`.
3. When prompted for an order number, enter a valid test order ID (for example, `10042`) and press `Enter`.
4. Confirm that the agent invokes `order_status_api_getOrderStatus`, traverses Service Directory and the regional internal Application Load Balancer over your hybrid connection, and returns the JSON status from your on-premises API server.

## Troubleshoot and scale

If your OpenAPI tool calls fail to reach the on-premises server, or if you plan
to scale this deployment for production, use the following guidance:

- **Check Envoy backend health status** : Because hybrid connectivity NEGs
  (`NON_GCP_PRIVATE_IP_PORT`) and regional internet NEGs (`INTERNET_FQDN_PORT`)
  are health checked directly by distributed Envoy proxies in your proxy-only
  subnet rather than centralized Google Cloud probers, the
  `gcloud compute backend-services get-health` command isn't supported for these
  backend types. Instead, verify backend health by enabling health check logging
  (`--enable-logging`) on your health check and querying Cloud Logging with
  the following filter:

      resource.type="gce_network_endpoint_group"
      log_id("compute.googleapis.com/healthchecks")
      jsonPayload.healthCheckProbeResult.healthState!=""

  If the logged `healthState` is `UNHEALTHY` or `TIMEOUT`, confirm that
  Cloud Router is advertising `PROXY_ONLY_SUBNET_RANGE` over BGP and
  that your on-premises firewall permits inbound TCP traffic from
  `PROXY_ONLY_SUBNET_RANGE` to `ON_PREM_API_IP:ON_PREM_API_PORT`.
- **Monitor Service Directory resolution with Data Access audit logs
  (`DATA_READ`)** : Service Directory private network access doesn't expose native
  Cloud Monitoring metrics. To observe service resolution activity and
  diagnose lookup failures, enable Data Access (`DATA_READ`) audit logs on the
  Service Directory API in your Service Directory project, and query
  Logging with the following filter (you can also create a
  log-based metric from this query):

      protoPayload.serviceName="servicedirectory.googleapis.com"
      protoPayload.methodName="google.cloud.servicedirectory.v1beta1.InternalLookupService.InternalResolveService"

- **Diagnose IAM and VPC Service Controls permission
  errors**:

  - **Build-time `PERMISSION_DENIED` on `servicedirectory.networks.attach`** : The administrator creating the Service Directory endpoint in [Register the internal load balancer in
    Service Directory](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises#register-service-directory) is missing the Service Directory Network Attacher (`roles/servicedirectory.networkAttacher`) role on the project that owns the VPC network (or Shared VPC host project).
  - **Runtime `PERMISSION_DENIED` on `servicedirectory.services.resolve`** : The Customer Engagement Suite service agent (`service-WORKLOAD_PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com`) is missing `roles/servicedirectory.viewer` on the project hosting the Service Directory service.
  - **Runtime `PERMISSION_DENIED` on `servicedirectory.networks.access`** : The Customer Engagement Suite service agent (`service-WORKLOAD_PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com`) is missing `roles/servicedirectory.pscAuthorizedService` on the project that owns the VPC network (or Shared VPC host project).
  - **VPC Service Controls perimeter alignment** : If your organization uses VPC Service Controls across split projects, confirm that the CX Agent Studio workload project, Service Directory project, and VPC host project belong to the same VPC Service Controls perimeter, or configure ingress and egress rules permitting `servicedirectory.googleapis.com` methods (`google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint` and `google.cloud.servicedirectory.v1beta1.InternalLookupService.InternalResolveService`).
- **Validate Service Directory with a private uptime check** : You can configure
  a [Monitoring private uptime
  check](https://docs.cloud.google.com/monitoring/uptime-checks/private-checks) targeting your
  Service Directory service to independently test TLS handshakes and HTTP status
  codes before testing from CX Agent Studio.

- **Scale to multiple on-premises APIs** : Although you can configure a separate
  Service Directory service on each OpenAPI tool or toolset in CX Agent Studio,
  routing multiple on-premises APIs through a single regional internal Application Load Balancer is
  recommended as a best practice. You can attach multiple backend services
  (pointing to different hybrid NEGs or regional internet NEGs) to the same load
  balancer and configure host and path rules in its URL map (`URL_MAP_NAME`) to
  route requests based on the hostname or URL path in each OpenAPI tool
  specification.

- **Multi-region deployments and agent-level failover** : Service Directory and
  private network access are regional services. Placing a cross-region internal Application Load Balancer behind
  a single regional Service Directory service still depends on that single
  Service Directory region's availability. For end-to-end multi-region high
  availability, deploy independent regional stacks (Service Directory, regional
  internal Application Load Balancer, and Cloud VPN or Cloud Interconnect) in at
  least two regions (for example, `us-central1` and `us-east1`), configure two
  regional OpenAPI tools on your agent (such as `order_status_api_primary` and
  `order_status_api_secondary`), and instruct the agent to fall back to the
  secondary regional tool if the primary tool returns a connection or timeout
  error.

## Clean up

To avoid incurring ongoing charges to your Google Cloud account for the
resources used in this tutorial, delete the provisioned resources in reverse
dependency order.

### Delete the CX Agent Studio agent and tool

1. Open the [CX Agent Studio console](https://ces.cloud.google.com/) and select your Google Cloud project (`PROJECT_ID`).
2. Select the `Order_Status_Agent` agent, open its settings menu, and delete the agent (or remove the `order_status_api` OpenAPI tool if you want to keep the agent).

### Delete the Service Directory resources

Deleting the Service Directory namespace automatically deletes all services and
endpoints contained within it:

```bash
gcloud service-directory namespaces delete "${NAMESPACE_NAME}" \
    --location="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet
```

### Delete the regional internal Application Load Balancer

Delete the load balancer components in the following order (forwarding rule,
reserved internal IP address, target HTTPS proxy, SSL certificate, URL map,
backend service, and health check):

```bash
# Delete the forwarding rule and reserved internal VIP
gcloud compute forwarding-rules delete "${FORWARDING_RULE_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

gcloud compute addresses delete "${ADDRESS_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

# Delete the target HTTPS proxy, SSL certificate, and URL map
gcloud compute target-https-proxies delete "${TARGET_PROXY_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

gcloud compute ssl-certificates delete "${CERTIFICATE_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

gcloud compute url-maps delete "${URL_MAP_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

# Delete the backend service and health check
gcloud compute backend-services delete "${BACKEND_SERVICE_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet

gcloud compute health-checks delete "${HEALTH_CHECK_NAME}" \
    --region="${REGION}" \
    --project="${PROJECT_ID}" \
    --quiet
```

### Delete the network endpoint group and Cloud DNS resources

Delete the NEG resources corresponding to the option you deployed in
[Create the network endpoint group](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-on-premises.md.txt#create-neg):

- If you created a hybrid connectivity NEG (Option A):

  ```bash
  gcloud compute network-endpoint-groups delete "${HYBRID_NEG_NAME}" \
      --zone="${ZONE}" \
      --project="${PROJECT_ID}" \
      --quiet
  ```
- If you created a regional internet NEG and Cloud DNS private zone
  (Option B):

  ```bash
  gcloud compute network-endpoint-groups delete "${INTERNET_NEG_NAME}" \
      --region="${REGION}" \
      --project="${PROJECT_ID}" \
      --quiet

  gcloud dns record-sets delete "${FQDN}." \
      --zone=onprem-private-zone \
      --type=A \
      --project="${PROJECT_ID}" \
      --quiet

  gcloud dns managed-zones delete onprem-private-zone \
      --project="${PROJECT_ID}" \
      --quiet
  ```

### Revert Cloud Router custom route advertisements

Revert your Cloud Router to default route advertisement mode (or remove
`${PROXY_ONLY_SUBNET_RANGE}` from your custom advertised ranges if you advertise
other custom ranges):

```bash
gcloud compute routers update "${ROUTER_NAME}" \
    --region="${REGION}" \
    --advertisement-mode=DEFAULT \
    --project="${PROJECT_ID}"
```

### Delete the firewall policy, subnets, and local files

1. Remove the network firewall policy association and delete the firewall
   policy:

   ```bash
   gcloud compute network-firewall-policies associations delete \
       --firewall-policy=gecx-onprem-fw-policy \
       --name="network-${NETWORK_NAME}" \
       --global-firewall-policy \
       --project="${PROJECT_ID}"

   gcloud compute network-firewall-policies delete gecx-onprem-fw-policy \
       --global \
       --project="${PROJECT_ID}" \
       --quiet
   ```
2. Delete the regional proxy-only subnet and load balancer subnet:

   ```bash
   gcloud compute networks subnets delete "${PROXY_ONLY_SUBNET_NAME}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}" \
       --quiet

   gcloud compute networks subnets delete "${LB_SUBNET_NAME}" \
       --region="${REGION}" \
       --project="${PROJECT_ID}" \
       --quiet
   ```
3. If you created a new dedicated VPC network for this tutorial,
   delete the VPC network:

   ```bash
   gcloud compute networks delete "${NETWORK_NAME}" \
       --project="${PROJECT_ID}" \
       --quiet
   ```
4. Remove the local TLS certificate and private key files from your workstation
   or Cloud Shell environment:

   ```bash
   rm -f server.key server.csr server.crt server.der
   ```
5. Optional: If you deployed the sample FastAPI server on your on-premises
   host, stop and remove the `systemd` service or Docker container, and delete
   the `~/order-status-api` directory.

## What's next

- Follow [Connect to an internal Cloud Run service within a
  VPC Service Controls
  perimeter](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound-cloud-run) to connect CX Agent Studio privately to an internal Cloud Run service over Shared VPC.
- Learn more about [setting up an internal Application Load Balancer with hybrid
  connectivity](https://docs.cloud.google.com/load-balancing/docs/l7-internal/setting-up-int-https-hybrid).
- Learn more about [advertising custom IP ranges with
  Cloud Router](https://docs.cloud.google.com/network-connectivity/docs/router/how-to/advertising-custom-ip).
- Return to the [outbound networking overview](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/network/outbound.md.txt).