

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

# 使用 AWS Boto3
<a name="braket-using-boto3"></a>

Boto3 是適用於 Python 的 AWS SDK。透過 Boto3，Python 開發人員可以建立、設定和管理 AWS 服務，例如 Amazon Braket。Boto3 提供物件導向的 API，以及對 Amazon Braket 的低階存取。

請遵循 [Boto3 Quickstart 指南](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)中的指示，了解如何安裝和設定 Boto3。

Boto3 提供與 Amazon Braket Python SDK 搭配使用的核心功能，協助您設定和執行量子任務。Python 客戶一律需要安裝 Boto3，因為這是核心實作。如果您想要使用其他協助程式方法，您也需要安裝 Amazon Braket SDK。

例如，當您呼叫 時`CreateQuantumTask`，Amazon Braket SDK 會將請求提交至 Boto3，然後呼叫 AWS API。

**Topics**
+ [開啟 Amazon Braket Boto3 用戶端](braket-using-boto3-client.md)
+ [設定 Boto3 和 Braket SDK 的 AWS CLI 設定檔](braket-using-boto3-profiles.md)

# 開啟 Amazon Braket Boto3 用戶端
<a name="braket-using-boto3-client"></a>

若要搭配 Amazon Braket 使用 Boto3，您必須匯入 Boto3，然後定義用來連線至 Amazon Braket 的用戶端API。在下列範例中，Boto3 用戶端名為 `braket`。

```
import boto3
import botocore

braket = boto3.client("braket")
```

