Tutorial ini menunjukkan cara membuat contoh few-shot secara iteratif dan
mengambilnya secara dinamis dari Example Store untuk memperbaiki perilaku LLM.
Dalam tutorial ini, Anda akan menggunakan model gemini-2.0-flash
.
Anda akan melakukan hal berikut:
Buat instance Example Store (
ExampleStore
).Buat contoh berdasarkan respons dari Gemini dan upload contoh tersebut ke instance Example Store.
Ambil contoh Anda secara dinamis dari Example Store untuk memandu LLM ke 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
- 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.
- Jika Anda memilih project, pastikan Anda memiliki peran IAM Pengguna Vertex AI (
roles/aiplatform.user
) di project tersebut. - Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
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.
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.
Jalankan perintah berikut untuk menginstal Vertex AI SDK untuk Python untuk Example Store.
pip install --upgrade google-cloud-aiplatform>=1.87.0
Gunakan contoh kode berikut untuk mengimpor dan melakukan inisialisasi 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.
Tentukan alat fungsi
get_current_weather
. Contoh yang Anda buat di langkah berikutnya akan memandu model tentang kapan harus memanggil fungsi ini dan argumen apa yang akan diteruskan ke fungsi tersebut.Untuk informasi selengkapnya tentang cara contoh dapat meningkatkan performa panggilan fungsi dan respons model, lihat Menggunakan contoh untuk meningkatkan performa panggilan fungsi. Untuk 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." } }, }, )
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=[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])] ) )
Lakukan salah satu hal berikut untuk membuat dan mengupload contoh.
Jika respons dari LLM menunjukkan perilaku yang diharapkan, gunakan contoh kode berikut untuk menulis contoh berdasarkan respons dan menguploadnya ke Contoh 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 mengalami kesulitan dalam 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])
Ulangi langkah 2 dan 3 untuk menulis 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.
Gunakan contoh kode berikut untuk menghapus instance Example Store.
example_store.delete()
Menghapus file apa pun yang dibuat secara lokal.
- Pelajari cara membuat instance Example Store.
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.
Untuk informasi selengkapnya, lihat Menyiapkan ADC untuk lingkungan pengembangan lokal dalam Google Cloud dokumentasi autentikasi.
Mengimpor library
Membuat instance Example Store
Gunakan contoh kode berikut untuk membuat instance Example Store yang menggunakan
model penyematan text-embedding-005
.
example_store = example_stores.ExampleStore.create(
example_store_config=example_stores.ExampleStoreConfig(
vertex_embedding_model="text-embedding-005"
)
)
Perhatikan bahwa pembuatan Contoh Toko memerlukan waktu beberapa menit.
Untuk mengetahui informasi selengkapnya tentang cara membuat atau menggunakan kembali instance Example Store, lihat Membuat instance Example Store.
Mengupload contoh ke instance Example Store
Lakukan langkah-langkah berikut untuk menulis dan mengupload contoh ke instance Contoh Store. Anda dapat mengupload maksimal lima contoh per permintaan.
Mengambil dan menggunakan contoh dengan Gemini
Telusuri contoh berdasarkan kemiripannya dengan perintah Anda. Kemudian, Anda dapat menyertakan contoh ini dalam perintah untuk memandu LLM ke perilaku yang diharapkan.
Menentukan fungsi bantuan untuk memformat contoh
Gunakan contoh kode berikut untuk menentukan class ExampleStorePrompt
dan fungsi
helper 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 ""
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
)
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-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])]
)
)
Meningkatkan kualitas respons secara iteratif
Untuk meningkatkan pola respons Gemini menggunakan contoh few-shot, ulangi langkah-langkah di bagian berikut:
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: