本教程演示了如何迭代创建少样本示例,并从 Example Store 中动态检索这些示例,以修正 LLM 的行为。
在本教程中,您将使用 gemini-2.0-flash
模型。您将执行以下操作:
创建 Example Store 实例 (
ExampleStore
)。根据 Gemini 的回答编写示例,并将这些示例上传到示例商店实例。
从 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.
-
Verify 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.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
- 如果您选择了项目,请确保您拥有该项目的 Vertex AI User (
roles/aiplatform.user
) IAM 角色。 运行以下命令以安装适用于示例商店的 Python 版 Vertex AI SDK。
pip install --upgrade google-cloud-aiplatform>=1.87.0
使用以下代码示例导入并初始化适用于示例商店的 SDK。
import vertexai from vertexai.preview import example_stores vertexai.init( project="PROJECT_ID", location="LOCATION" )
替换以下内容:
PROJECT_ID:您的项目 ID。
LOCATION:您的区域。 仅支持
us-central1
。
定义
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." } }, }, )
向 Gemini 发送请求,以使用
get_current_weather
函数生成内容。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 的响应显示了预期行为,请使用以下代码示例根据该响应编写示例,并将其上传到示例商店。
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 步,以创作和上传多个示例。 如果模型显示意外行为,或者上传的示例未涵盖您预期的所有函数、结果或推理,您可以上传更多示例。如需详细了解何时需要上传更多示例,请参阅上传示例。
使用以下代码示例删除示例商店实例。
example_store.delete()
删除所有本地创建的文件。
- 了解如何创建示例商店实例。
向 Vertex AI 进行身份验证
如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。
安装 Google Cloud CLI。
如果您使用的是外部身份提供方 (IdP),则必须先 使用联合身份登录 gcloud CLI。
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
导入库
创建 Example Store 实例
使用以下代码示例创建使用 text-embedding-005
嵌入模型的示例商店实例。
example_store = example_stores.ExampleStore.create(
example_store_config=example_stores.ExampleStoreConfig(
vertex_embedding_model="text-embedding-005"
)
)
请注意,创建示例商店需要几分钟时间。
如需详细了解如何创建或重复使用示例商店实例,请参阅创建示例商店实例。
将示例上传到示例商店实例
执行以下步骤,将示例编写并上传到示例商店实例。每个请求最多可以上传 5 个示例。
使用 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 项目。
否则,您可以逐个删除在本教程中创建的资源,具体操作如下: