Panduan memulai dengan Agent Development Kit

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

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

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

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

  2. Buat agen dan runner ADK lokal.

  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 Pengguna Vertex AI (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.

  10. Install the Google Cloud CLI.

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

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

    gcloud init
  13. 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.

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

    Mengimpor library

    Instal Agent Development Kit:

    pip install google-adk==1.2.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 Sesi dan Bank Memori Agent Engine Vertex AI.

    Membuat instance Vertex AI Agent Engine

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

    Jika Anda ingin Vertex AI Agent Engine Memory Bank membuat memori untuk Anda menggunakan model bahasa besar (LLM), berikan memoryBankConfig.generationConfig dan sertakan model yang ingin Anda gunakan Memory Bank untuk membuat memori. Vertex AI Reasoning Engine Service Agent project Anda harus memiliki izin aiplatform.endpoints.predict untuk menggunakan model.

    import requests
    
    import google.auth
    import google.auth.transport.requests
    
    credentials, _ = google.auth.default()
    auth_req = google.auth.transport.requests.Request()
    credentials.refresh(auth_req)
    
    url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines"
    
    response = requests.post(
        url=url,
        json={
            "contextSpec": {
                "memoryBankConfig": {
                    "generationConfig": {
                        "model": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_NAME"
                    },
                    "similaritySearchConfig": {
                        "embeddingModel": f"projects/PROJECT_ID/locations/LOCATION/publishers/google/models/EMBEDDING_MODEL_NAME"
                    }
                }
            }
        },
        headers={
            "Content-Type": "application/json; charset=utf-8",
            "Authorization": f"Bearer {credentials.token}"
        }
    
    )
    
    split_name = response.json()["name"].split("/")
    agent_engine_name = "/".join(split_name[:-2])
    

    Ganti kode berikut:

    • PROJECT_ID: Project ID Anda.
    • LOCATION: Region Anda. Hanya us-central1 yang didukung untuk Sesi dan Bank Memori Agent Engine Vertex AI.
    • MODEL_NAME: Model LLM untuk membuat memori. Anda dapat menggunakan model Gemini atau Model Garden.
    • EMBEDDING_MODEL_NAME: (Opsional) Model penyematan untuk menemukan kenangan serupa untuk cakupan tertentu. Anda dapat menggunakan model yang didukung Embeddings API yang mendukung panjang vektor 768 sebagai dimensi output.

    Membuat agen ADK

    1. Buat layanan memori berbasis Memory Bank Vertex AI Agent Engine dengan menggabungkan Memory Bank di BaseMemoryService ADK. Runner memanggil add_session_to_memory untuk memicu pembuatan memori dan search_memory untuk mengambil memori untuk cakupan saat ini.

      from datetime import datetime
      import json
      import pprint
      import requests
      
      from google import adk
      from google.adk.memory import BaseMemoryService
      from google.adk.memory import base_memory_service
      from google.adk.memory import memory_entry
      import google.auth
      import google.auth.transport.requests
      from google.genai import types
      
      class AgentEngineMemoryBankService(BaseMemoryService):
        """Memory service for Agent Engine Memory Bank."""
      
        def __init__(self, agent_engine_name):
          self.agent_engine_name = agent_engine_name
          self.url = f"https://us-central1-aiplatform.googleapis.com/v1beta1/{self.agent_engine_name}"
          self.credentials, _ = google.auth.default()
      
        async def add_session_to_memory(self, session: adk.sessions.Session):
          """Adds a session to Agent Engine Memory Bank.
      
          A session can be added multiple times during its lifetime.
      
          Args:
              session: The session to add.
          """
          auth_req = google.auth.transport.requests.Request()
          self.credentials.refresh(auth_req)
      
          response = requests.post(
              url=f"{self.url}/memories:generate",
              headers={
                  "Content-Type": "application/json; charset=utf-8",
                  "Authorization": f"Bearer {self.credentials.token}",
              },
              json={
                  "vertex_session_source": {
                      "session": f"{self.agent_engine_name}/sessions/{session.id}"
                  }
              }
          )
          return response.json()
      
        async def search_memory(
            self, app_name: str, user_id: str, query: str
        ) -> adk.memory.base_memory_service.SearchMemoryResponse:
          """Searches for memories that match the query."""
          auth_req = google.auth.transport.requests.Request()
          self.credentials.refresh(auth_req)
      
          filter = json.dumps(json.dumps({"user_id": user_id}))
      
          response = requests.get(
              url=f"{self.url}/memories?filter=scope={filter}",
              headers={
                  "Content-Type": "application/json; charset=utf-8",
                  "Authorization": f"Bearer {self.credentials.token}",
              },
          )
      
          memory_events = []
          for memory in response.json().get("memories", []):
              memory_events.append(
                  memory_entry.MemoryEntry(
                      author="user",
                      content=types.Content(
                        parts=[types.Part(text=memory.get("fact"))],
                        role="user"),
                      timestamp=memory.get("updateTime")
                  )
              )
      
          return base_memory_service.SearchMemoryResponse(memories=memory_events)
      
    2. Saat mengembangkan agen ADK, sertakan alat Memory, yang mengontrol kapan layanan memori digunakan dan cara memori disertakan dalam perintah. Contoh agen 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()]
      )
      
    3. Buat runner ADK, yang mengorkestrasi eksekusi agen, alat, dan callback Anda. Saat menggunakan VertexAiSessionService dengan class AgentEngineMemoryBankService, runner mengatur panggilan untuk membaca dan menulis sesi serta memori.

      from google.adk.sessions import VertexAiSessionService
      
      session_service = VertexAiSessionService(
        "PROJECT_ID", "LOCATION")
      
      memory_service = AgentEngineMemoryBankService(
        agent_engine_name="AGENT_ENGINE_NAME")
      
      runner = adk.Runner(
          agent=agent,
          app_name="AGENT_ENGINE_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:

      • AGENT_ENGINE_NAME: Nama instance Vertex AI Agent Engine yang Anda buat atau instance Vertex AI Agent Engine yang ada. Nama harus dalam format berikut: projects/PROJECT_ID/locations/LOCATION/reasoningEngines/REASONING_ENGINE_ID.

    Berinteraksi dengan agen

    Setelah menentukan agen dan menyiapkan Sesi serta 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 mereka inginkan:

      session = await session_service.create_session(
        app_name="AGENT_ENGINE_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"}.

      Untuk membuat kenangan menggunakan sesi, panggil add_session_to_memory:

      await memory_service.add_session_to_memory(session)
      
    2. Buat sesi kedua Anda. Jika Anda menggunakan PreloadMemoryTool, agen akan mengambil memori di awal setiap giliran untuk mengakses preferensi yang sebelumnya disampaikan pengguna kepada agen.

      session = await session_service.create_session(
        app_name="AGENT_ENGINE_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 digunakan untuk memulai.

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

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

      credentials, _ = google.auth.default()
      auth_req = google.auth.transport.requests.Request()
      credentials.refresh(auth_req)
      
      url = "https://LOCATION-aiplatform.googleapis.com/v1beta1/AGENT_ENGINE_NAME"
      
      response = requests.delete(
          url=url,
          json={"force": True},
          headers={
              "Content-Type": "application/json; charset=utf-8",
              "Authorization": f"Bearer {credentials.token}"
          }
      
      )
      
    2. Menghapus file apa pun yang dibuat secara lokal.

    Langkah berikutnya