ساخت برنامه‌های هوش مصنوعی با اکوسیستم گوگل، ساخت برنامه‌های هوش مصنوعی با اکوسیستم گوگل، ساخت برنامه‌های هوش مصنوعی با اکوسیستم گوگل

۱. قبل از شروع

توسعه نرم‌افزار تکامل یافته است. موفق‌ترین توسعه‌دهندگان فقط کد نمی‌نویسند؛ بلکه ابزارها و عوامل هوش مصنوعی را برای ساخت بهتر و سریع‌تر هماهنگ می‌کنند. اکوسیستم ابزارهای گوگل مجموعه‌ای جامع برای کل چرخه عمر ارائه می‌دهد: تولید رابط کاربری، نمونه‌سازی و استقرار برنامه، توسعه ویژگی‌های هوش مصنوعی و ادغام امن و مقیاس‌پذیر backend. در این آزمایشگاه کد، از Google Stitch برای طراحی رابط کاربری، Google AI Studio برای کدنویسی و استقرار برنامه و Firebase برای توسعه ویژگی‌های هوش مصنوعی و ذخیره اطلاعات در یک backend امن و مقیاس‌پذیر استفاده خواهید کرد.

اپلیکیشنی که قرار است در این آزمایشگاه کد بسازید، «برای من تصمیم بگیر» نام دارد - یک دستیار تصمیم‌گیری برای افراد مردد که با انتخاب‌های زندگی (مانند جابجایی آپارتمان، تغییر شغل یا انتخاب یک سرگرمی) روبرو هستند. کاربر وارد یک دوراهی و اولویت‌های خود در زندگی می‌شود و اپلیکیشن از هوش مصنوعی برای کمک به کاربر در تصمیم‌گیری بر اساس آنچه ناامیدی طولانی‌مدت را به حداقل می‌رساند، استفاده می‌کند. این اپلیکیشن همچنین یک گام اولیه مشخص به کاربر می‌دهد. نسخه نهایی اپلیکیشن شما باید شبیه به این باشد:

تصویر برنامه Decide For Me که رابط چت و پنل اولویت‌ها را نشان می‌دهد

آنچه یاد خواهید گرفت

  • طراحی رابط کاربری با گوگل استیچ
  • وایب با استفاده از گوگل هوش مصنوعی استودیو، یک اپلیکیشن وب کدنویسی کرد.
  • از Firebase برای توسعه ویژگی‌های هوش مصنوعی و ذخیره اطلاعات در فضای ابری استفاده کنید.
  • با استفاده از Google AI Studio (با پشتیبانی Cloud Run) یک برنامه وب را در محیط عملیاتی مستقر کنید.

۲. طراحی رابط کاربری با Stitch

  1. تصویر نمونه ( DecideForMeScreen.jpeg ) را دانلود کنید. آن را در یک پوشه محلی که بتوانید آن را پیدا کنید، ذخیره کنید.
  2. به Stitch بروید، فیلد ورودی را پیدا کنید و گزینه 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 که طراحی و سیستم طراحی رابط کاربری Decide For Me تولید شده را نشان می‌دهد

۳. ساخت اپلیکیشن با Google AI Studio

  1. صفحه‌ای که در Stitch ساخته‌اید را به Google AI Studio منتقل کنید:
    1. روی طرح تولید شده در Stitch کلیک کنید.
    2. روی «صادرات» در گوشه سمت راست بالای صفحه کلیک کنید.
    3. تأیید کنید که گزینه انتخاب شده Google AI Studio است.
    4. به پایین اسکرول کنید تا به فیلد توضیحات برسید.
  2. عبارت زیر را کپی کرده و در قسمت توضیحات پیست کنید:
    # 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 Firebase JS SDK for client-side services.
    - Set up Firebase Authentication 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
      (`self.FIREBASE_APPCHECK_DEBUG_TOKEN = true`) without a ReCaptchaV3Provider
      (we will add that later).
    
    # 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.
    
  3. روی «ساخت با Google AI Studio» کلیک کنید. این کار Google AI Studio را در یک برگه جدید باز می‌کند و فایل‌های طراحی شما را منتقل می‌کند و پیام زیر را نمایش می‌دهد:
    1. تأیید کنید که دستورالعمل به طور کامل منتقل شده است.
    2. اگر فقط بخشی از اعلان را می‌بینید، کل اعلان را دوباره جای‌گذاری کنید.
  4. روی ساخت (Build) کلیک کنید. گوگل هوش مصنوعی استودیو (Google AI Studio) شروع به تولید برنامه‌ی «برای من تصمیم بگیر» (Decid For Me) بر اساس درخواست و طراحی رابط کاربری شما می‌کند:
    1. در حین تولید، طرح‌های رابط کاربری جایگزین را پیشنهاد می‌دهد (این طرح‌ها را برای این آزمایشگاه کد نادیده بگیرید، اما می‌توانید در آینده طرح‌های دیگری را انتخاب کنید).
    2. وقتی از شما خواسته شد Firebase را فعال کنید، روی Enable کلیک کنید.
  5. برنامه تولید شده را بررسی و تأیید کنید:
    1. برنامه را در برگه پیش‌نمایش آزمایش کنید.
    2. برای بررسی تمام فایل‌ها و کدهای تولید شده، به برگه Code بروید.
    3. استودیوی هوش مصنوعی گوگل همچنین یک پروژه Firebase ایجاد کرده، احراز هویت Firebase و Firestore را فعال کرده و Firebase را در پایگاه کد خود پیکربندی کرده است. در مرحله بعدی این آزمایشگاه کد، به این پروژه Firebase دسترسی خواهید داشت و با آن کار خواهید کرد.

۴. اپلیکیشن خود را ثبت کنید. توکن اشکال‌زدایی را بررسی کنید.

وقتی Google AI Studio برنامه را تولید می‌کند، یک پروژه Firebase ایجاد می‌کند و برنامه شما را به آن متصل می‌کند. شما باید به این پروژه Firebase دسترسی پیدا کنید و محیط توسعه خود را در یک سرویس امنیتی مهم به نام Firebase App Check ثبت کنید.

به پروژه Firebase خود دسترسی پیدا کنید

  1. شناسه پروژه Firebase ایجاد شده توسط Google AI Studio را پیدا کنید:
    1. به برگه Code در Google AI Studio بروید.
    2. فایل firebase-applet-config.json را باز کنید.
    3. مقدار فیلد projectId را کپی کنید.
  2. به کنسول Firebase بروید و با استفاده از این شناسه، پروژه را جستجو کنید.

توکن اشکال‌زدایی خود را ثبت کنید

برنامه شما می‌تواند از Firebase App Check برای محافظت از سرویس‌های backend و مدل‌های هوش مصنوعی خود در برابر سوءاستفاده استفاده کند، به این صورت که اطمینان حاصل کند ترافیک ورودی فقط از برنامه‌های مشروع سرچشمه می‌گیرد.

