

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

API penyelesaian Mistral AI teks memungkinkan Anda menghasilkan teks dengan Mistral AI model.

Anda membuat permintaan inferensi ke Mistral AI model dengan [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)atau [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)(streaming). 

Mistral AImodel tersedia di bawah [lisensi Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt). Untuk informasi selengkapnya tentang penggunaan Mistral AI model, lihat [Mistral AIdokumentasi](https://docs.mistral.ai/).

**Topics**
+ [Model yang didukung](#mistral--text-completion-supported-models)
+ [Permintaan dan Tanggapan](#model-parameters-mistral-text-completion-request-response)
+ [Contoh kode](#api-inference-examples-mistral-text-completion)

## Model yang didukung
<a name="mistral--text-completion-supported-models"></a>

Anda dapat menggunakan Mistral AI model berikut.
+ Mistral 7B Instruct
+ Mixtral 8X7B Instruct
+ Mistral Large
+ Mistral Small

Anda memerlukan ID model untuk model yang ingin Anda gunakan. Untuk mendapatkan ID model, lihat[Model pondasi yang didukung di Amazon Bedrock](models-supported.md). 

## Permintaan dan Tanggapan
<a name="model-parameters-mistral-text-completion-request-response"></a>

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

Mistral AIModel memiliki parameter inferensi berikut. 

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

Berikut ini adalah parameter yang diperlukan.
+  **prompt** - (Wajib) Prompt yang ingin Anda lewatkan ke model, seperti yang ditunjukkan pada contoh berikut. 

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

  Contoh berikut menunjukkan cara memformat adalah prompt multi-putaran. 

  ```
  <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]
  ```

  Teks untuk peran pengguna ada di dalam `[INST]...[/INST]` token, teks di luar adalah peran asisten. Awal dan akhir string diwakili oleh token `<s>` (awal string) dan `</s>` (akhir string). Untuk informasi tentang mengirim prompt obrolan dalam format yang benar, lihat [Templat obrolan](https://docs.mistral.ai/models/#chat-template) di Mistral AI dokumentasi. 

Berikut ini adalah parameter opsional.
+ **max\$1tokens** — Tentukan jumlah maksimum token yang akan digunakan dalam respons yang dihasilkan. Model memotong respons setelah teks yang dihasilkan melebihi. `max_tokens`     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **stop** — Daftar urutan berhenti yang jika dihasilkan oleh model, menghentikan model dari menghasilkan output lebih lanjut.     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **suhu** — Mengontrol keacakan prediksi yang dibuat oleh model. Untuk informasi selengkapnya, lihat [Mempengaruhi generasi respons dengan parameter inferensi](inference-parameters.md).     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **top\$1p** — Mengontrol keragaman teks yang dihasilkan model dengan menetapkan persentase kandidat yang paling mungkin dipertimbangkan model untuk token berikutnya. Untuk informasi selengkapnya, lihat [Mempengaruhi generasi respons dengan parameter inferensi](inference-parameters.md).    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)
+ **top\$1k** — Mengontrol jumlah kandidat yang paling mungkin yang dipertimbangkan model untuk token berikutnya. Untuk informasi selengkapnya, lihat [Mempengaruhi generasi respons dengan parameter inferensi](inference-parameters.md).    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/bedrock/latest/userguide/model-parameters-mistral-text-completion.html)

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

`body`Tanggapan dari panggilan ke `InvokeModel` adalah sebagai berikut:

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

`body`Tanggapan memiliki bidang-bidang berikut:
+ **output** — Daftar output dari model. Setiap output memiliki bidang berikut.
  + **teks** — Teks yang dihasilkan model. 
  + **stop\$1reason** — Alasan mengapa respon berhenti menghasilkan teks. Kemungkinan nilainya adalah:
    + **stop** — Model telah selesai menghasilkan teks untuk prompt input. Model berhenti karena tidak memiliki konten lagi untuk dihasilkan atau jika model menghasilkan salah satu urutan berhenti yang Anda tentukan dalam parameter `stop` permintaan.
    + **panjang** — Panjang token untuk teks yang dihasilkan melebihi nilai `max_tokens` dalam panggilan ke `InvokeModel` (`InvokeModelWithResponseStream`, jika Anda streaming output). Respons terpotong menjadi token. `max_tokens` 

------

## Contoh kode
<a name="api-inference-examples-mistral-text-completion"></a>

Contoh ini menunjukkan cara memanggil Mistral 7B Instruct model.

```
# 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()
```