通过 Private Service Connect 端点,使用 Python SDK 在 Vertex AI 上使用 Anthropic Claude Opus 4.6 和 Gemini 3.1

1. 概览

您可以通过互联网访问 Vertex AI API,但在企业中,您可能希望以私密方式访问 Vertex AI API,而无需通过互联网。在本实验中,您将首先通过在虚拟机实例上运行的 Python SDK,通过公共互联网访问 Vertex 上的 Anthropic Claude Opus 4.6Gemini 3.1Pro

然后,您将为 Googleapis 创建 Private Service Connect 端点,并更改流量流以使用专用端点连接到 Vertex API。

Python 代码示例将获取输入问题,将其传递给 Claude Opus 以生成答案,然后将该输出传递给 Gemini 3 以创建文本摘要并生成图片。

在本实验中,您将创建以下模式。

图 1。

c8f37e193349bfd6.png

2. 目标

在本实验中,您将学习如何执行以下任务:

  • 设置虚拟机实例以使用 Python SDK
  • 在 Vertex AI 中启用 Anthropic 模型卡片
  • 通过 Python 脚本连接到 Anthropic Claude Opus 4.6Gemini 3.1 Pro
  • 配置 PSC 端点以连接到 Googleapis
  • 配置手动 DNS 条目
  • 验证与 Googleais 的连接路径
  • 执行 Python 脚本以查询模型

实验设置

自定进度的环境设置

  1. 登录 Google Cloud 控制台,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 账号,则必须 创建一个

295004821bab6a87.png

37d264871000675d.png

96d86d3d5655cdbe.png

  • 项目名称 是此项目参与者的显示名称。它是 Google API 尚未使用的字符串。您可以随时对其进行更新。
  • 项目 ID 在所有 Google Cloud 项目中是唯一的,并且是不可变的(一经设置便无法更改)。Cloud 控制台会自动生成一个唯一字符串;通常情况下,您无需关注该字符串。在大多数 Codelab 中,您都需要引用项目 ID(通常用 PROJECT_ID 标识)。如果您不喜欢生成的 ID,可以再随机生成一个 ID。或者,您也可以尝试自己的项目 ID,看看是否可用。完成此步骤后便无法更改该 ID,并且此 ID 在项目期间会一直保留。
  • 此外,还有第三个值,即部分 API 使用的项目编号,供您参考。如需详细了解所有这三个值,请参阅文档
  1. 接下来,您需要在 Cloud 控制台中启用结算功能,以便使用 Cloud 资源/API。运行此 Codelab 应该不会产生太多的费用(如果有的话)。若要关闭资源以避免产生超出本教程范围的结算费用,您可以删除自己创建的资源或删除项目。Google Cloud 新用户符合参与 300 美元免费试用计划的条件。

启动 Cloud Shell

虽然可以通过笔记本电脑对 Google Cloud 进行远程操作,但在此 Codelab 中,您将使用 Google Cloud Shell,这是一个在云端运行的命令行环境。

Google Cloud 控制台 中,点击右上角工具栏中的 Cloud Shell 图标:

激活 Cloud Shell

预配和连接到环境应该只需要片刻时间。完成后,您应该会看到如下内容:

Google Cloud Shell 终端的屏幕截图,显示环境已连接

这个虚拟机已加载了您需要的所有开发工具。它提供了一个持久的 5 GB 主目录,并且在 Google Cloud 中运行,大大增强了网络性能和身份验证功能。您在此 Codelab 中的所有工作都可以在浏览器中完成。您无需安装任何程序。

3. 设置环境

我们将创建具有防火墙规则的自定义 VPC。如果您已有 VPC 和项目,则可以跳过此部分。

打开控制台右上角的 Cloud Shell。并按如下所示进行配置:b51b80043d3bac90.png

  1. 启用我们将在本实验中使用的一些 API
gcloud services enable dns.googleapis.com
gcloud services enable aiplatform.googleapis.com
gcloud services enable servicedirectory.googleapis.com
  1. 设置一些变量。这些变量是自定义 VPC 的项目 ID 和网络 ID(您将在第 4 步中创建 VPC)。
