ساخت و ساز با گوگل آنتی گراویتی

۱. مقدمه

گوگل آنتی‌گراویتی (Google Antigravity) یک IDE عامل‌گرا از گوگل است. در شروع کار با کدلب آنتی‌گراویتی ، می‌توانید اصول اولیه آنتی‌گراویتی را بیاموزید. در این کدلب، ما از آنتی‌گراویتی برای ساخت برنامه‌های واقعی استفاده خواهیم کرد. ما از تحقیقات ساده وب به سمت تولید برنامه‌های فول‌استک و تست‌های واحد در سطح سازمانی حرکت خواهیم کرد.

پیش‌نیازها:

  • گوگل آنتی گراویتی نصب و پیکربندی شده است.
  • Basic understanding of Google Antigravity. It is recommended to complete the codelab: Getting Started with Google Antigravity .

۲. درباره موارد استفاده

از آنجایی که شما درک اولیه‌ای از Antigravity دارید، بیایید به چند مورد استفاده بپردازیم تا آن را در عمل ببینیم. توجه داشته باشید که Antigravity یک پلتفرم Agent-first است. این بدان معناست که در بیشتر موارد، ما به سادگی به Agent دستور می‌دهیم و Agent سپس به تنهایی شروع به کار می‌کند، وظیفه خود را انجام می‌دهد، در صورت نیاز درخواست مجوز می‌کند، مصنوعات را تولید می‌کند و سپس در صورت انجام وظیفه به ما اطلاع می‌دهد. در نتیجه، ما نمی‌توانیم هر خروجی مکالمه Agent را در هر یک از موارد استفاده زیر تولید کنیم. ما دستورالعمل‌ها و چند تصویر لازم از نتایج مورد انتظار را به اشتراک خواهیم گذاشت، اما نتایج شما ممکن است کمی متفاوت باشد.

The use cases that we will cover range from automating a few tasks with external sites, to generating and verifying unit test cases for a project, to a full web site development. Let's go.

۳. اخبار مهم

This is a simple use case but it can be the basis via which you can use the web browser to visit web sites, extract information, do some actions and then return data to the user.

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

ابتدا، برای شروع، پوشه‌ای با نام news-hightlights ایجاد کنید. در Antigravity، به Agent Manager بروید و پوشه تازه ایجاد شده خود را به عنوان یک فضای کاری با دکمه Add Workspace وارد کنید:

3935bb43b5112f71.png

Start a new conversation in the newly imported news-highlights workspace:

840c9d014bd4b8d8.png

Then give the following instruction: " visit news.google.com and get me the highlights at the moment. "

8513d489eea0b014.png

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

9d594588f2ffe6bc.png

Once it's done with its work, you should also see the Artifacts getting generated, as shown below:

d6cf4e7d8425df8.png

نمونه‌ای از اجرای برنامه توسط Agent در زیر نشان داده شده است:

fb7397cd2cce0682.png

Notice that on the left, we have the Thought process, you can also scroll through the points and view the playback and other data.

چیزهایی که باید امتحان کنید

  • وقتی این را فهمیدید، وب‌سایتی را انتخاب کنید که در دسترس است و می‌خواهید نماینده به آن مراجعه کند و برخی داده‌ها را از آن دریافت/خلاصه کند. وب‌سایتی را در نظر بگیرید که می‌دانید داشبورد و نمودار دارد و از آن بخواهید چند مقدار را انتخاب کند.
  • دستور زیر را امتحان کنید: Visit https://docs.cloud.google.com/release-notes and get me a summary of the release notes, categorized by product.

۴. ایجاد یک وب‌سایت پویا با پایتون + فلاسک

حالا بیایید یک برنامه وب کامل ایجاد کنیم. برنامه وب که قرار است ایجاد کنیم، سایتی است که اطلاعات مربوط به یک رویداد فنی یک روزه را ارائه می‌دهد، که در طول روز توسط چندین سخنران صحبت می‌شود.

