ساختن برنامه‌های چندحالته و عامل‌های مدیریت‌شده سفارشی با Gemini Interactions Java SDK

۱. توسعه‌دهنده Gemini، خوش آمدید!

یادداشت تصویری یادگیری‌های توسعه‌دهنده

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

‫Gemini Interactions API چیست؟

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

Gemini Interactions API این پیچیدگی را به سرور منتقل می‌کند. این میانای برنامه‌سازی کاربردی حالت‌دار و مبتنی بر جلسه است که در آن زیرساخت Google میزبان نمودار مکالمه است و آن را مدیریت می‌کند. یک تعامل نشان‌دهنده یک جلسه باوضعیت است. وقتی با آن تعامل می‌کنید، API یک خط زمان غنی و ساختاریافته متشکل از مراحل چندریختی برمی‌گرداند—مانند:

  • ThoughtStep: فرایند استدلال داخلی مدل.
  • ‫ModelOutputStep: محتوای نوشتاری، صوتی، یا تصویری تولیدشده توسط مدل.
  • ToolCallStep و ToolResultStep: فراخوانی‌های ابزار آغازشده توسط سیستم یا مدل.
  • UserInteractionStep: نقاطی که سیستم برای درخواست ورودی یا تأیید انسانی مکث می‌کند.

«عامل‌های مدیریت‌شده» چیست؟

سازمان‌دهی عامل‌های خودکار (مدیریت حلقه‌ها، منطق تکرار، محیط‌های اجرای ابزار، و مدیریت وضعیت) بسیار دشوار است.

عامل‌های مدیریت‌شده یک راه‌حل در سطح پلاتفرم هستند که توسط Gemini Interactions API ارائه می‌شوند. به‌جای اجرای حلقه‌های عامل به‌صورت محلی، می‌توانید عامل‌های تخصصی را مستقیماً در زیرساخت Google فراهم کنید:

  • عامل‌های داخلی: عامل‌های تخصصی آماده برای استفاده، مانند عامل Deep Research، که پژوهش‌های چندمرحله‌ای وب را انجام می‌دهد، یافته‌ها را جمع‌آوری می‌کند، و گزارش‌های جامع تولید می‌کند.
  • عامل‌های مدیریت‌شده سفارشی: نهادهای خودمختاری که شما تعریف می‌کنید. دستورالعمل‌های سیستم را ارائه می‌دهید، ابزارها (مانند «جستجوی Google» یا محیط اجرای Bash) را پیوست می‌کنید، و یک محیط آزمایشی Cloud پیکربندی می‌کنید—یک محیط زمان اجرای امن، مجزا، و کانتینری با قوانین خروج شبکه سفارشی‌سازی‌شدنی (مثلاً اجازه دسترسی فقط به دامنه‌های خاص مانند GitHub).

بااستفاده از Gemini Interactions Java SDK، می‌توانید به‌راحتی این نماینده‌های مدیریت‌شده را در برنامه‌های استاندارد Java راه‌اندازی، هماهنگ، و با آن‌ها مشارکت کنید.

آنچه خواهید آموخت

  • نحوه پیمایش در معماری چندریختی جدید مبتنی بر Step.
  • نحوه جاری‌سازی صدای «نوشتار به گفتار» رسا مستقیماً به بلندگوها.
  • نحوه تولید موسیقی (MP3 + متن ترانه) با Lyria.
  • نحوه تولید یادداشت‌های تصویری با Gemini 3 Pro Image.
  • نحوه هدایت کردن عامل Deep Research بااستفاده از «برنامه‌ریزی مشارکتی».
  • نحوه تأمین عامل سفارشی با ابزارها و قوانین خروج شبکه.

آنچه نیاز خواهید داشت

  • Java نسخه ۲۱ یا بالاتر.
  • Apache Maven.
  • ویرایشگر نوشتار یا IDE (IntelliJ IDEA،‏ VS Code، و غیره).
  • کلید Gemini API (از Google AI Studio).

۲. راه‌اندازی: پروژه و کلید میانای API

ایجاد پروژه Maven

بااستفاده از فرمان زیر، پروژه Maven جدیدی را از پایانه خود راه‌اندازی کنید:

mvn archetype:generate \
    -DgroupId=com.example \
    -DartifactId=gemini-interactions-demo \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DarchetypeVersion=1.5 \
    -DinteractiveMode=false

به فهرست راهنمای پروژه تازه ایجادشده‌تان بروید:

cd gemini-interactions-demo

فایل pom.xml را باز کنید و آن را پیکربندی کنید:

  1. ویژگی‌های نسخه Java را برای هدف قرار دادن Java 21 به‌روز کنید:
    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
    </properties>
    
  2. وابستگی کیت توسعه نرم‌افزار را در بلوک اضافه کنید:
    <dependency>
        <groupId>io.github.glaforge</groupId>
        <artifactId>gemini-interactions-api-sdk</artifactId>
        <version>0.10.1</version>
    </dependency>
    

پیکربندی کلید میانای برنامه‌سازی کاربردی

کلید Gemini API را از Google AI Studio دریافت کنید.

کلید را به‌عنوان متغیر محیطی در پایانه تنظیم کنید:

macOS / Linux:

export GEMINI_API_KEY="your_actual_api_key"

Windows (خط فرمان):

set GEMINI_API_KEY="your_actual_api_key"

۳. سلام دنیا: پیمایش معماری گام

Interactions API یک معماری خط زمان چندریختی و مرحله‌محور را معرفی کرد. به‌جای برگرداندن فهرست مسطحی از خروجی‌ها، API دنباله‌ای از اشیاء Step تایپ‌شده (مثلاً ModelOutputStep، ThoughtStep، FunctionCallStep) را برمی‌گرداند.

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

ساختن HelloInteractions.java

فایل src/main/java/com/example/HelloInteractions.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.InteractionParams.ModelInteractionParams;

public class HelloInteractions {
    public static void main(String[] args) {
        // 1. Initialize the client
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        // 2. Build the request
        ModelInteractionParams request = ModelInteractionParams.builder()
            .model("gemini-3.5-flash")
            .input("Explain the difference between a library and a framework in one sentence.")
            .build();

        // 3. Send request
        Interaction response = client.create(request);
        
        // 4. Navigate the step-based architecture to get the output
        response.steps().stream()
            .filter(step -> step instanceof Step.ModelOutputStep)
            .map(step -> (Step.ModelOutputStep) step)
            .findFirst()
            .ifPresent(step -> System.out.println(step.content().get(0)));
    }
}

اجرای کد

کلاس را کامپایل و اجرا کنید:

mvn compile exec:java -Dexec.mainClass=com.example.HelloInteractions

۴. صدای قابل‌هدایت: جاری‌سازی «نوشتار به گفتار» رسا

‫Gemini 3.1 Flash «نوشتار به گفتار» (TTS) قابل‌هدایت را معرفی می‌کند. می‌توانید سرعت، لحن، و محیط صدا را بااستفاده از پیام‌واره‌ها کنترل کنید و از برچسب‌های احساسی (مانند [excitedly] یا [whispers]) در میان جمله استفاده کنید.

در این مرحله، صدای رسا تولید خواهید کرد و آن را مستقیماً به بلندگوهایتان جاری خواهید کرد.

ساختن StreamingDJ.java

فایل src/main/java/com/example/StreamingDJ.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.Config.SpeechConfig;
import io.github.glaforge.gemini.interactions.model.InteractionParams.ModelInteractionParams;
import javax.sound.sampled.*;
import java.util.Base64;
import java.util.stream.Stream;