projectid=$(gcloud config get-value project)
networkid=anthropic-net 
echo $projectid
echo $networkid
  1. 现在,创建自定义 VPC (anthropic-net)、子网 (vm1-subnet) 和防火墙规则
gcloud compute networks create $networkid \
--project=$projectid \
--subnet-mode=custom \
--mtu=1460 \
--bgp-routing-mode=global

gcloud compute networks subnets create vm-subnet \
--project=$projectid --range=10.0.88.0/24 \
--stack-type=IPV4_ONLY --network=$networkid \
--region=us-east1

gcloud compute firewall-rules create $networkid-allow-icmp --project=$projectid \
--network=$networkid \
--description="Allows ICMP connections from any source to any instance on the network." \
--direction=INGRESS \
--priority=65534 \
--source-ranges=0.0.0.0/0 \
--action=ALLOW \
--rules=icmp

gcloud compute firewall-rules create $networkid-allow-ssh \
--project=$projectid \
--network=$networkid \
--description="Allows TCP connections from any source to any instance on the network using port 22." \
--direction=INGRESS --priority=65534 \
--source-ranges=0.0.0.0/0 --action=ALLOW \
--rules=tcp:22

gcloud compute firewall-rules create $networkid-allow-web \
--project=$projectid \
--network=$networkid \
--description="Allows TCP connections on port 8080." \
--direction=INGRESS --priority=1000 \
--source-ranges=0.0.0.0/0 --action=ALLOW \
--rules=tcp:8080

4. 在 Vertex 模型花园中启用 Anthropic

我们需要授予出站外部互联网访问权限,因此请创建 Cloud NAT 网关并将其连接。

  1. 前往 Vertex AI 信息中心 ,然后选择 Model Garden
  2. 搜索 Anthropic ,然后选择 Claude Opus 4.6

143753757bcc3ef0.png

  1. 选择启用,系统会要求您填写一些信息。填写表单,然后选择下一步
  2. 在最后一页上,选择同意 以启用 Claude 4.6 Opus

ece502115e10ca47.png

  1. 您应该会看到成功页面。

7290e50f7dd82a89.png

5. 创建 NAT 网关和虚拟机

我们需要授予出站外部互联网访问权限,因此请创建 Cloud NAT 网关并将其连接。

在 Cloud Shell 中使用以下命令

  1. 创建 Cloud NAT 和 Cloud NAT 网关
gcloud compute routers create anthro-out-nat \
    --network $networkid \
    --region us-east1 

gcloud compute routers nats create anthro-out-nat-gw \
    --router-region us-east1 \
    --router anthro-out-nat \
    --nat-all-subnet-ip-ranges \
    --auto-allocate-nat-external-ips

现在,让我们创建一个虚拟机,以通过 Python SDK 访问 Vertex AI 上的 Anthropic。

  1. 在同一 Cloud Shell 会话中,使用以下命令创建 anthro-vm(请等待 3-4 分钟,以便在启动脚本安装时激活虚拟机)
gcloud compute instances create anthro-vm \
--project=$projectid \
--zone=us-east1-b \
--network-interface=stack-type=IPV4_ONLY,subnet=vm-subnet,no-address,network=$networkid \
--metadata startup-script="#! /bin/bash
      apt-get update
      apt-get install python3 python3-dev python3-venv tcpdump dnsutils -y
      python3 -m venv /opt/py-anthro-env
      /opt/py-anthro-env/bin/pip install -U google-genai 'anthropic[vertex]' rich
      chmod -R 777 /opt/py-anthro-env"

您应该会看到创建的虚拟机没有公共 IP 地址。现在,让我们配置虚拟机

6. 配置虚拟机并进行测试

  1. 在 Google Cloud Shell 中,让我们通过 SSH 连接到名为 anthro-vm 的新虚拟机。(您可能需要等待 3 分钟,以确保虚拟机完全设置完毕)
