借助零样本优化器,您可以自动优化和改进用户撰写的提示。通常,由于语言含糊不清、缺少上下文或包含无关信息,提示可能无法生成您想要的模型回答。此优化器会分析并改写现有提示,使其更清晰、更有效,并与模型的功能更好地契合,最终生成更优质的回答。
零样本优化器特别适合以下情况:
适应模型更新:升级到较新版本的模型后,您现有的提示可能无法再发挥最佳效果。
增强提示理解能力:当提示措辞复杂或可能被误解时,该工具可以重新措辞,以最大限度地提高清晰度和精确度,从而减少出现不良结果的可能性。
您可以通过以下两种方式使用优化工具:
指令生成:您无需从头开始编写复杂的系统指令,只需用简单明了的语言描述您的目标或任务即可。然后,优化器将生成一套完整且结构合理的系统指令,旨在实现您的目标。
提示优化:您有一个可用的提示,但模型的输出不一致、略微偏离主题,或者缺乏您想要的细节。优化器可以帮助改进提示,以便获得更好的输出。
优化器支持 Gemini 支持的所有语言的提示优化,并且可通过 Vertex AI SDK 使用
准备工作
为确保 Compute Engine 默认服务账号具有优化提示所需的权限,请让您的管理员为 Compute Engine 默认服务账号授予项目的以下 IAM 角色:
-
Vertex AI User (
roles/aiplatform.user
) -
Vertex AI Service Agent (
roles/aiplatform.serviceAgent
)
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
您的管理员也可以通过自定义角色或其他预定义角色为 Compute Engine 默认服务账号授予所需的权限。
优化提示
# Import libraries
import vertexai
import logging
# Google Colab authentication
from google.colab import auth
PROJECT_NAME = "PROJECT"
auth.authenticate_user(project_id=PROJECT_NAME)
# Initialize the Vertex AI client
client = vertexai.Client(project=PROJECT_NAME, location='us-central1')
# Input original prompt to optimize
prompt = """You are a professional chef. Your goal is teaching how to cook healthy cooking recipes to your apprentice.
Given a question from your apprentice and some context, provide the correct answer to the question.
Use the context to return a single and correct answer with some explanation.
"""
# Optimize prompt
output = client.prompt_optimizer.optimize_prompt(prompt=prompt)
# View optimized prompt
print(output.model_dump_json(indent=2))
此 output
对象属于 OptimizeResponse
类型,可提供有关优化流程的信息。最重要的部分是 suggested_prompt
,其中包含经过优化的提示,您可以使用该提示从模型中获得更好的结果。其他字段(尤其是 applicable_guidelines
)有助于了解系统改进提示的原因和方式,从而帮助您日后撰写更好的提示。以下是输出示例:
{
"optimization_mode": "zero_shot",
"applicable_guidelines": [
{
"applicable_guideline": "Structure",
"suggested_improvement": "Add role definition.",
"text_before_change": "...",
"text_after_change": "Role: You are an AI assistant...\n\nTask Context:\n..."
},
{
"applicable_guideline": "RedundancyInstructions",
"suggested_improvement": "Remove redundant explanation.",
"text_before_change": "...",
"text_after_change": ""
}
],
"original_prompt": "...",
"suggested_prompt": "Role: You are an AI assistant...\n\nTask Context:\n..."
}