本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
產生 Amazon Bedrock API 金鑰
您可以使用 AWS Management Console 或 API 產生 Amazon Bedrock AWS API 金鑰。我們建議您使用 AWS Management Console ,只需幾個步驟即可輕鬆產生 Amazon Bedrock API 金鑰。
我們強烈建議限制使用 Amazon Bedrock API 金鑰來探索 Amazon Bedrock。當您準備好將 Amazon Bedrock 納入具有更高安全需求的應用程式時,您應該切換到短期憑證。如需詳細資訊,請參閱《IAM 使用者指南》中的長期存取金鑰的替代方案。
使用主控台產生 Amazon Bedrock API 金鑰
若要使用主控台產生 Amazon Bedrock API 金鑰,請執行下列動作:
使用 API 產生長期 Amazon Bedrock API 金鑰
在 API 中建立長期 Amazon Bedrock API 金鑰的一般步驟如下:
若要了解如何產生長期 Amazon Bedrock API 金鑰,請選擇您偏好方法的索引標籤,然後遵循下列步驟:
- CLI
-
若要建立長期 Amazon Bedrock API 金鑰,您可以使用 AWS Identity and Access Management API 操作。首先,請確定您已完成先決條件:
先決條件
請確定您的設定允許 AWS CLI 自動辨識您的 AWS 登入資料。若要進一步了解,請參閱設定 的設定 AWS CLI。
開啟終端機並執行下列命令:
-
建立 IAM 使用者。您可以將名稱取代為您選擇的其中一個名稱:
aws iam create-user --user-name bedrock-api-user
-
將 AmazonBedrockLimitedAccess 連接至使用者。您可以使用要新增至 API 金鑰的任何其他 AWS受管或自訂政策ARNs 重複此步驟:
aws iam attach-user-policy --user-name bedrock-api-user --policy-arn arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess
-
建立長期 Amazon Bedrock API 金鑰,以您希望金鑰持續的天數取代 ${NUMBER-OF-DAYS}
:
aws iam create-service-specific-credential \
--user-name bedrock-api-user \
--service-name bedrock.amazonaws.com \
--credential-age-days ${NUMBER-OF-DAYS}
- Python
-
若要建立長期 Amazon Bedrock API 金鑰,您可以使用 AWS Identity and Access Management API 操作。首先,請確定您已完成先決條件:
先決條件
請確定您的設定允許 Python 自動辨識您的 AWS 登入資料。若要進一步了解,請參閱設定 的設定 AWS CLI。
執行下列指令碼來建立 IAM 使用者、連接執行 Amazon Bedrock 動作的許可,以及產生要與使用者建立關聯的長期 Amazon Bedrock API 金鑰:
import boto3
from datetime import datetime, timedelta
# Replace with name for your IAM user
username = "bedrock-api-user"
# Add any AWS-managed or custom policies that you want to the user
bedrock_policies = [
"arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess", # Limited access
# "arn:aws:iam::aws:policy/AmazonBedrockMarketplaceAccess", # Optional: Access to Amazon Bedrock Marketplace actions
]
# Set the key expiration time to a number of your choice
expiration_time_in_days = 30
iam_client = boto3.client("iam")
# Create IAM user
user = iam_client.create_iam_user(username)
# Attach policies to user
for policy_arn in bedrock_policies:
iam_client.attach_managed_policy(username, policy_arn)
# Create long-term Amazon Bedrock API key and return it
service_credentials = iam_client.create_service_specific_credential(
user_name=username,
service_name="bedrock",
credential_age_days=expiration_time_in_days
)
api_key = service_credentials["ServiceApiKeyValue"]
print(api_key)
使用用戶端程式庫產生短期 Amazon Bedrock API 金鑰
短期金鑰具有下列屬性:
-
適用於下列較短的值:
-
繼承連接至用來產生金鑰之主體的許可。
-
只能在您產生它的 AWS 區域中使用。
對於長時間執行的應用程式,aws-bedrock-token-generator 用戶端程式庫可以在重新整理登入資料時視需要建立新的 Amazon Bedrock 短期 API 金鑰。如需詳細資訊,請參閱設定自動重新整理短期 Amazon Bedrock API 金鑰。
- Python
-
開啟終端機並執行下列命令:
pip install aws-bedrock-token-generator
- Javascript
-
開啟終端機並執行下列命令:
npm install @aws/bedrock-token-generator
- Java
-
如果您使用 Maven,請將下列相依性新增至您的 pom.xml
:
<dependency>
<groupId>software.amazon.bedrock</groupId>
<artifactId>aws-bedrock-token-generator</artifactId>
<version>1.1.0</version>
</dependency>
如果您使用 Gradle,請將下列項目新增至您的 build.gradle
:
implementation 'software.amazon.bedrock:aws-bedrock-token-generator:1.1.0'
範例
若要查看使用字符產生器產生短期 Amazon Bedrock API 金鑰搭配不同語言預設登入資料的範例,請選擇您偏好方法的索引標籤,然後遵循下列步驟:
- Python
-
from aws_bedrock_token_generator import provide_token
token = provide_token()
print(f"Token: {token}")
- Javascript
-
import { getTokenProvider } from "@aws/bedrock-token-generator";
// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
const provideToken = getTokenProvider();
async function example() {
const token = await provideToken();
// Use the token for API calls. The token has a default expiration of 12 hour.
// If the expiresInSeconds parameter is specified during token creation, the
// expiration can be configured up to a maximum of 12 hours. However, the actual
// token validity period will always be the minimum of the requested expiration
// time and the AWS credentials' expiry time
console.log(`Bearer Token: ${token}`);
}
- Java
-
import software.amazon.bedrock.token.BedrockTokenGenerator;
// Credentials and region will be picked up from the default provider chain
BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();
tokenGenerator.getToken();
若要查看產生字符時不同使用案例的更多範例,請參閱以下連結:
設定自動重新整理短期 Amazon Bedrock API 金鑰
您可以在aws-bedrock-token-generator
套件的協助下建立指令碼,以程式設計方式在目前金鑰過期時重新產生新的短期金鑰。首先,請確定您已滿足 的先決條件使用用戶端程式庫產生短期 Amazon Bedrock API 金鑰。若要查看擷取字符並提出 Converse 請求的範例指令碼,請選擇您偏好方法的標籤,然後遵循以下步驟:
- Python
-
from aws_bedrock_token_generator import provide_token
import requests
def get_new_token():
url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"
payload = {
"messages": [
{
"role": "user",
"content": [{"text": "Hello"}]
}
]
}
# Create a token provider that uses default credentials and region providers.
# You can configure it to use other credential providers.
# https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md
# It can be used for each API call as it is inexpensive.
token = provide_token()
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
if __name__ == "__main__":
get_new_token()
- Javascript
-
import { getTokenProvider } from "@aws/bedrock-token-generator";
// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
// https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md
// This can be created just once. Use await provideToken() to fetch the token
const provideToken = getTokenProvider();
async function example() {
const url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse";
const payload = {
messages: [
{
role: "user",
content: [{ text: "Hello" }]
}
]
};
const headers = {
"Content-Type": "application/json",
// provideToken retrieves a valid token. It can be used for each API call as it is inexpensive.
"Authorization": `Bearer ${await provideToken()}`
};
await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
})
}
- Java
-
package com.amazon.bedrocktoken;
import software.amazon.bedrock.token.BedrockTokenGenerator;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class GetNewToken {
public static void main(String[] args) throws Exception {
// Use default credentials and region from environment/profile chain
// Create a token generator that uses default credentials and region providers.
// You can configure it to use other credential providers.
// https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md
BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();
// getToken() retrieves a valid token. It can be used for each API call as it is inexpensive.
String token = tokenGenerator.getToken();
String url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse";
String payload = "{\n" +
" \"messages\": [\n" +
" {\n" +
" \"role\": \"user\",\n" +
" \"content\": [{ \"text\": \"Hello\" }]\n" +
" }\n" +
" ]\n" +
"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}