สร้างแอปหลายรูปแบบและ Agent ที่ได้รับการจัดการที่กำหนดเองด้วย Gemini Interactions Java SDK

1. ยินดีต้อนรับ นักพัฒนา Gemini

Sketchnote เกี่ยวกับสิ่งที่นักพัฒนาแอปได้เรียนรู้

ใน Codelab นี้ คุณจะได้เรียนรู้วิธีสร้างแอปพลิเคชัน AI รุ่นถัดไปใน Java โดยใช้ Gemini Interactions SDK ที่กำหนดเอง

Gemini Interactions API คืออะไร

API ของ LLM แบบดั้งเดิมเป็นแบบไม่เก็บสถานะและขับเคลื่อนด้วยคำขอและการตอบกลับ ที่ผ่านมา หากต้องการสร้างผู้ช่วยแชทแบบหลายเทิร์นหรือลูป Agent ที่ซับซ้อน นักพัฒนาซอฟต์แวร์ต้องจัดการสถานะการสนทนา การตัดประวัติ การจัดการการเรียกใช้เครื่องมือ และลูปการดำเนินการทั้งหมดในโค้ดของแอปพลิเคชันฝั่งไคลเอ็นต์

Gemini Interactions API จะย้ายความซับซ้อนนี้ไปยังเซิร์ฟเวอร์ API นี้เป็น API แบบเก็บสถานะและอิงตามเซสชัน ซึ่งโครงสร้างพื้นฐานของ Google จะโฮสต์และจัดการกราฟการสนทนา การโต้ตอบเดียวแสดงถึงเซสชันที่มีสถานะ เมื่อคุณโต้ตอบกับ API ระบบจะแสดงผลไทม์ไลน์ที่มีโครงสร้างสมบูรณ์ซึ่งประกอบด้วย Steps แบบ Polymorphic เช่น

  • ThoughtStep: กระบวนการให้เหตุผลภายในของโมเดล
  • ModelOutputStep: เนื้อหาข้อความ เสียง หรือรูปภาพที่โมเดลสร้างขึ้น
  • ToolCallStep และ ToolResultStep: การเรียกใช้เครื่องมือที่เริ่มต้นโดยระบบหรือโมเดล
  • UserInteractionStep: จุดที่ระบบหยุดชั่วคราวเพื่อขอข้อมูลหรือการอนุมัติจากเจ้าหน้าที่

Agent ที่ได้รับการจัดการคืออะไร

การจัดระเบียบ Agent อัตโนมัติ ซึ่งรวมถึงการจัดการลูป ตรรกะการลองใหม่ สภาพแวดล้อมการเรียกใช้เครื่องมือ และการจัดการสถานะ เป็นเรื่องที่ยากมาก

Agent ที่ได้รับการจัดการเป็นโซลูชันระดับแพลตฟอร์มที่ Gemini Interactions API มีให้ คุณสามารถจัดสรร Agent เฉพาะทางในโครงสร้างพื้นฐานของ Google ได้โดยตรง แทนที่จะเรียกใช้ลูป Agent ในเครื่อง ดังนี้

  • Agent ในตัว: Agent เฉพาะทางที่พร้อมใช้งาน เช่น Agent Deep Research ซึ่งทำการค้นคว้าข้อมูลบนเว็บแบบหลายขั้นตอน รวบรวมข้อมูลที่พบ และสร้างรายงานที่ครอบคลุม
  • Managed Agent ที่กำหนดเอง: เอนทิตีแบบอัตโนมัติที่คุณกำหนด คุณต้องระบุคำสั่งของระบบ แนบเครื่องมือ (เช่น Google Search หรือสภาพแวดล้อมการดำเนินการ Bash) และกำหนดค่า Cloud Sandbox ซึ่งเป็นสภาพแวดล้อมรันไทม์ที่ปลอดภัย แยกต่างหาก และอยู่ในคอนเทนเนอร์ พร้อมกฎขาออกของเครือข่ายที่ปรับแต่งได้ (เช่น อนุญาตให้เข้าถึงเฉพาะโดเมนที่เฉพาะเจาะจง เช่น GitHub)

