本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
生成 Amazon Bedrock API 密钥
您可以使用 AWS Management Console 或 API 生成 Amazon Bedrock AWS API 密钥。我们建议您使用通过几个步骤轻松生成 Amazon Bedrock API 密钥。 AWS Management Console
我们强烈建议限制使用亚马逊 Bedrock API 密钥来探索亚马逊 Bedrock。当您准备将 Amazon Bedrock 整合到具有更高安全要求的应用程序中时,应切换到短期证书。有关更多信息,请参阅 IAM 用户指南中的长期访问密钥替代方案。
使用控制台生成 Amazon Bedrock API 密钥
要使用控制台生成 Amazon Bedrock API 密钥,请执行以下操作:
-
使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS Management Console 然后,在 https://console.aws.amazon.com/bedrock 上打开 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 密钥 ARNs 中的任何其他 AWS托管策略或自定义策略重复此步骤:
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());
}
}