使用 Vertex AI 进行文本生成

此示例演示了如何将 Vertex AI 的 Generative Text API 与接地功能结合使用。借助“接地”功能,您可以向模型提供其他信息(例如文档或网址),从而提高生成文本的准确性和相关性。 此特定示例展示了如何将 Google 搜索用作依据来源,以便模型通过网页搜索访问现实世界中的信息。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Python API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import vertexai

from vertexai.language_models import GroundingSource, TextGenerationModel

# TODO(developer): Update project_id and location
vertexai.init(project=PROJECT_ID, location="us-central1")

# TODO developer - override these parameters as needed:
parameters = {
    "temperature": 0.7,  # Temperature controls the degree of randomness in token selection.
    "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
    "top_p": 0.8,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
    "top_k": 40,  # A top_k of 1 means the selected token is the most probable among all tokens.
}

model = TextGenerationModel.from_pretrained("text-bison@002")

# TODO(developer): Update values for data_store_location, data_store_id
# data_store_id = ""
# data_store_location = ""
if data_store_id and data_store_location:
    # Use Vertex AI Search data store
    grounding_source = GroundingSource.VertexAISearch(
        data_store_id=data_store_id, location=data_store_location
    )
else:
    # Use Google Search for grounding (Private Preview)
    grounding_source = GroundingSource.WebSearch()

response = model.predict(
    "What are the price, available colors, and storage size options of a Pixel Tablet?",
    grounding_source=grounding_source,
    **parameters,
)
print(f"Response from Model: {response.text}")
print(f"Grounding Metadata: {response.grounding_metadata}")

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器