

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

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

------