gcloud compute ssh anthro-vm \
    --project=$projectid \
    --zone=us-east1-b \
    --tunnel-through-iap \
    -- -L 8080:localhost:8080
  1. 连接后,让我们快速测试一下,看看是否可以连接到 Vertex Gemini API。
dig *-aiplatform.googleapis.com
  1. 您应该会看到类似的内容(地址会有所不同 )。请注意,由于 API 是公共 API,因此路径是通过公共 IP 地址。
; <<>> DiG 9.18.39-0ubuntu0.24.04.2-Ubuntu <<>> *-aiplatform.googleapis.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3728
;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;*-aiplatform.googleapis.com.   IN      A

;; ANSWER SECTION:
*-aiplatform.googleapis.com. 300 IN     A       172.217.204.95
*-aiplatform.googleapis.com. 300 IN     A       172.217.203.95
*-aiplatform.googleapis.com. 300 IN     A       173.194.215.95
*-aiplatform.googleapis.com. 300 IN     A       142.250.98.95
*-aiplatform.googleapis.com. 300 IN     A       173.194.217.95
*-aiplatform.googleapis.com. 300 IN     A       142.251.107.95
*-aiplatform.googleapis.com. 300 IN     A       74.125.196.95
  1. 现在,激活您的 venv 环境:
source /opt/py-anthro-env/bin/activate
  1. 现在,让我们对其进行身份验证,以便稍后进行一些测试。在虚拟机中运行以下命令,并在出现提示时按 y
gcloud auth application-default login
  1. 接下来,复制以 https:// 开头的网址,在实验浏览器窗口中打开一个新标签页,然后粘贴该网址。接受提示。
  2. 当您看到以下内容时,请选择“复制”,切换回虚拟机 anthro-vm 会话,然后对于 Enter authorization code: (输入授权代码:),粘贴您复制的代码并按 Enter 进行身份验证。

b703db7aa2aa286a.png

  1. 现在,让我们在 env 中使用 Python。这会创建一个 Python 文件 super-gen-ai.py,该文件会询问 Claude Opus 4.6 "构建智能体 AI 的关键步骤是什么?"然后获取输出并将其传递给 Gemini 3.1 Pro,后者会创建摘要,然后 Gemini 3 Pro Image 会生成图片并将其保存在虚拟机上。

复制并粘贴以下内容。

cat << 'EOF' > super-gen-ai.py
import os
import subprocess
import google.auth
from google import genai
from google.genai import types
from anthropic import AnthropicVertex
from rich.console import Console
from rich.panel import Panel
from rich.spinner import SPINNERS
from rich.text import Text

# Custom Super Me Animation Spinner - Now with moving power-up!
SPINNERS["super_me"] = {
    "interval": 120,
    "frames": [
        "🧱🦖          🍄",
        "🧱 🦖        🍄 ",
        "🧱  🦖      🍄  ",
        "🧱   🦕    🍄   ",
        "🧱    🦖  🍄    ",
        "🧱     🦖🍄     ",
        "🧱      🌟      ",
        "🧱       🌟     ",
        "🧱        🌟    ",
        "🧱         🌟   ",
        "🧱        🌟    ",
        "🧱       🌟     ",
        "🧱      🌟      ",
        "🧱     🌟       ",
        "🧱    🌟        ",
        "🧱   🌟         ",
        "🧱  🌟          ",
        "🧱 🌟           ",
        "🧱🌟            "
    ]
}

console = Console()

def print_super_me_header():
    super_me_art = """
[bold red]   _____                       [/bold red][bold green]  __  __      _ [/bold green]
[bold red]  / ____|                      [/bold red][bold green] |  \/  |    | |[/bold green]
[bold red] | (___  _   _ _ __   ___ _ __ [/bold red][bold green] | \  / | ___| |[/bold green]
[bold red]  \___ \| | | | '_ \ / _ \ '__|[/bold red][bold green] | |\/| |/ _ \ |[/bold green]
[bold red]  ____) | |_| | |_) |  __/ |   [/bold red][bold green] | |  | |  __/_|[/bold green]
[bold red] |_____/ \__,_| .__/ \___|_|   [/bold red][bold green] |_|  |_|\___(_)[/bold green]
[bold red]              | |              [/bold red][bold green]                 [/bold green]
[bold red]              |_|              [/bold red][bold green]                 [/bold green]
    """
    console.print(super_me_art)
    console.rule("[bold gold1]⭐ LEVEL 1-1: Vertex AI Orchestrator ⭐[/bold gold1]")