**注意**  
[Braket 支援 IPv6](https://docs.aws.amazon.com/vpc/latest/userguide/aws-ipv6-support.html)。如果您使用IPv6-only的網路，或希望確保工作負載使用 IPv6 流量，請使用雙堆疊端點，如[雙堆疊和 FIPS 端點](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html)指南中所述。

現在您已建立`braket`用戶端，您可以從 Amazon Braket 服務提出請求和處理回應。您可以在 [API 參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/braket.html)中取得請求和回應資料的詳細資訊。

**Topics**
+ [搜尋裝置](#braket-using-boto3-example-search-devices)
+ [擷取裝置](#braket-using-boto3-example-retrieve-devices)
+ [建立量子任務](#braket-using-boto3-example-create-task)
+ [擷取量子任務](#braket-using-boto3-example-retrieve-task)
+ [搜尋量子任務](#braket-using-boto3-example-search-tasks)
+ [取消量子任務](#braket-using-boto3-example-cancel-task)

## 搜尋裝置
<a name="braket-using-boto3-example-search-devices"></a>
+  `search_devices(**kwargs)` 

使用指定的篩選條件搜尋裝置。

```
# Pass search filters and optional parameters when sending the
# request and capture the response
response = braket.search_devices(filters=[{
    'name': 'deviceArn',
    'values': ['arn:aws:braket:::device/quantum-simulator/amazon/sv1']
}], maxResults=10)

print(f"Found {len(response['devices'])} devices")

for i in range(len(response['devices'])):
    device = response['devices'][i]
    print(device['deviceArn'])
```

## 擷取裝置
<a name="braket-using-boto3-example-retrieve-devices"></a>
+  `get_device(deviceArn)` 

擷取 Amazon Braket 中可用的裝置。

```
# Pass the device ARN when sending the request and capture the repsonse
response = braket.get_device(deviceArn='arn:aws:braket:::device/quantum-simulator/amazon/sv1')

print(f"Device {response['deviceName']} is {response['deviceStatus']}")
```

## 建立量子任務
<a name="braket-using-boto3-example-create-task"></a>
+  `create_quantum_task(**kwargs)` 

建立量子任務。

```
# Create parameters to pass into create_quantum_task()
kwargs = {
    # Create a Bell pair
    'action': '{"braketSchemaHeader": {"name": "braket.ir.jaqcd.program", "version": "1"}, "results": [], "basis_rotation_instructions": [], "instructions": [{"type": "h", "target": 0}, {"type": "cnot", "control": 0, "target": 1}]}',
    # Specify the SV1 Device ARN
    'deviceArn': 'arn:aws:braket:::device/quantum-simulator/amazon/sv1',
    # Specify 2 qubits for the Bell pair
    'deviceParameters': '{"braketSchemaHeader": {"name": "braket.device_schema.simulators.gate_model_simulator_device_parameters", "version": "1"}, "paradigmParameters": {"braketSchemaHeader": {"name": "braket.device_schema.gate_model_parameters", "version": "1"}, "qubitCount": 2}}',
    # Specify where results should be placed when the quantum task completes.
    # You must ensure the S3 Bucket exists before calling create_quantum_task()
    'outputS3Bucket': 'amazon-braket-examples',
    'outputS3KeyPrefix': 'boto-examples',
    # Specify number of shots for the quantum task
    'shots': 100
}

# Send the request and capture the response
response = braket.create_quantum_task(**kwargs)

print(f"Quantum task {response['quantumTaskArn']} created")
```

## 擷取量子任務
<a name="braket-using-boto3-example-retrieve-task"></a>
+  `get_quantum_task(quantumTaskArn)` 

擷取指定的量子任務。

```
# Pass the quantum task ARN when sending the request and capture the response
response = braket.get_quantum_task(quantumTaskArn='arn:aws:braket:us-west-1:123456789012:quantum-task/ce78c429-cef5-45f2-88da-123456789012')

print(response['status'])
```

## 搜尋量子任務
<a name="braket-using-boto3-example-search-tasks"></a>
+  `search_quantum_tasks(**kwargs)` 

搜尋符合指定篩選條件值的量子任務。

```
# Pass search filters and optional parameters when sending the
# request and capture the response
response = braket.search_quantum_tasks(filters=[{
    'name': 'deviceArn',
    'operator': 'EQUAL',
    'values': ['arn:aws:braket:::device/quantum-simulator/amazon/sv1']
}], maxResults=25)

print(f"Found {len(response['quantumTasks'])} quantum tasks")

for n in range(len(response['quantumTasks'])):
    task = response['quantumTasks'][n]
    print(f"Quantum task {task['quantumTaskArn']} for {task['deviceArn']} is {task['status']}")
```

## 取消量子任務
<a name="braket-using-boto3-example-cancel-task"></a>
+  `cancel_quantum_task(quantumTaskArn)` 

取消指定的量子任務。

```
# Pass the quantum task ARN when sending the request and capture the response
response = braket.cancel_quantum_task(quantumTaskArn='arn:aws:braket:us-west-1:123456789012:quantum-task/ce78c429-cef5-45f2-88da-123456789012')

print(f"Quantum task {response['quantumTaskArn']} is {response['cancellationStatus']}")
```

# 設定 Boto3 和 Braket SDK 的 AWS CLI 設定檔
<a name="braket-using-boto3-profiles"></a>

除非您另有明確指定，否則 Amazon Braket SDK 依賴預設 AWS CLI 登入資料。我們建議您在受管 Amazon Braket 筆記本上執行 時保持預設值，因為您必須提供具有啟動筆記本執行個體許可的 IAM 角色。

或者，如果您在本機 （例如 Amazon EC2 執行個體） 執行程式碼，您可以建立具名 AWS CLI 設定檔。您可以為每個設定檔提供不同的許可集，而不是定期覆寫預設設定檔。

本節提供如何設定此類 CLI `profile`以及如何將該設定檔併入 Amazon Braket 的簡短說明，以便使用來自該設定檔的許可進行API呼叫。

**Topics**
+ [步驟 1：設定本機 AWS CLI `profile`](#braket-using-boto3-profiles-step-1)
+ [步驟 2：建立 Boto3 工作階段物件](#braket-using-boto3-profiles-step-2)
+ [步驟 3：將 Boto3 工作階段併入 Braket AwsSession](#braket-using-boto3-profiles-step-3)

## 步驟 1：設定本機 AWS CLI `profile`
<a name="braket-using-boto3-profiles-step-1"></a>

超出本文件的範圍，說明如何建立使用者，以及如何設定非預設設定檔。如需這些主題的詳細資訊，請參閱：
+  [開始使用](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) 
+  [設定 AWS CLI 以使用 AWS IAM Identity Center](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html) 

若要使用 Amazon Braket，您必須向此使用者  和相關聯的 CLI `profile` 提供 必要的 Braket 許可。例如，您可以連接 **AmazonBraketFullAccess** 政策。

## 步驟 2：建立 Boto3 工作階段物件
<a name="braket-using-boto3-profiles-step-2"></a>

若要建立 Boto3 工作階段物件，請利用下列程式碼範例。

```
from boto3 import Session

# Insert CLI profile name here
boto_sess = Session(profile_name=`profile`)
```

**注意**  
如果預期的API呼叫具有與`profile`預設區域不相符的區域型限制，您可以指定 Boto3 工作階段的區域，如下列範例所示。

```
# Insert CLI profile name _and_ region
boto_sess = Session(profile_name=`profile`, region_name=`region`)
```

對於指定為 的引數`region`，請取代對應至其中一個可用 Amazon Braket AWS 區域 的值`us-west-1`，例如 `us-east-1`、 等。

## 步驟 3：將 Boto3 工作階段併入 Braket AwsSession
<a name="braket-using-boto3-profiles-step-3"></a>

下列範例顯示如何初始化 Boto3 Braket 工作階段，並執行個體化該工作階段中的裝置。

```
from braket.aws import AwsSession, AwsDevice

# Initialize Braket session with Boto3 Session credentials
aws_session = AwsSession(boto_session=boto_sess)

# Instantiate any Braket QPU device with the previously initiated AwsSession
sim_arn = 'arn:aws:braket:::device/quantum-simulator/amazon/sv1'
device = AwsDevice(sim_arn, aws_session=aws_session)
```

在此設定完成後，您可以將量子任務提交到該執行個體化`AwsDevice`物件 （例如呼叫 `device.run(…​)`命令）。該裝置進行的所有API呼叫都可以使用與您先前指定為 的 CLI 設定檔相關聯的 IAM 憑證`profile`。