از آنجا که برنامه شما در محیط پیش‌نمایش Google AI Studio اجرا می‌شود، از ارائه‌دهنده اشکال‌زدایی App Check استفاده می‌کند ( self.FIREBASE_APPCHECK_DEBUG_TOKEN = true ). هنگامی که برنامه وب بارگذاری می‌شود، Firebase به طور خودکار یک توکن اشکال‌زدایی را به کنسول توسعه‌دهنده مرورگر شما ارسال می‌کند.

  1. توکن اشکال‌زدایی خود را پیدا کنید:
    1. در Google AI Studio، هنگام مشاهده پیش‌نمایش برنامه، ابزارهای توسعه‌دهنده مرورگر خود را باز کنید:
      • کروم، اج یا فایرفاکس: کلید F12 را فشار دهید (یا در هر قسمتی از پیش‌نمایش کلیک راست کرده و گزینه Inspect را انتخاب کنید)، و سپس تب Console را انتخاب کنید.
      • macOS: کلیدهای Cmd+Option+I را فشار دهید و سپس تب Console را انتخاب کنید.
    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. در کنسول فایربیس، به بخش امنیت > بررسی برنامه > تب برنامه‌ها بروید.
    2. برنامه وب خود را در لیست پیدا کنید، روی منوی سه نقطه ( ⋮ ) کلیک کنید و مدیریت توکن‌های اشکال‌زدایی را انتخاب کنید.
    3. روی افزودن توکن اشکال‌زدایی کلیک کنید، توکن کپی‌شده خود را جای‌گذاری کنید، نامی مانند Google AI Studio Preview وارد کنید و روی ذخیره (Save) کلیک کنید.
    تصویری از آیتم منوی مدیریت توکن‌های اشکال‌زدایی در کنسول فایربیس

۵. اپلیکیشن را تست کنید

اکنون که پروژه شما متصل شده و توکن اشکال‌زدایی شما در App Check ثبت شده است، ویژگی‌های پایه: احراز هویت و Firestore را آزمایش کنید.

  1. احراز هویت کاربر را آزمایش کنید و اولویت‌های ذخیره را ذخیره کنید:
    1. در پیش‌نمایش برنامه‌ی Decide For Me در Google AI Studio، با ورود به سیستم با یک حساب Google، صفحه‌ی احراز هویت را آزمایش کنید.
    2. با استفاده از پنل سمت راست ( اولویت‌های من )، اولویت‌های زندگی خود را ذخیره کنید.
  2. تأیید اعتبار در کنسول Firebase:
    1. به کنسول Firebase بروید و Authentication را باز کنید.
    2. تأیید کنید که حساب گوگلی که برای تأیید اعتبار در برنامه Decide For Me استفاده کرده‌اید، در آنجا فهرست شده است:
    صفحه احراز هویت کنسول فایربیس که حساب گوگل احراز هویت شده را نشان می‌دهد
  3. تأیید ذخیره سازی داده های Firestore:
    1. Firestore را در کنسول Firebase باز کنید.
    2. تأیید کنید که اولویت‌های شما در سندی در مسیر users/{userId} ذخیره شده‌اند:
    کنسول فایربیس، پایگاه داده فایراستور که اولویت‌های ذخیره شده در زیر users/{userId} را نشان می‌دهد.

۶. با استفاده از Firebase یک جریان تصمیم‌گیرنده مبتنی بر هوش مصنوعی بسازید

برنامه شما از هوش مصنوعی برای تقویت عملکردهای « برای من تصمیم بگیر» (Decid For Me) استفاده خواهد کرد. می‌توانید از فایربیس (Firebase) برای ساخت این جریان «تصمیم‌گیر» مبتنی بر هوش مصنوعی استفاده کنید.

تنظیم منطق هوش مصنوعی فایربیس

  1. فعال کردن Gemini Developer API در Firebase AI Logic:
    1. Firebase AI Logic را در کنسول Firebase باز کنید و سپس روی Get started کلیک کنید.
    2. Gemini Developer API را انتخاب کنید و دستورالعمل‌های موجود در کنسول را برای فعال کردن API دنبال کنید.
  2. تنظیمات منطق هوش مصنوعی فایربیس را پیکربندی کنید:
    1. به برگه تنظیمات بروید.
    2. گزینه حالت Enforce template-only را به Enforced تغییر دهید.
    3. گزینه حالت Enforce authenticated-users را به Enforced تغییر دهید.

یک الگوی اعلان سرور ایجاد کنید

در این آزمایشگاه کد، از قالب‌های اعلان سرور برای تعاملات خود با API Gemini از طریق Firebase AI Logic استفاده خواهید کرد.

قبل از اینکه با الگو ادامه دهید، موارد زیر را مرور کنید تا بفهمید چرا ذخیره پیکربندی مدل، دستورالعمل‌های سیستم و اعلان‌ها در سمت سرور مهم است:

  • حفاظت از مالکیت معنوی: اعلان‌ها را از دستگاه کلاینت خارج کرده و آنها را در پشت صحنه ایمن نگه می‌دارد.
  • جلوگیری از حملات تزریق سریع: کلاینت فقط می‌تواند متغیرهای خاصی را با اعتبارسنجی طرحواره backend پر کند.
  • به‌روزرسانی بدون انتشار نسخه جدید برنامه: می‌توانید اعلان‌ها، دستورالعمل‌های سیستم و پیکربندی‌های مدل را در کنسول و بدون انتشار نسخه جدید برنامه به‌روزرسانی کنید.

در اینجا نحوه ایجاد و آزمایش یک الگوی اعلان سرور آورده شده است:

  1. الگوی اعلان سرور را ایجاد کنید:
    1. به برگه الگوهای اعلان بروید.
    2. روی ایجاد الگو کلیک کنید.
    3. قالب خالی را انتخاب کنید.
    4. با استفاده از اطلاعات زیر، اولین الگوی خود را ایجاد کنید:
      • نام الگو: جریان تصمیم‌گیرنده
      • شناسه الگو: decider-flow
      • پیکربندی (مقدمه)
        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. پاسخ آزمایشی (Test response) را پیدا کنید و بررسی کنید که تمام فیلدهایی که در اعلان (premium) مشخص کرده‌اید ( verdict (redict)، justification ) و firstStep )) را داشته باشد.
    3. اگر همه چیز با پاسخ مورد انتظار مطابقت داشت، قالب را با استفاده از نماد قفل در گوشه بالا سمت راست قالب قفل کنید تا از پایداری نسخه اطمینان حاصل شود و از تغییرات تصادفی جلوگیری شود.

قالب شما آماده استفاده توسط برنامه شماست!

۷. از الگوی دستور تصمیم‌گیری در برنامه استفاده کنید

