

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

# Mistral AI 模型
<a name="model-parameters-mistral"></a>

本節說明 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 模型進行推論呼叫。本節也包含 Python 程式碼範例，示範如何呼叫 Mistral AI 模型。若要在推論操作中使用模型，您需要模型的模型 ID。若要取得模型 ID，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。某些模型也可以使用 [Converse API](conversation-inference.md)。若要檢查 Converse API 是否支援特定 Mistral AI 模型，請參閱 [支援的模型和模型功能](conversation-inference-supported-models-features.md)。如需更多程式碼範例，請參閱 [使用 AWS SDKs Amazon Bedrock 程式碼範例](service_code_examples.md)。

Amazon Bedrock 中的基礎模型支援輸入和輸出模態，因模型而異。若要檢查 Mistral AI 模型支援的模態，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。若要檢查 Mistral AI 模型支援的 Amazon Bedrock 功能，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。若要檢查哪些 AWS 區域提供 Mistral AI 模型，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。

當您使用 Mistral AI 模型進行推論呼叫時，您會包含模型的提示。如需建立 Amazon Bedrock 支援之模型提示的相關資訊，請參閱 [提示工程概念](prompt-engineering-guidelines.md)。如需 Mistral AI 特定提示資訊，請參閱《[Mistral AI 提示工程指南](https://docs.mistral.ai/guides/prompting_capabilities/)》。

**Topics**
+ [Mistral AI 文字完成](model-parameters-mistral-text-completion.md)
+ [Mistral AI 聊天完成](model-parameters-mistral-chat-completion.md)
+ [Mistral AI Large (24.07) 參數與推論](model-parameters-mistral-large-2407.md)
+ [Pixtral Large (25.02) 參數與推論](model-parameters-mistral-pixtral-large.md)

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

# Mistral AI 聊天完成
<a name="model-parameters-mistral-chat-completion"></a>

Mistral AI 聊天完成 API 可建立對話式應用程式。

**提示**  
您可以使用 Mistral AI 聊天完成 API 搭配基本推論操作 ([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))。不過，我們建議您使用 Converse API 在應用程式中實作訊息。Converse API 提供一組統一的參數，可用於支援訊息的所有模型。如需詳細資訊，請參閱 [與 Converse API 操作進行對話](conversation-inference.md)。

Mistral AI 模型可在 [Apache 2.0 授權](https://www.apache.org/licenses/LICENSE-2.0.txt)下使用。如需使用 Mistral AI 模型的詳細資訊，請參閱 [Mistral AI 文件](https://docs.mistral.ai/)。

**Topics**
+ [支援的模型](#mistral-supported-models-chat-completion)
+ [請求與回應](#model-parameters-mistral-chat-completion-request-response)

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

您可以使用下列 Mistral AI 模型。
+ Mistral Large

您需要您想要使用的模型的模型 ID。若要取得模型 ID，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。

## 請求與回應
<a name="model-parameters-mistral-chat-completion-request-response"></a>

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

這些 Mistral AI 模型具有下列推論參數。

```
{
    "messages": [
        {
            "role": "system"|"user"|"assistant",
            "content": str
        },
        {
            "role": "assistant",
            "content": "",
            "tool_calls": [
                {
                    "id": str,
                    "function": {
                        "name": str,
                        "arguments": str
                    }
                }
            ]
        },
        {
            "role": "tool",
            "tool_call_id": str,
            "content": str
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": str,
                "description": str,
                "parameters": dict
            }
        }
    ],
    "tool_choice": "auto"|"any"|"none",
    "max_tokens": int,
    "top_p": float,
    "temperature": float
}
```

以下是必要的參數。
+  **messages** – (必要) 您要傳遞給模型的訊息。
  + **role** – 訊息的角色。有效的值如下：
    + **system** – 在對話中設定模型的行為和內容。
    + **user** – 要傳送給模型的訊息。
    + **assistant** – 來自模型的回應。
  + **content** – 訊息的內容。

  ```
  [
      {
          "role": "user",
          "content": "What is the most popular song on WZPZ?"
      }
  ]
  ```

  若要傳遞工具結果，請將 JSON 搭配下列欄位使用。
  + **role** – 訊息的角色。 值必須為 `tool`。
  + **tool\$1call\$1id** – 工具請求的 ID。您可以從上一個請求其回應中的 `tool_calls` 欄位取得 ID。
  + **content** – 工具的結果。

  下列範例是可從廣播電台取得熱門歌曲的工具提供的結果。

  ```
  {
      "role": "tool",
      "tool_call_id": "v6RMMiRlT7ygYkT4uULjtg",
      "content": "{\"song\": \"Elemental Hotel\", \"artist\": \"8 Storey Hike\"}"
  }
  ```

以下是選用參數。
+  **tools** – 模型可使用之工具的定義。

  如果您在請求中包含 `tools`，模型可能會在訊息中傳回 `tool_calls` 欄位，代表模型使用這些工具。然後，您可以使用模型產生的工具輸入來執行這些工具，然後使用 `tool_result` 內容區塊選擇性地將結果傳回至模型。

  下列範例適用於在廣播電台上取得最熱門歌曲的工具。

  ```
  [
      {
          "type": "function",
          "function": {
              "name": "top_song",
              "description": "Get the most popular song played on a radio station.",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "sign": {
                          "type": "string",
                          "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP."
                      }
                  },
                  "required": [
                      "sign"
                  ]
              }
          }
      }
  ]
  ```
+  **tool\$1choice** – 指定函數的呼叫方式。如果設定為 `none`，則模型不會呼叫函數，而是產生訊息。如果設定為 `auto`，則模型可以選擇產生訊息或呼叫函數。如果設定為 `any`，則會強制模型呼叫函數。
+ **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-chat-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-chat-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-chat-completion.html)

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

來自對 `InvokeModel` 的呼叫的 `body` 回應如下：

```
{
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": str,
                "tool_calls": [...]
            },
            "stop_reason": "stop"|"length"|"tool_calls"
        }
    ]
}
```

`body` 回應具有以下欄位：
+ **choices** – 來自模型欄位的輸出。
  + **index** – 訊息的索引。
  + **message** – 來自模型的訊息。
    + **role** – 訊息的角色。
    + **content** – 訊息的內容。
    + **tool\$1calls** – 如果 `stop_reason` 的值為 `tool_calls`，則此欄位包含模型希望您執行之工具請求的清單。
      + **id** – 工具請求的 ID。
      + **function** – 模型正在請求的函數。
        + **name** – 函數的名稱。
        + **arguments** – 傳遞至工具的引數。

      下列範例請求適用於取得廣播電台最高排名歌曲的工具。

      ```
      [
                          {
                              "id": "v6RMMiRlT7ygYkT4uULjtg",
                              "function": {
                                  "name": "top_song",
                                  "arguments": "{\"sign\": \"WZPZ\"}"
                              }
                          }
                      ]
      ```
  + **stop\$1reason** – 回應停止產生文字的原因。可能值為：
    + **stop** — 模型已完成產生輸入提示的文字。模型會停止，因為它不再有要產生的內容，或者如果模型產生您在 `stop` 請求參數中定義的其中一個停止序列。
    + **length** – 所產生文字的字符長度超過 `max_tokens` 的值。回應會截斷為 `max_tokens` 記號。
    + **tool\$1calls** – 模型正在請求您執行工具。

------

# Mistral AI Large (24.07) 參數與推論
<a name="model-parameters-mistral-large-2407"></a>

Mistral AI 聊天完成 API 可讓您建立對話式應用程式。您也可以搭配此模型使用 Amazon Bedrock Converse API。您可以使用工具進行函數呼叫。

**提示**  
您可以使用 Mistral AI 聊天完成 API 搭配基本推論操作 ([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))。不過，我們建議您使用 Converse API 在應用程式中實作訊息。Converse API 提供一組統一的參數，可用於支援訊息的所有模型。如需詳細資訊，請參閱 [與 Converse API 操作進行對話](conversation-inference.md)。

Mistral AI 模型可在 [Apache 2.0 授權](https://www.apache.org/licenses/LICENSE-2.0.txt)下使用。如需使用 Mistral AI 模型的詳細資訊，請參閱 [Mistral AI 文件](https://docs.mistral.ai/)。

**Topics**
+ [支援的模型](#mistral-supported-models-chat-completion)
+ [請求和回應範例](#model-parameters-mistral-large-2407-request-response)

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

您可以使用下列 Mistral AI 模型搭配此頁面上的程式碼範例。
+ Mistral Large 2 (24.07)

您需要您想要使用的模型的模型 ID。若要取得模型 ID，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。

## 請求和回應範例
<a name="model-parameters-mistral-large-2407-request-response"></a>

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

Mistral AI Large (24.07) 調用模型範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2') 
response = bedrock.invoke_model( 
        modelId='mistral.mistral-large-2407-v1:0', 
        body=json.dumps({
            'messages': [ 
                { 
                    'role': 'user', 
                    'content': 'which llm are you?' 
                } 
             ], 
         }) 
       ) 

print(json.dumps(json.loads(response['body']), indent=4))
```

------
#### [ Converse ]

Mistral AI Large (24.07) 反向範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2')
response = bedrock.converse( 
    modelId='mistral.mistral-large-2407-v1:0', 
    messages=[ 
        { 
            'role': 'user', 
            'content': [ 
                { 
                    'text': 'which llm are you?' 
                } 
             ] 
          } 
     ] 
  ) 

print(json.dumps(json.loads(response['body']), indent=4))
```

------
#### [ invoke\$1model\$1with\$1response\$1stream ]

Mistral AI Large (24.07) invoke\$1model\$1with\$1response\$1stream 範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2')
response = bedrock.invoke_model_with_response_stream(
    "body": json.dumps({
        "messages": [{"role": "user", "content": "What is the best French cheese?"}],
        }),
        "modelId":"mistral.mistral-large-2407-v1:0"
)

stream = response.get('body')
if stream:
        for event in stream:
            chunk=event.get('chunk')
            if chunk:
                chunk_obj=json.loads(chunk.get('bytes').decode())
                print(chunk_obj)
```

------
#### [ converse\$1stream ]

Mistral AI Large (24.07) converse\$1stream 範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2')
mistral_params = {
    "messages": [{
            "role": "user","content": [{"text": "What is the best French cheese? "}]
         }],
            "modelId":"mistral.mistral-large-2407-v1:0",
        }
    response = bedrock.converse_stream(**mistral_params)
    stream = response.get('stream')
    if stream:
        for event in stream:

            if 'messageStart' in event:
                print(f"\nRole: {event['messageStart']['role']}")

            if 'contentBlockDelta' in event:
                print(event['contentBlockDelta']['delta']['text'], end="")

            if 'messageStop' in event:
                print(f"\nStop reason: {event['messageStop']['stopReason']}")

            if 'metadata' in event:
                metadata = event['metadata']
                if 'usage' in metadata:
                    print("\nToken usage ... ")
                    print(f"Input tokens: {metadata['usage']['inputTokens']}")
                    print(
                        f":Output tokens: {metadata['usage']['outputTokens']}")
                    print(f":Total tokens: {metadata['usage']['totalTokens']}")
                if 'metrics' in event['metadata']:
                    print(
                        f"Latency: {metadata['metrics']['latencyMs']} milliseconds")
```

------
#### [ JSON Output ]

Mistral AI Large (24.07) JSON 輸出範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2')
mistral_params = {
        "body": json.dumps({
            "messages": [{"role": "user", "content": "What is the best French meal? Return the name and the ingredients in short JSON object."}]
        }),
        "modelId":"mistral.mistral-large-2407-v1:0",
    }
response = bedrock.invoke_model(**mistral_params)

body = response.get('body').read().decode('utf-8')
print(json.loads(body))
```

------
#### [ Tooling ]

Mistral AI Large (24.07) 工具範例。

```
data = {
    'transaction_id': ['T1001', 'T1002', 'T1003', 'T1004', 'T1005'],
    'customer_id': ['C001', 'C002', 'C003', 'C002', 'C001'],
    'payment_amount': [125.50, 89.99, 120.00, 54.30, 210.20],
    'payment_date': ['2021-10-05', '2021-10-06', '2021-10-07', '2021-10-05', '2021-10-08'],
    'payment_status': ['Paid', 'Unpaid', 'Paid', 'Paid', 'Pending']
}

# Create DataFrame
df = pd.DataFrame(data)


def retrieve_payment_status(df: data, transaction_id: str) -> str:
    if transaction_id in df.transaction_id.values: 
        return json.dumps({'status': df[df.transaction_id == transaction_id].payment_status.item()})
    return json.dumps({'error': 'transaction id not found.'})

def retrieve_payment_date(df: data, transaction_id: str) -> str:
    if transaction_id in df.transaction_id.values: 
        return json.dumps({'date': df[df.transaction_id == transaction_id].payment_date.item()})
    return json.dumps({'error': 'transaction id not found.'})

tools = [
    {
        "type": "function",
        "function": {
            "name": "retrieve_payment_status",
            "description": "Get payment status of a transaction",
            "parameters": {
                "type": "object",
                "properties": {
                    "transaction_id": {
                        "type": "string",
                        "description": "The transaction id.",
                    }
                },
                "required": ["transaction_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "retrieve_payment_date",
            "description": "Get payment date of a transaction",
            "parameters": {
                "type": "object",
                "properties": {
                    "transaction_id": {
                        "type": "string",
                        "description": "The transaction id.",
                    }
                },
                "required": ["transaction_id"],
            },
        },
    }
]

names_to_functions = {
    'retrieve_payment_status': functools.partial(retrieve_payment_status, df=df),
    'retrieve_payment_date': functools.partial(retrieve_payment_date, df=df)
}



test_tool_input = "What's the status of my transaction T1001?"
message = [{"role": "user", "content": test_tool_input}]


def invoke_bedrock_mistral_tool():
   
    mistral_params = {
        "body": json.dumps({
            "messages": message,
            "tools": tools           
        }),
        "modelId":"mistral.mistral-large-2407-v1:0",
    }
    response = bedrock.invoke_model(**mistral_params)
    body = response.get('body').read().decode('utf-8')
    body = json.loads(body)
    choices = body.get("choices")
    message.append(choices[0].get("message"))

    tool_call = choices[0].get("message").get("tool_calls")[0]
    function_name = tool_call.get("function").get("name")
    function_params = json.loads(tool_call.get("function").get("arguments"))
    print("\nfunction_name: ", function_name, "\nfunction_params: ", function_params)
    function_result = names_to_functions[function_name](**function_params)

    message.append({"role": "tool", "content": function_result, "tool_call_id":tool_call.get("id")})
   
    new_mistral_params = {
        "body": json.dumps({
                "messages": message,
                "tools": tools           
        }),
        "modelId":"mistral.mistral-large-2407-v1:0",
    }
    response = bedrock.invoke_model(**new_mistral_params)
    body = response.get('body').read().decode('utf-8')
    body = json.loads(body)
    print(body)
invoke_bedrock_mistral_tool()
```

------

# Pixtral Large (25.02) 參數與推論
<a name="model-parameters-mistral-pixtral-large"></a>

Pixtral Large 25.02 是 124B 參數多模態模型，結合了state-of-the-art影像理解與強大的文字處理功能。 AWS 是第一個交付 Pixtral Large (25.02) 作為全受管無伺服器模型的雲端供應商。此模型在執行文件分析、圖表解釋和自然影像理解任務時，提供邊境效能，同時維持 Mistral Large 2 的進階文字功能。

透過 128K 內容視窗，Pixtral Large 25.02 可在包括 MathVista、DocVQA 和 VQAv2 等關鍵基準上實現同級最佳效能。此模型提供跨多種語言的全方位多語言支援，並針對超過 80 種程式設計語言進行訓練。主要功能包括進階數學推理、原生函數呼叫、JSON 輸出，以及 RAG 應用程式的強大內容遵循度。

Mistral AI 聊天完成 API 可讓您建立對話式應用程式。您也可以搭配此模型使用 Amazon Bedrock Converse API。您可以使用工具進行函數呼叫。

**提示**  
您可以使用 Mistral AI 聊天完成 API 搭配基本推論操作 ([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))。不過，我們建議您使用 Converse API 在應用程式中實作訊息。Converse API 提供一組統一的參數，可用於支援訊息的所有模型。如需詳細資訊，請參閱[與 Converse API 操作進行對話](conversation-inference.md)。

Mistral AI Pixtral Large 模型可在 [Mistral 研究授權](https://mistral.ai/licenses/MRL-0.1.md)下使用。如需使用 Mistral AI 模型的詳細資訊，請參閱 [Mistral AI 文件](https://docs.mistral.ai/)。

**Topics**
+ [支援的模型](#mistral-supported-models-chat-completion)
+ [請求和回應範例](#model-parameters-pixtral-large-2502-request-response)

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

您可以使用下列 Mistral AI 模型搭配此頁面上的程式碼範例。
+ Pixtral Large (25.02)

您需要您想要使用的模型的模型 ID。若要取得模型 ID，請參閱 [Amazon Bedrock 中支援的基礎模型](models-supported.md)。

## 請求和回應範例
<a name="model-parameters-pixtral-large-2502-request-response"></a>

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

Pixtral Large (25.02) 調用模型範例。

```
import boto3
import json
import base64


input_image = "image.png"
with open(input_image, "rb") as f:
    image = f.read()

image_bytes = base64.b64encode(image).decode("utf-8")

bedrock = boto3.client(
    service_name='bedrock-runtime',
    region_name="us-east-1")


request_body = {
    "messages" : [
        {
          "role" : "user",
          "content" : [
            {
              "text": "Describe this picture:",
              "type": "text"
            },
            {
              "type" : "image_url",
              "image_url" : {
                "url" : f"data:image/png;base64,{image_bytes}"
              }
            }
          ]
        }
      ],
      "max_tokens" : 10
    }

response = bedrock.invoke_model(
        modelId='us.mistral.pixtral-large-2502-v1:0',
        body=json.dumps(request_body)
       )


print(json.dumps(json.loads(response.get('body').read()), indent=4))
```

------
#### [ Converse ]

Pixtral Large (25.02) 反向範例。

```
import boto3
import json
import base64

input_image = "image.png"
with open(input_image, "rb") as f:
    image_bytes = f.read()


bedrock = boto3.client(
    service_name='bedrock-runtime',
    region_name="us-east-1")

messages =[
    {
        "role" : "user",
        "content" : [
            {
              "text": "Describe this picture:"
            },
            {
                "image": {
                    "format": "png",
                    "source": {
                        "bytes": image_bytes
                    }
                }
            }
        ]
    }
]

response = bedrock.converse(
        modelId='mistral.pixtral-large-2502-v1:0',
        messages=messages
       )

print(json.dumps(response.get('output'), indent=4))
```

------
#### [ invoke\$1model\$1with\$1response\$1stream ]

Pixtral Large (25.02) invoke\$1model\$1with\$1response\$1stream 範例。

```
import boto3
import json
import base64


input_image = "image.png"
with open(input_image, "rb") as f:
    image = f.read()

image_bytes = base64.b64encode(image).decode("utf-8")

bedrock = boto3.client(
    service_name='bedrock-runtime',
    region_name="us-east-1")


request_body = {
    "messages" : [
        {
          "role" : "user",
          "content" : [
            {
              "text": "Describe this picture:",
              "type": "text"
            },
            {
              "type" : "image_url",
              "image_url" : {
                "url" : f"data:image/png;base64,{image_bytes}"
              }
            }
          ]
        }
      ],
      "max_tokens" : 10
    }

response = bedrock.invoke_model_with_response_stream(
        modelId='us.mistral.pixtral-large-2502-v1:0',
        body=json.dumps(request_body)
       )

stream = response.get('body')
if stream:
    for event in stream:
        chunk=event.get('chunk')
        if chunk:
            chunk_obj=json.loads(chunk.get('bytes').decode())
            print(chunk_obj)
```

------
#### [ converse\$1stream ]

Pixtral Large (25.02) converse\$1stream 範例。

```
import boto3
import json
import base64

input_image = "image.png"
with open(input_image, "rb") as f:
    image_bytes = f.read()


bedrock = boto3.client(
    service_name='bedrock-runtime',
    region_name="us-east-1")

messages =[
    {
        "role" : "user",
        "content" : [
            {
              "text": "Describe this picture:"
            },
            {
                "image": {
                    "format": "png",
                    "source": {
                        "bytes": image_bytes
                    }
                }
            }
        ]
    }
]

response = bedrock.converse_stream(
        modelId='mistral.pixtral-large-2502-v1:0',
        messages=messages
       )

stream = response.get('stream')
if stream:
    for event in stream:
        if 'messageStart' in event:
            print(f"\nRole: {event['messageStart']['role']}")

        if 'contentBlockDelta' in event:
            print(event['contentBlockDelta']['delta']['text'], end="")

        if 'messageStop' in event:
            print(f"\nStop reason: {event['messageStop']['stopReason']}")

        if 'metadata' in event:
            metadata = event['metadata']
            if 'usage' in metadata:
                print("\nToken usage ... ")
                print(f"Input tokens: {metadata['usage']['inputTokens']}")
                print(
                    f":Output tokens: {metadata['usage']['outputTokens']}")
                print(f":Total tokens: {metadata['usage']['totalTokens']}")
            if 'metrics' in event['metadata']:
                print(
                    f"Latency: {metadata['metrics']['latencyMs']} milliseconds")
```

------
#### [ JSON Output ]

Pixtral Large (25.02) JSON 輸出範例。

```
import boto3 
import json

bedrock = session.client('bedrock-runtime', 'us-west-2')
mistral_params = {
        "body": json.dumps({
            "messages": [{"role": "user", "content": "What is the best French meal? Return the name and the ingredients in short JSON object."}]
        }),
        "modelId":"us.mistral.pixtral-large-2502-v1:0",
    }
response = bedrock.invoke_model(**mistral_params)

body = response.get('body').read().decode('utf-8')
print(json.loads(body))
```

------
#### [ Tooling ]

Pixtral Large (25.02) 工具範例。

```
data = {
    'transaction_id': ['T1001', 'T1002', 'T1003', 'T1004', 'T1005'],
    'customer_id': ['C001', 'C002', 'C003', 'C002', 'C001'],
    'payment_amount': [125.50, 89.99, 120.00, 54.30, 210.20],
    'payment_date': ['2021-10-05', '2021-10-06', '2021-10-07', '2021-10-05', '2021-10-08'],
    'payment_status': ['Paid', 'Unpaid', 'Paid', 'Paid', 'Pending']
}

# Create DataFrame
df = pd.DataFrame(data)


def retrieve_payment_status(df: data, transaction_id: str) -> str:
    if transaction_id in df.transaction_id.values: 
        return json.dumps({'status': df[df.transaction_id == transaction_id].payment_status.item()})
    return json.dumps({'error': 'transaction id not found.'})

def retrieve_payment_date(df: data, transaction_id: str) -> str:
    if transaction_id in df.transaction_id.values: 
        return json.dumps({'date': df[df.transaction_id == transaction_id].payment_date.item()})
    return json.dumps({'error': 'transaction id not found.'})

tools = [
    {
        "type": "function",
        "function": {
            "name": "retrieve_payment_status",
            "description": "Get payment status of a transaction",
            "parameters": {
                "type": "object",
                "properties": {
                    "transaction_id": {
                        "type": "string",
                        "description": "The transaction id.",
                    }
                },
                "required": ["transaction_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "retrieve_payment_date",
            "description": "Get payment date of a transaction",
            "parameters": {
                "type": "object",
                "properties": {
                    "transaction_id": {
                        "type": "string",
                        "description": "The transaction id.",
                    }
                },
                "required": ["transaction_id"],
            },
        },
    }
]

names_to_functions = {
    'retrieve_payment_status': functools.partial(retrieve_payment_status, df=df),
    'retrieve_payment_date': functools.partial(retrieve_payment_date, df=df)
}



test_tool_input = "What's the status of my transaction T1001?"
message = [{"role": "user", "content": test_tool_input}]


def invoke_bedrock_mistral_tool():
   
    mistral_params = {
        "body": json.dumps({
            "messages": message,
            "tools": tools           
        }),
        "modelId":"us.mistral.pixtral-large-2502-v1:0",
    }
    response = bedrock.invoke_model(**mistral_params)
    body = response.get('body').read().decode('utf-8')
    body = json.loads(body)
    choices = body.get("choices")
    message.append(choices[0].get("message"))

    tool_call = choices[0].get("message").get("tool_calls")[0]
    function_name = tool_call.get("function").get("name")
    function_params = json.loads(tool_call.get("function").get("arguments"))
    print("\nfunction_name: ", function_name, "\nfunction_params: ", function_params)
    function_result = names_to_functions[function_name](**function_params)

    message.append({"role": "tool", "content": function_result, "tool_call_id":tool_call.get("id")})
   
    new_mistral_params = {
        "body": json.dumps({
                "messages": message,
                "tools": tools           
        }),
        "modelId":"us.mistral.pixtral-large-2502-v1:0",
    }
    response = bedrock.invoke_model(**new_mistral_params)
    body = response.get('body').read().decode('utf-8')
    body = json.loads(body)
    print(body)
invoke_bedrock_mistral_tool()
```

------