def main():
    os.system('clear')  # Clears the terminal for a clean UI
    print_super_me_header()
    
    # Create the images directory
    os.makedirs("images", exist_ok=True)

    with console.status("[bold yellow]🪙  Collecting Coins (Authenticating)...[/bold yellow]", spinner="super_me"):
        try:
            creds, project_id = google.auth.default()
            LOCATION = "global" 
        except Exception as e:
            console.print(f"[bold red]💥 GAME OVER! Authentication failed:[/bold red] {e}")
            return 

    with console.status(f"[bold green]🍄 Powering up Clients for {project_id}...[/bold green]", spinner="super_me"):
        google_client = genai.Client(vertexai=True, location=LOCATION, project=project_id)
        claude_client = AnthropicVertex(region=LOCATION, project_id=project_id)

    console.print("\n[bold cyan]The Kingdom needs a strategy![/bold cyan]")
    
    # Auto-run prompt without user interaction
    question = "What are the key steps to building Agentic AI?"
    
    console.print(Panel(question, title="[bold green]Green Dino (Claude Opus) is entering the pipe...[/bold green]", border_style="green"))

    with console.status("[bold green]🟢 Green Dino is clearing the level...\n[/bold green]", spinner="super_me"):
        try:
            msg = claude_client.messages.create(
                model="claude-opus-4-6", 
                max_tokens=2048,
                messages=[{"role": "user", "content": question}]
            )
            claude_text = msg.content[0].text
            console.print(f"[bold green]✓ Level Cleared! Green Dino generated {len(claude_text)} bytes of strategy.[/bold green]\n")
        except Exception as e:
            console.print(f"[bold red]💥 BOSS ATTACK (Claude API Error):[/bold red] {e}")
            return

    with console.status("[bold red]🔴 Red Hero (Gemini 3.1 Pro Preview) is summarizing the map...\n[/bold red]", spinner="super_me"):
        text_prompt = f"""
        I am providing you with a response generated by Claude.
        1. READ the text below.
        2. GENERATE a concise, bulleted executive summary.

        --- INPUT TEXT ---
        {claude_text}
        """
        
        try:
            text_response = google_client.models.generate_content(
                model="gemini-3.1-pro-preview", 
                contents=text_prompt,
                config=types.GenerateContentConfig(temperature=0.7)
            )
            console.print("[bold red]✓ Super Me! Text Summary Complete.[/bold red]")
        except Exception as e:
            console.print(f"[bold red]💥 CHOMPER PLANT (Gemini Text Error):[/bold red] {e}")
            return

    with console.status("[bold blue]🔵 Mushroom Friend (Gemini 3 Pro Image) is painting the castle...\n[/bold blue]", spinner="super_me"):
        image_prompt = f"""
        CREATE a high-quality, futuristic illustration of autonomous AI agents for a tech blog header (16:9 aspect ratio).
        Base the image directly on the following text summary:
        
        {text_response.text}
        """
        
        try:
            image_response = google_client.models.generate_content(
                model="gemini-3-pro-image-preview", 
                contents=image_prompt,
                config=types.GenerateContentConfig(
                    response_modalities=['TEXT', 'IMAGE'],
                    temperature=0.7
                )
            )
            console.print("[bold blue]✓ Masterpiece Complete![/bold blue]\n")
        except Exception as e:
            console.print(f"[bold red]💥 FALLING BLOCK (Gemini Image Error):[/bold red] {e}")
            return

    console.rule("[bold gold1]🚩 COURSE CLEAR! 🚩[/bold gold1]")
    
    if text_response.text:
        console.print(Panel(text_response.text.strip(), 
                            title="[bold gold1]Gemini 3.1 Pro Summary[/bold gold1]", 
                            border_style="gold1"))

    for part in image_response.parts:
        if image := part.as_image():
            # Save inside the images folder with the focus-specific name
            filename = "images/building-agentic.png"
            image.save(filename)
            console.print(f"\n[bold green]✓ REWARD SAVED:[/bold green] [underline]{os.path.abspath(filename)}[/underline]")

    console.rule("[bold red]Web Server Warp Pipe[/bold red]")
    with console.status("[bold yellow]Opening the warp pipe (HTTP server)...[/bold yellow]", spinner="super_me"):
        # Kill any existing server first so it doesn't crash on port binding
        os.system('pkill -f "http.server" > /dev/null 2>&1')
        
        # Start the server with the root directory set specifically to 'images'
        subprocess.Popen(
            ["python3", "-m", "http.server", "8080", "--directory", "images"], 
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.DEVNULL
        )
        
    console.print("[bold green]✓ Warp Pipe is open in the background![/bold green]")
    console.print("[bold magenta]View your files here (Click Web Preview -> Preview on port 8080):[/bold magenta] [underline]http://localhost:8080/[/underline]\n")