การใช้ Gemini Interactions Java SDK ช่วยให้คุณสามารถเริ่มต้น ประสานงาน และทำงานร่วมกับ Agent ที่มีการจัดการเหล่านี้ในแอปพลิเคชัน Java มาตรฐานได้อย่างง่ายดาย

สิ่งที่คุณจะได้เรียนรู้

  • วิธีไปยังส่วนต่างๆ ของสถาปัตยกรรมแบบ Polymorphic ใหม่ที่ใช้ Step
  • วิธีสตรีมเสียง TTS ที่สื่ออารมณ์ไปยังลำโพงโดยตรง
  • วิธีสร้างเพลง (MP3 + เนื้อเพลง) ด้วย Lyria
  • วิธีสร้างภาพสเก็ตช์โน้ตด้วย Gemini 3 Pro สำหรับรูปภาพ
  • วิธีควบคุมตัวแทน Deep Research โดยใช้การวางแผนร่วมกัน
  • วิธีจัดสรร Agent ที่กำหนดเองด้วยกฎและเครื่องมือขาออกของเครือข่าย

สิ่งที่คุณต้องมี

  • Java 21 ขึ้นไป
  • Apache Maven
  • เครื่องมือแก้ไขข้อความหรือ IDE (IntelliJ IDEA, VS Code ฯลฯ)
  • คีย์ Gemini API (จาก Google AI Studio)

2. การตั้งค่า: โปรเจ็กต์และคีย์ 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 ของ SDK ภายในบล็อก ดังนี้
    <dependency>
        <groupId>io.github.glaforge</groupId>
        <artifactId>gemini-interactions-api-sdk</artifactId>
        <version>0.10.1</version>
    </dependency>
    

กำหนดค่าคีย์ API

รับคีย์ Gemini API จาก Google AI Studio

ตั้งค่าคีย์เป็นตัวแปรสภาพแวดล้อมในเทอร์มินัลโดยทำดังนี้

macOS / Linux:

export GEMINI_API_KEY="your_actual_api_key"

Windows (Command Prompt):

set GEMINI_API_KEY="your_actual_api_key"

3. Hello World: การทำความเข้าใจสถาปัตยกรรมของ Step

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

4. Steerable Audio: การสตรีม TTS ที่สื่ออารมณ์ได้

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 ที่สร้างขึ้น (tts_output.wav)

5. การสร้างเพลงด้วย Lyria 3

คุณสามารถสร้างเพลงและจิงเกิลได้โดยใช้โมเดล Lyria 3 ของ DeepMind การขอรูปแบบการตอบกลับแบบคู่ (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)

6. การแสดงภาพด้วย Sketchnotes (Nano Banana Pro)

Gemini 3 Pro Image (หรือที่เรียกว่า Nano Banana Pro) สามารถสร้างรูปภาพได้ เมื่อขอรูปแบบ IMAGE คุณจะสร้างอินโฟกราฟิก แผนภาพ หรือภาพสเก็ตช์โน้ตตามการป้อนข้อความได้

ในขั้นตอนนี้ คุณจะสร้างสรุปภาพสเก็ตช์โน้ตของบทความเกี่ยวกับ Managed Agent และบันทึกเป็นไฟล์ 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 ที่สร้างขึ้น

นี่คือ Sketchnote (sketchnote.png) ที่สร้างขึ้นโดยโมเดล

Sketchnote ที่สร้างขึ้น

7. Steering Agent: การทำ Deep Research ร่วมกัน