public class StreamingDJ {
    public static void main(String[] args) throws Exception {
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        // Prompt defining the voice profile and emotional tags
        String prompt = """
            # AUDIO PROFILE: Jaz R.
            ## THE SCENE: London Studio
            ### DIRECTOR'S NOTES
            Accent: Jaz is a DJ from Brixton, London.
            Style: Bouncy, energetic, high-speed delivery.
            
            #### TRANSCRIPT
            [excitedly] Yes, massive vibes in the studio! 
            [whispers] But keep it down, the boss is coming... 
            [shouting] Turn this up! Let's go!
            """;

        ModelInteractionParams request = ModelInteractionParams.builder()
            .model("gemini-3.1-flash-tts-preview")
            .input(prompt)
            .responseModalities(Interaction.Modality.AUDIO)
            .speechConfig(new SpeechConfig("Algenib", "en-GB"))
            .stream(true) // Enable streaming
            .build();

        System.out.println("Streaming audio from Gemini...");

        try (Stream<Events> eventStream = client.stream(request)) {
            // Configure the Java Audio System for 24kHz Mono 16-bit PCM
            AudioFormat format = new AudioFormat(24000, 16, 1, true, false);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
                line.open(format);
                line.start();

                // Process the stream and play audio chunks as they arrive
                eventStream.forEach(event -> {
                    if (event instanceof Events.StepDelta cd && cd.delta() instanceof Events.AudioDelta audioDelta) {
                        byte[] audioData = Base64.getDecoder().decode(audioDelta.data());
                        line.write(audioData, 0, audioData.length);
                    }
                });
                line.drain();
            }
        }
    }
}

اجرای کد

mvn compile exec:java -Dexec.mainClass=com.example.StreamingDJ

گوش دادن به برونداد

در اینجا نمونه‌ای صوتی از آنچه هنگام اجرای کد خواهید شنید (بااستفاده از صدای Algenib با برچسب‌های احساسی) آورده شده است:

به برونداد تولیدشده «نوشتار به گفتار» (tts_output.wav) گوش دهید

۵. تولید موسیقی با Lyria 3

بااستفاده از مدل DeepMind Lyria 3، می‌توانید موسیقی و آگهی آهنگین تولید کنید. با درخواست کردن حالت‌های پاسخ دوگانه (AUDIO و TEXT)، می‌توانید هم صدای تولیدشده (MP3) و هم متن ترانه را بازیابی کنید.

ساختن MusicGenerator.java

