使用 Google 生态系统构建 AI 应用

1. 准备工作

软件开发已经发生了演变。最成功的开发者不仅会编写代码,还会协调 AI 工具和智能体,以更快、更好地构建应用。Google 的工具生态系统提供了一套全面的工具,涵盖整个生命周期:界面生成、应用原型设计和部署、AI 功能开发以及安全、可扩缩的后端集成。在此 Codelab 中,您将使用 Google Stitch 设计界面,使用 Google AI Studio 氛围编程并部署应用,以及使用 Firebase 开发 AI 功能并在安全、可扩缩的后端中存储信息。

您将在此 Codelab 中构建的应用名为 Decide For Me,这是一款决策助手,可帮助优柔寡断的人做出生活选择(例如搬家、换工作或选择爱好)。用户输入自己面临的困境和生活中的优先事项,应用会使用 AI 帮助用户做出决定,尽可能减少长期失望。该应用还为用户提供了具体的第一步。应用的最终版本应如下所示:

“Decide For Me”应用的屏幕截图,其中显示了聊天界面和优先级面板

学习内容

  • 使用 Google Stitch 设计界面。
  • 使用 Google AI Studio 进行氛围编程,打造 Web 应用。
  • 使用 Firebase 开发 AI 功能并在云端存储信息。
  • 使用 Google AI Studio(由 Cloud Run 提供支持)将 Web 应用部署到生产环境。

2. 使用 Stitch 设计界面

  1. 下载视觉稿图片 (DecideForMeScreen.jpeg)。将其保存到本地文件夹中,以便您能找到它。
  2. 前往 Stitch,找到输入字段,然后选择 Web 选项。(在本 Codelab 中,您将专注于 Web 体验,但您也可以使用 Stitch 生成移动设备屏幕。)
  3. 上传视觉稿图片:
    1. 点击 +(添加按钮)。
    2. 选择上传文件。
    3. 附加您在设置步骤 (DecideForMeScreen.jpeg) 中下载的图片。通过这张手绘视觉稿,您可以测试 Stitch 的多模态功能。
  4. 复制以下提示并将其粘贴到输入字段中:
    # General Guidance
    Create a modern, clean, and highly polished UI for a web application called
    "Decide For Me" - a hyper-rational decision assistant.
    
    CRITICAL: Replicate the exact layout, structure, and element placement shown in
    the hand-drawn mockup file DecideForMeScreen.jpeg. Do not add any extra menus,
    sidebars, buttons, or top/bottom navigation bars that are not explicitly drawn
    in the file. Stick strictly to the skeleton provided in the mockup.
    
    # Layout & Structure
    - Two-Column Split Screen:
      - Left Side (Main Chat Area): Takes up roughly 70-75% of the screen width. It
        should feel like a premium, focused workspace.
      - Right Side (Configuration Panel): A sidebar taking up 25-30% of the screen
        width with a distinct, subtle background color to separate it from the
        chat.
    
    # Right Panel: Configuration Screen
    - Header: Title it "My Priorities" with a clean, minimalist typography.
    - Content Card: A styled card containing a text box or paragraph area
      showcasing the user's priorities.
    - Interactions: Include a clear "Edit Priorities" button. When clicked, this
      area should visually toggle into an editable textarea or input field.
    
    # Left Panel: Chat & Dilemma Decision Screen
    - Chat History: A clean vertical flow of message bubbles.
      - The first message bubble must be aligned to the left (system message) and
        say: "Tell me your dilemma". Use a friendly, neutral background color for
        this bubble.
    - Bottom Input Area: Instead of a traditional single-line chat bar, create a
      unified, beautiful "Decision Submission" layout positioned at the bottom:
      - Dual Input Fields: Place two horizontal or cleanly stacked input fields.
        - Input 1 label: "Option A"
        - Input 2 label: "Option B"
      - Action Button: A prominent, styled "Go" action button to trigger the
        reasoning loop.
    
    # Theme & Aesthetic
    - Vibe: Hyper-rational, clean, trustworthy, and modern. Use a sophisticated
      color palette (e.g., deep slates, clean whites/grays, and a sharp accent
      color like a subtle indigo or teal for active states and buttons).
    - Spacing & Typography: Use generous whitespace, soft rounded corners
      (border-radius) for cards and buttons, and a highly legible sans-serif font.
    
  5. 点击输入字段右下角的生成箭头。Stitch 会生成屏幕和整个设计体系,包括调色板、字体选项、图像学以及界面元素的整体风格:

