本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用匡威 API 进行推理
Converse API 仅在bedrock-runtime终端节点上可用。
您可以使用 Amazon Bedrock Converse API 创建对话应用程序,用于向/从 Amazon Bedrock 模型发送/接收消息。例如,您可以创建一个聊天机器人,该机器人可以在多个回合中保持对话,并使用适合您需求的角色或语气自定义,例如有用的技术支持助理。
要使用 Converse API,您可以使用 Converse 或 ConverseStream(用于流式传输响应)操作向模型发送消息。可以将现有的基础推理运算(InvokeModel或 InvokeModelWithResponseStream)用于对话应用程序。但是,建议使用 Converse API,因为它提供一致的 API,适用于所有支持消息的 Amazon Bedrock 模型。这意味着您只需编写一次代码,即可将其用于不同的模型。如果模型具有唯一的推理参数,Converse API 还允许您在模型特定的结构中传递这些唯一参数。
您可以使用 Converse API 在应用程序中实施工具使用和护栏。
有关代码示例,请参阅以下内容:
使用 Converse API
要使用 Converse API,您需要调用 Converse 或 ConverseStream 操作向模型发送消息。要调用 Converse,需具有 bedrock:InvokeModel 操作的权限。要调用 ConverseStream,需具有 bedrock:InvokeModelWithResponseStream 操作的权限。
请求
当您对 Amazon Bedrock 运行时端点发出 Converse 请求时,可以包含以下字段:
当您将提示管理器提示与 Converse 或 ConverseStream 结合使用时,以下限制适用:
-
您不能包含 additionalModelRequestFields、inferenceConfig、system 或 toolConfig 字段。
-
如果您包含 messages 字段,则消息将附加到在提示中定义的消息之后。
-
如果包含 guardrailConfig 字段,则护栏将应用于整个提示。如果您在ContentBlock字段中包含guardContent方块,则护栏将仅应用于这些方块。
展开各部分可了解有关 Converse 请求正文中字段的更多信息:
消息
messages 字段是一组 Message 对象,每个对象都定义了用户和模型之间的消息。Message 对象包含以下字段:
您可以在后续 Converse 请求中包含对话中的所有消息,并使用 role 字段指定消息是来自用户还是模型,以此来维护对话上下文。
该content字段映射到一个ContentBlock对象数组。在每个字段ContentBlock中,您可以指定以下字段之一(要查看哪些模型支持哪些模块,请查看模型一览):
- text
-
text 字段会映射到指定提示的字符串。该text字段与同一字段中指定的其他字段一起解释ContentBlock。
下面显示了一个 M essag e 对象,其content数组仅包含文本 ContentBlock:
{
"role": "user",
"content": [
{
"text": "string"
}
]
}
- image
-
该image字段映射到 ImageBlock. 为 bytes 字段中的图像传递以 base64 编码的原始字节。如果您使用 AWS 软件开发工具包,则无需在 base64 中对字节进行编码。
如果排除 text 字段,则模型描述图像。
下面显示了一个示例 Mess ag e 对象,其content数组仅包含图像 ContentBlock:
{
"role": "user",
"content": [
{
"image": {
"format": "png",
"source": {
"bytes": "image in bytes"
}
}
}
]
}
您也可以指定 Amazon S3 URI,而不是直接在请求正文中传递字节。下面显示了一个示例 Message 对象,其内容数组包含通过 Amazon S3 URI 传递的源。
{
"role": "user",
"content": [
{
"image": {
"format": "png",
"source": {
"s3Location": {
"uri": "s3://amzn-s3-demo-bucket/myImage",
"bucketOwner": "111122223333"
}
}
}
}
]
}
- document
-
该document字段映射到 DocumentBlock. 如果包含 DocumentBlock,请检查您的请求是否符合以下限制:
使用文档时,您可以启用 citations 标签,该标签将在 API 调用的响应中提供特定于文档的引文。有关更多详细信息,请参阅 DocumentBlockAPI。
下面显示了一个示例 Mess ag e 对象,其content数组仅包含文档ContentBlock和必需的随附文本ContentBlock。
{
"role": "user",
"content": [
{
"text": "string"
},
{
"document": {
"format": "pdf",
"name": "MyDocument",
"source": {
"bytes": "document in bytes"
}
}
}
]
}
您也可以指定 Amazon S3 URI,而不是直接在请求正文中传递字节。下面显示了一个示例 Message 对象,其内容数组包含通过 Amazon S3 URI 传递的源。
{
"role": "user",
"content": [
{
"text": "string"
},
{
"document": {
"format": "pdf",
"name": "MyDocument",
"source": {
"s3Location": {
"uri": "s3://amzn-s3-demo-bucket/myDocument",
"bucketOwner": "111122223333"
}
}
}
}
]
}
- video
-
该video字段映射到一个VideoBlock对象。在 bytes 字段中,传递以 base64 编码的原始字节。如果您使用 AWS 软件开发工具包,则无需在 base64 中对字节进行编码。
如果未包含 text 字段,则模型将描述视频。
下面显示了一个示例 Mess ag e 对象,其content数组仅包含视频ContentBlock。
{
"role": "user",
"content": [
{
"video": {
"format": "mp4",
"source": {
"bytes": "video in bytes"
}
}
}
]
}
您也可以指定 Amazon S3 URI,而不是直接在请求正文中传递字节。下面显示了一个示例 Message 对象,其内容数组包含通过 Amazon S3 URI 传递的源。
{
"role": "user",
"content": [
{
"video": {
"format": "mp4",
"source": {
"s3Location": {
"uri": "s3://amzn-s3-demo-bucket/myVideo",
"bucketOwner": "111122223333"
}
}
}
}
]
}
代入的角色必须具有该 Amazon S3 URI 的 s3:GetObject 权限。bucketOwner 字段可选,但如果发出请求的账户并非 Amazon S3 URI 所在存储桶的拥有者,则必须指定此字段。有关更多信息,请参阅 配置对 Amazon S3 存储桶的访问权限。
- cachePoint
-
通过使用cachePoint字段来使用提示缓存,您可以将缓存检查点作为一个块添加到消息中,以及随附的提示。提示缓存是一项功能,让您可以开始缓存对话上下文,从而节省成本和降低延迟。有关更多信息,请参阅 用于加快模型推理速度的提示缓存。
下面显示了一个示例 Mess ag e 对象,该对象包含一个包含文档ContentBlock和必需的随附文本的content数组 ContentBlock,以及一个将文档和文本内容都添加到缓存中的 CachePoint。
{
"role": "user",
"content": [
{
"text": "string"
},
{
"document": {
"format": "pdf",
"name": "string",
"source": {
"bytes": "document in bytes"
}
}
},
{
"cachePoint": {
"type": "default"
}
}
]
}
- guardContent
-
该guardContent字段映射到一个GuardrailConverseContentBlock对象。您可以使用此字段来定位要由 guardrailConfig 字段中定义的护栏进行评估的输入。如果您未指定此字段,则护栏将评估请求正文中的所有消息。您可以在 GuardBlock 中传递以下内容类型:
-
text — 下面显示了一个示例 Mess ag e 对象,其content数组仅包含文本 GuardrailConverseContentBlock:
{
"role": "user",
"content": [
{
"text": "Tell me what stocks to buy.",
"qualifiers": [
"guard_content"
]
}
]
}
您定义要评估的文本,并提供用于上下文一致性的任意限定词。
-
image — 下面显示了一个 M essag e 对象,其content数组仅包含图像 GuardrailConverseContentBlock:
{
"role": "user",
"content": [
{
"format": "png",
"source": {
"bytes": "image in bytes"
}
}
]
}
您可以指定图像的格式并以字节为单位定义图像。
有关使用护栏的更多信息,请参阅使用 Amazon Bedrock 护栏检测和筛选掉有害内容。
- reasoningContent
-
该reasoningContent字段映射到 a ReasoningContentBlock. 此单元包含关于推理的内容,此推理由生成随附 ContentBlock 中的响应的模型执行。
下面显示了一个 Message 对象,其 content 数组仅包含 ReasoningContentBlock 和一个随附的文本 ContentBlock。
{
"role": "user",
"content": [
{
"text": "string"
},
{
"reasoningContent": {
"reasoningText": {
"text": "string",
"signature": "string"
}
"redactedContent": "base64-encoded binary data object"
}
}
]
}
ReasoningContentBlock 包含用于生成 reasoningText 字段中随附内容的推理,以及模型提供商出于信任和安全原因,在 redactedContent 字段中加密的推理中的任何内容。
在 reasoningText 字段中,text 字段描述了推理。signature 字段是对话中所有消息的哈希值,用于防止篡改模型使用的推理。您必须在后续 Converse 请求中包含签名和之前的所有消息。如果任何消息发生更改,响应就会引发错误。
- toolUse
-
包含有关模型要使用的工具的信息。有关更多信息,请参阅 使用工具完成 Amazon Bedrock 模型响应。
- toolResult
-
包含有关模型使用工具得出的结果的信息。有关更多信息,请参阅 使用工具完成 Amazon Bedrock 模型响应。
在以下 messages 示例中,用户要求提供一个包含三首流行歌曲的列表,模型生成了一个歌曲列表。
[
{
"role": "user",
"content": [
{
"text": "Create a list of 3 pop songs."
}
]
},
{
"role": "assistant",
"content": [
{
"text": "Here is a list of 3 pop songs by artists from the United Kingdom:\n\n1. \"As It Was\" by Harry Styles\n2. \"Easy On Me\" by Adele\n3. \"Unholy\" by Sam Smith and Kim Petras"
}
]
}
]
系统
系统提示是一种提示,它向模型提供有关其应执行的任务或在对话中应采用的角色的说明或上下文。您可以在 system (SystemContentBlock) 字段中为请求指定系统提示列表,如以下示例所示。
[
{
"text": "You are an app that creates play lists for a radio station that plays rock and pop music. Only return song names and the artist. "
}
]
inferenceConfig
ConverseAPI 支持您在inferenceConfig字段 (InferenceConfiguration) 中设置的一组基本推理参数。基本推理参数集包括:
-
MaxTokens – 允许在生成的响应中使用的最大词元数。
-
stopSequences – 停止序列的列表。停止序列是一个字符序列,会使模型停止生成响应。
-
temperature – 模型在生成响应时选择更高概率选项的可能性。
-
topP – 模型为下一个词元考虑的最有可能的候选项所占百分比。
有关更多信息,请参阅 利用推理参数影响响应生成。
以下示例 JSON 设置了 temperature 推理参数。
{"temperature": 0.5}
额外的 ModelRequestFields
如果您使用的模型具有其他推理参数,则可以通过在 additionalModelRequestFields 字段中将其指定为 JSON 来设置这些参数。以下示例 JSON 演示了如何设置 top_k,该参数在 Anthropic Claude 模型中可用,但不是 messages API 中的基本推理参数。
{"top_k": 200}
promptVariables
如果您在 modelId 中指定提示管理器中的提示作为对其运行推理的资源,则使用此字段将实际值填充到提示变量中。promptVariables 字段映射到一个 JSON 对象,其键对应于在提示中定义的变量,其值用于替换变量。
例如,假设您有一个提示 Make me a {{genre}} playlist consisting of the following number of songs: {{number}}.。提示的 ID 是 PROMPT12345,其版本是 1。您可以发送以下 Converse 请求来替换变量:
POST /model/arn:aws:bedrock:us-east-1:111122223333:prompt/PROMPT12345:1/converse HTTP/1.1
Content-type: application/json
{
"promptVariables": {
"genre": {
"text": "pop"
},
"number": {
"text": "3"
}
}
}
guardrailConfig
您可以通过包括此字段来应用您使用 Amazon Bedrock 护栏创建的护栏。要将护栏应用于对话中的特定消息,请将该消息包含在中。GuardrailConverseContentBlock如果您在请求正文中未包含任何 GuardrailConverseContentBlock,则会将护栏应用于 messages 字段中的所有消息。有关示例,请参阅随附护栏 Converse API。
此字段让您可以为模型定义工具,用于帮助模型生成响应。有关更多信息,请参阅 使用工具完成 Amazon Bedrock 模型响应。
额外的 ModelResponseFieldPaths
您可以在 additionalModelResponseFieldPaths 字段中指定其他模型参数的路径,如以下示例所示。
[ "/stop_sequence" ]
API 会返回您在 additionalModelResponseFields 字段中请求的其他字段。
该requestMetadata字段映射到一个包含键值标签的 JSON 对象,这些标签与请求一起记录在模型调用日志中。您可以使用请求元数据按团队、应用程序、环境或每次调用不同的任何其他维度筛选和聚合日志。
同样的功能在 HTTP 标头上InvokeModel和InvokeModelWithResponseStream通过 X-Amzn-Bedrock-Request-Metadata HTTP 标头可用。有关支持的 API、限制以及请求元数据在调用日志中的显示方式的详细信息,请参阅Per-request 元数据标记。
服务等级
此字段映射到 JSON 对象。您可以为特定请求指定服务级别。
以下示例显示了serviceTier结构:
"serviceTier": {
"type": "reserved" | "priority" | "default" | "flex"
}
有关服务等级的详细信息,包括定价和性能特征,请参阅用于优化性能和成本的服务分层。
根据所用的模型,您也可以选择向 system 或 tools 字段添加缓存检查点来使用提示缓存。有关更多信息,请参阅 用于加快模型推理速度的提示缓存。
响应
您从 Converse API 获得的响应取决于您调用的操作(Converse 或 ConverseStream)。
Converse 响应
在来自的响应中Converse,output字段 (ConverseOutput) 包含模型生成的消息(消息)。消息内容位于 content (ContentBlock) 字段中,消息对应的角色(user或assistant)位于该role字段中。
如果您使用了提示缓存,则在使用情况字段中,cacheReadInputTokens 和 cacheWriteInputTokens 会分别指明对缓存读取和写入的词元总数。
如果您使用了服务层,那么在响应字段中,service tier会告诉您请求使用了哪个服务层。
字metrics段 (ConverseMetrics) 包含呼叫的指标。要确定模型停止生成内容的原因,请检查 stopReason 字段。通过选中usage字段 (TokenUsage),您可以获取有关在请求中传递给模型的令牌以及响应中生成的令牌的信息。如果您在请求中指定了其他响应字段,API 会在 additionalModelResponseFields 字段中将其作为 JSON 返回。
以下示例演示了您在传递 请求 中讨论的提示时 Converse 的响应。
{
"output": {
"message": {
"role": "assistant",
"content": [
{
"text": "Here is a list of 3 pop songs by artists from the United Kingdom:\n\n1. \"Wannabe\" by Spice Girls\n2. \"Bitter Sweet Symphony\" by The Verve \n3. \"Don't Look Back in Anger\" by Oasis"
}
]
}
},
"stopReason": "end_turn",
"usage": {
"inputTokens": 125,
"outputTokens": 60,
"totalTokens": 185
},
"metrics": {
"latencyMs": 1175
}
}
ConverseStream 响应
如果您调用 ConverseStream 以流式传输来自模型的响应,则会在 stream 响应字段中返回该流。流按以下顺序发出以下事件。
ConverseStream 将完整的内容块作为ContentBlockStartEvent事件、一个或多个事件和一个ContentBlockDeltaEventContentBlockStopEvent事件进行流式传输。使用 contentBlockIndex 字段作为索引,关联构成内容块的事件。
以下示例是来自 ConverseStream 的部分响应。
{'messageStart': {'role': 'assistant'}}
{'contentBlockDelta': {'delta': {'text': ''}, 'contentBlockIndex': 0}}
{'contentBlockDelta': {'delta': {'text': ' Title'}, 'contentBlockIndex': 0}}
{'contentBlockDelta': {'delta': {'text': ':'}, 'contentBlockIndex': 0}}
.
.
.
{'contentBlockDelta': {'delta': {'text': ' The'}, 'contentBlockIndex': 0}}
{'messageStop': {'stopReason': 'max_tokens'}}
{'metadata': {'usage': {'inputTokens': 47, 'outputTokens': 20, 'totalTokens': 67}, 'metrics': {'latencyMs': 100.0}}}
Converse API 示例
以下示例演示了如何使用 Converse 和 ConverseStream 操作。
- Text
-
此示例演示了如何使用 Anthropic Claude 3 Sonnet 模型调用 Converse 操作。此示例演示了如何发送模型独有的输入文本、推理参数和其他参数。该代码通过让模型创建歌曲列表来开始对话。然后,它继续对话,要求这些歌曲是由英国艺术家创作的。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the <noloc>Converse</noloc> API with Anthropic Claude 3 Sonnet (on demand).
"""
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_conversation(bedrock_client,
model_id,
system_prompts,
messages):
"""
Sends messages to a model.
Args:
bedrock_client: The Boto3 Bedrock runtime client.
model_id (str): The model ID to use.
system_prompts (JSON) : The system prompts for the model to use.
messages (JSON) : The messages to send to the model.
Returns:
response (JSON): The conversation that the model generated.
"""
logger.info("Generating message with model %s", model_id)
# Inference parameters to use.
temperature = 0.5
top_k = 200
# Base inference parameters to use.
inference_config = {"temperature": temperature}
# Additional inference parameters to use.
additional_model_fields = {"top_k": top_k}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
system=system_prompts,
inferenceConfig=inference_config,
additionalModelRequestFields=additional_model_fields
)
# Log token usage.
token_usage = response['usage']
logger.info("Input tokens: %s", token_usage['inputTokens'])
logger.info("Output tokens: %s", token_usage['outputTokens'])
logger.info("Total tokens: %s", token_usage['totalTokens'])
logger.info("Stop reason: %s", response['stopReason'])
return response
def main():
"""
Entrypoint for Anthropic Claude 3 Sonnet example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
# Setup the system prompts and messages to send to the model.
system_prompts = [{"text": "You are an app that creates playlists for a radio station that plays rock and pop music. Only return song names and the artist."}]
message_1 = {
"role": "user",
"content": [{"text": "Create a list of 3 pop songs."}]
}
message_2 = {
"role": "user",
"content": [{"text": "Make sure the songs are by artists from the United Kingdom."}]
}
messages = []
try:
bedrock_client = boto3.client(service_name='bedrock-runtime')
# Start the conversation with the 1st message.
messages.append(message_1)
response = generate_conversation(
bedrock_client, model_id, system_prompts, messages)
# Add the response message to the conversation.
output_message = response['output']['message']
messages.append(output_message)
# Continue the conversation with the 2nd message.
messages.append(message_2)
response = generate_conversation(
bedrock_client, model_id, system_prompts, messages)
output_message = response['output']['message']
messages.append(output_message)
# Show the complete conversation.
for message in messages:
print(f"Role: {message['role']}")
for content in message['content']:
print(f"Text: {content['text']}")
print()
except ClientError as err:
message = err.response['Error']['Message']
logger.error("A client error occurred: %s", message)
print(f"A client error occured: {message}")
else:
print(
f"Finished generating text with model {model_id}.")
if __name__ == "__main__":
main()
- Image
-
此示例演示了如何将图像作为消息的一部分发送,并要求模型对图像进行描述。此示例使用 Converse 操作和 Anthropic Claude 3 Sonnet 模型。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send an image with the <noloc>Converse</noloc> API with an accompanying text prompt to Anthropic Claude 3 Sonnet (on demand).
"""
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_conversation(bedrock_client,
model_id,
input_text,
input_image):
"""
Sends a message to a model.
Args:
bedrock_client: The Boto3 Bedrock runtime client.
model_id (str): The model ID to use.
input text : The text prompt accompanying the image.
input_image : The path to the input image.
Returns:
response (JSON): The conversation that the model generated.
"""
logger.info("Generating message with model %s", model_id)
# Get image extension and read in image as bytes
image_ext = input_image.split(".")[-1]
with open(input_image, "rb") as f:
image = f.read()
message = {
"role": "user",
"content": [
{
"text": input_text
},
{
"image": {
"format": image_ext,
"source": {
"bytes": image
}
}
}
]
}
messages = [message]
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages
)
return response
def main():
"""
Entrypoint for Anthropic Claude 3 Sonnet example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
input_text = "What's in this image?"
input_image = "path/to/image"
try:
bedrock_client = boto3.client(service_name="bedrock-runtime")
response = generate_conversation(
bedrock_client, model_id, input_text, input_image)
output_message = response['output']['message']
print(f"Role: {output_message['role']}")
for content in output_message['content']:
print(f"Text: {content['text']}")
token_usage = response['usage']
print(f"Input tokens: {token_usage['inputTokens']}")
print(f"Output tokens: {token_usage['outputTokens']}")
print(f"Total tokens: {token_usage['totalTokens']}")
print(f"Stop reason: {response['stopReason']}")
except ClientError as err:
message = err.response['Error']['Message']
logger.error("A client error occurred: %s", message)
print(f"A client error occured: {message}")
else:
print(
f"Finished generating text with model {model_id}.")
if __name__ == "__main__":
main()
- Document
-
此示例演示了如何将文档作为消息的一部分发送,并要求模型对文档内容进行描述。此示例使用 Converse 操作和 Anthropic Claude 3 Sonnet 模型。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send an document as part of a message to Anthropic Claude 3 Sonnet (on demand).
"""
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_message(bedrock_client,
model_id,
input_text,
input_document_path):
"""
Sends a message to a model.
Args:
bedrock_client: The Boto3 Bedrock runtime client.
model_id (str): The model ID to use.
input text : The input message.
input_document_path : The path to the input document.
Returns:
response (JSON): The conversation that the model generated.
"""
logger.info("Generating message with model %s", model_id)
# Get format from path and read the path
input_document_format = input_document_path.split(".")[-1]
with open(input_document_path, 'rb') as input_document_file:
input_document = input_document_file.read()
# Message to send.
message = {
"role": "user",
"content": [
{
"text": input_text
},
{
"document": {
"name": "MyDocument",
"format": input_document_format,
"source": {
"bytes": input_document
}
}
}
]
}
messages = [message]
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages
)
return response
def main():
"""
Entrypoint for Anthropic Claude 3 Sonnet example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
input_text = "What's in this document?"
input_document_path = "path/to/document"
try:
bedrock_client = boto3.client(service_name="bedrock-runtime")
response = generate_message(
bedrock_client, model_id, input_text, input_document_path)
output_message = response['output']['message']
print(f"Role: {output_message['role']}")
for content in output_message['content']:
print(f"Text: {content['text']}")
token_usage = response['usage']
print(f"Input tokens: {token_usage['inputTokens']}")
print(f"Output tokens: {token_usage['outputTokens']}")
print(f"Total tokens: {token_usage['totalTokens']}")
print(f"Stop reason: {response['stopReason']}")
except ClientError as err:
message = err.response['Error']['Message']
logger.error("A client error occurred: %s", message)
print(f"A client error occured: {message}")
else:
print(
f"Finished generating text with model {model_id}.")
if __name__ == "__main__":
main()
- Streaming
-
此示例演示了如何使用 Anthropic Claude 3 Sonnet 模型调用 ConverseStream 操作。此示例演示了如何发送模型独有的输入文本、推理参数和其他参数。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the <noloc>Converse</noloc> API to stream a response from Anthropic Claude 3 Sonnet (on demand).
"""
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def stream_conversation(bedrock_client,
model_id,
messages,
system_prompts,
inference_config,
additional_model_fields):
"""
Sends messages to a model and streams the response.
Args:
bedrock_client: The Boto3 Bedrock runtime client.
model_id (str): The model ID to use.
messages (JSON) : The messages to send.
system_prompts (JSON) : The system prompts to send.
inference_config (JSON) : The inference configuration to use.
additional_model_fields (JSON) : Additional model fields to use.
Returns:
Nothing.
"""
logger.info("Streaming messages with model %s", model_id)
response = bedrock_client.converse_stream(
modelId=model_id,
messages=messages,
system=system_prompts,
inferenceConfig=inference_config,
additionalModelRequestFields=additional_model_fields
)
stream = response.get('stream')
if stream:
for event in stream:
if 'messageStart' in event:
print(f"\nRole: {event['messageStart']['role']}")
if 'contentBlockDelta' in event:
print(event['contentBlockDelta']['delta']['text'], end="")
if 'messageStop' in event:
print(f"\nStop reason: {event['messageStop']['stopReason']}")
if 'metadata' in event:
metadata = event['metadata']
if 'usage' in metadata:
print("\nToken usage")
print(f"Input tokens: {metadata['usage']['inputTokens']}")
print(
f":Output tokens: {metadata['usage']['outputTokens']}")
print(f":Total tokens: {metadata['usage']['totalTokens']}")
if 'metrics' in event['metadata']:
print(
f"Latency: {metadata['metrics']['latencyMs']} milliseconds")
def main():
"""
Entrypoint for streaming message API response example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
system_prompt = """You are an app that creates playlists for a radio station
that plays rock and pop music. Only return song names and the artist."""
# Message to send to the model.
input_text = "Create a list of 3 pop songs."
message = {
"role": "user",
"content": [{"text": input_text}]
}
messages = [message]
# System prompts.
system_prompts = [{"text" : system_prompt}]
# inference parameters to use.
temperature = 0.5
top_k = 200
# Base inference parameters.
inference_config = {
"temperature": temperature
}
# Additional model inference parameters.
additional_model_fields = {"top_k": top_k}
try:
bedrock_client = boto3.client(service_name='bedrock-runtime')
stream_conversation(bedrock_client, model_id, messages,
system_prompts, inference_config, additional_model_fields)
except ClientError as err:
message = err.response['Error']['Message']
logger.error("A client error occurred: %s", message)
print("A client error occured: " +
format(message))
else:
print(
f"Finished streaming messages with model {model_id}.")
if __name__ == "__main__":
main()
- Video
-
此示例演示了如何将视频作为消息的一部分发送,并要求模型描述视频。此示例使用 Converse 操作和 Amazon Nova Pro 模型。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send a video with the <noloc>Converse</noloc> API to Amazon Nova Pro (on demand).
"""
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_conversation(bedrock_client,
model_id,
input_text,
input_video):
"""
Sends a message to a model.
Args:
bedrock_client: The Boto3 Bedrock runtime client.
model_id (str): The model ID to use.
input text : The input message.
input_video : The input video.
Returns:
response (JSON): The conversation that the model generated.
"""
logger.info("Generating message with model %s", model_id)
# Message to send.
with open(input_video, "rb") as f:
video = f.read()
message = {
"role": "user",
"content": [
{
"text": input_text
},
{
"video": {
"format": 'mp4',
"source": {
"bytes": video
}
}
}
]
}
messages = [message]
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages
)
return response
def main():
"""
Entrypoint for Amazon Nova Pro example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = "amazon.nova-pro-v1:0"
input_text = "What's in this video?"
input_video = "path/to/video"
try:
bedrock_client = boto3.client(service_name="bedrock-runtime")
response = generate_conversation(
bedrock_client, model_id, input_text, input_video)
output_message = response['output']['message']
print(f"Role: {output_message['role']}")
for content in output_message['content']:
print(f"Text: {content['text']}")
token_usage = response['usage']
print(f"Input tokens: {token_usage['inputTokens']}")
print(f"Output tokens: {token_usage['outputTokens']}")
print(f"Total tokens: {token_usage['totalTokens']}")
print(f"Stop reason: {response['stopReason']}")
except ClientError as err:
message = err.response['Error']['Message']
logger.error("A client error occurred: %s", message)
print(f"A client error occured: {message}")
else:
print(
f"Finished generating text with model {model_id}.")
if __name__ == "__main__":
main()