Panduan memulai cepat Example Store dengan Gemini

Tutorial ini menunjukkan cara membuat contoh few-shot secara iteratif dan mengambilnya secara dinamis dari Example Store untuk mengoreksi perilaku LLM. Anda akan melakukan hal berikut:

  • Buat instance Example Store (ExampleStore).

  • Buat contoh penulis berdasarkan respons dari Gemini dan upload contoh tersebut ke instance Example Store.

  • Ambil contoh Anda secara dinamis dari Example Store untuk memandu LLM menuju perilaku yang diharapkan.

  • Jalankan pembersihan.

Sebelum memulai

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

Menyiapkan project

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Cloud de Confiance project.

  3. Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. Jika Anda memilih project, pastikan Anda memiliki peran IAM Pengguna platform agen (roles/aiplatform.user) di project tersebut.

Melakukan autentikasi ke Agent Platform

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. Instal Google Cloud CLI.

  2. Konfigurasi gcloud CLI agar menggunakan identitas gabungan Anda.

    Untuk mengetahui informasi selengkapnya, lihat Login ke gcloud CLI dengan identitas gabungan Anda.

  3. Buat kredensial autentikasi lokal untuk akun pengguna Anda:

    gcloud auth application-default login

    Jika error autentikasi ditampilkan, pastikan Anda telah login ke gcloud CLI dengan identitas gabungan Anda.

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

Mengimpor library

  1. Jalankan perintah berikut untuk menginstal Agent Platform SDK for Example Store.

    pip install --upgrade google-cloud-aiplatform>=1.87.0
  2. Gunakan contoh kode berikut untuk mengimpor dan menginisialisasi SDK untuk Example Store.

    import vertexai
    from vertexai.preview import example_stores
    
    vertexai.init(
      project="PROJECT_ID",
      location="LOCATION"
    )
    

    Ganti kode berikut:

    • PROJECT_ID: Project ID Anda.

    • LOCATION: Region Anda. Hanya us-central1 yang didukung.

Membuat instance Example Store

Gunakan contoh kode berikut untuk membuat instance Example Store yang menggunakan model embedding text-embedding-005.

example_store = example_stores.ExampleStore.create(
    example_store_config=example_stores.ExampleStoreConfig(
        vertex_embedding_model="text-embedding-005"
    )
)

Perhatikan bahwa pembuatan Toko Contoh memerlukan waktu beberapa menit.

Untuk mengetahui informasi selengkapnya tentang cara membuat atau menggunakan kembali instance Toko Contoh, lihat Membuat instance Toko Contoh.

Mengupload contoh ke instance Example Store