Stitch 界面,显示生成的“帮我决定”界面设计和设计系统

3. 使用 Google AI Studio 构建应用

  1. 创建 Firebase 项目:
    1. 使用您在 Stitch 中使用的 Google 账号登录 Firebase 控制台。
    2. 点击相应按钮以创建新项目,然后输入项目名称(例如 Decider App)。
    3. 点击继续。
    4. 如果看到相关提示,请查看并接受 Firebase 条款,然后点击继续。
    5. (可选)在 Firebase 控制台中启用 AI 辅助功能(称为“Gemini in Firebase”)。
    6. 对于此 Codelab,您不需要使用 Google Analytics,因此请关闭 Google Analytics 选项。
    7. 点击创建项目,等待您的项目完成预配,然后点击继续。
  2. 将您在 Stitch 中构建的屏幕导出到 Google AI Studio:
    1. 在 Stitch 中点击生成的设计。
    2. 点击屏幕右上角的导出。
    3. 确认所选选项为 Google AI Studio。
    4. 向下滚动到说明字段。
  3. 复制以下提示并将其粘贴到说明字段中。将 [FIREBASE_PROJECT_ID] 替换为第 1 步中的实际项目 ID(如果您不记得项目 ID,可以在“项目设置”中找到):
    # General Guidance
    Build the "Decide For Me" app: A hyper-rational decision assistant for
    chronically indecisive people facing life choices (moving apartments, changing
    careers, picking a hobby). The user enters a dilemma and their top priorities
    in life. The app will help with the decision. Follow the instructions below to
    build it:
    
    # UI Instructions
    Using the design artifacts exported from Stitch (the PNG image and HTML file),
    build a fully functional web application that accurately mirrors the design and
    layout.
    
    # App Architecture & Initialization Instructions
    - Initialize the latest Firebase JS SDK for client-side services. Use the
      Firebase project with ID [FIREBASE_PROJECT_ID].
    - Enable Firebase Authentication in this project using the Google provider.
      If a user is not logged in, show a clean, minimalist sign-in state. If the
      user is logged in, take them directly to the dilemma decision screen.
    - Initialize Firebase App Check in debug mode with the following code:
      `self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;`
      `initializeAppCheck(app, { /* App Check options */ });`
    
    
    # State & Database Management Instructions
    - User Priorities:
      - Once authenticated, pull the user's saved priorities from Firebase
        Firestore at the path: `users/{userId}`. Each document should contain one
        string field: 'priorities'.
      - Bind this data to the Right Panel ("My Priorities").
      - When the user clicks the "Edit" button, toggle the view to a textarea, with
        a 'save' button. When saved, write the updated string back to
        `users/{userId}`.
      - Make sure to implement and deploy strong Security Rules for Firestore.
    
    # UI Stream Update & Display Instructions
    - Once the user submits option A and option B in the dilemma decision screen,
      display both options as a single message on the user side of the chat. Then,
      display a sleek loading state in the main chat panel. Leave the app in this
      "loading" state and do nothing else, we will process both options and build
      the server-side thinking later.
    
  4. 点击 Build with Google AI Studio(使用 Google AI Studio 构建)。这会在新标签页中打开 Google AI Studio,并带入您的设计文件和提示:
    1. 确认提示已完整转移。
    2. 如果您只看到部分提示,请再次粘贴整个提示。
  5. 点击构建。Google AI Studio 会根据您的提示和界面设计开始生成帮我决定应用:
    1. 在生成过程中,它会建议替代界面设计(在本 Codelab 中,请忽略这些设计,但您以后可以选择不同的设计)。
    2. 当系统提示您启用 Firebase 时,点击启用。
  6. 检查并验证生成的应用:
    1. 在预览标签页中测试应用。
    2. 切换到代码标签页,查看所有生成的文件和代码。
    3. Google AI Studio 还创建了一个 Firebase 项目,启用了 Firebase Authentication 和 Firestore,并在您的代码库中配置了 Firebase。您将在本 Codelab 的下一步中访问和使用此 Firebase 项目。