کاری کنید که برنامه وب شما از الگو استفاده کند:

  1. به برنامه خود در Google AI Studio برگردید.
  2. از نماینده‌ی استودیوی هوش مصنوعی گوگل بخواهید که اقدام «برای من تصمیم بگیر» را پیاده‌سازی کند:
    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. به تب Code بروید و مطمئن شوید که یک کلید API در فایل firebase-applet-config.json شما وجود دارد. اگر کلید API Firebase در فایل پیکربندی نیست، از Google AI Studio بخواهید آن را وارد کند.
    3. به برگه پیش‌نمایش بروید
    4. گزینه‌های الف و ب را ارسال کنید و تأیید کنید که هوش مصنوعی، حکم تصمیم، توجیه و مرحله اول را برمی‌گرداند.

برای مرجع، کد تولید شده توسط 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. در کنسول فایربیس، به بخش سرویس‌های هوش مصنوعی > منطق هوش مصنوعی > تب نظارت بر هوش مصنوعی بروید.
  2. معیارهای کمی را در داشبورد بررسی کنید:
    • حجم و وضعیت درخواست‌ها: بررسی کنید که آیا درخواست‌های ورودی به بک‌اند می‌رسند و آیا 200 OK را برمی‌گردانند یا با خطاهای کلاینت یا سرور مواجه می‌شوند.
    • تأخیر: نمودار تأخیر را بررسی کنید تا زمان پاسخ سرتاسری را بررسی کنید.
    • تعداد توکن‌ها: نظارت بر میزان استفاده از توکن‌های ورودی و خروجی به ازای هر درخواست.
  3. بررسی رد درخواست‌های منفرد برای اشکال‌زدایی عمیق: برای بررسی بار مفید (payload) یک رد درخواست خاص در جدول ردها، روی آن کلیک کنید.
    • ورودی‌ها: تأیید کنید که متغیرها ( priorities ، optionA و optionB ) به درستی از برنامه‌ی کلاینت ارسال شده‌اند.
    • خروجی‌ها: متن خام تولید شده توسط مدل را مشاهده کنید تا تأیید کنید که آیا JSON معتبری را مطابق با طرحواره برگردانده است یا خیر.
    • جزئیات خطا: اگر درخواستی با شکست مواجه شد، گزارش خطای ردیابی را برای دلایلی مانند توکن‌های نامعتبر App Check، رد احراز هویت، محدودیت‌های سهمیه یا خطاهای اعتبارسنجی سریع بررسی کنید.
  4. عیب‌یابی و حل مشکلات با Google AI Studio:
    • اگر در ردیابی خطایی شناسایی کردید (برای مثال، تجزیه نادرست پاسخ JSON یا پارامترهای از دست رفته)، پیام خطا یا payload را کپی کنید.
    • به Google AI Studio برگردید و از دستیار بخواهید مشکل مربوطه را در کد برنامه برطرف کند.

۸. اختیاری: استقرار برنامه

حالا که برنامه شما در حالت پیش‌نمایش کار می‌کند، آن را به محیط عملیاتی (production) منتقل کنید.

برای محافظت از نقاط پایانی Firebase خود در محیط عملیاتی، یک ارائه‌دهنده گواهی تولید را برای استفاده با Firebase App Check پیکربندی کنید (در این آزمایشگاه کد، از reCAPTCHA نسخه ۳ استفاده خواهید کرد).

شما ابتدا باید برنامه خود را مستقر کنید تا URL دقیق آن را بدست آورید تا بتوانید دامنه خاص را با reCAPTCHA ثبت کنید و دیگر نیازی به اجازه دادن به همه برنامه‌های ai.studio نباشد.

