このチュートリアルでは、少数ショットの例を反復的に作成し、Example Store から動的に取得して LLM の動作を修正する方法について説明します。このチュートリアルでは、gemini-1.5-pro-001
モデルを使用します。次の操作を行います。
サンプル ストア インスタンス���
ExampleStore
)を作成します。Gemini からのレスポンスに基づいてサンプルを作成し、それらのサンプルを Example Store インスタンスにアップロードします。
Example Store からサンプルを動的に取得して、LLM を期待される動作に導きます。
クリーンアップする。
始める前に
このチュートリアルで説明する手順を完了するには、まずプロジェクトと環境を設定する必要があります。
プロジェクトを設定する
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
- プロジェクトを選択した場合は、プロジェクトに対する Vertex AI ユーザー(
roles/aiplatform.user
)IAM ロールがあることを確認します。
Vertex AI に対する認証
ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
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.
詳細については、 Google Cloud 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。
ライブラリをインポートする
次のコマンドを実行して、Vertex AI SDK for Python for Example Store をインストールします。
pip install --upgrade google-cloud-aiplatform>=1.87.0
次のコードサンプルを使用し、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 インスタンスにアップロードします。リクエストごとにアップロードできるサンプルは 5 つまでです。
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." } }, }, )
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])] ) )
次のいずれかの方法でサンプルを作成してアップロードします。
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])
必要に応じて、手順 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 のレスポンス パターンを改善するには、次のセクションの手順を繰り返します。
クリーンアップ
このプロジェクトで使用しているすべてのリソースをクリーンアップするには、クイックスタートで使用した プロジェクトを削除 Google Cloud します。
それ以外の場合は、このチュートリアルで作成し��個々のリソースを次のように削除できます。
次のコードサンプルを使用して、Example Store インスタンスを削除します。
example_store.delete()
ローカルで作成したファイルを削除します。
次のステップ
- Example Store インスタンスを作成する方法を学習する。