本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 Amazon Bedrock API 金鑰
若要使用您的 API 金鑰,您必須先將其設定為名為 的環境變數,AWS_BEARER_TOKEN_BEDROCK
才能進行 API 呼叫。您有下列選項可設定金鑰:
若要查看使用 API 金鑰傳送 Converse 請求以產生回應的範例,請選擇您偏好方法的索引標籤,然後遵循下列步驟:
- Python
-
下列範例示範如何使用 傳送 API 請求 適用於 Python (Boto3) 的 AWS SDK。如果您尚未將 API 金鑰設定為AWS_BEARER_TOKEN_BEDROCK
環境變數,請在下列程式碼中指定它來取代 ${api-key}
:
import os
import boto3
# If you already set the API key as an environment variable, you can comment this line out
os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}
"
# Create an Amazon Bedrock client
client = boto3.client(
service_name="bedrock-runtime",
region_name="us-east-1" # If you've configured a default region, you can omit this line
)
# Define the model and message
model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
messages = [{"role": "user", "content": [{"text": "Hello"}]}]
response = client.converse(
modelId=model_id,
messages=messages,
)
- HTTP Client (requests package in Python)
-
先決條件:開啟終端機並執行下列命令來安裝requests
套件:
python3 -m pip install requests
下列範例示範如何使用 HTTP 用戶端直接傳送 API 請求。在 標頭中指定 ${api-key}
。
import requests
url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"
payload = {
"messages": [
{
"role": "user",
"content": [{"text": "Hello"}]
}
]
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer ${api-key}
"
}
response = requests.request("POST", url, json=payload, headers=headers)
print(response.text)
- HTTP request using cURL
-
下列範例示範如何使用 cURL 直接傳送 API 請求。如果您未將 API 金鑰設定為 AWS_BEARER_TOKEN_BEDROCK 環境變數,則必須將$AWS_BEARER_TOKEN_BEDROCK
範例中的 取代為金鑰的常值。
curl -X POST "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK" \
-d '{
"messages": [
{
"role": "user",
"content": [{"text": "Hello"}]
}
]
}'