Lakukan langkah-langkah berikut untuk membuat dan mengupload contoh ke instance Example Store. Anda dapat mengupload maksimal lima contoh per permintaan.

  1. Tentukan alat fungsi get_current_weather. Contoh yang Anda buat pada langkah-langkah berikutnya akan memandu model tentang kapan harus memanggil fungsi ini dan argumen apa yang harus diteruskan ke fungsi tersebut.

    Untuk mengetahui informasi selengkapnya tentang cara contoh dapat meningkatkan performa panggilan fungsi dan respons model, lihat Menggunakan contoh untuk meningkatkan performa panggilan fungsi. Untuk mengetahui informasi selengkapnya tentang cara membuat aplikasi panggilan fungsi, lihat Pengantar panggilan fungsi.

    from google.genai import types as genai_types
    
    get_current_weather_func = genai_types.FunctionDeclaration(
      name="get_current_weather",
      description="Get the current weather in a given location",
      parameters={
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
      },
    )
    
  2. Kirim permintaan ke Gemini untuk membuat konten menggunakan fungsi get_current_weather.

    Lihat Membuat klien untuk Gen AI SDK.

    from google import genai
    
    client = genai.Client(
        http_options=genai_types.HttpOptions(api_version="v1"),
        vertexai=True,
        project="PROJECT_ID",
        location="LOCATION")
    
    user_content = genai_types.Content(
      role="user",
      parts=[genai_types.Part(text="What is the weather like in Boston?")],
    )
    response = client.models.generate_content(
      model="gemini-3.5-flash",
      user_content,
      config=genai_types.GenerateContentConfig(
        tools=[
          genai_types.Tool(function_declarations=[get_current_weather_func])]
      )
    )
    
  3. Lakukan salah satu tindakan berikut untuk membuat dan mengupload contoh.

    • Jika respons dari LLM menunjukkan perilaku yang diharapkan, gunakan contoh kode berikut untuk membuat contoh berdasarkan respons dan menguploadnya ke Example Store.

      function_response = genai_types.Content(
        parts=[
          genai_types.Part(
            function_response={
              "name": "get_current_weather",
              "response": {
                "location": "New York, NY", "temperature": 38,
                "description": "Partly Cloudy",
                "icon": "partly-cloudy", "humidity": 65,
                "wind": { "speed": 10, "direction": "NW" }
              }
            }
          )
        ]
      )
      final_model_response = genai_types.Content(
        role="model",
        parts=[genai_types.Part(text="The weather in NYC is 38 degrees and partly cloudy.")],
      )
      example = {
        "contents_example": {
          "contents": [user_content.to_json_dict()],
          "expected_contents": [
            {"content": response.candidates[0].content.to_json_dict()},
            {"content": function_response.to_json_dict()},
            {"content": final_model_response.to_json_dict()},
          ],
        },
        "search_key": user_content.parts[0].text,
      }
      example_store.upsert_examples(examples=[example])
      
    • Atau, jika respons tidak mencakup semua fungsi atau hasil yang Anda harapkan atau Anda melihat model kesulitan melakukan penalaran, gunakan contoh kode berikut untuk menulis respons guna memperbaiki perilaku model.

      expected_function_call = genai_types.Content(
        parts=[
          genai_types.Part(
            function_call={
              "name": "get_current_weather",
              "args": {"location": "New York, NY"}
            }
          )
        ]
      )
      function_response = genai_types.Content(
        parts=[
          genai_types.Part(
            function_response={
              "name": "get_current_weather",
              "response": {
                "location": "New York, NY", "temperature": 38,
                "description": "Partly Cloudy",
                "icon": "partly-cloudy", "humidity": 65,
                "wind": { "speed": 10, "direction": "NW" }
              }
            }
          )
        ]
      )
      final_model_response = genai_types.Content(
        role="model",
        parts=[genai_types.Part(text="The weather in NYC is 38 degrees and partly cloudy.")],
      )
      example = {
        "contents_example": {
          "contents": [user_content.to_json_dict()],
          "expected_contents": [
            {"content": expected_function_call.to_json_dict()},
            {"content": function_response.to_json_dict()},
            {"content": final_model_response.to_json_dict()},
          ],
        },
        "search_key": user_content.parts[0].text,
      }
      example_store.upsert_examples(examples=[example])
      
  4. Ulangi langkah 2 dan 3 untuk membuat dan mengupload beberapa contoh, sesuai kebutuhan. Anda dapat mengupload contoh tambahan jika model menunjukkan perilaku yang tidak terduga atau contoh yang diupload tidak mencakup semua fungsi, hasil, atau penalaran yang Anda harapkan. Untuk mengetahui informasi selengkapnya tentang kapan Anda perlu mengupload contoh tambahan, lihat Mengupload contoh.

Mengambil dan menggunakan contoh dengan Gemini

Telusuri contoh berdasarkan kemiripannya dengan perintah Anda. Kemudian, Anda dapat menyertakan contoh ini dalam perintah untuk mengarahkan LLM ke perilaku yang diharapkan.

Menentukan fungsi bantuan untuk memformat contoh

Gunakan contoh kode berikut untuk menentukan class ExampleStorePrompt dan fungsi pembantu yang memungkinkan Anda menelusuri dan mengambil contoh.

import abc
import jinja2
import json