برنامه خود را مستقر کنید و reCAPTCHA را پیکربندی کنید:

  1. برنامه وب را با Google AI Studio مستقر کنید:
    1. در Google AI Studio، روی Publish در نوار ناوبری بالا کلیک کنید.
    2. روی شروع کار کلیک کنید، نام و توضیحات برنامه را مرور یا سفارشی کنید و روی انتشار برنامه خود کلیک کنید.
    3. منتظر بمانید تا Google AI Studio برنامه شما را بسازد و مستقر کند (معمولاً ۱ تا ۲ دقیقه).
    4. آدرس اینترنتی (URL) ایجاد شده را کپی کنید (برای مثال، https://decide-for-me-123.ai.studio ) و دامنه آن را یادداشت کنید (برای مثال، decide-for-me-123.ai.studio ).
  2. ایجاد کلیدهای reCAPTCHA نسخه ۳ در Google reCAPTCHA:
    1. به کنسول مدیریت reCAPTCHA گوگل بروید.
    2. یک برچسب وارد کنید (برای مثال، Decide For Me - Production ).
    3. نوع reCAPTCHA را انتخاب کنید > reCAPTCHA نسخه ۳ (مبتنی بر امتیاز) .
    4. در بخش دامنه‌ها ، دامنه‌ی دقیق پیاده‌سازی‌شده‌ی برنامه‌ی خود (برای مثال، decide-for-me-123.ai.studio ، بدون حذف https:// و هرگونه مسیر) یا یک دامنه‌ی سفارشی در صورت تمایل به استفاده از آن را اضافه کنید.
    5. شرایط خدمات را بپذیرید و روی ارسال کلیک کنید.
    6. این برگه را باز نگه دارید: شما به هر دو کلید سایت (کلید عمومی کلاینت) و کلید مخفی (کلید خصوصی سرور) نیاز خواهید داشت.
  3. کلید مخفی خود را در کنسول Firebase ثبت کنید:
    1. در کنسول فایربیس به بخش بررسی برنامه (App Check) بروید.
    2. به برگه برنامه‌ها بروید.
    3. برنامه وب خود را در لیست پیدا کنید، روی آن کلیک کنید (یا روی منوی سه نقطه ⋮ کلیک کنید) و 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. اگر کد را مستقیماً در تب Code بررسی می‌کنید، مطمئن شوید که مقداردهی اولیه 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. ترافیک عملیاتی را تأیید کنید و بررسی برنامه را نظارت کنید:
    1. آدرس اینترنتی (URL) برنامه‌ی زنده‌ی خود را در یک پنجره‌ی مرورگر ناشناس باز کنید، با حساب گوگل خود وارد شوید و ارسال یک مشکل را امتحان کنید.
    2. به بخش App Check در کنسول Firebase برگردید و تب‌های API و Monitoring را بررسی کنید تا مطمئن شوید درخواست‌ها با موفقیت برای Firestore و Firebase AI Logic ثبت شده‌اند.

۹. نتیجه‌گیری

تبریک! شما یک برنامه مفید با ویژگی‌های هوش مصنوعی را از ابتدا و با استفاده از ابزارهای موجود در Builder Stack گوگل ساختید. این فقط آغاز کار است؛ کارهای بسیار بیشتری می‌توانید با ابزارهای گوگل انجام دهید. اکنون یک پروژه Firebase + Google Cloud دارید؛ تمام سرویس‌های موجود برای خود را بررسی کنید!

برای دریافت نشان Completed Builder Journey به این لینک مراجعه کنید!

برای ادامه سفرتان، برای آزمایشگاه بعدی به goo.gle/builders بروید.

اگر از قبل از Antigravity 2.0 ، پلتفرم اختصاصی گوگل برای هماهنگ‌سازی چندین عامل مستقل به صورت موازی، استفاده می‌کنید، می‌توانید به سرعت پروژه خود را از Google AI Studio صادر کرده و آن را به Antigravity وارد کنید تا به صورت محلی روی آن کار کنید. Antigravity مهارت‌های عامل برای Firebase را برای نصب با یک کلیک در دسترس دارد. این مهارت‌ها همچنین از توسعه موبایل پشتیبانی می‌کنند که به شما کمک می‌کند در صورت تمایل، این برنامه را در محیط‌های اندروید و iOS تکرار کنید.

،

۱. قبل از شروع

توسعه نرم‌افزار تکامل یافته است. موفق‌ترین توسعه‌دهندگان فقط کد نمی‌نویسند؛ بلکه ابزارها و عوامل هوش مصنوعی را برای ساخت بهتر و سریع‌تر هماهنگ می‌کنند. اکوسیستم ابزارهای گوگل مجموعه‌ای جامع برای کل چرخه عمر ارائه می‌دهد: تولید رابط کاربری، نمونه‌سازی و استقرار برنامه، توسعه ویژگی‌های هوش مصنوعی و ادغام امن و مقیاس‌پذیر backend. در این آزمایشگاه کد، از Google Stitch برای طراحی رابط کاربری، Google AI Studio برای کدنویسی و استقرار برنامه و Firebase برای توسعه ویژگی‌های هوش مصنوعی و ذخیره اطلاعات در یک backend امن و مقیاس‌پذیر استفاده خواهید کرد.

اپلیکیشنی که قرار است در این آزمایشگاه کد بسازید، «برای من تصمیم بگیر» نام دارد - یک دستیار تصمیم‌گیری برای افراد مردد که با انتخاب‌های زندگی (مانند جابجایی آپارتمان، تغییر شغل یا انتخاب یک سرگرمی) روبرو هستند. کاربر وارد یک دوراهی و اولویت‌های خود در زندگی می‌شود و اپلیکیشن از هوش مصنوعی برای کمک به کاربر در تصمیم‌گیری بر اساس آنچه ناامیدی طولانی‌مدت را به حداقل می‌رساند، استفاده می‌کند. این اپلیکیشن همچنین یک گام اولیه مشخص به کاربر می‌دهد. نسخه نهایی اپلیکیشن شما باید شبیه به این باشد:

تصویر برنامه Decide For Me که رابط چت و پنل اولویت‌ها را نشان می‌دهد

آنچه یاد خواهید گرفت

  • طراحی رابط کاربری با گوگل استیچ
  • وایب با استفاده از گوگل هوش مصنوعی استودیو، یک اپلیکیشن وب کدنویسی کرد.
  • از Firebase برای توسعه ویژگی‌های هوش مصنوعی و ذخیره اطلاعات در فضای ابری استفاده کنید.
  • با استفاده از Google AI Studio (با پشتیبانی Cloud Run) یک برنامه وب را در محیط عملیاتی مستقر کنید.

۲. طراحی رابط کاربری با Stitch

  1. تصویر نمونه ( DecideForMeScreen.jpeg ) را دانلود کنید. آن را در یک پوشه محلی که بتوانید آن را پیدا کنید، ذخیره کنید.
  2. به Stitch بروید، فیلد ورودی را پیدا کنید و گزینه 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 که طراحی و سیستم طراحی رابط کاربری Decide For Me تولید شده را نشان می‌دهد

۳. ساخت اپلیکیشن با Google AI Studio

  1. صفحه‌ای که در Stitch ساخته‌اید را به Google AI Studio منتقل کنید:
    1. روی طرح تولید شده در Stitch کلیک کنید.
    2. روی «صادرات» در گوشه سمت راست بالای صفحه کلیک کنید.
    3. تأیید کنید که گزینه انتخاب شده Google AI Studio است.
    4. به پایین اسکرول کنید تا به فیلد توضیحات برسید.
  2. عبارت زیر را کپی کرده و در قسمت توضیحات پیست کنید:
    # 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 Firebase JS SDK for client-side services.
    - Set up Firebase Authentication 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
      (`self.FIREBASE_APPCHECK_DEBUG_TOKEN = true`) without a ReCaptchaV3Provider
      (we will add that later).
    
    # 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.
    
  3. روی «ساخت با Google AI Studio» کلیک کنید. این کار Google AI Studio را در یک برگه جدید باز می‌کند و فایل‌های طراحی شما را منتقل می‌کند و پیام زیر را نمایش می‌دهد:
    1. تأیید کنید که دستورالعمل به طور کامل منتقل شده است.
    2. اگر فقط بخشی از اعلان را می‌بینید، کل اعلان را دوباره جای‌گذاری کنید.
  4. روی ساخت (Build) کلیک کنید. گوگل هوش مصنوعی استودیو (Google AI Studio) شروع به تولید برنامه‌ی «برای من تصمیم بگیر» (Decid For Me) بر اساس درخواست و طراحی رابط کاربری شما می‌کند:
    1. در حین تولید، طرح‌های رابط کاربری جایگزین را پیشنهاد می‌دهد (این طرح‌ها را برای این آزمایشگاه کد نادیده بگیرید، اما می‌توانید در آینده طرح‌های دیگری را انتخاب کنید).
    2. وقتی از شما خواسته شد Firebase را فعال کنید، روی Enable کلیک کنید.
  5. برنامه تولید شده را بررسی و تأیید کنید:
    1. برنامه را در برگه پیش‌نمایش آزمایش کنید.
    2. برای بررسی تمام فایل‌ها و کدهای تولید شده، به برگه Code بروید.
    3. استودیوی هوش مصنوعی گوگل همچنین یک پروژه Firebase ایجاد کرده، احراز هویت Firebase و Firestore را فعال کرده و Firebase را در پایگاه کد خود پیکربندی کرده است. در مرحله بعدی این آزمایشگاه کد، به این پروژه Firebase دسترسی خواهید داشت و با آن کار خواهید کرد.

۴. اپلیکیشن خود را ثبت کنید. توکن اشکال‌زدایی را بررسی کنید.

وقتی Google AI Studio برنامه را تولید می‌کند، یک پروژه Firebase ایجاد می‌کند و برنامه شما را به آن متصل می‌کند. شما باید به این پروژه Firebase دسترسی پیدا کنید و محیط توسعه خود را در یک سرویس امنیتی مهم به نام Firebase App Check ثبت کنید.

به پروژه Firebase خود دسترسی پیدا کنید

  1. شناسه پروژه Firebase ایجاد شده توسط Google AI Studio را پیدا کنید:
    1. به برگه Code در Google AI Studio بروید.
    2. فایل firebase-applet-config.json را باز کنید.
    3. مقدار فیلد projectId را کپی کنید.
  2. به کنسول Firebase بروید و با استفاده از این شناسه، پروژه را جستجو کنید.

توکن اشکال‌زدایی خود را ثبت کنید

برنامه شما می‌تواند از Firebase App Check برای محافظت از سرویس‌های backend و مدل‌های هوش مصنوعی خود در برابر سوءاستفاده استفاده کند، به این صورت که اطمینان حاصل کند ترافیک ورودی فقط از برنامه‌های مشروع سرچشمه می‌گیرد.

از آنجا که برنامه شما در محیط پیش‌نمایش Google AI Studio اجرا می‌شود، از ارائه‌دهنده اشکال‌زدایی App Check استفاده می‌کند ( self.FIREBASE_APPCHECK_DEBUG_TOKEN = true ). هنگامی که برنامه وب بارگذاری می‌شود، Firebase به طور خودکار یک توکن اشکال‌زدایی را به کنسول توسعه‌دهنده مرورگر شما ارسال می‌کند.

  1. توکن اشکال‌زدایی خود را پیدا کنید:
    1. در Google AI Studio، هنگام مشاهده پیش‌نمایش برنامه، ابزارهای توسعه‌دهنده مرورگر خود را باز کنید:
      • کروم، اج یا فایرفاکس: کلید F12 را فشار دهید (یا در هر قسمتی از پیش‌نمایش کلیک راست کرده و گزینه Inspect را انتخاب کنید)، و سپس تب Console را انتخاب کنید.
      • macOS: کلیدهای Cmd+Option+I را فشار دهید و سپس تب Console را انتخاب کنید.
    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. در کنسول فایربیس، به بخش امنیت > بررسی برنامه > تب برنامه‌ها بروید.
    2. برنامه وب خود را در لیست پیدا کنید، روی منوی سه نقطه ( ⋮ ) کلیک کنید و مدیریت توکن‌های اشکال‌زدایی را انتخاب کنید.
    3. روی افزودن توکن اشکال‌زدایی کلیک کنید، توکن کپی‌شده خود را جای‌گذاری کنید، نامی مانند Google AI Studio Preview وارد کنید و روی ذخیره (Save) کلیک کنید.
    تصویری از آیتم منوی مدیریت توکن‌های اشکال‌زدایی در کنسول فایربیس

۵. اپلیکیشن را تست کنید

اکنون که پروژه شما متصل شده و توکن اشکال‌زدایی شما در App Check ثبت شده است، ویژگی‌های پایه: احراز هویت و Firestore را آزمایش کنید.

  1. احراز هویت کاربر را آزمایش کنید و اولویت‌های ذخیره را ذخیره کنید:
    1. در پیش‌نمایش برنامه‌ی Decide For Me در Google AI Studio، با ورود به سیستم با یک حساب Google، صفحه‌ی احراز هویت را آزمایش کنید.
    2. با استفاده از پنل سمت راست ( اولویت‌های من )، اولویت‌های زندگی خود را ذخیره کنید.
  2. تأیید اعتبار در کنسول Firebase:
    1. به کنسول Firebase بروید و Authentication را باز کنید.
    2. تأیید کنید که حساب گوگلی که برای تأیید اعتبار در برنامه Decide For Me استفاده کرده‌اید، در آنجا فهرست شده است:
    صفحه احراز هویت کنسول فایربیس که حساب گوگل احراز هویت شده را نشان می‌دهد
  3. تأیید ذخیره سازی داده های Firestore:
    1. Firestore را در کنسول Firebase باز کنید.
    2. تأیید کنید که اولویت‌های شما در سندی در مسیر users/{userId} ذخیره شده‌اند:
    کنسول فایربیس، پایگاه داده فایراستور که اولویت‌های ذخیره شده در زیر users/{userId} را نشان می‌دهد.

۶. با استفاده از Firebase یک جریان تصمیم‌گیرنده مبتنی بر هوش مصنوعی بسازید

برنامه شما از هوش مصنوعی برای تقویت عملکردهای « برای من تصمیم بگیر» (Decid For Me) استفاده خواهد کرد. می‌توانید از فایربیس (Firebase) برای ساخت این جریان «تصمیم‌گیر» مبتنی بر هوش مصنوعی استفاده کنید.

تنظیم منطق هوش مصنوعی فایربیس

  1. فعال کردن Gemini Developer API در Firebase AI Logic:
    1. Firebase AI Logic را در کنسول Firebase باز کنید و سپس روی Get started کلیک کنید.
    2. Gemini Developer API را انتخاب کنید و دستورالعمل‌های موجود در کنسول را برای فعال کردن API دنبال کنید.
  2. تنظیمات منطق هوش مصنوعی فایربیس را پیکربندی کنید:
    1. به برگه تنظیمات بروید.
    2. گزینه حالت Enforce template-only را به Enforced تغییر دهید.
    3. گزینه حالت Enforce authenticated-users را به Enforced تغییر دهید.

یک الگوی اعلان سرور ایجاد کنید

در این آزمایشگاه کد، از قالب‌های اعلان سرور برای تعاملات خود با API Gemini از طریق Firebase AI Logic استفاده خواهید کرد.

قبل از اینکه با الگو ادامه دهید، موارد زیر را مرور کنید تا بفهمید چرا ذخیره پیکربندی مدل، دستورالعمل‌های سیستم و اعلان‌ها در سمت سرور مهم است:

  • حفاظت از مالکیت معنوی: اعلان‌ها را از دستگاه کلاینت خارج کرده و آنها را در پشت صحنه ایمن نگه می‌دارد.
  • جلوگیری از حملات تزریق سریع: کلاینت فقط می‌تواند متغیرهای خاصی را با اعتبارسنجی طرحواره backend پر کند.
  • به‌روزرسانی بدون انتشار نسخه جدید برنامه: می‌توانید اعلان‌ها، دستورالعمل‌های سیستم و پیکربندی‌های مدل را در کنسول و بدون انتشار نسخه جدید برنامه به‌روزرسانی کنید.

در اینجا نحوه ایجاد و آزمایش یک الگوی اعلان سرور آورده شده است:

  1. الگوی اعلان سرور را ایجاد کنید:
    1. به برگه الگوهای اعلان بروید.
    2. روی ایجاد الگو کلیک کنید.
    3. قالب خالی را انتخاب کنید.
    4. با استفاده از اطلاعات زیر، اولین الگوی خود را ایجاد کنید:
      • نام الگو: جریان تصمیم‌گیرنده
      • شناسه الگو: decider-flow
      • پیکربندی (مقدمه)
        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. پاسخ آزمایشی (Test response) را پیدا کنید و بررسی کنید که تمام فیلدهایی که در اعلان (premium) مشخص کرده‌اید ( verdict (redict)، justification ) و firstStep )) را داشته باشد.
    3. اگر همه چیز با پاسخ مورد انتظار مطابقت داشت، قالب را با استفاده از نماد قفل در گوشه بالا سمت راست قالب قفل کنید تا از پایداری نسخه اطمینان حاصل شود و از تغییرات تصادفی جلوگیری شود.