4. 注册 App Check 调试令牌

Google AI Studio 生成应用时,会创建一个 Firebase 项目并将您的应用关联到该项目。您需要访问此 Firebase 项目,并向一项名为 Firebase App Check 的重要安全服务注册您的开发环境。

访问您的 Firebase 项目

  1. 找到由 Google AI Studio 创建的 Firebase 项目的项目 ID:
    1. 在 Google AI Studio 中切换到代码标签页。
    2. 打开 firebase-applet-config.json 文件。
    3. 复制 projectId 字段的值。
  2. 前往 Firebase 控制台,然后使用此 ID 搜索项目。

注册调试令牌

您的应用可以使用 Firebase App Check 来确保传入流量仅来自合法应用,从而保护后端服务和 AI 模型免遭滥用。

由于您的应用在 Google AI Studio 预览环境中运行,因此它会使用 App Check 调试提供程序 (self.FIREBASE_APPCHECK_DEBUG_TOKEN = true)。Web 应用加载后,Firebase 会自动将调试令牌输出到浏览器的开发者控制台。

  1. 查找调试令牌:
    1. 在 Google AI Studio 中,在查看应用预览时打开浏览器的开发者工具:
      • Chrome、Edge 或 Firefox:按 F12(或右键点击预览中的任意位置,然后选择检查),然后选择控制台标签页。
      • macOS:按 Cmd+Option+I,然后选择控制台标签页。
    2. 在控制台日志中,找到 App Check 调试消息:
      AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678".
      You will need to safelist it in the Firebase console for it to work.
      
    3. 复制令牌字符串(不带引号)。
  2. 注册调试令牌:
    1. 在 Firebase 控制台中,依次前往安全性 > App Check > 应用标签页。
    2. 在列表中找到您的 Web 应用,点击三点状菜单 (⋮),然后选择管理调试令牌。
    3. 点击添加调试令牌,粘贴复制的令牌,输入名称(例如 Google AI Studio Preview),然后点击保存。
    Firebase 控制台中“管理调试令牌”菜单项的屏幕截图

5. 测试应用

现在,您的项目已关联,并且您的调试令牌已在 App Check 中注册,接下来请测试基准功能:Authentication 和 Firestore。

  1. 测试用户身份验证并保存优先级:
    1. 在 Google AI Studio 的帮我决定应用预览中,使用 Google 账号登录,测试身份验证界面。
    2. 使用右侧面板(我的优先事项)保存您的人生优先事项。
  2. 在 Firebase 控制台中验证身份验证:
    1. 前往 Firebase 控制台,然后打开身份验证。
    2. 确认您在“Decide For Me”应用中用于身份验证的 Google 账号已列在其中:
    Firebase 控制台 Authentication 页面,其中显示了经过身份验证的 Google 账号
  3. 验证 Firestore 数据存储:
    1. 在 Firebase 控制台中打开 Firestore。
    2. 确认您的优先级存储在 users/{userId} 路径下的文档中:
    Firebase 控制台 Firestore 数据库,其中显示了存储在 users/{userId} 下的优先级

6. 使用 Firebase 构建 AI 赋能的 Decider 流程

您的应用将使用 AI 来赋能其帮我决定操作。您可以使用 Firebase 构建此 AI 赋能的 Decider 流程。

设置 Firebase AI Logic

  1. 在 Firebase AI Logic 中启用 Gemini Developer API:
    1. 在 Firebase 控制台中打开 Firebase AI Logic,然后点击开始使用。
    2. 选择 Gemini Developer API,然后按照控制台中的说明启用该 API。
  2. 配置 Firebase AI Logic 设置:
    1. 前往设置标签页。
    2. 将强制执行“仅模板”模式选项切换为强制执行。
    3. 将强制执行“已通过身份验证的用户”模式选项切换为强制执行。

创建服务器提示模板

在此 Codelab 中,您将使用服务器提示模板,通过 Firebase AI Logic 与 Gemini API 进行交互。

在继续使用模板之前,请先查看以下内容,了解为什么在服务器端存储模型配置、系统指令和提示非常重要:

  • 保护知识产权:将提示词从客户端设备中移除,并将其安全地存储在后端。
  • 防范提示词注入攻击:客户端只能通过后端架构验证来填充特定变量。
  • 无需发布应用即可更新:您可以在控制台中更新提示、系统指令和模型配置,而无需发布新的应用版本。

下面介绍了如何创建和测试服务器提示模板:

  1. 创建服务器提示模板:
    1. 前往提示模板标签页。
    2. 点击创建模板。
    3. 选择空白模板。
    4. 使用以下信息创建您的第一个模板:
      • 模板名称:Decider Flow
      • 模板 ID: decider-flow
      • 配置 (frontmatter)
        model: "gemini-3.5-flash-lite"
        input:
          schema:
            priorities: "string, user's core priorities"
            optionA: "string, option A under consideration"
            optionB: "string, option B under consideration"
        output:
          format: json
          schema:
            verdict: string
            justification: string
            firstStep: string
        
      • 提示和(可选)系统指令
        {role "system"}
        You are the Decider Agent, a multi-stage reasoning engine that
        combines the roles of an honest and polite behavioral economist, a
        long-term strategic forecaster, and an executive decision coach.
        Your job is to take a user's dilemma and their core priorities, run
        them through a rigorous, adversarial 3-phase thinking process, and
        output a highly analytical, reasoning-backed final verdict. You must be
        direct, sharp, and realistic. Do not give generic platitudes or claim
        that "both options are great." You must force a clear choice.
        
        {role "user"}
        # Context & Inputs
        You are analyzing a critical life decision for the user. Base your
        entire multi-phase reasoning flow strictly on these three specific
        inputs:
        - User's Core Priorities: {{priorities}}
        - Option A under consideration: {{optionA}}
        - Option B under consideration: {{optionB}}
        
        Execute your reasoning flow through the following three phases:
        
        # Phase 1: Cynical Breakdown (Input-Driven Analysis)
        Analyze {{optionA}} and {{optionB}} strictly through the lens of the
        user's explicit {{priorities}}. Do not evaluate them in a vacuum.
        - Identify the hidden flaws, compromises, and psychological costs
          embedded in both choices.
        - Pinpoint exactly how {{optionA}} could directly conflict with or
          undermine their {{priorities}}.
        - Pinpoint exactly how {{optionB}} could directly conflict with or
          undermine their {{priorities}}.
        - Uncover any cognitive biases (like status quo bias or loss aversion)
          the user might be falling for in either option.
        
        # Phase 2: Long-Term Regret Projection
        Project the user 5 years into the future. Apply the Regret Minimization
        Framework to both paths:
        - The {{optionA}} Timeline: Quantify the absolute worst-case, deep,
          structural 5-year regret of choosing this path. Focus heavily on
          failures of courage vs. failures of action based on their
          {{priorities}}.
        - The {{optionB}} Timeline: Quantify the matching 5-year regret for
          this path.
        - Contrast these two timelines. Which option carries the kind of regret
          that fundamentally breaks the user's {{priorities}}?
        
        # Phase 3: Final Recommendation & Action Step
        Synthesize the cynical critiques and long-term regret scores.
        Weigh them against the user's {{priorities}} to determine which
        choice minimizes long-term disappointment.
        - Verdict: You must declare either {{optionA}} or {{optionB}} as the
          definitive winner. No compromise, no "it depends," and no hybrid
          options.
        - Justification: Provide a sharp, reasoning-backed explanation showing why
          the losing option was eliminated based on the Phase 1 and Phase 2
          analysis.
        - First Step: Give one microscopic, low-friction task the user can
          execute within the next 15 minutes to commit to or move toward the
          chosen verdict.
        
        在 {role "system"} 和 {role "user"} 周围添加额外的 {},以正确的语法编写系统指令和提示:9db2a4f2c5cf2ec7.png
      • 测试输入
        {
          "priorities": "Be financially stable, have a good work-life balance where I can travel twice a year",
          "optionA": "Buy a house for 615000 British pounds with a mortgage of 2800 per month for the next 35 years",
          "optionB": "Keep renting for 2400 per month for the foreseeable"
        }
        
  2. 点击保存模板。
  3. 测试模板:
    1. 点击运行提示测试。
    2. 找到测试回答,并检查其中是否包含您在提示中指定的所有字段(verdict、justification 和 firstStep)。
    3. 如果一切都符合预期回答,请使用模板右上角的锁形图标锁定模板,以确保版本稳定性并防止意外修改。