فایل src/main/java/com/example/MusicGenerator.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.InteractionParams.ModelInteractionParams;
import io.github.glaforge.gemini.interactions.model.Content.AudioContent;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MusicGenerator {
    public static void main(String[] args) throws Exception {
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        ModelInteractionParams request = ModelInteractionParams.builder()
            .model("models/lyria-3-clip-preview") // 30-second clip
            .input("An uplifting rock song with acoustic guitars about coding in Java.")
            .responseModalities(
                Interaction.Modality.AUDIO,
                Interaction.Modality.TEXT) // Request both MP3 and Lyrics
            .build();

        System.out.println("Generating music (this might take a moment)...");
        Interaction response = client.create(request);

        // 1. Print the lyrics (TEXT output)
        System.out.println("\n--- Generated Lyrics ---");
        response.steps().stream()
            .filter(step -> step instanceof Step.ModelOutputStep)
            .flatMap(step -> ((Step.ModelOutputStep) step).content().stream())
            .filter(content -> content instanceof Content.TextContent)
            .forEach(content -> System.out.println(((Content.TextContent) content).text()));

        // 2. Save the MP3 (AUDIO output)
        response.steps().stream()
            .filter(step -> step instanceof Step.ModelOutputStep)
            .flatMap(step -> ((Step.ModelOutputStep) step).content().stream())
            .filter(content -> content instanceof AudioContent)
            .map(content -> (AudioContent) content)
            .findFirst()
            .ifPresent(audio -> {
                try {
                    Files.write(Paths.get("coding_song.mp3"), audio.data());
                    System.out.println("\nSuccess: Song saved to coding_song.mp3");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
    }
}

اجرای کد

mvn compile exec:java -Dexec.mainClass=com.example.MusicGenerator

گوش دادن به آهنگ تولیدشده

این فایل MP3 تولیدشده (coding_song.mp3) حاوی موسیقی و متن ترانه است:

به آهنگ موسیقی تولیدشده (coding_song.mp3) گوش دهید

‫۶. تجسم کردن با Sketchnotes‏ (Nano Banana Pro)

‫Gemini 3 Pro Image (که با نام Nano Banana Pro نیز شناخته می‌شود) می‌تواند تصویر تولید کند. با درخواست کردن حالت IMAGE، می‌توانید براساس ورودی نوشتاری، اطلاع‌نگاشت، نمودار، یا یادداشت تصویری تولید کنید.

در این مرحله، خلاصه یادداشت تصویری از مقاله‌ای درباره «عامل‌های مدیریت‌شده» تولید می‌کنید و آن را به‌صورت فایل PNG ذخیره می‌کنید.

ساختن ImageGenerator.java

فایل src/main/java/com/example/ImageGenerator.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.InteractionParams.ModelInteractionParams;
import io.github.glaforge.gemini.interactions.model.Content.ImageContent;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ImageGenerator {
    public static void main(String[] args) throws Exception {
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        String articleSummary = """
            Managed Agents in the Gemini API allow developers to run autonomous agents
            that reason, plan, use tools, and execute code inside isolated cloud sandboxes.
            The Gemini API handles the infrastructure (containers, network, runtime).
            It is powered by the Antigravity agent running on Gemini 3.5 Flash.
            The Java Interactions SDK supports these capabilities, utilizing a Step-based
            architecture to model the execution timeline.
            """;

        ModelInteractionParams request = ModelInteractionParams.builder()
            .model("gemini-3-pro-image-preview")
            .input(String.format("""
                Create a hand-drawn and hand-written sketchnote
                style summary infographic, with a pure white background,
                about the following information:
                
                %s
                """, articleSummary))
            .responseModalities(Interaction.Modality.IMAGE) // Request IMAGE modality
            .build();

        System.out.println("Generating sketchnote (this might take a moment)...");
        Interaction response = client.create(request);

        // Save the generated image
        response.steps().stream()
            .filter(step -> step instanceof Step.ModelOutputStep)
            .flatMap(step -> ((Step.ModelOutputStep) step).content().stream())
            .filter(content -> content instanceof ImageContent)
            .map(content -> (ImageContent) content)
            .findFirst()
            .ifPresent(image -> {
                try {
                    Files.write(Paths.get("sketchnote.png"), image.data());
                    System.out.println("Success: Sketchnote saved to sketchnote.png");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
    }
}

اجرای کد

mvn compile exec:java -Dexec.mainClass=com.example.ImageGenerator

یادداشت تصویری تولیدشده

این یادداشت تصویری تولیدشده (sketchnote.png) است که مدل ایجاد کرده است:

یادداشت تصویری تولیدشده

‫۷. Steering Agents: Collaborative Deep Research

‫Deep Research یک عامل قدرتمند است که می‌تواند تکالیف پژوهشی چندمرحله‌ای را اجرا کند. اما به‌جای اجرای فوری، می‌توانید از برنامه‌ریزی مشارکتی برای مرور، اصلاح، و هدایت طرح پژوهشی قبل‌از شروع جمع‌آوری داده توسط عامل استفاده کنید.

مکالمه‌ای چندنوبتی را پیاده‌سازی خواهید کرد که از همان وضعیت سمت سرور (previousInteractionId) برای اصلاح طرح استفاده می‌کند.

ساختن CollaborativeResearch.java

فایل src/main/java/com/example/CollaborativeResearch.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.InteractionParams.AgentInteractionParams;
import io.github.glaforge.gemini.interactions.model.Config.DeepResearchAgentConfig;
import io.github.glaforge.gemini.interactions.model.Config.ThinkingSummaries;
import io.github.glaforge.gemini.interactions.model.Config.Visualization;

public class CollaborativeResearch {
    public static void main(String[] args) throws Exception {
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        String agentModel = "deep-research-preview-04-2026";

        // --- Phase 1: Request a Plan ---
        System.out.println("Phase 1: Requesting research plan...");
        AgentInteractionParams planParams = AgentInteractionParams.builder()
            .agent(agentModel)
            .input("Research the latest generations of Google Cloud TPUs (TPU7x and the 8th generation TPU 8t and TPU 8i).")
            .agentConfig(new DeepResearchAgentConfig(
                "deep-research", 
                ThinkingSummaries.AUTO, 
                Visualization.AUTO, 
                true // TRUE enables collaborative planning
            ))
            .background(true)
            .store(true)
            .build();

        Interaction planInteraction = client.create(planParams);
        planInteraction = waitForCompletion(client, planInteraction.id());
        
        System.out.println("\n--- Proposed Plan ---");
        printOutputText(planInteraction);

        // --- Phase 2: Refine the Plan ---
        System.out.println("\nPhase 2: Refining research plan...");
        AgentInteractionParams refineParams = AgentInteractionParams.builder()
            .agent(agentModel)
            .input("Focus on comparing the architectural, performance, and scaling differences between the TPU7x generation and the two flavors of the eighth generation: TPU 8t (optimized for training at scale) and TPU 8i (optimized for low-latency reasoning and inference).")
            .agentConfig(new DeepResearchAgentConfig(
                "deep-research", 
                ThinkingSummaries.AUTO, 
                Visualization.AUTO, 
                true // Keep collaborative planning TRUE to iterate
            ))
            .previousInteractionId(planInteraction.id()) // Resume session
            .background(true)
            .store(true)
            .build();

        Interaction refinedInteraction = client.create(refineParams);
        refinedInteraction = waitForCompletion(client, refinedInteraction.id());

        System.out.println("\n--- Refined Plan ---");
        printOutputText(refinedInteraction);

        // --- Phase 3: Approve and Execute ---
        System.out.println("\nPhase 3: Approving plan and starting deep research (this will take a few minutes)...");
        AgentInteractionParams executeParams = AgentInteractionParams.builder()
            .agent(agentModel)
            .input("Plan looks good, execute!")
            .agentConfig(new DeepResearchAgentConfig(
                "deep-research", 
                ThinkingSummaries.AUTO, 
                Visualization.AUTO, 
                false // FALSE approves the plan and executes the research
            ))
            .previousInteractionId(refinedInteraction.id()) // Resume session
            .background(true)
            .store(true)
            .build();

        Interaction finalReport = client.create(executeParams);
        finalReport = waitForCompletion(client, finalReport.id());

        System.out.println("\n--- Final Research Report ---");
        printOutputText(finalReport);
    }

    private static Interaction waitForCompletion(GeminiInteractionsClient client, String id) throws Exception {
        Interaction interaction = client.get(id);
        while (interaction.status() != Interaction.Status.COMPLETED && interaction.status() != Interaction.Status.FAILED) {
            Thread.sleep(5000);
            interaction = client.get(id);
        }
        if (interaction.status() == Interaction.Status.FAILED) {
            throw new RuntimeException("Interaction failed. Status: " + interaction.status());
        }
        return interaction;
    }

    private static void printOutputText(Interaction interaction) {
        interaction.steps().stream()
            .filter(step -> step instanceof Step.ModelOutputStep)
            .flatMap(step -> ((Step.ModelOutputStep) step).content().stream())
            .filter(content -> content instanceof Content.TextContent)
            .forEach(content -> System.out.println(((Content.TextContent) content).text()));
    }
}

اجرای کد

mvn compile exec:java -Dexec.mainClass=com.example.CollaborativeResearch

برونداد گزارش تولیدشده

عامل Deep Research گزارشی جامع و ساختاریافته تولید خواهد کرد. می‌توانید گزارش کامل تولیدشده توسط اجرای نمونه را در اینجا مشاهده کنید:

مشاهده «گزارش Deep Research» تولیدشده (tpu_history_report.md)

‫۸. عوامل سفارشی و جعبه‌های ایمنی Cloud

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

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

ساختن GitHubAnalyzer.java

فایل src/main/java/com/example/GitHubAnalyzer.java را با محتوای زیر ایجاد کنید:

package com.example;

import io.github.glaforge.gemini.interactions.GeminiInteractionsClient;
import io.github.glaforge.gemini.interactions.model.*;
import io.github.glaforge.gemini.interactions.model.InteractionParams.AgentInteractionParams;
import java.util.List;

public class GitHubAnalyzer {
    public static void main(String[] args) throws Exception {
        GeminiInteractionsClient client = GeminiInteractionsClient.builder()
            .apiKey(System.getenv("GEMINI_API_KEY"))
            .build();

        String agentId = "github-analyzer-codelab";

        // 1. Define the Custom Agent with Network Egress and Tools
        Agent customAgent = Agent.builder()
            .id(agentId)
            .description("Clones and analyzes GitHub repos.")
            .baseAgent("antigravity-preview-09-2026")
            .baseEnvironment(new EnvironmentConfig(
                new EnvironmentNetworkEgressAllowlist(List.of(
                    new AllowlistEntry("github.com") // Allow git clone over HTTPS
                )),
                List.of()
            ))
            .systemInstruction("You are an architect. Clone the repo, inspect files, and write a summary.")
            .tools(List.of(
                new AgentTool.CodeExecution(), // Enables terminal bash execution in sandbox
                new AgentTool.GoogleSearch()
            ))
            .build();

        // 2. Provision the Agent
        System.out.println("Provisioning custom agent in the cloud...");
        client.createAgent(customAgent);

        try {
            // 3. Start the Interaction
            AgentInteractionParams params = AgentInteractionParams.builder()
                .agent(agentId)
                .input("Clone https://github.com/glaforge/gemini-interactions-api-sdk and explain its pom.xml structure.")
                .environment("remote") // Crucial: Run in cloud sandbox
                .build();

            System.out.println("Starting clone and analysis (polling status)...");
            Interaction interaction = client.create(params);

            // 4. Poll for completion
            while (interaction.status() != Interaction.Status.COMPLETED) {
                System.out.println("Agent working... Status: " + interaction.status());
                Thread.sleep(5000);
                interaction = client.get(interaction.id());
            }

            // 5. Output the results
            System.out.println("\n--- Architectural Analysis ---");
            interaction.steps().stream()
                .filter(step -> step instanceof Step.ModelOutputStep)
                .flatMap(step -> ((Step.ModelOutputStep) step).content().stream())
                .filter(content -> content instanceof Content.TextContent)
                .forEach(content -> System.out.println(((Content.TextContent) content).text()));

        } finally {
            // 6. Clean up resources
            client.deleteAgent(agentId);
            System.out.println("\nCustom agent resource deleted from cloud.");
        }
    }
}

اجرای کد

mvn compile exec:java -Dexec.mainClass=com.example.GitHubAnalyzer

برونداد تجزیه‌وتحلیل تولیدشده

می‌توانید گزارش کامل تحلیل معماری را که توسط نماینده سفارشی پس‌از شبیه‌سازی مخزن تولید شده است در اینجا مشاهده کنید:

مشاهده خروجی GitHub Analyzer (github_analysis_report.md)

‫۹. تبریک!

شما codelab را تکمیل کرده‌اید و یاد گرفته‌اید که چگونه بااستفاده از Gemini Interactions SDK، گردش‌های کاری پیچیده، چندحالتی، و عامل‌گرا را در جاوا بسازید.

آنچه انجام داده‌اید:

  1. پیمایش معماری گام: از معماری گام چندریختی جدید برای پُرسمان مدل‌های استاندارد استفاده کرد.
  2. «نوشتار به گفتار» احساسی جاری‌سازی‌شده: از «یادداشت‌های کارگردان» و برچسب‌های احساسی درون‌خطی برای جاری‌سازی هم‌زمان صدا استفاده کرد.
  3. موسیقی تولیدشده: قطعه‌های MP3 و متن ترانه تولیدشده با Lyria 3.
  4. یادداشت‌های تصویری تولیدشده: خلاصه‌های تصویری بااستفاده از Gemini 3 Pro Image‏ (Nano Banana Pro) ایجاد شد.
  5. ‫Steered Deep Research: از «برنامه‌ریزی مشارکتی» برای اصلاح طرح‌های پژوهشی استفاده کرد.
  6. عامل‌های سفارشی آماده‌سازی‌شده: محیط‌های جعبه شنی با کنترل خروجی شبکه سفارشی برای اجرای ایمن کد ایجاد کردیم.

کسب اطلاعات بیشتر:

  • کد منبع کیت توسعه نرم‌افزار و چارچوب‌های تست بیشتر را در GitHub کاوش کنید: glaforge/gemini-interactions-api-sdk
  • درباره الگوهای طراحی عامل‌گرا در وبلاگ Guillaume بیشتر بخوانید: glaforge.dev