قالب شما آماده استفاده توسط برنامه شماست!

۷. از الگوی دستور تصمیم‌گیری در برنامه استفاده کنید

کاری کنید که برنامه وب شما از الگو استفاده کند:

  1. به برنامه خود در Google AI Studio برگردید.
  2. از نماینده‌ی استودیوی هوش مصنوعی گوگل بخواهید که اقدام «برای من تصمیم بگیر» را پیاده‌سازی کند:
    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. به تب Code بروید و مطمئن شوید که یک کلید API در فایل firebase-applet-config.json شما وجود دارد. اگر کلید API Firebase در فایل پیکربندی نیست، از Google AI Studio بخواهید آن را وارد کند.
    3. به برگه پیش‌نمایش بروید
    4. گزینه‌های الف و ب را ارسال کنید و تأیید کنید که هوش مصنوعی، حکم تصمیم، توجیه و مرحله اول را برمی‌گرداند.

برای مرجع، کد تولید شده توسط 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. در کنسول فایربیس، به بخش سرویس‌های هوش مصنوعی > منطق هوش مصنوعی > تب نظارت بر هوش مصنوعی بروید.
  2. معیارهای کمی را در داشبورد بررسی کنید:
    • حجم و وضعیت درخواست‌ها: بررسی کنید که آیا درخواست‌های ورودی به بک‌اند می‌رسند و آیا 200 OK را برمی‌گردانند یا با خطاهای کلاینت یا سرور مواجه می‌شوند.
    • تأخیر: نمودار تأخیر را بررسی کنید تا زمان پاسخ سرتاسری را بررسی کنید.
    • تعداد توکن‌ها: نظارت بر میزان استفاده از توکن‌های ورودی و خروجی به ازای هر درخواست.
  3. بررسی رد درخواست‌های منفرد برای اشکال‌زدایی عمیق: برای بررسی بار مفید (payload) یک رد درخواست خاص در جدول ردها، روی آن کلیک کنید.
    • ورودی‌ها: تأیید کنید که متغیرها ( priorities ، optionA و optionB ) به درستی از برنامه‌ی کلاینت ارسال شده‌اند.
    • خروجی‌ها: متن خام تولید شده توسط مدل را مشاهده کنید تا تأیید کنید که آیا JSON معتبری را مطابق با طرحواره برگردانده است یا خیر.
    • جزئیات خطا: اگر درخواستی با شکست مواجه شد، گزارش خطای ردیابی را برای دلایلی مانند توکن‌های نامعتبر App Check، رد احراز هویت، محدودیت‌های سهمیه یا خطاهای اعتبارسنجی سریع بررسی کنید.
  4. عیب‌یابی و حل مشکلات با Google AI Studio:
    • اگر در ردیابی خطایی شناسایی کردید (برای مثال، تجزیه نادرست پاسخ JSON یا پارامترهای از دست رفته)، پیام خطا یا payload را کپی کنید.
    • به Google AI Studio برگردید و از دستیار بخواهید مشکل مربوطه را در کد برنامه برطرف کند.