یک بار دیگر، یک پوشه جدید به نام conference-website ایجاد کنید. مطمئن شوید که در Agent Manager هستید و فضای کاری conference-website را وارد و انتخاب کرده‌اید. همچنین حالت Planning را اضافه کنید تا مطمئن شوید که agent قبل از اجرا برنامه‌ریزی می‌کند.

دستور زیر را بدهید:

I would like to generate a website that is a 1-day technical conference informational site.

The website should have the following functionality:
        1. A home page that shows the current date, location, schedule and time table.
        2. The 1-day event is a list of 8 talks in total.
        3. Each talk has 1 or 2 max. speakers. 
        4. A talk has an ID, Title, Speakers, Category (1 or 2), Description and time of the talk.
        5. Each speaker has a First Name, Last Name and LinkedIn url.
        6. Allow for users to search by category, speaker, title.
        7. Give a lunch break of 60 minutes.
        8. Use dummy data for events and speakers, come up with a schedule, the event is about Google Cloud Technologies.
        9. Tech Stack: Python and Flask framework on server side. Front-end is basic HTML, CSS and JavaScript. 
        10. Test out the site on your own for all functionality and provide a detailed README on how to setup, run and make any further changes. 
11. Launch the web application for me to review. 

You can begin the conversation by giving the above prompt:

As the Agent goes about its task, it will proceed with creating the artifacts:

  • مصنوع وظیفه
  • مصنوع پیاده‌سازی
  • مصنوعات پیاده روی

مصنوع وظیفه‌ای که در زیر آورده شده است، توالی اولیه وظایفی است که عامل بر اساس وظیفه‌ای که به او داده شده بود، رمزگشایی کرد و باید انجام دهد. نمونه‌ای از تصویر اجرا در زیر نشان داده شده است:

c95d82e1c040698f.png

سپس می‌توانید روی مصنوع طرح اجرا کلیک کنید. نمونه‌ای از تصویر در زیر نشان داده شده است:

632169a236bc62cc.png

And finally, you have the Walkthrough artifact. It contains all that the Agent did as shown below:

e3f6152d6f54d4f9.png

Notice that it has started the server and has provided me the URL, which I click and I have the application, a sample screenshot is shown below:

abf879f2ce53d055.png

اگر به ویرایشگر بروم، متوجه خواهید شد که پوشه‌ای که برنامه پایتون فلاسک در آن تولید می‌شود در آن قرار دارد. همچنین متوجه خواهید شد که Agent mode در سمت راست برچسب‌گذاری شده است و می‌توانید مکالمه را در آنجا نیز ادامه دهید.

b0fea8aa65c3a1c5.png

Now, let's say that we want to add some more talks to the event. We can stay in the Editor and in the Agent panel, give an instruction like Add two more talks to the schedule .

This will result in the Agent analyzing the requirement, updating the Task, Implementation Plan and then validating the updated functionality too. A sample conversation is shown below:

ba8455e6f68973e9.png

You can switch back to the Agent Manager if you'd like. This process should help you understand the process between shifting from Agent Manager to Editor, making changes accordingly and so on.

چیزهایی که باید امتحان کنید

  • قابلیت‌های اضافی مورد نظر خود را به برنامه اضافه کنید. جزئیات را به عامل ارائه دهید و توجه کنید که چگونه با تغییر لیست وظایف، سپس طرح پیاده‌سازی و غیره، وظایف خود را انجام می‌دهد.
  • از نماینده بخواهید که یک README یا مستندات بیشتری برای برنامه ایجاد کند.

۵. یک اپلیکیشن بهره‌وری ساده ایجاد کنید

اکنون قصد داریم یک برنامه وب تایمر پومودورو ساده ایجاد کنیم.

یک پوشه pomodoro-timer ایجاد کنید. مطمئن شوید که در Agent Manager هستید، فضای کاری pomodoro-timer را وارد و انتخاب کرده‌اید. با این دستور شروع کنید:

Create a productivity app that features a Pomodoro timer. Give a calm and aesthetic look to the application.

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

5be0a668e5a67d85.png

