

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

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

Mistral AI text completion API では、Mistral AI モデルを使用してテキストを生成できます。

Mistral AI モデル with [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 モデルは [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/ja_jp/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **stop** – モデルによって生成された場合、モデルがそれ以上の出力を生成できないストップシーケンスのリスト。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/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/ja_jp/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/ja_jp/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/ja_jp/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)

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

`InvokeModel` を呼び出した場合の `body` レスポンスを以下に示します。

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

`body` レスポンスに指定できるフィールドについて説明します。
+ **outputs** – モデルからの出力リスト。各出力には以下のフィールドがあります。
  + **text** – モデルが生成したテキスト。
  + **stop\$1reason** – モデルがテキストの生成を停止した理由。可能な値は以下のとおりです。
    + **停止** - モデルは入力プロンプトのテキストの生成を終了しました。モデルは、生成するコンテンツがなくなったか、`stop` リクエストパラメータで定義したストップシーケンスのいずれかがモデルによって生成された場合に停止します。
    + **長さ** - 生成されたテキストにおけるトークンの長さが `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()
```