本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
Cohere Command R 以及 Command R+ 模型
你向发出推理请求 Cohere Command R 以及 Cohere Command R+ 带InvokeModel或的模型 InvokeModelWithResponseStream(直播)。您需要获取想要使用的模型的模型 ID。要获取模型 ID,请参阅 Amazon Bedrock 中支持的根基模型。
请求和响应
- Request
-
这些区域有:Cohere Command 模型具有以下推理参数。
{
"message": string,
"chat_history": [
{
"role":"USER or CHATBOT
",
"message": string
}
],
"documents": [
{"title": string, "snippet": string},
],
"search_queries_only" : boolean,
"preamble" : string,
"max_tokens": int,
"temperature": float,
"p": float,
"k": float,
"prompt_truncation" : string,
"frequency_penalty" : float,
"presence_penalty" : float,
"seed" : int,
"return_prompt" : boolean,
"tools" : [
{
"name": string,
"description": string,
"parameter_definitions": {
"parameter name
": {
"description": string,
"type": string,
"required": boolean
}
}
}
],
"tool_results" : [
{
"call": {
"name": string,
"parameters": {
"parameter name
": string
}
},
"outputs": [
{
"text
": string
}
]
}
],
"stop_sequences": [string],
"raw_prompting" : boolean
}
以下是必要参数。
以下是可选参数。
-
chat_history – 用户和模型之间先前消息的列表,旨在为模型提供对话上下文,以便回应用户的信息。
以下是必填字段。
以下是该chat_history
字段JSON的示例
"chat_history": [
{"role": "USER", "message": "Who discovered gravity?"},
{"role": "CHATBOT", "message": "The man who is widely credited with discovering gravity is Sir Isaac Newton"}
]
-
documents – 模型可以引用以生成更准确回复的文本列表。每个文档都是一个字符串字典。生成的结果包括引用其中一些文档的引文。我们建议您将字典中字符串的总数控制在 300 字以内。您可以选择性地提供 _excludes
字段(字符串数组),以省略向模型显示的某些键值对。有关更多信息,请参阅《文档模式》指南 Cohere 文档中)。
以下是该documents
字段JSON的示例。
"documents": [
{"title": "Tall penguins", "snippet": "Emperor penguins are the tallest."},
{"title": "Penguin habitats", "snippet": "Emperor penguins only live in Antarctica."}
]
-
search_queries_only – 默认为 false
。为 true
时,响应将只包含生成的搜索查询列表,但不会进行搜索,也不会生成模型对用户 message
的回复。
-
preamble – 覆盖用于生成搜索查询的默认前言。对工具使用生成没有影响。
-
max_tokens – 模型在响应中应生成的最大词元数。请注意,设置较低的值可能会导致生成不完整。当与 tools
或 documents
字段一起使用时,设置 max_tokens
可能会导致生成不完整或没有生成。
-
temperature – 使用较低的值可降低响应中的随机性。增加参数 p
的值可以进一步最大限度地提高随机性。
-
p – Top P。使用较低的值可忽略不太可能的选项。
默认 |
最小值 |
最大值 |
0.75
|
0.01
|
0.99
|
-
k – Top K。指定模型用于生成下一个词元的词元选项数。
-
prompt_truncation – 默认为 OFF
。决定提示的构建方式。当 prompt_truncation
设置为 AUTO_PRESERVE_ORDER
时,chat_history
和 documents
中的一些元素将被删除,以生成符合模型上下文长度限制的提示。在此过程中,文档和聊天历史记录的顺序将被保留。如果 prompt_truncation
设置为 OFF
,则不会删除任何元素。
-
frequency_penalty – 用于减少生成的词元的重复性。该值越大,对之前存在的词元的惩罚力度就越大,惩罚力度与这些词元在提示或之前的生成中出现的次数成正比。
-
presence_penalty – 用于减少生成的词元的重复性。类似于 frequency_penalty
,唯一的不同是这种惩罚同等地适用于所有已经出现的词元,无论它们的确切频率如何。
-
seed – 如果指定,后端将尽最大努力确定性地对词元进行采样,这样,使用相同种子和参数的重复请求将返回相同的结果。不过,确定性无法完全保证。
-
return_prompt – 指定为 true
时,将返回发送给模型的完整提示信息。默认值为 false
。在响应中,请注意 prompt
字段中的提示。
-
tools – 模型可能建议在生成文本响应之前调用的可用工具(函数)的列表。当传递 tools
时(不传递 tool_results
),响应中的 text
字段将为 ""
,而响应中的 tool_calls
字段将由需要调用的工具列表填充。如果不需要进行任何调用,则 tool_calls
数组将为空。
有关更多信息,请参阅中的 “工具使用” Cohere 文档中)。
以下是该tools
字段JSON的示例。
[
{
"name": "top_song",
"description": "Get the most popular song played on a radio station.",
"parameter_definitions": {
"sign": {
"description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP.",
"type": "str",
"required": true
}
}
}
]
有关更多信息,请参阅《单步工具使用(函数调用)》中的 Cohere 文档中)。
-
tools_results – 模型在上一轮聊天中推荐的工具的调用结果列表。结果用于生成文本响应,并在引文中引用。使用 tool_results
时,必须同时传递 tools
。每个 tool_result
都包含有关其调用方式的信息,以及字典形式的输出列表。Cohere 独特的精细引用逻辑要求输出必须是一个列表。如果输出只有一项,如 {"status": 200}
,您仍应将其封装在列表中。
有关更多信息,请参阅中的 “工具使用” Cohere 文档中)。
以下是该tools_results
字段JSON的示例。
[
{
"call": {
"name": "top_song",
"parameters": {
"sign": "WZPZ"
}
},
"outputs": [
{
"song": "Elemental Hotel"
}
]
}
]
-
stop_sequences – 停止序列的列表。检测到停止序列后,模型将停止生成更多词元。
-
raw_prompting – 指定为 true
,以便不经任何预处理就将用户 message
发送给模型,否则为 false。
- Response
-
此响应可能包含以下字段:
{
"response_id": string,
"text": string,
"generation_id": string,
"citations": [
{
"start": int,
"end": int,
"text": "string",
"document_ids": [
"string"
]
}
],
"finish_reason": string,
"tool_calls": [
{
"name": string,
"parameters": {
"parameter name
": string
}
}
],
{
"meta": {
"api_version": {
"version": string
},
"billed_units": {
"input_tokens": int,
"output_tokens": int
}
}
}
-
response_id – 聊天完成的唯一标识符
-
text – 模型对聊天信息输入的响应。
-
generation_id – 聊天完成的唯一标识符,与 Cohere 平台上的反馈端点一起使用。
-
citations – 生成回复的内联引文和相关元数据的数组。包含以下字段:
-
prompt – 发送给模型的完整提示。指定 return_prompt
字段可返回此字段。
-
finish_reason – 模型停止生成输出的原因。可以是以下任一种:
-
complete – 完成达到生成词元的终点,请确保这是完成原因以确保获得最佳性能。
-
error_toxic – 由于内容筛选器的原因,生成无法完成。
-
error_limit – 由于达到了模型的上下文限制,生成无法完成。
-
error – 由于错误,生成无法完成。
-
user_cancel – 由于用户停止,生成无法完成。
-
max_tokens – 由于用户在请求中指定了 max_tokens
限制,且已达到该限制,生成无法完成。可能无法获得最佳性能。
-
tool_calls – 要调用的相应工具的列表。仅在您指定了 tools
输入字段后才会返回。
有关更多信息,请参阅中的 “工具使用” Cohere 文档中)。
以下是该tool_calls
字段JSON的示例。
[
{
"name": "top_song",
"parameters": {
"sign": "WZPZ"
}
}
]
-
meta — API 使用情况数据(仅用于流式传输)。
代码示例
此示例说明如何调用 Cohere Command R模型。
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the Cohere Command R model.
"""
import json
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_text(model_id, body):
"""
Generate text using a Cohere Command R model.
Args:
model_id (str): The model ID to use.
body (str) : The reqest body to use.
Returns:
dict: The response from the model.
"""
logger.info("Generating text with Cohere model %s", model_id)
bedrock = boto3.client(service_name='bedrock-runtime')
response = bedrock.invoke_model(
body=body,
modelId=model_id
)
logger.info(
"Successfully generated text with Cohere Command R model %s", model_id)
return response
def main():
"""
Entrypoint for Cohere example.
"""
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
model_id = 'cohere.command-r-v1:0'
chat_history = [
{"role": "USER", "message": "What is an interesting new role in AI if I don't have an ML background?"},
{"role": "CHATBOT", "message": "You could explore being a prompt engineer!"}
]
message = "What are some skills I should have?"
try:
body = json.dumps({
"message": message,
"chat_history": chat_history,
"max_tokens": 2000,
"temperature": 0.6,
"p": 0.5,
"k": 250
})
response = generate_text(model_id=model_id,
body=body)
response_body = json.loads(response.get('body').read())
response_chat_history = response_body.get('chat_history')
print('Chat history\n------------')
for response_message in response_chat_history:
if 'message' in response_message:
print(f"Role: {response_message['role']}")
print(f"Message: {response_message['message']}\n")
print("Generated text\n--------------")
print(f"Stop reason: {response_body['finish_reason']}")
print(f"Response text: \n{response_body['text']}")
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 generating text with Cohere model {model_id}.")
if __name__ == "__main__":
main()