您的模板已可供应用使用!

7. 在应用中使用 Decider 提示模板

让您的 Web 应用使用该模板:

  1. 返回 Google AI Studio 中的应用。
  2. 让 Google AI Studio 智能体实现帮我决定操作:
    1. 复制以下提示:
      Now let's implement the "Decide For Me" button action. When clicked, it
      should call the Firebase AI Logic SDK using a Template Generative Model.
      The prompt is stored in a prompt template with the id "decider-flow". When
      calling the API, pass the following variables as the input payload object:
      - priorities
      - optionA
      - optionB
      
      The API will return a JSON object. Handle the response asynchronously and
      extract:
      - verdict
      - justification
      - firstStep
      
      Once the data is received, update the UI state to append a new message to
      the chat array. Ensure it renders as a system chat bubble positioned on
      the left side of the chat screen, mapping these three fields clearly into
      the bubble's layout.
      
      Please provide the necessary front-end component state updates and the
      Firebase SDK call.
      
    2. 将提示粘贴到 Google AI Studio 对话输入框中,然后点击发送。
  3. 验证配置并测试决策助理:
    1. 等待 Google AI Studio 完成向应用添加 Firebase AI Logic 的操作。
    2. 切换到代码标签页,确保 firebase-applet-config.json 文件中包含 API 密钥。如果配置文件中没有 Firebase API 密钥,请让 Google AI Studio 导入该密钥。
    3. 切换到预览标签页
    4. 提交选项 A 和 B,并验证 AI 是否返回了决策结果、理由和第一步。

作为参考,Google AI Studio 生成的代码应如下所示:

const aiInstance = getAI(app);
const templateModel = getTemplateGenerativeModel(aiInstance);

const result = await templateModel.generateContent('decider-flow', {
  priorities: priorities,
  optionA: optA,
  optionB: optB
});

const rawText = result.response.text();

// Parse response text to extract fields
const cleaned = rawText.replace(/```json|```/g, '').trim();
const parsedData: { verdict?: string; justification?: string; firstStep?: string } = JSON.parse(cleaned);

const verdict = parsedData.verdict;
const justification = parsedData.justification;
const firstStep = parsedData.firstStep;

调试和监控请求

如果您的应用遇到错误、无法生成回答,或者您想详细检查 API 流量,请使用 Firebase AI Logic 的内置分析和监控工具:

  1. 在 Firebase 控制台中,依次前往 AI 服务 > AI Logic > AI 监控标签页。
  2. 在信息中心内查看量化指标:
    • 请求量和状态:验证传入请求是否到达后端并返回 200 OK,或因客户端或服务器错误而失败。
    • 延迟时间:查看延迟时间图表,检查端到端响应时间。
    • Token 数量:监控每个请求的输入和输出 token 用量。
  3. 检查各个请求跟踪记录,以进行深度调试:在跟踪记录表中点击特定请求跟踪记录,即可检查其载荷。
    • 输入:确认变量(priorities、optionA 和 optionB)已从客户端应用正确传递。
    • 输出:查看模型生成的原始文本,验证其是否返回了与架构匹配的有效 JSON。
    • 错误详情:如果请求失败,请查看跟踪记录错误日志,了解失败原因,例如 App Check 令牌无效、身份验证被拒、配额限制或提示验证错误。
  4. 排查和解决 Google AI Studio 的问题:
    • 如果您在跟踪记录中发现错误(例如,JSON 响应解析格式错误或缺少参数),请复制出错提示或载荷。
    • 返回 Google AI Studio,提示助理修复应用代码中的相应问题。

8. 可选:部署应用

