本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
生成 Amazon Bedrock API 密钥
您可以使用 AWS 管理控制台或 AWS API 生成 Amazon Bedrock API 密钥。我们建议您使用 AWS 管理控制台,通过几个步骤轻松生成 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 托管策略或自定义策略的 ARN,您可以重复此步骤:
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());
}
}