

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

# Mistral AI 文本补全
<a name="model-parameters-mistral-text-completion"></a>

借助 Mistral AI 文本补全 API，您可以使用 Mistral AI 模型生成文本。

您可以使用 [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)（流式传输）向 Mistral AI 模型发出推理请求。

Mistral AI 模型在 [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) 许可下可用。有关使用 Mistral AI 模型的更多信息，请参阅 [https://docs.mistral.ai/](https://docs.mistral.ai/) 文档。

**Topics**
+ [

## 支持的模型
](#mistral--text-completion-supported-models)
+ [

## 请求和响应
](#model-parameters-mistral-text-completion-request-response)
+ [

## 代码示例
](#api-inference-examples-mistral-text-completion)

## 支持的模型
<a name="mistral--text-completion-supported-models"></a>

您可以使用以下 Mistral AI 模型。
+ Mistral 7B Instruct
+ Mixtral 8X7B Instruct
+ Mistral Large
+ Mistral Small

您需要获取想要使用的模型的模型 ID。要获取模型 ID，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)。

## 请求和响应
<a name="model-parameters-mistral-text-completion-request-response"></a>

------
#### [ Request ]

Mistral AI 模型具有以下推理参数。

```
{
    "prompt": string,
    "max_tokens" : int,
    "stop" : [string],    
    "temperature": float,
    "top_p": float,
    "top_k": int
}
```

以下是必要参数。
+  **prompt** –（必要）要传递给模型的提示，如下例所示。

  ```
  <s>[INST] What is your favourite condiment? [/INST]
  ```

  以下示例说明了如何格式化为多轮提示。

  ```
  <s>[INST] What is your favourite condiment? [/INST]
  Well, I'm quite partial to a good squeeze of fresh lemon juice. 
  It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!</s> 
  [INST] Do you have mayonnaise recipes? [/INST]
  ```

  `[INST]...[/INST]` 词元内的文本为用户角色，词元外的文本为助手角色。字符串的开头和结尾用 `<s>`（字符串开头）和 `</s>`（字符串结尾）词元表示。有关以正确格式发送聊天提示的信息，请参阅 Mistral AI 文档中的[聊天模板](https://docs.mistral.ai/models/#chat-template)。

以下是可选参数。
+ **max\$1tokens** – 指定要在生成的响应中使用的最大词元数。一旦生成的文本超过 `max_tokens`，模型就会截断响应。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **stop** – 停止序列的列表，如果模型生成了停止序列，就会阻止模型生成进一步输出。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **temperature** – 控制模型所做预测的随机性。有关更多信息，请参阅 [利用推理参数影响响应生成](inference-parameters.md)。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **top\$1p** – 通过设置模型为下一个词元考虑的最有可能的候选项所占百分比，控制模型生成的文本的多样性。有关更多信息，请参阅 [利用推理参数影响响应生成](inference-parameters.md)。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **top\$1k** – 模型为下一个词元考虑的最有可能的候选项所占百分比。有关更多信息，请参阅 [利用推理参数影响响应生成](inference-parameters.md)。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)

------
#### [ Response ]

以下是来自对 `InvokeModel` 的调用的 `body` 响应。

```
{
  "outputs": [
    {
        "text": string,
        "stop_reason": string
    }
  ]
}
```

`body` 响应含有以下值：
+ **outputs** – 模型的输出的列表。每个输出都包含以下字段。
  + **text** – 模型生成的文本。
  + **stop\$1reason** – 响应停止生成文本的原因。可能的值有：
    + **stop** – 模型已结束为输入提示生成文本。模型停止的原因是没有更多内容要生成，或者模型生成了您在 `stop` 请求参数中定义的停止序列之一。
    + **length** – 生成的文本的令牌长度超过了对 `InvokeModel`（如果您要对输出进行流式传输，则为 `InvokeModelWithResponseStream`）的调用中的 `max_tokens` 值。响应被截断为 `max_tokens` 个令牌。

------

## 代码示例
<a name="api-inference-examples-mistral-text-completion"></a>

此示例展示了如何调用 Mistral 7B Instruct 模型。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate text using a Mistral AI 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 Mistral AI model.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        JSON: The response from the model.
    """

    logger.info("Generating text with Mistral AI 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 Mistral AI model %s", model_id)

    return response


def main():
    """
    Entrypoint for Mistral AI example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    try:
        model_id = 'mistral.mistral-7b-instruct-v0:2'

        prompt = """<s>[INST] In Bash, how do I list all text files in the current directory
          (excluding subdirectories) that have been modified in the last month? [/INST]"""

        body = json.dumps({
            "prompt": prompt,
            "max_tokens": 400,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50
        })

        response = generate_text(model_id=model_id,
                                 body=body)

        response_body = json.loads(response.get('body').read())

        outputs = response_body.get('outputs')

        for index, output in enumerate(outputs):

            print(f"Output {index + 1}\n----------")
            print(f"Text:\n{output['text']}\n")
            print(f"Stop reason: {output['stop_reason']}\n")

    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 Mistral AI model {model_id}.")


if __name__ == "__main__":
    main()
```