现在,您的应用可在预览模式下运行,请将其部署到生产环境。

如需在生产环境中保护 Firebase 端点,请配置一个生产环境认证提供方,以便与 Firebase App Check 搭配使用(在本 Codelab 中,您将使用 reCAPTCHA v3)。

您需要先部署应用,以获取其确切的实际网址,这样您就可以向 reCAPTCHA 注册特定网域,而不是允许所有 ai.studio 应用。

部署应用并配置 reCAPTCHA:

  1. 使用 Google AI Studio 部署 Web 应用:
    1. 在 Google AI Studio 中,点击顶部导航栏中的发布。
    2. 点击开始使用,查看或自定义应用名称和说明,然后点击发布应用。
    3. 等待 Google AI Studio 构建并部署您的应用(通常需要 1-2 分钟)。
    4. 复制生成的实时个性化网址(例如 https://decide-for-me-123.ai.studio),并记下其网域(例如 decide-for-me-123.ai.studio)。
  2. 在 Google reCAPTCHA 中创建 reCAPTCHA v3 密钥:
    1. 前往 Google reCAPTCHA 管理控制台。
    2. 输入标签(例如 Decide For Me - Production)。
    3. 依次选择 reCAPTCHA 类型 > reCAPTCHA v3(基于分数)。
    4. 在网域部分中,添加应用的确切部署网域(例如 decide-for-me-123.ai.studio,省略 https:// 和任何路径),或者添加自定义网域(如果您打算使用自定义网域)。
    5. 接受服务条款,然后点击提交。
    6. 请保持此标签页处于打开状态:您需要同时使用网站密钥(公开客户端密钥)和密钥(私有服务器密钥)。
  3. 在 Firebase 控制台中注册您的密钥:
    1. 前往 Firebase 控制台中的 App Check。
    2. 前往应用标签页。
    3. 在列表中找到您的 Web 应用,点击该应用(或点击三点状菜单 ⋮),然后选择 reCAPTCHA v3。
    4. 将 reCAPTCHA 密钥粘贴到相应字段中,然后点击保存。
  4. 将客户端应用配置为使用 ReCaptchaV3Provider:
    1. 在 Google AI Studio 中,切换到聊天面板,并提示助理更新 App Check 配置,以便用于生产环境:
      Please update our Firebase App Check initialization to use
      ReCaptchaV3Provider with the reCAPTCHA site key "YOUR_RECAPTCHA_SITE_KEY",
      while retaining support for debug tokens in non-production environments.
      
    2. 如果您直接在代码标签页中查看代码,请确保您的 App Check 初始化代码与以下结构一致:
      import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
      
      const appCheck = initializeAppCheck(app, {
        provider: new ReCaptchaV3Provider("YOUR_RECAPTCHA_SITE_KEY"),
        isTokenAutoRefreshEnabled: true
      });
      
    3. 更新代码后,在 Google AI Studio 中重新发布应用,以便将更新后的 App Check 配置推送到线上网站。
  5. 验证生产流量并监控 App Check:
    1. 在无痕式浏览器窗口中打开您的实时应用网址,使用 Google 账号登录,然后测试提交一个两难问题。
    2. 返回 Firebase 控制台中的 App Check,然后查看 API 和监控标签页,验证 Firestore 和 Firebase AI Logic 的请求是否已成功注册。

9. 总结

恭喜!您使用 Google Builder Stack 中的工具,从头开始构建了一个具有 AI 功能的实用应用。这只是一个开始,您还可以使用 Google 工具完成更多工作。您现在拥有了一个 Firebase + Google Cloud 云项目;探索所有可用的服务!

访问此链接,领取“完成构建者之旅”徽章!

如需继续您的学习之旅,请前往 goo.gle/builders,开始下一个实验。

如果您已经在使用 Antigravity 2.0(Google 专用于并行编排多个自主智能体的平台),则可以快速从 Google AI Studio 导出项目,并将其导入 Antigravity,以便在本地继续处理。Antigravity 提供了 Agent Skills for Firebase,可一键安装。这些技能还提供移动开发支持,可帮助您在 Android 和 iOS 环境中复制此应用(如果您愿意)。