if __name__ == "__main__":
    main()
EOF

python3 super-gen-ai.py

该脚本在有趣的界面中运行并启动 Web 服务器,以便您可以查看图片输出。如需再次运行该脚本,请键入 python3 super-gen-ai.py.

  1. 如需使用 Cloud Shell 中的网页预览选项,请选择“在端口 8080 上预览”6dcb2bf9a08aacaf.png
  2. 在打开的 Web 会话中,选择 building_agentic.png 以查看生成的图片。(以下是 AI 生成的示例图片)
    fdcb79d8410dadc5.png
  3. Cloud Shell 中,如需退出 Web 服务器,请运行以下命令。
pkill -f "http.server"
  1. 接下来,键入 exit 以返回到 Cloud Shell 主页。完成后,让我们继续。

7. 为 Googleapis 创建 PSC 端点

如需启用与 Vertex API 端点的专用连接,我们将为 Googleapis 创建 Private Service Connect 端点。这样,我们就可以使用分配给我们的专用 IP 地址将流量路由到我们需要的 Googleapis(在本例中为 Vertex Gemini)。

  1. 如果尚未打开,请打开 Cloud Shell。我们将为 PSC 端点创建一个 IP,并创建 Private Service Connect 端点。在本例中,我们将使用 192.168.255.230
projectid=$(gcloud config get-value project)
networkid=anthropic-net

gcloud compute addresses create anthro-ip \
    --global \
    --purpose=PRIVATE_SERVICE_CONNECT \
    --addresses=192.168.255.230 \
    --network=$networkid

gcloud compute forwarding-rules create pscanthrovertex \
    --global \
    --network=$networkid \
    --address=anthro-ip \
    --target-google-apis-bundle=all-apis
  1. 验证
gcloud compute addresses list --filter="name=( 'anthro-ip' ...)"

gcloud compute forwarding-rules describe pscanthrovertex --global

8. 为 Googleapis 创建手动 DNS 条目

您可以使用专用 DNS 创建手动 DNS 条目以指向 PSC 端点。这会影响您分配给它的所有网络。您现在将创建以下内容

  • 为 googleapis.com 创建专用 DNS 区域 ,并将其连接到 anthropic-net 网络。
  • 将根域名映射到 Private Service Connect 端点 IP (192.168.255.230) 的 A 记录
  • 通配符 CNAME 记录,用于将所有子网域(例如 aiplatform.googleapis.com)重定向到根 A 记录
  1. 在 Cloud Shell 中运行以下命令。
gcloud dns managed-zones create googleapis-private \
    --description="Private DNS zone for googleapis.com" \
    --dns-name="googleapis.com." \
    --visibility="private" \
    --networks="anthropic-net"

gcloud dns record-sets create "googleapis.com." \
    --zone="googleapis-private" \
    --type="A" \
    --ttl="300" \
    --rrdatas="192.168.255.230"

