与匡威进行对话 - Amazon Bedrock

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与匡威进行对话

您可以使用 Amazon Bedrock Converse API 创建对话应用程序,用于向 Amazon Bedrock 模型发送和接收消息。例如,您可以创建一个聊天机器人,该机器人可以在多个回合中保持对话,并使用适合您需求的角色或语气自定义,例如有用的技术支持助理。

要使用 ConverseAPI,您可以使用 ConverseConverseStream(用于流式传输响应)操作向模型发送消息。可以将现有的推理操作(InvokeModelInvokeModelWithResponseStream)用于对话应用程序。但是,我们建议使用匡威,API因为它提供了一致性API,适用于所有支持消息的 Amazon Bedrock 型号。这意味着您只需编写一次代码,即可将其用于不同的模型。如果模型具有唯一的推理参数,Converse API 还允许您在模型特定的结构中传递这些唯一参数。

您可以使用 Converse API 在应用程序中实现工具使用护栏

注意

与 Mistral AI 以及 Meta 模型,Converse 会将你的输入API嵌入到特定于模型的提示模板中,该模板可以进行对话。

支持的型号和型号功能

匡威API支持以下 Amazon Bedrock 型号和型号功能。匡威API不支持任何嵌入模型(例如 Titan Embeddings G1 - Text) 或图像生成模型(例如 Stability AI).

模型 交谈 ConverseStream 系统提示 文档聊天 视觉 工具使用 流媒体工具的使用 防护机制

AI21 Jamba-Instruct

AI21 Labs Jurassic-2 (文本)

有限。不支持聊天。

Amazon Titan 模型

不支持

是(除了 Titan Text Premier)

Anthropic Claude 2 及更早版本

Anthropic Claude 3

Anthropic Claude 3.5

Cohere Command

有限。不支持聊天。

有限。不支持聊天。

Cohere Command Light

有限。不支持聊天。

有限。不支持聊天。

Cohere Command R 以及 Command R+

Meta Llama 2 以及 Llama 3

Meta Llama 3.1

Mistral AI Instruct

Mistral Large

Mistral Large 2 (24.07)

Mistral Small
注意

Cohere Command (文本)和 AI21 Labs Jurassic-2 (文本)不支持与匡威API聊天。这些模型一次只能处理一条用户消息,并且无法维护对话的历史记录。如果您尝试传递多条消息,则会出现错误。

使用匡威 API

要使用 ConverseAPI,您可以调用ConverseConverseStream操作向模型发送消息。要拨打电话Converse,您需要获得bedrock:InvokeModel操作权限。要拨打电话ConverseStream,您需要获得bedrock:InvokeModelWithResponseStream操作权限。

请求

您可以通过设置modelId字段来指定要使用的模型。有关 Amazon Bedrock 支持的型号IDs列表,请参阅Amazon Bedrock 模型 IDs

对话是用户和模特之间的一系列消息。您可以通过以用户(用户角色)的身份向模型发送消息来开始对话。然后,模型充当助手(助理角色),生成一个响应,并在消息中返回该响应。如果需要,您可以通过向模特发送更多用户角色消息来继续对话。要维护对话上下文,请务必在后续请求中包含您从模特那里收到的所有助理角色消息。有关代码示例,请参阅 匡威示例 API

您在messages字段中提供要传递给模型的消息,该消息映射到一个 M es sage 对象数组。每条消息都包含消息的内容以及该消息在对话中扮演的角色。

注意

Amazon Bedrock 不会存储您作为内容提供的任何文本、图像或文档。数据仅用于生成响应。使用 Converse 时API,必须使用大小小于 4.5 MB 的未压缩和解码文档。

您将消息的内容存储在字段中,该content字段映射到ContentBlock对象数组。在每个字段ContentBlock中,您可以指定以下字段之一(要查看哪些模型支持哪些模式,请参阅支持的型号和型号功能):

text

text字段映射到指定提示符的字符串。该text字段与同一字段中指定的其他字段一起解释ContentBlock

下面显示了一个 M essag e 对象,其content数组仅包含文本 ContentBlock

{ "role": "user | assistant", "content": [ { "text": "string" } ] }
image

image字段映射到 ImageBlock. 为字段中的图像传递以 base64 编码的原始字节。bytes如果你使用 AWS SDK,你不需要在 base64 中对字节进行编码。

如果您排除该text字段,则模型将描述图像。

下面显示了一个 M essag e 对象,其content数组仅包含图像 ContentBlock

{ "role": "user", "content": [ { "image": { "format": "png | jpeg | gif | webp", "source": { "bytes": "image in bytes" } } } ] }
document

document字段映射到 DocumentBlock. 如果您包含DocumentBlock,请检查您的请求是否符合以下限制:

  • 在 Mess ag e 对象的content字段中,还必须包括一个带有与文档相关的提示的text字段。

  • 为字段中的文档传递以 base64 编码的原始字节。bytes如果你使用 AWS SDK,你不需要用 base64 对文档字节进行编码。

  • name字段只能包含以下字符:

    • 字母数字字符

    • 空格字符(连续不超过一个)

    • 连字符

    • 圆括号

    • 方括号

    注意

    name字段容易受到即时注入的影响,因为模型可能会无意中将其解释为指令。因此,我们建议您指定一个中性名称。