Deep Research เป็น Agent ที่ทรงพลังซึ่งสามารถทำงานวิจัยแบบหลายขั้นตอนได้ อย่างไรก็ตาม แทนที่จะเรียกใช้ทันที คุณสามารถใช้การวางแผนร่วมกันเพื่อตรวจสอบ แก้ไข และควบคุมแผนการค้นคว้าข้อมูลก่อนที่ Agent จะเริ่มรวบรวมข้อมูลได้

คุณจะใช้การสนทนาแบบหลายรอบซึ่งใช้สถานะฝั่งเซิร์ฟเวอร์เดียวกัน (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

เอาต์พุตรายงานที่สร้างขึ้น

จากนั้น Agent ของ Deep Research จะสร้างรายงานที่มีโครงสร้างและครอบคลุม คุณดูรายงานฉบับเต็มที่สร้างขึ้นจากการเรียกใช้ตัวอย่างได้ที่นี่

ดูรายงานการค้นคว้าข้อมูล Deep Research ที่สร้างขึ้น (tpu_history_report.md)

8. Custom Agents และ Cloud Sandboxes

สำหรับงานที่ซับซ้อนของนักพัฒนาซอฟต์แวร์ คุณสามารถจัดสรร Agent ที่กำหนดเองได้ คุณสามารถกำหนดคำสั่งของระบบ ติดตั้งเครื่องมือ (เช่น การเรียกใช้โค้ด/Bash) และกำหนดค่าสภาพแวดล้อมระยะไกล (เช่น กฎขาออกของเครือข่าย)

ในขั้นตอนนี้ คุณจะจัดสรร Agent ที่มีการเข้าถึงอินเทอร์เน็ตอย่างปลอดภัยไปยัง 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

เอาต์พุตการวิเคราะห์ที่สร้างขึ้น

คุณสามารถดูรายงานการวิเคราะห์สถาปัตยกรรมฉบับเต็มที่สร้างโดย Agent ที่กำหนดเองหลังจากโคลนที่เก็บได้ที่นี่

ดูเอาต์พุตของ GitHub Analyzer (github_analysis_report.md)

9. ยินดีด้วย

คุณได้ทำ Codelab เสร็จแล้ว และได้เรียนรู้วิธีสร้างเวิร์กโฟลว์ที่ซับซ้อน หลายรูปแบบ และเป็นแบบ Agentic ใน Java โดยใช้ Gemini Interactions SDK

สิ่งที่คุณทำสำเร็จ

  1. ไปยังส่วนต่างๆ ของสถาปัตยกรรมขั้นตอน: ใช้สถาปัตยกรรมขั้นตอนแบบ Polymorphic ใหม่เพื่อค้นหาโมเดลมาตรฐาน
  2. TTS ที่แสดงอารมณ์แบบสตรีม: ใช้โน้ตของผู้กำกับและแท็กอารมณ์ในบรรทัดเพื่อสตรีมเสียงแบบเรียลไทม์
  3. เพลงที่สร้างขึ้น: แทร็ก MP3 และเนื้อเพลงที่สร้างขึ้นด้วย Lyria 3
  4. Sketchnote ที่สร้างขึ้น: สร้างสรุปภาพโดยใช้ Gemini 3 Pro Image (Nano Banana Pro)
  5. Steered Deep Research: ใช้การวางแผนร่วมกันเพื่อปรับแต่งแผนการค้นคว้าข้อมูล
  6. Agent ที่กำหนดเองซึ่งจัดสรรไว้: สร้างสภาพแวดล้อมแซนด์บ็อกซ์ที่มีการควบคุมขาออกของเครือข่ายที่กำหนดเองเพื่อเรียกใช้โค้ดอย่างปลอดภัย

ดูข้อมูลเพิ่มเติม:

  • สำรวจซอร์สโค้ด SDK และกรอบการทดสอบเพิ่มเติมใน GitHub: glaforge/gemini-interactions-api-sdk
  • อ่านเพิ่มเติมเกี่ยวกับรูปแบบการออกแบบ Agentic ได้ในบล็อกของ Guillaume: glaforge.dev