gcloud dns record-sets create "*.googleapis.com." \
    --zone="googleapis-private" \
    --type="CNAME" \
    --ttl="300" \
    --rrdatas="googleapis.com."
  1. 列出区域中的记录集,以确认 A 记录和 CNAME 已正确创建。
gcloud dns record-sets list --zone="googleapis-private"
  1. 在控制台视图中,它应如下所示。您应该会看到一个设置,其中包含 A 记录和 CNAME ,如下所示 a51a8b8caa7a0f1e.png
  2. 接下来,我们验证对 anthro-vm 的这些更改的连接

9. 通过 IP 地址验证端点连接

让我们使用专用端点连接到 Gemini。

  1. 在 Google Cloud Shell 中,让我们通过 SSH 连接到名为 anthro-vm 的新虚拟机。
gcloud compute ssh anthro-vm \
    --project=$projectid \
    --zone=us-east1-b \
    --tunnel-through-iap \
    -- -L 8080:localhost:8080
  1. 在虚拟机中,使用 dig 命令检查与 aiplatform-pscanthrovertex.p.googleapis.com 的连接路径。您应该会看到 PSC 端点的 IP 192.168.255.230
dig aiplatform-pscanthrovertex.p.googleapis.com +noall +answer

让我们使用专用端点连接到 Gemini。

  1. 现在,让我们执行 dig,看看是否可以连接到 Vertex Gemini API。
dig *-aiplatform.googleapis.com
  1. 您应该会看到类似的内容(地址会有所不同)。请注意,路径是通过 PSC 端点 IP 地址。
; <<>> DiG 9.18.41-1~deb12u1-Debian <<>> *-aiplatform.googleapis.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33703
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;*-aiplatform.googleapis.com.   IN      A

;; ANSWER SECTION:
*-aiplatform.googleapis.com. 300 IN     CNAME   googleapis.com.
googleapis.com.         300     IN      A       192.168.255.230

;; Query time: 8 msec
;; SERVER: 169.254.169.254#53(169.254.169.254) (UDP)
;; WHEN: Sat Nov 29 15:19:15 UTC 2025
;; MSG SIZE  rcvd: 86
  1. 使用 ping 命令。我们可以快速测试一下。注意:此 IP 是 PSC 端点,您的 ping 将会失败。
ping -c 2 aiplatform.googleapis.com
  1. 现在,激活您的 venv 环境:
source /opt/py-anthro-env/bin/activate
  1. 现在,让我们在 env 中使用 Python。这会创建一个 Python 文件 star-me.py,该文件会询问 Claude Opus 4.6“请给我一个面向初学者的 roti 制作分步食谱?”然后获取输出并将其传递给 Gemini 3.1 Pro,后者会创建摘要,然后 Gemini 3 Pro Image 会生成图片并将其保存在虚拟机上
cat << 'EOF' > star-me.py
import os
import subprocess
import google.auth
from google import genai
from google.genai import types
from anthropic import AnthropicVertex
from rich.console import Console
from rich.panel import Panel
from rich.spinner import SPINNERS
from rich.text import Text

# Custom Star Me Animation Spinner - Directional Flight!
SPINNERS["star_me"] = {
    "interval": 120,
    "frames": [
        "🌌 🚀              🛸 ",
        "🌌  🚀            🛸  ",
        "🌌   🚀          🛸   ",
        "🌌    🚀        🛸    ",
        "🌌     🚀      🛸     ",
        "🌌      🚀    🛸      ",
        "🌌       🚀  🛸       ",
        "🌌        🚀🛸        ",
        "🌌         💥         ",
        "🌌        ✨ ✨       ",
        "🌌       ✨   ✨      ",
        "🌌      ✨     ✨     ",
        "🌌     ✨       ✨    ",
        "🌌                    "
    ]
}

console = Console()

