

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 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 模型的詳細資訊，請參閱 [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_tw/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **stop** – 停止序列清單，如果序列由模型產生，則會阻止模型產生進一步的輸出。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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` 呼叫之 `max_tokens` 的值 (如果您正在串流輸出則為 `InvokeModelWithResponseStream`)。回應會截斷為 `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()
```