إنشاء تطبيقات متعددة الوسائط ووكلاء مُدارين مخصّصين باستخدام حزمة تطوير البرامج (SDK) للغة Java الخاصة بتفاعلات Gemini

1. مرحبًا بك في Gemini Developer!

ملاحظات مرسومة حول ما تعلّمه المطوّرون

في هذا الدرس التطبيقي حول الترميز، ستتعلّم كيفية إنشاء تطبيقات الذكاء الاصطناعي التوليدي من الجيل التالي بلغة Java باستخدام حزمة تطوير البرامج (SDK) المخصّصة للتفاعلات مع Gemini.

ما هي Gemini Interactions API؟

تعتمد واجهات برمجة التطبيقات التقليدية للنماذج اللغوية الكبيرة على الطلبات والاستجابات ولا تحتفظ بالبيانات. لإنشاء مساعد محادثة متعدّد الجولات أو حلقة وكيل معقّدة، كان على المطوّرين في السابق إدارة حالة المحادثة واقتطاع السجلّ وتنظيم طلبات الأدوات وحلقات التنفيذ بالكامل في الرمز البرمجي للتطبيق من جهة العميل.

تنقل واجهة برمجة التطبيقات Gemini Interactions API هذا التعقيد إلى الخادم. وهي واجهة برمجة تطبيقات مستندة إلى الجلسات وتحتفظ بالبيانات، حيث تستضيف بنية Google الأساسية الرسم البياني للمحادثة وتديره. يمثّل التفاعل الواحد جلسة ذات حالة. عند التفاعل معها، تعرض واجهة برمجة التطبيقات مخططًا زمنيًا غنيًا ومنظّمًا يتألف من خطوات متعددة الأشكال، مثل:

  • ‫ThoughtStep: عملية الاستدلال الداخلي للنموذج
  • ‫ModelOutputStep: محتوى نصي أو صوتي أو صور أنشأها النموذج.
  • ‫ToolCallStep وToolResultStep: عمليات استدعاء الأدوات التي يبدأها النظام أو النموذج
  • ‫UserInteractionStep: النقاط التي يتوقف عندها النظام مؤقتًا لطلب إدخال أو موافقة من المستخدم

ما المقصود بـ "الوكلاء المُدارون"؟

إنّ تنسيق الوكلاء المستقلين، أي التعامل مع التكرارات الحلقية ومنطق إعادة المحاولة وبيئات تنفيذ الأدوات وإدارة الحالة، هو أمر صعب للغاية.

الوكلاء المُدارون هم حلّ على مستوى المنصة توفّره Gemini Interactions API. بدلاً من تشغيل حلقات الوكلاء محليًا، يمكنك توفير وكلاء متخصّصين مباشرةً على بنية Google الأساسية:

  • الوكلاء المضمَّنون: وكلاء متخصّصون جاهزون للاستخدام، مثل وكيل Deep Research الذي يُجري أبحاثًا متعدّدة الخطوات على الويب ويجمع النتائج وينشئ تقارير شاملة.
  • الوكلاء المُدارون المخصّصون: كيانات مستقلة تحدّدها أنت. يمكنك تقديم تعليمات النظام وإرفاق الأدوات (مثل "بحث Google" أو بيئة تنفيذ Bash) وضبط Cloud Sandbox، وهي بيئة تشغيل آمنة ومعزولة ومستندة إلى حاويات مع قواعد خروج مخصّصة للشبكة (مثل السماح بالوصول إلى نطاقات معيّنة فقط مثل GitHub).

باستخدام حزمة تطوير البرامج (SDK) الخاصة بـ Gemini Interactions Java، يمكنك بسهولة تشغيل هؤلاء الوكلاء المُدارين وتنسيقهم والتعاون معهم في تطبيقات Java العادية.

أهداف الدورة التعليمية

  • كيفية التنقّل في البنية الجديدة المتعددة الأشكال المستندة إلى Step
  • كيفية بثّ صوت "تحويل النص إلى كلام" التعبيري مباشرةً إلى مكبّرات الصوت
  • كيفية إنشاء موسيقى (MP3 + كلمات الأغاني) باستخدام Lyria
  • كيفية إنشاء ملاحظات مرئية باستخدام Gemini 3 Pro Image
  • كيفية توجيه وكيل Deep Research باستخدام ميزة "التخطيط التعاوني"
  • كيفية توفير وكيل مخصّص يتضمّن قواعد وأدوات خروج الشبكة

المتطلبات

  • ‫Java 21 أو إصدار أحدث
  • Apache Maven
  • محرِّر نصوص أو بيئة تطوير متكاملة (IntelliJ IDEA أو VS Code أو غيرهما)
  • مفتاح Gemini API (من Google AI Studio)

2. الإعداد: المشروع ومفتاح واجهة برمجة التطبيقات

إنشاء مشروع 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. أضِف تبعية حزمة تطوير البرامج (SDK) داخل مجموعة :
    <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"

3- مرحبًا بكم في عالم "رفيق دربي": استكشاف بنية التطبيق

قدّمت واجهة برمجة التطبيقات Interactions 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. الصوت القابل للتوجيه: بث ميزة "تحويل النص إلى كلام" التعبيرية

يقدّم 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)

5- إنشاء الموسيقى باستخدام 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)

6. إنشاء صور باستخدام 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) التي أنشأها النموذج:

ملاحظة مرئية تم إنشاؤها

7. توجيه الوكلاء: أبحاث معمّقة وتعاونية

‫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)

8. الوكلاء المخصّصون وبيئات 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)

9. تهانينا!

لقد أكملت الدرس التطبيقي حول الترميز وتعلّمت كيفية إنشاء مهام سير عمل معقّدة ومتعدّدة الوسائط ومستندة إلى الوكلاء في Java باستخدام حزمة تطوير البرامج (SDK) لـ Gemini Interactions.

ما أنجزته:

  1. التنقّل في بنية الخطوات: تم استخدام بنية الخطوات الجديدة المتعددة الأشكال لطلب النماذج العادية.
  2. تحويل النص إلى كلام معبّر في الوقت الفعلي: استخدِم "ملاحظات المخرج" وعلامات المشاعر المضمّنة لبث الصوت في الوقت الفعلي.
  3. الموسيقى التي تم إنشاؤها: مقاطع صوتية بتنسيق MP3 وكلمات أغانٍ تم إنشاؤها باستخدام Lyria 3.
  4. الملاحظات المرسومة التي تم إنشاؤها: تم إنشاء ملخّصات مرئية باستخدام Gemini 3 Pro Image (Nano Banana Pro).
  5. ميزة Deep Research الموجَّهة: استخدمنا ميزة "التخطيط التعاوني" لتحسين خطط البحث.
  6. الوكلاء المخصّصون المزوّدون بالموارد: تم إنشاء بيئات معزولة مع عناصر تحكّم مخصّصة في حركة البيانات الصادرة من الشبكة لتنفيذ الرموز البرمجية بأمان.

مزيد من المعلومات:

  • يمكنك استكشاف الرمز المصدر لحزمة SDK والمزيد من إطارات الاختبار على GitHub: glaforge/gemini-interactions-api-sdk
  • يمكنك الاطّلاع على مزيد من المعلومات حول أنماط التصميم المستندة إلى الوكلاء في مدوّنة "غيوم": glaforge.dev