def print_star_me_header():
    star_me_art = """
[bold cyan]   _____ _______       _____    __  __ ______ [/bold cyan]
[bold cyan]  / ____|__   __|/\   |  __ \  |  \/  |  ____|[/bold cyan]
[bold cyan] | (___    | |  /  \  | |__) | | \  / | |__   [/bold cyan]
[bold cyan]  \___ \   | | / /\ \ |  _  /  | |\/| |  __|  [/bold cyan]
[bold cyan]  ____) |  | |/ ____ \| | \ \  | |  | | |____ [/bold cyan]
[bold cyan] |_____/   |_/_/    \_\_|  \_\ |_|  |_|______|[/bold cyan]
    """
    console.print(star_me_art)
    console.rule("[bold gold1]⭐ EPISODE I: The AI Awakening ⭐[/bold gold1]")

def main():
    os.system('clear')  # Clears the terminal for a clean UI
    print_star_me_header()
    
    # Create the images directory
    os.makedirs("images", exist_ok=True)

    with console.status("[bold yellow]🪙  Bypassing Security (Authenticating)...[/bold yellow]", spinner="star_me"):
        try:
            creds, project_id = google.auth.default()
            LOCATION = "global" 
        except Exception as e:
            console.print(f"[bold red]💥 COMM LINK SEVERED! Authentication failed:[/bold red] {e}")
            return 

    with console.status(f"[bold cyan]📡 Establishing secure connection for {project_id}...[/bold cyan]", spinner="star_me"):
        google_client = genai.Client(vertexai=True, location=LOCATION, project=project_id)
        claude_client = AnthropicVertex(region=LOCATION, project_id=project_id)

    console.print("\n[bold cyan]The Galaxy needs sustenance![/bold cyan]")
    
    # Auto-run prompt for the recipe
    question = "Give me a step by step recipe to make a roti for a beginner?"
    
    console.print(Panel(question, title="[bold green]Space Master (Claude Opus) is searching the archives...[/bold green]", border_style="green"))

    with console.status("[bold green]🟢 Space Master is compiling the ancient texts...\n[/bold green]", spinner="star_me"):
        try:
            msg = claude_client.messages.create(
                model="claude-opus-4-6", 
                max_tokens=2048,
                messages=[{"role": "user", "content": question}]
            )
            claude_text = msg.content[0].text
            console.print(f"[bold green]✓ Archives Retrieved! Space Master generated a {len(claude_text)}-character Holocron.[/bold green]\n")
        except Exception as e:
            console.print(f"[bold red]💥 INTERFERENCE DETECTED (Claude API Error):[/bold red] {e}")
            return

    with console.status("[bold gold1]🟡 Protocol Bot (Gemini 3.1 Pro Preview) is translating the recipe...\n[/bold gold1]", spinner="star_me"):
        text_prompt = f"""
        I am providing you with a response generated by a Space Master.
        1. READ the text below.
        2. GENERATE a concise, bulleted executive summary.

        --- INPUT TEXT ---
        {claude_text}
        """
        
        try:
            text_response = google_client.models.generate_content(
                model="gemini-3.1-pro-preview", 
                contents=text_prompt,
                config=types.GenerateContentConfig(temperature=0.7)
            )
            console.print("[bold gold1]✓ Translation Complete! The Protocol Bot has summarized the steps.[/bold gold1]")
        except Exception as e:
            console.print(f"[bold red]💥 SYSTEM FAILURE (Gemini Text Error):[/bold red] {e}")
            return

    with console.status("[bold blue]🔵 Astro Bot (Gemini 3 Pro Image) is projecting the hologram...\n[/bold blue]", spinner="star_me"):
        image_prompt = f"""
        CREATE a high-quality, beautiful illustration for a blog header (16:9 aspect ratio) of someone making roti, but with a subtle sci-fi, cinematic lighting aesthetic.
        Base the image directly on the following text summary:
        
        {text_response.text}
        """
        
        try:
            image_response = google_client.models.generate_content(
                model="gemini-3-pro-image-preview", 
                contents=image_prompt,
                config=types.GenerateContentConfig(
                    response_modalities=['TEXT', 'IMAGE'],
                    temperature=0.7
                )
            )
            console.print("[bold blue]✓ Hologram Projection Ready![/bold blue]\n")
        except Exception as e:
            console.print(f"[bold red]💥 BAD COMPRESSOR (Gemini Image Error):[/bold red] {e}")
            return

    console.rule("[bold cyan]🚩 MISSION ACCOMPLISHED 🚩[/bold cyan]")
    
    if text_response.text:
        console.print(Panel(text_response.text.strip(), 
                            title="[bold gold1]Protocol Bot Recipe Summary[/bold gold1]", 
                            border_style="gold1"))

    for part in image_response.parts:
        if image := part.as_image():
            # Save inside the images folder with the focus-specific name
            filename = "images/cookingroti.png"
            image.save(filename)
            console.print(f"\n[bold green]✓ DATA SECURED:[/bold green] [underline]{os.path.abspath(filename)}[/underline]")

    console.rule("[bold cyan]Hyperlink Uplink[/bold cyan]")
    with console.status("[bold yellow]Opening the frequencies (HTTP server)...[/bold yellow]", spinner="star_me"):
        # Kill any existing server first so it doesn't crash on port binding
        os.system('pkill -f "http.server" > /dev/null 2>&1')
        
        # Start the server with the root directory set specifically to 'images'
        subprocess.Popen(
            ["python3", "-m", "http.server", "8080", "--directory", "images"], 
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.DEVNULL
        )
        
    console.print("[bold green]✓ Transmitting on Port 8080![/bold green]")
    console.print("[bold magenta]View your files here (Click Web Preview -> Preview on port 8080):[/bold magenta] [underline]http://localhost:8080/[/underline]\n")