در این حالت، باید مرورگر Antigravity را نیز اجرا کند، آزمایش‌های خود را انجام دهد و سپس تأیید کند که آزمایش‌ها با موفقیت انجام شده‌اند. یکی از چیزهایی که ایجاد کرد، یک Media Artifact بود که شامل ویدیوی تأیید آن است. این یک روش عالی برای دیدن آنچه آزمایش شده است، می‌باشد. من همچنین برخی تغییرات سبک را پیشنهاد دادم، زیرا این تغییرات اعمال نشد و توانست این کار را انجام دهد.

برنامه نهایی شبیه به برنامه زیر بود و ظاهر بسیار خوبی دارد.

c9ab6bca97a51a8c.png

چطور است که یک تصویر تایمر زیبا به برنامه اضافه کنیم؟ تنها کاری که باید انجام دهیم این است که دستورالعمل تکمیلی را مانند زیر صادر کنیم:

Add an image to the application that displays a timer.

این منجر به اضافه شدن یک وظیفه جدید توسط عامل به مصنوع وظیفه شد:

498dd946d4e9ae55.png

سپس همزمان با انجام وظیفه خود، تصویری تولید کرد:

c291da9bdb37ff96.png

در نهایت، برنامه تصویر مورد نظر ما را داشت:

de8f418ba8e4600d.png

چیزهایی که باید امتحان کنید

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

۶. ایجاد تست‌های واحد، نمونه‌های آزمایشی (Mock Stubs) و اعتبارسنجی تست‌ها

مورد استفاده نهایی که در اینجا امتحان خواهیم کرد، تولید تست‌های واحد برای یک فایل کد خاص است که داریم و اینکه عامل نیز تست‌ها را اجرا و آنها را اعتبارسنجی کند.

برای این کار، ما یک فضای کاری خواهیم داشت که یک فایل پایتون واحد دارد، همانطور که در زیر نشان داده شده است:

from typing import Dict

# --- Custom Exceptions ---
class InventoryShortageError(Exception):
    """Raised when there is not enough item stock."""
    pass

class PaymentFailedError(Exception):
    """Raised when the payment gateway rejects the transaction."""
    pass

class InvalidOrderError(Exception):
    """Raised when the order violates business rules."""
    pass

# --- External Service Interfaces (To be Mocked) ---
class InventoryService:
    def get_stock(self, product_id: str) -> int:
        """Connects to DB to check stock."""
        raise NotImplementedError("Real connection required")

    def decrement_stock(self, product_id: str, quantity: int):
        """Connects to DB to reduce stock."""
        raise NotImplementedError("Real connection required")

class PaymentGateway:
    def charge(self, amount: float, currency: str) -> bool:
        """Connects to Stripe/PayPal."""
        raise NotImplementedError("Real connection required")