from google.protobuf import json_format
# --BOILERPLATE CODE FOR FORMATTING--

EXAMPLES_PREAMBLE = """<EXAMPLES>
The following are examples of user queries and model responses using the available python libraries.

Begin few-shot
"""

EXAMPLES_POSTAMBLE = """
End few-shot

Now, try to follow these examples and complete the following conversation:
</EXAMPLES>
"""

EXAMPLE_PREAMBLE = "EXAMPLE"

TEMPLATE = """
"""

class ExampleStorePrompt:

    def __init__(
          self, template = TEMPLATE, example_preamble = EXAMPLE_PREAMBLE,
          examples_preamble = EXAMPLES_PREAMBLE,
          examples_postamble = EXAMPLES_POSTAMBLE):

        self.template = jinja2.Template(template)
        self.example_preamble = example_preamble
        self.examples_preamble = examples_preamble
        self.examples_postamble = examples_postamble

    @abc.abstractmethod
    def process_function_response(self, function_response):
        return json.dumps(function_response)

    @abc.abstractmethod
    def process_function_call(self, function_call):
        args_list = []
        for key, value in function_call.get("args", []).items():
            if isinstance(value, str):
                # Wrap strings in quotes.
                value = f'"{value}"'
            if isinstance(value, list):
                value = ', '.join(
                    f'"{item}"' if isinstance(item, str)
                    else str(item) for item in value)
                value = f"[{value}]"
            if isinstance(value, dict):
                value = json.dumps(value)
            args_list.append(f'{key}={value}')
        args = ", ".join(args_list)
        return f"```\n{function_call.get('name')}({args})\n```"

    @abc.abstractmethod
    def process_part(self, part):
        if "function_call" in part:
            return self.process_function_call(part["function_call"])
        if "text" in part:
            return part.get("text")
        if "function_response" in part:
            return self.process_function_response(part["function_response"])

    @abc.abstractmethod
    def process_content(self, content):
        response = []
        for part in content.get("parts", []):
            response.append(self.process_part(part))
        return [content.get("role"), response]

    @abc.abstractmethod
    def example_formatter(self, example: dict):
        response = []
        for content in example.get("contents", []):
            response.append(self.process_content(content))
        for content in example.get("expected_contents", []):
            content = content.get("content", {})
            response.append(self.process_content(content))
        return response

    def get_prompt(self, examples: list):
        if not examples:
          return ""
        examples = [self.example_formatter(example) for example in examples]
        return self.template.render(
            examples=examples,
            example_preamble=self.example_preamble,
            examples_preamble=self.examples_preamble,
            examples_postamble=self.examples_postamble
        )

Menelusuri contoh yang relevan

Gunakan contoh kode berikut untuk menelusuri contoh yang relevan dengan percakapan yang sedang berlangsung dengan LLM. Kemudian, Anda dapat menggunakan fungsi bantuan untuk menyertakan contoh ini dalam perintah Anda.

query = "what's the fastest way to get to disney from lax"

# Search for relevant examples.
examples = example_store.search_examples(
  {"stored_contents_example_key": query}, top_k=3)

prompt = ExampleStorePrompt().get_prompt(examples.get("results", []))

model_response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="How do I get to LAX?",
    config=genai_types.GenerateContentConfig(
      system_instruction=prompt,
      tools=[
        genai_types.Tool(function_declarations=[get_current_weather_func])]
  )
)

Meningkatkan kualitas respons secara iteratif

Untuk meningkatkan pola respons Gemini menggunakan contoh few-shot, ulangi langkah-langkah di bagian berikut:

  1. Buat dan upload contoh ke instance Example Store.

  2. Mengambil dan menggunakan contoh dengan Gemini

Pembersihan

Untuk membersihkan semua resource yang digunakan dalam project ini, Anda dapat menghapus Cloud de Confiance by S3NS 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 Example Store.

    example_store.delete()
    
  2. Hapus semua file yang dibuat secara lokal.

Langkah berikutnya