Gemini クイックスタートを使用したショップの例

このチュートリアルでは、少数ショットの例を繰り返し作成し、Example Store から動的に取得して LLM の動作を修正する方法について説明します。このチュートリアルでは、gemini-2.0-flash モデルを使用します。次の操作を行います。

  • Example Store インスタンス(ExampleStore)を作成します。

  • Gemini からのレスポンスに基づいてサンプルを作成し、それらのサンプルを Example Store インスタンスにアップロードします。

  • Example Store からサンプルを動的に取得して、LLM を期待される動作に導きます。

  • クリーンアップする。

始める前に

このチュートリアルで説明する手順を完了するには、まずプロジェクトと環境を設定する必要があります。

プロジェクトを設定する

  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. プロジェクトを選択した場合は、そのプロジェクトに対する Vertex AI ユーザーroles/aiplatform.user)IAM ロールがあることを確認します。
  9. Vertex AI に対する認証

    ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

    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.

    詳細については、 Google Cloud 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。

    ライブラリをインポートする

    1. 次のコマンドを実行して、Vertex AI SDK for Python for Example Store をインストールします。

      pip install --upgrade google-cloud-aiplatform>=1.87.0
    2. 次のコードサンプルを使用し、Example Store の SDK をインポートして初期化します。

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

      次のように置き換えます。

      • PROJECT_ID: プロジェクト ID。

      • LOCATION: リージョン。us-central1 のみがサポートされています。

    Example Store インスタンスを作成する

    次のコードサンプルを使用して、text-embedding-005 エンベディング モデルを使用する Example Store インスタンスを作成します。

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

    Example Store の作成には数分かかります。

    Example Store インスタンスの作成または再利用の詳細については、Example Store インスタンスを作成するをご覧ください。

    サンプルを Example Store インスタンスにアップロードする

    次の手順に沿って、サンプルを作成して Example Store インスタンスにアップロードします。リクエストごとにアップロードできるサンプルは 5 つまでです。

    1. get_current_weather 関数ツールを定義します。以降の手順で作成する例は、この関数を呼び出すタイミングと、渡す引数をモデルに指示します。

      サンプルを使用して関数呼び出しのパフォーマンスとモデルのレスポンスを改善する方法については、サンプルを使用して関数呼び出しのパフォーマンスを改善するをご覧ください。関数呼び出しのアプリケーションを作成する方法については、関数呼び出しの概要をご覧ください。

      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. get_current_weather 関数を使用してコンテンツを生成するリクエストを Gemini に送信します。

      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=[Part(text="What is the weather like in Boston?")],
      )
      response = client.models.generate_content(
        model="gemini-2.0-flash",
        user_content,
        config=genai_types.GenerateContentConfig(
          tools=[
            genai_types.Tool(function_declarations=[get_current_weather_func])]
        )
      )
      
    3. 次のいずれかの方法で例を作成してアップロードします。

      • LLM からのレスポンスが想定どおりの動作を示す場合は、次のコードサンプルを使用して、レスポンスに基づいてサンプルを作成し、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])
        
      • また、レスポンスが期待したすべての関数や結果を網羅していない場合や、モデルが推論に苦労している場合は、次のコードサンプルを使用して、モデルの動作を修正するレスポンスを作成します。

        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. 必要に応じて、手順 2 と 3 を繰り返して、複数の例を作成してアップロードします。モデルで予期しない動作が発生した場合や、アップロードした例で想定されるすべての関数、結果、推論が網羅されていない場合は、追加の例をアップロードできます。追加の例をアップロードする必要がある場合について詳しくは、例をアップロードするをご覧ください。

    Gemini で例を取得して使用する

    プロンプトとの類似性に基づいて例を検索します。その後、これらの例をプロンプトに含めて、LLM を期待される動作に導くことができます。

    例の形式を設定するヘルパー関数を定義する

    次のコードサンプルを使用して、例を検索して取得できる ExampleStorePrompt クラスとヘルパー関数を定義します。

    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 ""
            contents_example = example.get("example", {}).get(
              "stored_contents_example", {}).get("contents_example", {})
            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
            )
    

    関連する例を検索する

    次のコードサンプルを使用して、LLM との進行中の会話に関連する例を検索します。その後、ヘルパー関数を使用して、これらの例をプロンプトに含めることができます。

    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-2.0-flash",
        contents="How do I get to LAX?",
        config=genai_types.GenerateContentConfig(
          system_instruction=prompt,
          tools=[
            genai_types.Tool(function_declarations=[track_flight_status_function])]
      )
    )
    

    回答の品質を反復的に改善する

    少数ショットの例を使用して Gemini のレスポンス パターンを改善するには、次のセクションの手順を繰り返します。

    1. Example Store インスタンスにサンプルを作成してアップロードします。

    2. Gemini で例を取得して使用する

    クリーンアップ

    このプロジェクトで使用しているすべてのリソースをクリーンアップするには、クイックスタートで使用した Google Cloud プロジェクトを削除します。

    それ以外の場合は、このチュートリアルで作成した個々のリソースを次のように削除できます。

    1. 次のコードサンプルを使用して、Example Store インスタンスを削除します。

      example_store.delete()
      
    2. ローカルで作成したファイルを削除します。

    次のステップ