下面显示了一个 M essag e 对象,其content数组仅包含文档ContentBlock和必需的随附文本ContentBlock

{ "role": "user", "content": [ { "text": "string" }, { "document": { "format": "pdf | csv | doc | docx | xls | xlsx | html | txt | md", "name": "string", "source": { "bytes": "document in bytes" } } } ] }

中的其他字段ContentBlock仅供工具使用

您可以在role字段中指定角色。该角色可以是以下角色之一:

  • user-向模型发送消息的人。

  • 助手 — 向人类用户发送消息的模型。

注意

以下限制与该content领域有关:

  • 您最多可以包含 20 张图片。每张图片的大小、高度和宽度必须分别不超过 3.75 MB、8,000 像素和 8,000 像素。

  • 您最多可以包括五个文档。每个文档的大小不得超过 4.5 MB。

  • 如果role是,则只能包含图像和文档user

在以下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 playlists for a radio station that plays rock and pop music. Only return song names and the artist. " } ]

推理参数

Converse API 支持您在inferenceConfig字段 () InferenceConfiguration中设置的一组基本推理参数。基本的推理参数集为:

  • maxTokens— 生成的响应中允许的最大令牌数。

  • stopSequences— 停止序列列表。停止序列是导致模型停止生成响应的字符序列。

  • 温度-模型在生成响应时选择更高概率选项的可能性。

  • TopP — 模型考虑的下一个代币中最有可能的候选人的百分比。

有关更多信息,请参阅 使用推理参数生成影响响应

以下示例JSON设置temperature推理参数。

{"temperature": 0.5}

如果您使用的模型具有其他推理参数,则可以通过在additionalModelRequestFields字段JSON中指定这些参数来设置这些参数。以下示例JSON显示了如何设置top_k,可在中找到 Anthropic Claude 模型,但不是消息API中的基本推理参数。

{"top_k": 200}

您可以在additionalModelResponseFieldPaths字段中为其他模型参数指定路径,如以下示例所示。

[ "/stop_sequence" ]

API返回您在该字段中请求的其他字additionalModelResponseFields段。

响应

您从 Converse 获得的响应API取决于您调用的操作ConverseConverseStream

匡威回应

在来自的响应中Converseoutput字段 (ConverseOutput) 包含模型生成的消息(消息)。消息内容位于 content (ContentBlock) 字段中,消息对应的角色(userassistant)位于该role字段中。

metrics段 (ConverseMetrics) 包含呼叫的指标。要确定模型停止生成内容的原因,请选中该stopReason字段。通过选中usage字段 (TokenUsage),您可以获取有关在请求中传递给模型的令牌以及响应中生成的令牌的信息。如果您在请求中指定了其他响应字段,则会像在additionalModelResponseFields字段JSON中一样API返回这些字段。

以下示例显示了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响应字段中返回该流。直播按以下顺序发出以下事件。

  1. messageStart(MessageStartEvent)。消息的开始事件。包括消息的角色。

  2. contentBlockStart(ContentBlockStartEvent)。内容区块启动事件。仅限工具使用。

  3. contentBlockDelta(ContentBlockDeltaEvent)。内容区块增量事件。包括模型生成的部分文本或用于工具的部分输入 json。

  4. contentBlockStop(ContentBlockStopEvent)。内容屏蔽停止事件。

  5. messageStop(MessageStopEvent)。消息的停止事件。包括模型停止生成输出的原因。

  6. metadata(ConverseStreamMetadataEvent)。请求的元数据。元数据包括 usage (TokenUsage) 中的令牌使用情况和 metrics (ConverseStreamMetadataEvent) 中调用的指标。

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}}}

匡威示例 API

以下示例向您展示了如何使用ConverseConverseStream操作。

主题
    Conversation with text message example

    此示例说明如何使用调用Converse操作 Anthropic Claude 3 Sonnet模型。该示例说明如何发送模型独有的输入文本、推理参数和其他参数。该代码通过要求模特创建歌曲列表来开始对话。然后,它继续对话,询问这些歌曲是英国艺术家创作的。

    # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use the Converse 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()
    Conversation with image example

    此示例说明如何将图像作为消息的一部分发送,并要求模型对图像进行描述。该示例使用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 Converse API 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 input message. input_image : The input image. Returns: response (JSON): The conversation that the model generated. """ logger.info("Generating message with model %s", model_id) # Message to send. with open(input_image, "rb") as f: image = f.read() message = { "role": "user", "content": [ { "text": input_text }, { "image": { "format": 'png', "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()
    Conversation with document example

    此示例说明如何将文档作为消息的一部分发送,并要求模型描述文档的内容。该示例使用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): """ 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 : The input document. Returns: response (JSON): The conversation that the model generated. """ logger.info("Generating message with model %s", model_id) # Message to send. message = { "role": "user", "content": [ { "text": input_text }, { "document": { "name": "MyDocument", "format": "txt", "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/to/document.pdf' try: bedrock_client = boto3.client(service_name="bedrock-runtime") response = generate_message( bedrock_client, model_id, input_text, input_document) 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()
    Conversation streaming example

    此示例说明如何使用调用ConverseStream操作 Anthropic Claude 3 Sonnet模型。该示例说明如何发送模型独有的输入文本、推理参数和其他参数。

    # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use the Converse 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()