기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Amazon Bedrock API 키 생성
AWS Management Console 또는 API를 사용하여 Amazon Bedrock AWS API 키를 생성할 수 있습니다. AWS Management Console 를 사용하여 몇 단계만으로 Amazon Bedrock API 키를 쉽게 생성하는 것이 좋습니다.
Amazon Bedrock 탐색을 위해 Amazon Bedrock API 키 사용을 제한하는 것이 좋습니다. 보안 요구 사항이 더 큰 애플리케이션에 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 증명을 자동으로 인식 AWS CLI 하도록 허용하는지 확인합니다. 자세한 내용은에 대한 설정 구성을 참조하세요 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-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());
}
}