# --- Main Business Logic ---
class Order:
    def __init__(self, 
                 inventory_service: InventoryService, 
                 payment_gateway: PaymentGateway,
                 customer_email: str,
                 is_vip: bool = False):
        
        self.inventory = inventory_service
        self.payment = payment_gateway
        self.customer_email = customer_email
        self.is_vip = is_vip
        self.items: Dict[str, Dict] = {} # {product_id: {'price': float, 'qty': int}}
        self.is_paid = False
        self.status = "DRAFT"

    def add_item(self, product_id: str, price: float, quantity: int = 1):
        """Adds items to the cart. Rejects invalid prices or quantities."""
        if price < 0:
            raise ValueError("Price cannot be negative")
        if quantity <= 0:
            raise ValueError("Quantity must be greater than zero")

        if product_id in self.items:
            self.items[product_id]['qty'] += quantity
        else:
            self.items[product_id] = {'price': price, 'qty': quantity}

    def remove_item(self, product_id: str):
        """Removes an item entirely from the cart."""
        if product_id in self.items:
            del self.items[product_id]

    @property
    def total_price(self) -> float:
        """Calculates raw total before discounts."""
        return sum(item['price'] * item['qty'] for item in self.items.values())

    def apply_discount(self) -> float:
        """
        Applies business logic:
        1. VIPs get flat 20% off.
        2. Regulars get 10% off if total > 100.
        3. No discount otherwise.
        """
        total = self.total_price
        
        if self.is_vip:
            return round(total * 0.8, 2)
        elif total > 100:
            return round(total * 0.9, 2)
        
        return round(total, 2)

    def checkout(self):
        """
        Orchestrates the checkout process:
        1. Validates cart is not empty.
        2. Checks stock for all items.
        3. Calculates final price.
        4. Charges payment.
        5. Updates inventory.
        """
        if not self.items:
            raise InvalidOrderError("Cannot checkout an empty cart")

        # 1. Check Inventory Logic
        for product_id, data in self.items.items():
            available_stock = self.inventory.get_stock(product_id)
            if available_stock < data['qty']:
                raise InventoryShortageError(f"Not enough stock for {product_id}")

        # 2. Calculate Final Price
        final_amount = self.apply_discount()

        # 3. Process Payment
        try:
            success = self.payment.charge(final_amount, "USD")
            if not success:
                raise PaymentFailedError("Transaction declined by gateway")
        except Exception as e:
            # Catching generic network errors from the gateway
            raise PaymentFailedError(f"Payment gateway error: {str(e)}")

        # 4. Decrement Stock (Only occurs if payment succeeded)
        for product_id, data in self.items.items():
            self.inventory.decrement_stock(product_id, data['qty'])

        self.is_paid = True
        self.status = "COMPLETED"
        
        return {"status": "success", "charged_amount": final_amount}

Ensure that you have the above Python file locally in a new folder and you load that as a workspace in Antigravity.

این یک سرویس سفارش ساده است که قابلیت‌های کلیدی زیر را در بخش checkout دارد:

  1. اعتبارسنجی می‌کند که سبد خرید خالی نیست.
  2. موجودی همه اقلام را بررسی کنید.
  3. قیمت نهایی را محاسبه می‌کند.
  4. هزینه‌ها را پرداخت می‌کند.
  5. موجودی را به‌روزرسانی می‌کند.

ما قصد داریم وظیفه تولید موارد تست واحد، ارائه پیاده‌سازی‌های Mock و اجرای تست‌ها را برای اطمینان از موفقیت آنها به Agent واگذار کنیم.

We will open our specific workspace folder and you will notice that we can now use the @ symbol too to reference the file. For example, we could do the following:

۸۳۶۸۸۵۶e۵۱a۷۵۶۱a.png

This comes up with some explanation of what this file is:

b69c217d3372d802.png

می‌توانیم از آن بخواهیم که از طریق اعلان، تجسم بهتری ایجاد کند:

Can you visually show this class for better understanding

da5bd701323818d4.png

Our next step is to generate the unit tests and ask the Agent to test it out. I give the following prompt:

generate unit tests for this module and test it out with mock implementations.

مصنوع وظیفه زیر را تولید کرد و به وظیفه خود عمل کرد.

۲۱۴۲۵۳۷۹db336dc6.png

You can also see the details of the tests that it ran:

48f3320cd76b5cd8.png

یکی از فایل‌هایی که تولید کرد، فایل آزمایشی نیز بود. تصویری از آن در زیر نشان داده شده است:

f962061f115c040f.png

چیزهایی که باید امتحان کنید

Take your own code and see what you can ask the Agent to do, right from adding more functionality to refactoring parts of your code.

۷. تبریک

Congratulations! You have successfully used Google Antigravity to:

  • به صورت مستقل در وب تحقیق کنید.
  • برنامه‌های وب فول‌استک را بسازید و روی آنها تکرار کنید.
  • دارایی‌ها را تولید کنید و زیبایی‌شناسی رابط کاربری را اصلاح کنید.
  • تست‌های واحد پیچیده را با نمونه‌های آزمایشی (mocks) بنویسید و اعتبارسنجی کنید.

اکنون آماده‌اید تا مسئولیت سنگین پروژه‌هایتان را به Antigravity بسپارید.

اسناد مرجع