۸. اختیاری: استقرار برنامه

حالا که برنامه شما در حالت پیش‌نمایش کار می‌کند، آن را به محیط عملیاتی (production) منتقل کنید.

برای محافظت از نقاط پایانی Firebase خود در محیط عملیاتی، یک ارائه‌دهنده گواهی تولید را برای استفاده با Firebase App Check پیکربندی کنید (در این آزمایشگاه کد، از reCAPTCHA نسخه ۳ استفاده خواهید کرد).

شما ابتدا باید برنامه خود را مستقر کنید تا URL دقیق آن را بدست آورید تا بتوانید دامنه خاص را با reCAPTCHA ثبت کنید و دیگر نیازی به اجازه دادن به همه برنامه‌های ai.studio نباشد.

برنامه خود را مستقر کنید و reCAPTCHA را پیکربندی کنید:

  1. برنامه وب را با Google AI Studio مستقر کنید:
    1. در Google AI Studio، روی Publish در نوار ناوبری بالا کلیک کنید.
    2. روی شروع کار کلیک کنید، نام و توضیحات برنامه را مرور یا سفارشی کنید و روی انتشار برنامه خود کلیک کنید.
    3. Wait for Google AI Studio to build and deploy your app (typically 1–2 minutes).
    4. Copy the generated live vanity URL (for example, https://decide-for-me-123.ai.studio ) and note its domain (for example, decide-for-me-123.ai.studio ).
  2. Create reCAPTCHA v3 keys in Google reCAPTCHA:
    1. Go to the Google reCAPTCHA Admin Console .
    2. Enter a Label (for example, Decide For Me - Production ).
    3. Select reCAPTCHA type > reCAPTCHA v3 (Score-based) .
    4. In the Domains section, add your app's exact deployed domain (for example, decide-for-me-123.ai.studio , omitting https:// and any paths) or a custom domain if you plan to use one.
    5. Accept the terms of service and click Submit .
    6. Keep this tab open: you'll need both the Site Key (public client key) and the Secret Key (private server key).
  3. Register your secret key in the Firebase console:
    1. Go to App Check in the Firebase console.
    2. Go to the Apps tab.
    3. Locate your web application in the list, click it (or click the three-dot menu ⋮ ), and select reCAPTCHA v3 .
    4. Paste your reCAPTCHA Secret Key into the field and click Save .
  4. Configure the client app to use ReCaptchaV3Provider :
    1. In Google AI Studio, switch to the chat panel and prompt the assistant to update your App Check configuration for production:
      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. If you review the code directly in the Code tab, ensure your App Check initialization matches this structure:
      import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
      
      const appCheck = initializeAppCheck(app, {
        provider: new ReCaptchaV3Provider("YOUR_RECAPTCHA_SITE_KEY"),
        isTokenAutoRefreshEnabled: true
      });
      
    3. After updating the code, republish your app in Google AI Studio to push the updated App Check configuration to your live site.
  5. Verify production traffic and monitor App Check:
    1. Open your live app URL in an incognito browser window, sign in with Google, and test submitting a dilemma.
    2. Return to App Check in the Firebase console, and inspect the APIs and Monitoring tabs to verify that requests are successfully registered for Firestore and Firebase AI Logic.

۹. نتیجه‌گیری

Congratulations! You built a useful app with AI features from scratch, using tools in Google's Builder Stack. This is only the beginning; there's much more you can do with Google tools. You now have a Firebase + Google Cloud project; explore all the services available to you!

Visit this link to claim the Completed Builder Journey badge!

To continue your journey, head to goo.gle/builders for your next lab.

If you're already using Antigravity 2.0 , Google's dedicated platform to orchestrate multiple autonomous agents in parallel, you can quickly export your project from Google AI Studio and import it into Antigravity to keep working on it locally. Antigravity has Agent Skills for Firebase available to install with one click. These skills also offer support for mobile development, which helps you replicate this app in both Android and iOS environments if you want to.

،

1. Before you begin

Software development has evolved. The most successful developers don't only write code; they orchestrate AI tools and agents to build better and faster. Google's ecosystem of tools provides a comprehensive suite for the entire lifecycle: UI generation, app prototyping and deployment, AI feature development, and secure, scalable backend integration. In this codelab, you'll use Google Stitch to design the UI, Google AI Studio to vibe code and deploy the app, and Firebase to develop AI features and store information in a secure, scalable backend.

The app you're going to build in this codelab is called Decide For Me —a decision assistant for indecisive people facing life choices (such as moving apartments, changing careers, or picking a hobby). The user enters a dilemma and their priorities in life, and the app uses AI to help the user decide based on what minimizes long-term disappointment. The app also gives the user a concrete first step. The final version of your app should be similar to this:

Screenshot of the Decide For Me application showing the chat interface and priorities panel

آنچه یاد خواهید گرفت

  • Design UIs with Google Stitch.
  • Vibe code a web app with Google AI Studio.
  • Use Firebase to develop AI features and store information in the cloud.
  • Deploy a web app to production with Google AI Studio (powered by Cloud Run).

2. Design the UI with Stitch

  1. Download the mockup image ( DecideForMeScreen.jpeg ). Save it to a local folder where you can find it.
  2. Go to Stitch , locate the input field, and select the Web option. (For this codelab, you'll focus on the web experience, but you can also use Stitch to generate mobile screens.)
  3. Upload the mockup image:
    1. Click + (the add button).
    2. Select Upload Files .
    3. Attach the image you downloaded in the setup step ( DecideForMeScreen.jpeg ). This hand-drawn mockup lets you test Stitch's multimodal capabilities.
  4. Copy the following prompt and paste it into the input field:
    # 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. Click the generate arrow in the bottom-right corner of the input field. Stitch generates the screen and an entire design system, including a color palette, font options, iconography, and the general feel for UI elements:

Stitch interface showing the generated Decide For Me UI design and design system

3. Build the app with Google AI Studio

  1. Export the screen you built in Stitch to Google AI Studio:
    1. Click the generated design in Stitch.
    2. Click Export in the top-right corner of the screen.
    3. Confirm that the selected option is Google AI Studio .
    4. Scroll down to the Description field.
  2. Copy the following prompt and paste it into the Description field:
    # 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 Firebase JS SDK for client-side services.
    - Set up Firebase Authentication 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
      (`self.FIREBASE_APPCHECK_DEBUG_TOKEN = true`) without a ReCaptchaV3Provider
      (we will add that later).
    
    # 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.
    
  3. Click Build with Google AI Studio . This opens Google AI Studio in a new tab and carries over your design files and prompt:
    1. Confirm that the prompt was fully carried over.
    2. If you see only part of the prompt, paste the entire prompt again.
  4. Click Build . Google AI Studio starts generating the Decide For Me app according to your prompt and UI design:
    1. While it generates, it suggests alternative UI designs (ignore these designs for this codelab, but you can opt for different designs in the future).
    2. When prompted to enable Firebase, click Enable .
  5. Inspect and verify the generated app:
    1. Test the app in the Preview tab.
    2. Switch to the Code tab to review all generated files and code.
    3. Google AI Studio has also created a Firebase project, enabled Firebase Authentication and Firestore , and configured Firebase in your codebase. You'll access and work with this Firebase project in the next step of this codelab.

4. Register your App Check debug token

When Google AI Studio generates the app, it creates a Firebase project and connects your app to it. You need to access this Firebase project and register your development environment with an important security service called Firebase App Check.

Access your Firebase project

  1. Find the project ID of the Firebase project created by Google AI Studio:
    1. Switch to the Code tab in Google AI Studio.
    2. Open the firebase-applet-config.json file.
    3. Copy the value of the projectId field.
  2. Go to the Firebase console and search for the project using this ID.

Register your debug token

Your app can use Firebase App Check to protect your backend services and AI models from abuse by ensuring that incoming traffic originates only from legitimate apps.

Because your app is running in the Google AI Studio preview environment, it uses the App Check debug provider ( self.FIREBASE_APPCHECK_DEBUG_TOKEN = true ). When the web app loads, Firebase automatically outputs a debug token to your browser's developer console.

  1. Find your debug token:
    1. In Google AI Studio, open your browser's developer tools while viewing your app preview:
      • Chrome, Edge, or Firefox: Press F12 (or right-click anywhere in the preview and select Inspect ), and then select the Console tab.
      • macOS: Press Cmd+Option+I, and then select the Console tab.
    2. In the console logs, locate the App Check debug message:
      AppCheck debug token: "123a4567-b89c-12d3-e456-789012345678".
      You will need to safelist it in the Firebase console for it to work.
      
    3. Copy the token string (without the quotes).
  2. Register your debug token:
    1. In the Firebase console, go to Security > App Check > Apps tab .
    2. Find your web app in the list, click the three-dot menu ( ⋮ ), and select Manage debug tokens .
    3. Click Add debug token , paste your copied token, enter a name such as Google AI Studio Preview , and click Save .
    تصویری از آیتم منوی مدیریت توکن‌های اشکال‌زدایی در کنسول فایربیس

5. Test the app

Now that your project is connected and your debug token is registered with App Check, test the baseline features: Authentication and Firestore.

  1. Test user authentication and save priorities:
    1. In the Decide For Me app preview in Google AI Studio, test the authentication screen by signing in with a Google Account.
    2. Save your life priorities using the right panel ( My Priorities ).
  2. Verify authentication in the Firebase console:
    1. Go to the Firebase console and open Authentication .
    2. Confirm that the Google Account you used to authenticate in the Decide For Me app is listed there:
    Firebase console Authentication page showing the authenticated Google Account
  3. Verify Firestore data storage:
    1. Open Firestore in the Firebase console.
    2. Confirm that your priorities are stored in a document under the users/{userId} path:
    Firebase console Firestore database showing priorities stored under users/{userId}

6. Build an AI-powered Decider flow using Firebase

Your app will use AI to power its Decide For Me actions. You can use Firebase to build this AI-powered Decider flow.

Set up Firebase AI Logic

  1. Enable the Gemini Developer API in Firebase AI Logic:
    1. Open Firebase AI Logic in the Firebase console, and then click Get started .
    2. Select Gemini Developer API and follow the instructions in the console to enable the API.
  2. Configure Firebase AI Logic settings:
    1. Go to the Settings tab.
    2. Toggle the Enforce template-only mode option to Enforced .
    3. Toggle the Enforce authenticated-users mode option to Enforced .

Create a server prompt template

In this codelab, you'll use server prompt templates for your interactions with the Gemini API via Firebase AI Logic.

Before you proceed with the template, review the following to understand why storing model configuration, system instructions, and prompts server-side is important:

  • Protecting intellectual property: Pulls prompts off the client device and keeps them secure on the backend.
  • Preventing prompt injection attacks: The client can only fill in specific variables with backend schema validation.
  • Updating without app releases: You can update prompts, system instructions, and model configurations in the console without releasing a new app version.

Here's how you create and test a server prompt template:

  1. Create the server prompt template:
    1. Go to the Prompt templates tab.
    2. Click Create template .
    3. Select Blank template .
    4. Create your first template using the following information:
      • Template name: Decider Flow
      • Template ID: decider-flow
      • Configuration (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
        
      • Prompt and (optional) system instructions
        {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.
        
        Add an extra {} around {role "system"} and {role "user"} to write your system instructions and prompt in the correct syntax: 9db2a4f2c5cf2ec7.png
      • Test input
        {
          "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. Click Save template .
  3. Test the template:
    1. Click Run prompt test .
    2. Locate the Test response and check that it has all the fields you specified in the prompt ( verdict , justification , and firstStep ).
    3. If everything matches the expected response, lock the template using the lock icon in the top-right corner of the template to ensure version stability and prevent accidental modifications.

Your template is ready to be used by your app!

7. Use the Decider prompt template in the app

Make your web app use the template:

  1. Go back to your app in Google AI Studio.
  2. Ask the Google AI Studio agent to implement the Decide For Me action:
    1. Copy the following prompt:
      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. Paste the prompt into the Google AI Studio chat input and click Send .
  3. Verify configuration and test the decision assistant:
    1. Wait until Google AI Studio finishes adding Firebase AI Logic to your app.
    2. Switch to the Code tab and make sure there's an API key in your firebase-applet-config.json file. If the Firebase API key isn't in the configuration file, ask Google AI Studio to import it.
    3. Switch to the Preview tab
    4. Submit options A and B, and verify that the AI returns the decision verdict, justification, and first step.

For reference, the code generated by Google AI Studio should look similar to this:

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;

Debug and monitor requests

If your app encounters errors, fails to generate a response, or you want to inspect API traffic in detail, use Firebase AI Logic's built-in analytics and monitoring tools:

  1. In the Firebase console, go to AI Services > AI Logic > AI monitoring tab .
  2. Check quantitative metrics on the dashboard:
    • Request volume and status: Verify whether incoming requests reach the backend and return 200 OK or fail with client or server errors.
    • Latency: Inspect the latency graph to check end-to-end response time.
    • Token counts: Monitor input and output token usage per request.
  3. Inspect individual request traces for deep debugging:Click a specific request trace in the traces table to inspect its payload.
    • Inputs: Confirm that the variables ( priorities , optionA , and optionB ) were correctly passed from the client app.
    • Outputs: View the raw text generated by the model to verify whether it returned valid JSON matching the schema.
    • Error details: If a request fails, check the trace error log for reasons such as invalid App Check tokens, authentication rejection, quota limits, or prompt validation errors.
  4. Troubleshoot and resolve issues with Google AI Studio:
    • If you identify an error in the trace (for example, malformed JSON response parsing or missing parameters), copy the error message or payload.
    • Return to Google AI Studio and prompt the assistant to fix the corresponding issue in the app code.

8. Optional: Deploy the app

Now that your app works in preview mode, deploy it to production.

To protect your Firebase endpoints in production, configure a production attestation provider for use with Firebase App Check (in this codelab, you'll use reCAPTCHA v3 ).

You need to deploy your app first to obtain its exact live URL so that you can register the specific domain with reCAPTCHA rather than allowing all ai.studio apps.

Deploy your app and configure reCAPTCHA:

  1. Deploy the web app with Google AI Studio:
    1. In Google AI Studio, click Publish in the top navigation bar.
    2. Click Get started , review or customize the application name and description, and click Publish your app .
    3. Wait for Google AI Studio to build and deploy your app (typically 1–2 minutes).
    4. Copy the generated live vanity URL (for example, https://decide-for-me-123.ai.studio ) and note its domain (for example, decide-for-me-123.ai.studio ).
  2. Create reCAPTCHA v3 keys in Google reCAPTCHA:
    1. Go to the Google reCAPTCHA Admin Console .
    2. Enter a Label (for example, Decide For Me - Production ).
    3. Select reCAPTCHA type > reCAPTCHA v3 (Score-based) .
    4. In the Domains section, add your app's exact deployed domain (for example, decide-for-me-123.ai.studio , omitting https:// and any paths) or a custom domain if you plan to use one.
    5. Accept the terms of service and click Submit .
    6. Keep this tab open: you'll need both the Site Key (public client key) and the Secret Key (private server key).
  3. Register your secret key in the Firebase console:
    1. Go to App Check in the Firebase console.
    2. Go to the Apps tab.
    3. Locate your web application in the list, click it (or click the three-dot menu ⋮ ), and select reCAPTCHA v3 .
    4. Paste your reCAPTCHA Secret Key into the field and click Save .
  4. Configure the client app to use ReCaptchaV3Provider :
    1. In Google AI Studio, switch to the chat panel and prompt the assistant to update your App Check configuration for production:
      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. If you review the code directly in the Code tab, ensure your App Check initialization matches this structure:
      import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
      
      const appCheck = initializeAppCheck(app, {
        provider: new ReCaptchaV3Provider("YOUR_RECAPTCHA_SITE_KEY"),
        isTokenAutoRefreshEnabled: true
      });
      
    3. After updating the code, republish your app in Google AI Studio to push the updated App Check configuration to your live site.
  5. Verify production traffic and monitor App Check:
    1. Open your live app URL in an incognito browser window, sign in with Google, and test submitting a dilemma.
    2. Return to App Check in the Firebase console, and inspect the APIs and Monitoring tabs to verify that requests are successfully registered for Firestore and Firebase AI Logic.

۹. نتیجه‌گیری

Congratulations! You built a useful app with AI features from scratch, using tools in Google's Builder Stack. This is only the beginning; there's much more you can do with Google tools. You now have a Firebase + Google Cloud project; explore all the services available to you!

Visit this link to claim the Completed Builder Journey badge!

To continue your journey, head to goo.gle/builders for your next lab.

If you're already using Antigravity 2.0 , Google's dedicated platform to orchestrate multiple autonomous agents in parallel, you can quickly export your project from Google AI Studio and import it into Antigravity to keep working on it locally. Antigravity has Agent Skills for Firebase available to install with one click. These skills also offer support for mobile development, which helps you replicate this app in both Android and iOS environments if you want to.