Panduan memulai dengan Agent Development Kit

Setelah Anda mengonfigurasi agen Agent Development Kit (ADK) untuk menggunakan Sesi dan Bank Memori Vertex AI Agent Engine, agen Anda akan otomatis membaca dan menulis memori serta sesi untuk Anda.

Untuk panduan memulai menggunakan REST API, lihat Panduan memulai dengan REST API.

Tutorial ini menunjukkan cara menggunakan Sesi dan Bank Memori Vertex AI Agent Engine dengan ADK untuk membuat dan menggunakan sesi serta memori jangka panjang:

  1. Buat instance Vertex AI Agent Engine untuk mengakses Sesi Vertex AI Agent Engine dan Bank Memori.

  2. Buat agen dan peluncur ADK lokal Anda.

  3. Berinteraksi dengan agen Anda untuk membuat memori jangka panjang secara dinamis yang dapat diakses di seluruh sesi.

  4. Pembersihan.

Sebelum memulai

Untuk menyelesaikan langkah-langkah yang ditunjukkan dalam tutorial ini, Anda harus menyiapkan project dan lingkungan terlebih dahulu.

Menyiapkan project

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. Jika Anda memilih project, pastikan Anda memiliki peran IAM Vertex AI user (roles/aiplatform.user) di project tersebut.
  9. Melakukan autentikasi ke Vertex AI

    Untuk menggunakan contoh Python di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Untuk mengetahui informasi selengkapnya, lihat Menyiapkan ADC untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud .

    Mengimpor library

    Instal Agent Development Kit dan Vertex AI SDK:

    pip install google-adk>=1.5.0
    pip install google-cloud-aiplatform>=1.100.0

    Menetapkan variabel lingkungan

    Untuk menggunakan ADK, tetapkan variabel lingkungan Anda:

    import os
    
    os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "TRUE"
    os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
    os.environ["GOOGLE_CLOUD_LOCATION"] = "LOCATION"
    

    Ganti kode berikut:

    • PROJECT_ID: Project ID Anda.
    • LOCATION: Region Anda. Hanya us-central1 yang didukung untuk Bank Memori Vertex AI Agent Engine.

    Buat instance Vertex AI Agent Engine Anda

    Untuk mengakses Sesi Vertex AI Agent Engine dan Bank Memori Vertex AI Agent Engine, Anda harus membuat instance Vertex AI Agent Engine terlebih dahulu. Anda tidak perlu men-deploy kode apa pun untuk mulai menggunakan Sesi dan Bank Memori. Tanpa deployment kode, pembuatan instance Vertex AI Agent Engine akan memakan waktu beberapa detik.

    import vertexai
    
    client = vertexai.Client(
        project="PROJECT_ID",
        location="LOCATION",
    )
    
    agent_engine = client.agent_engines.create()
    

    Buat agen ADK Anda

    1. Saat mengembangkan agen ADK, sertakan alat Memory, yang mengontrol kapan layanan memori digunakan dan cara menyertakan memori dalam perintah. Agen contoh menggunakan PreloadMemoryTool, yang selalu mengambil memori di awal setiap giliran dan menyertakan memori dalam petunjuk sistem:

      from google import adk
      
      agent = adk.Agent(
          model="gemini-2.0-flash",
          name='stateful_agent',
          instruction="""You are a Vehicle Voice Agent, designed to assist users with information and in-vehicle actions.
      
      1.  **Direct Action:** If a user requests a specific vehicle function (e.g., "turn on the AC"), execute it immediately using the corresponding tool. You don't have the outcome of the actual tool execution, so provide a hypothetical tool execution outcome.
      2.  **Information Retrieval:** Respond concisely to general information requests with your own knowledge (e.g., restaurant recommendation).
      3.  **Clarity:** When necessary, try to seek clarification to better understand the user's needs and preference before taking an action.
      4.  **Brevity:** Limit responses to under 30 words.
      """,
          tools=[adk.tools.preload_memory_tool.PreloadMemoryTool()]
      )
      
    2. Buat layanan memori VertexAiMemoryBankService, yang digunakan peluncur ADK untuk mengambil kenangan.

      from google.adk.memory import VertexAiMemoryBankService
      
      agent_engine_id = agent_engine.api_resource.name.split("/")[-1]
      
      memory_service = VertexAiMemoryBankService(
          project="PROJECT_ID",
          location="LOCATION",
          agent_engine_id=agent_engine_id
      )
      
    3. Buat runner ADK, yang mengorkestrasi eksekusi agen, alat, dan callback Anda.

      from google.adk.sessions import VertexAiSessionService
      from google.genai import types
      
      # You can use any ADK session service.
      session_service = VertexAiSessionService(
          project="PROJECT_ID",
          location="LOCATION",
          agent_engine_id=agent_engine_id
      )
      
      app_name="APP_NAME"
      runner = adk.Runner(
          agent=agent,
          app_name=app_name,
          session_service=session_service,
          memory_service=memory_service
      )
      
      def call_agent(query, session, user_id):
        content = types.Content(role='user', parts=[types.Part(text=query)])
        events = runner.run(user_id=user_id, session_id=session, new_message=content)
      
        for event in events:
            if event.is_final_response():
                final_response = event.content.parts[0].text
                print("Agent Response: ", final_response)
      

      Ganti kode berikut:

      • APP_NAME: Nama aplikasi ADK Anda.

    Berinteraksi dengan agen Anda

    Setelah menentukan agen dan menyiapkan Sesi dan Bank Memori, Anda dapat berinteraksi dengan agen.

    1. Buat sesi pertama Anda. Karena tidak ada memori yang tersedia selama sesi pertama dengan pengguna, agen tidak mengetahui preferensi pengguna, seperti suhu yang diinginkan:

      session = await session_service.create_session(
          app_name=app_name,
          user_id="USER_ID"
      )
      
      call_agent(
          "Can you update the temperature to my preferred temperature?",
          session.id,
          "USER_ID"
      )
      
      # Agent response: "What is your preferred temperature?"
      call_agent("I like it at 71 degrees", session.id, "USER_ID")
      # Agent Response:  Setting the temperature to 71 degrees Fahrenheit.
      # Temperature successfully changed.
      

      Ganti kode berikut:

      • USER_ID: ID untuk pengguna Anda. Kenangan yang dihasilkan dari sesi ini diberi kunci oleh ID buram ini. Cakupan kenangan yang dihasilkan disimpan sebagai {"user_id": "USER_ID"}.
    2. Membuat kenangan untuk sesi Anda saat ini. Jika Memory Bank mengekstrak kenangan dari percakapan, kenangan tersebut akan disimpan dalam cakupan {"user_id": USER_ID, "app_name": APP_NAME}.

      session = await session_service.get_session(
          app_name=app_name,
          user_id="USER_ID",
          session_id=session.id
      )
      await memory_service.add_session_to_memory(session)
      
    3. Buat sesi kedua Anda. Jika Anda menggunakan PreloadMemoryTool, agen akan mengambil memori di awal setiap giliran untuk mengakses preferensi yang sebelumnya dikomunikasikan pengguna kepada agen.

      session = await session_service.create_session(
          app_name=app_name,
          user_id="USER_ID"
      )
      
      call_agent("Fix the temperature!", session.id, "USER_ID")
      # Agent Response:  Setting temperature to 71 degrees.  Is that correct?
      

    Pembersihan

    Untuk membersihkan semua resource yang digunakan dalam project ini, Anda dapat menghapus Google Cloud project yang Anda gunakan untuk panduan memulai.

    Atau, Anda dapat menghapus setiap resource yang dibuat dalam tutorial ini, sebagai berikut:

    1. Gunakan contoh kode berikut untuk menghapus instance Vertex AI Agent Engine, yang juga menghapus Sesi atau Memori apa pun yang dimiliki Vertex AI Agent Engine tersebut.

      agent_engine.delete(force=True)
      
    2. Hapus semua file yang dibuat secara lokal.

    Langkah berikutnya