

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

# Cohere Command R and Command R\+   模型
<a name="model-parameters-cohere-command-r-plus"></a>

您可以使用[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)（流式传输）向CohereCommand R和CohereCommand R\+模型发出推理请求。您需要获取想要使用的模型的模型 ID。要获取模型 ID，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)。

**提示**  
对于对话式应用程序，我们建议您使用 Converse API。Converse API 提供了一组统一的参数，适用于所有支持消息的模型。有关更多信息，请参阅 [使用匡威 API 进行推理](conversation-inference.md)。

**Topics**
+ [请求和响应](#model-parameters-cohere-command-request-response)
+ [代码示例](#api-inference-examples-cohere-command-r)

## 请求和响应
<a name="model-parameters-cohere-command-request-response"></a>

------
#### [ 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

}
```

以下是必要参数。
+ **message** –（必要）模型要响应的文本输入。

以下是可选参数。
+ **chat\_history** – 用户和模型之间先前消息的列表，旨在为模型提供对话上下文，以便回应用户的信息。

  以下是必填字段。
  + `role` – 消息的角色。有效值为 `USER` 或 `CHATBOT`。
  + `message` – 消息的文本内容。

  以下是 `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 文档中的[文档模式指南](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode)。

  以下是 `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` 的值可以进一步最大限度地提高随机性。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **p** – Top P。使用较低的值可忽略不太可能的选项。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **k** – Top K。指定模型用于生成下一个词元的词元选项数。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+  **prompt\_truncation** – 默认为 `OFF`。决定提示的构建方式。当 `prompt_truncation` 设置为 `AUTO_PRESERVE_ORDER` 时，`chat_history` 和 `documents` 中的一些元素将被删除，以生成符合模型上下文长度限制的提示。在此过程中，文档和聊天历史记录的顺序将被保留。如果 `prompt_truncation` 设置为 `OFF`，则不会删除任何元素。
+  **frequency\_penalty** – 用于减少生成的词元的重复性。该值越大，对之前存在的词元的惩罚力度就越大，惩罚力度与这些词元在提示或之前的生成中出现的次数成正比。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+  **presence\_penalty** – 用于减少生成的词元的重复性。类似于 `frequency_penalty`，唯一的不同是这种惩罚同等地适用于所有已经出现的词元，无论它们的确切频率如何。    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html)
+ **seed** – 如果指定，后端将尽最大努力确定性地对词元进行采样，这样，使用相同种子和参数的重复请求将返回相同的结果。不过，确定性无法完全保证。
+ **return\_prompt** – 指定为 `true` 时，将返回发送给模型的完整提示信息。默认值为 `false`。在响应中，请注意 `prompt` 字段中的提示。
+ **tools** – 模型可能建议在生成文本响应之前调用的可用工具（函数）的列表。当传递 `tools` 时（不传递 `tool_results`），响应中的 `text` 字段将为 `""`，而响应中的 `tool_calls` 字段将由需要调用的工具列表填充。如果不需要进行任何调用，则 `tool_calls` 数组将为空。

  有关更多信息，请参阅 Cohere 文档中的 [Tool Use](https://docs.cohere.com/docs/tool-use)。
**提示**  
建议您使用 Converse API 将工具使用集成到应用程序中。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

  以下是 `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文档中的[Single-Step 工具使用（函数调用）](https://docs.cohere.com/docs/tool-use)。
+ **tools\_results** – 模型在上一轮聊天中推荐的工具的调用结果列表。结果用于生成文本响应，并在引文中引用。使用 `tool_results` 时，必须同时传递 `tools`。每个 `tool_result` 都包含有关其调用方式的信息，以及字典形式的输出列表。Cohere 独特的精细引用逻辑要求输出必须是一个列表。如果输出只有一项，如 `{"status": 200}`，您仍应将其封装在列表中。

  有关更多信息，请参阅 Cohere 文档中的 [Tool Use](https://docs.cohere.com/docs/tool-use)。

  以下是 `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** – 生成回复的内联引文和相关元数据的数组。包含以下字段：
  + **start** – 引用起始的索引，从 0 开始。
  + **end** – 引用结束的索引，从 0 开始。
  + **text** – 引文涉及的文本。
  + **document\_ids** – 与文本引用的文档相对应的文档 ID 数组。
+ **prompt** – 发送给模型的完整提示。指定 `return_prompt` 字段可返回此字段。
+ **finish\_reason** – 模型停止生成输出的原因。可以是以下任一种：
  + **complete** – 完成达到生成词元的终点，请确保这是完成原因以确保获得最佳性能。
  + **error\_toxic** – 由于内容筛选器的原因，生成无法完成。
  + **error\_limit** – 由于达到了模型的上下文限制，生成无法完成。
  + **error** – 由于错误，生成无法完成。
  + **user\_cancel** – 由于用户停止，生成无法完成。
  + **max\_tokens** – 由于用户在请求中指定了 `max_tokens` 限制，且已达到该限制，生成无法完成。可能无法获得最佳性能。
+ **tool\_calls** – 要调用的相应工具的列表。仅在您指定了 `tools` 输入字段后才会返回。

  有关更多信息，请参阅 Cohere 文档中的 [Tool Use](https://docs.cohere.com/docs/tool-use)。
**提示**  
建议您使用 Converse API 将工具使用集成到应用程序中。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

  以下是 `tool_calls` 字段的 JSON 示例。

  ```
  [
          {
              "name": "top_song",
              "parameters": {
                  "sign": "WZPZ"
              }
          }
      ]
  ```
+ **meta** – API 使用数据（仅适用于流式传输）。
  + `api_version` – API 版本。版本位于 `version` 字段。
  + `billed_units` – 计费单位。可能的值有：
    + `input_tokens` – 已计费的输入词元数量。
    + `output_tokens` – 已计费的输出词元数量。

------

## 代码示例
<a name="api-inference-examples-cohere-command-r"></a>

此示例展示了如何调用 *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()
```