if __name__ == "__main__":
    main()
EOF

python3 star-me.py

该脚本在有趣的界面中运行并启动 Web 服务器,以便您可以查看图片输出。如需再次运行该脚本,请键入 python3 star-me.py

  1. 现在,前往 Cloud Shell 中的网页预览选项,选择“在端口 8080 上预览”

6dcb2bf9a08aacaf.png

  1. 选择 cookingroti.png 以查看生成的图片。(以下是 AI 生成的示例)bcf43fffede275cb.png
  2. Cloud Shell 中,如需退出 Web 服务器并返回到虚拟机,请运行以下命令。
pkill -f "http.server"
  1. 接下来,键入 exit 以返回到 Cloud Shell 主页。

10. 恭喜

恭喜!您玩得开心,并且成功连接到 Vertex 上的 Anthropic Claude Opus 4.6Gemini 3.1 Pro ,既使用了公共 API 地址,也使用了 Googleapis 的 Private Service Connect 端点以私密方式连接。此功能可以将私有 API 连接扩展到通过(互连、Cross-Cloud Interconnect 和 VPC)连接的本地/其他云环境。

清理

gcloud compute instances delete anthro-vm --zone=us-east1-b --quiet

gcloud compute routers nats delete anthro-out-nat-gw --router=anthro-out-nat --region=us-east1 --quiet

gcloud compute routers delete anthro-out-nat --region=us-east1 --quiet

gcloud compute firewall-rules delete anthropic-net-allow-icmp anthropic-net-allow-ssh anthropic-net-allow-web --quiet

gcloud compute forwarding-rules delete pscanthrovertex --global --quiet

gcloud dns record-sets delete googleapis.com. --zone googleapis-private --type A --quiet

gcloud dns record-sets delete *.googleapis.com --zone googleapis-private --type CNAME --quiet

gcloud dns managed-zones delete googleapis-private --quiet

gcloud compute addresses delete anthro-ip --global --quiet

gcloud compute networks subnets delete vm-subnet --region=us-east1 --quiet

gcloud compute networks delete anthropic-net --quiet

后续步骤 / 了解详情

您可以详细了解 Vertex AI 网络

Codelab通过 Private Service Connect 端点使用 Python SDK 访问 Gemini 3 Pro 对话

Codelab使用 ADK 构建 AI 智能体:基础知识

参与下一项实验

继续完成 Google Cloud 挑战任务,并查看下方列出的其他 Google Cloud Skills Boost 实验: