쿠키 기본 설정 선택

당사는 사이트와 서비스를 제공하는 데 필요한 필수 쿠키 및 유사한 도구를 사용합니다. 고객이 사이트를 어떻게 사용하는지 파악하고 개선할 수 있도록 성능 쿠키를 사용해 익명의 통계를 수집합니다. 필수 쿠키는 비활성화할 수 없지만 '사용자 지정' 또는 ‘거부’를 클릭하여 성능 쿠키를 거부할 수 있습니다.

사용자가 동의하는 경우 AWS와 승인된 제3자도 쿠키를 사용하여 유용한 사이트 기능을 제공하고, 사용자의 기본 설정을 기억하고, 관련 광고를 비롯한 관련 콘텐츠를 표시합니다. 필수가 아닌 모든 쿠키를 수락하거나 거부하려면 ‘수락’ 또는 ‘거부’를 클릭하세요. 더 자세한 내용을 선택하려면 ‘사용자 정의’를 클릭하세요.

SDK for Python(Boto3)을 사용한 Amazon Bedrock Agents 예제 - AWS SDK 코드 예제

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SDK for Python(Boto3)을 사용한 Amazon Bedrock Agents 예제

다음 코드 예제에서는 Amazon Bedrock Agents와 AWS SDK for Python (Boto3) 함께를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 관련 시나리오의 컨텍스트에 따라 표시되며, 개별 서비스 함수를 직접적으로 호출하는 방법을 보여줍니다.

시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

각 예시에는 전체 소스 코드에 대한 링크가 포함되어 있으며, 여기에서 컨텍스트에 맞춰 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있습니다.

작업

다음 코드 예시에서는 CreateAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 생성합니다.

def create_agent(self, agent_name, foundation_model, role_arn, instruction): """ Creates an agent that orchestrates interactions between foundation models, data sources, software applications, user conversations, and APIs to carry out tasks to help customers. :param agent_name: A name for the agent. :param foundation_model: The foundation model to be used for orchestration by the agent. :param role_arn: The ARN of the IAM role with permissions needed by the agent. :param instruction: Instructions that tell the agent what it should do and how it should interact with users. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.create_agent( agentName=agent_name, foundationModel=foundation_model, agentResourceRoleArn=role_arn, instruction=instruction, ) except ClientError as e: logger.error(f"Error: Couldn't create agent. Here's why: {e}") raise else: return response["agent"]
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 CreateAgent를 참조하세요.

다음 코드 예시에서는 CreateAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 생성합니다.

def create_agent(self, agent_name, foundation_model, role_arn, instruction): """ Creates an agent that orchestrates interactions between foundation models, data sources, software applications, user conversations, and APIs to carry out tasks to help customers. :param agent_name: A name for the agent. :param foundation_model: The foundation model to be used for orchestration by the agent. :param role_arn: The ARN of the IAM role with permissions needed by the agent. :param instruction: Instructions that tell the agent what it should do and how it should interact with users. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.create_agent( agentName=agent_name, foundationModel=foundation_model, agentResourceRoleArn=role_arn, instruction=instruction, ) except ClientError as e: logger.error(f"Error: Couldn't create agent. Here's why: {e}") raise else: return response["agent"]
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 CreateAgent를 참조하세요.

다음 코드 예시에서는 CreateAgentActionGroup을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 작업 그룹을 생성합니다.

def create_agent_action_group( self, name, description, agent_id, agent_version, function_arn, api_schema ): """ Creates an action group for an agent. An action group defines a set of actions that an agent should carry out for the customer. :param name: The name to give the action group. :param description: The description of the action group. :param agent_id: The unique identifier of the agent for which to create the action group. :param agent_version: The version of the agent for which to create the action group. :param function_arn: The ARN of the Lambda function containing the business logic that is carried out upon invoking the action. :param api_schema: Contains the OpenAPI schema for the action group. :return: Details about the action group that was created. """ try: response = self.client.create_agent_action_group( actionGroupName=name, description=description, agentId=agent_id, agentVersion=agent_version, actionGroupExecutor={"lambda": function_arn}, apiSchema={"payload": api_schema}, ) agent_action_group = response["agentActionGroup"] except ClientError as e: logger.error(f"Error: Couldn't create agent action group. Here's why: {e}") raise else: return agent_action_group

다음 코드 예시에서는 CreateAgentActionGroup을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 작업 그룹을 생성합니다.

def create_agent_action_group( self, name, description, agent_id, agent_version, function_arn, api_schema ): """ Creates an action group for an agent. An action group defines a set of actions that an agent should carry out for the customer. :param name: The name to give the action group. :param description: The description of the action group. :param agent_id: The unique identifier of the agent for which to create the action group. :param agent_version: The version of the agent for which to create the action group. :param function_arn: The ARN of the Lambda function containing the business logic that is carried out upon invoking the action. :param api_schema: Contains the OpenAPI schema for the action group. :return: Details about the action group that was created. """ try: response = self.client.create_agent_action_group( actionGroupName=name, description=description, agentId=agent_id, agentVersion=agent_version, actionGroupExecutor={"lambda": function_arn}, apiSchema={"payload": api_schema}, ) agent_action_group = response["agentActionGroup"] except ClientError as e: logger.error(f"Error: Couldn't create agent action group. Here's why: {e}") raise else: return agent_action_group

다음 코드 예시에서는 CreateAgentAlias을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 별칭을 생성합니다.

def create_agent_alias(self, name, agent_id): """ Creates an alias of an agent that can be used to deploy the agent. :param name: The name of the alias. :param agent_id: The unique identifier of the agent. :return: Details about the alias that was created. """ try: response = self.client.create_agent_alias( agentAliasName=name, agentId=agent_id ) agent_alias = response["agentAlias"] except ClientError as e: logger.error(f"Couldn't create agent alias. {e}") raise else: return agent_alias
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 CreateAgentAlias를 참조하세요.

다음 코드 예시에서는 CreateAgentAlias을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 별칭을 생성합니다.

def create_agent_alias(self, name, agent_id): """ Creates an alias of an agent that can be used to deploy the agent. :param name: The name of the alias. :param agent_id: The unique identifier of the agent. :return: Details about the alias that was created. """ try: response = self.client.create_agent_alias( agentAliasName=name, agentId=agent_id ) agent_alias = response["agentAlias"] except ClientError as e: logger.error(f"Couldn't create agent alias. {e}") raise else: return agent_alias
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 CreateAgentAlias를 참조하세요.

다음 코드 예시에서는 DeleteAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 삭제합니다.

def delete_agent(self, agent_id): """ Deletes an Amazon Bedrock agent. :param agent_id: The unique identifier of the agent to delete. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.delete_agent( agentId=agent_id, skipResourceInUseCheck=False ) except ClientError as e: logger.error(f"Couldn't delete agent. {e}") raise else: return response
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 DeleteAgent를 참조하세요.

다음 코드 예시에서는 DeleteAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 삭제합니다.

def delete_agent(self, agent_id): """ Deletes an Amazon Bedrock agent. :param agent_id: The unique identifier of the agent to delete. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.delete_agent( agentId=agent_id, skipResourceInUseCheck=False ) except ClientError as e: logger.error(f"Couldn't delete agent. {e}") raise else: return response
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 DeleteAgent를 참조하세요.

다음 코드 예시에서는 DeleteAgentAlias을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 별칭을 삭제합니다.

def delete_agent_alias(self, agent_id, agent_alias_id): """ Deletes an alias of an Amazon Bedrock agent. :param agent_id: The unique identifier of the agent that the alias belongs to. :param agent_alias_id: The unique identifier of the alias to delete. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.delete_agent_alias( agentId=agent_id, agentAliasId=agent_alias_id ) except ClientError as e: logger.error(f"Couldn't delete agent alias. {e}") raise else: return response
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 DeleteAgentAlias를 참조하세요.

다음 코드 예시에서는 DeleteAgentAlias을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트 별칭을 삭제합니다.

def delete_agent_alias(self, agent_id, agent_alias_id): """ Deletes an alias of an Amazon Bedrock agent. :param agent_id: The unique identifier of the agent that the alias belongs to. :param agent_alias_id: The unique identifier of the alias to delete. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: response = self.client.delete_agent_alias( agentId=agent_id, agentAliasId=agent_alias_id ) except ClientError as e: logger.error(f"Couldn't delete agent alias. {e}") raise else: return response
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 DeleteAgentAlias를 참조하세요.

다음 코드 예시에서는 GetAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 가져옵니다.

def get_agent(self, agent_id, log_error=True): """ Gets information about an agent. :param agent_id: The unique identifier of the agent. :param log_error: Whether to log any errors that occur when getting the agent. If True, errors will be logged to the logger. If False, errors will still be raised, but not logged. :return: The information about the requested agent. """ try: response = self.client.get_agent(agentId=agent_id) agent = response["agent"] except ClientError as e: if log_error: logger.error(f"Couldn't get agent {agent_id}. {e}") raise else: return agent
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 GetAgent를 참조하세요.

다음 코드 예시에서는 GetAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 가져옵니다.

def get_agent(self, agent_id, log_error=True): """ Gets information about an agent. :param agent_id: The unique identifier of the agent. :param log_error: Whether to log any errors that occur when getting the agent. If True, errors will be logged to the logger. If False, errors will still be raised, but not logged. :return: The information about the requested agent. """ try: response = self.client.get_agent(agentId=agent_id) agent = response["agent"] except ClientError as e: if log_error: logger.error(f"Couldn't get agent {agent_id}. {e}") raise else: return agent
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 GetAgent를 참조하세요.

다음 코드 예시에서는 ListAgentActionGroups을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트의 작업 그룹을 나열합니다.

def list_agent_action_groups(self, agent_id, agent_version): """ List the action groups for a version of an Amazon Bedrock Agent. :param agent_id: The unique identifier of the agent. :param agent_version: The version of the agent. :return: The list of action group summaries for the version of the agent. """ try: action_groups = [] paginator = self.client.get_paginator("list_agent_action_groups") for page in paginator.paginate( agentId=agent_id, agentVersion=agent_version, PaginationConfig={"PageSize": 10}, ): action_groups.extend(page["actionGroupSummaries"]) except ClientError as e: logger.error(f"Couldn't list action groups. {e}") raise else: return action_groups

다음 코드 예시에서는 ListAgentActionGroups을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트의 작업 그룹을 나열합니다.

def list_agent_action_groups(self, agent_id, agent_version): """ List the action groups for a version of an Amazon Bedrock Agent. :param agent_id: The unique identifier of the agent. :param agent_version: The version of the agent. :return: The list of action group summaries for the version of the agent. """ try: action_groups = [] paginator = self.client.get_paginator("list_agent_action_groups") for page in paginator.paginate( agentId=agent_id, agentVersion=agent_version, PaginationConfig={"PageSize": 10}, ): action_groups.extend(page["actionGroupSummaries"]) except ClientError as e: logger.error(f"Couldn't list action groups. {e}") raise else: return action_groups

다음 코드 예시에서는 ListAgentKnowledgeBases을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트와 연결된 지식 기반을 나열합니다.

def list_agent_knowledge_bases(self, agent_id, agent_version): """ List the knowledge bases associated with a version of an Amazon Bedrock Agent. :param agent_id: The unique identifier of the agent. :param agent_version: The version of the agent. :return: The list of knowledge base summaries for the version of the agent. """ try: knowledge_bases = [] paginator = self.client.get_paginator("list_agent_knowledge_bases") for page in paginator.paginate( agentId=agent_id, agentVersion=agent_version, PaginationConfig={"PageSize": 10}, ): knowledge_bases.extend(page["agentKnowledgeBaseSummaries"]) except ClientError as e: logger.error(f"Couldn't list knowledge bases. {e}") raise else: return knowledge_bases

다음 코드 예시에서는 ListAgentKnowledgeBases을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트와 연결된 지식 기반을 나열합니다.

def list_agent_knowledge_bases(self, agent_id, agent_version): """ List the knowledge bases associated with a version of an Amazon Bedrock Agent. :param agent_id: The unique identifier of the agent. :param agent_version: The version of the agent. :return: The list of knowledge base summaries for the version of the agent. """ try: knowledge_bases = [] paginator = self.client.get_paginator("list_agent_knowledge_bases") for page in paginator.paginate( agentId=agent_id, agentVersion=agent_version, PaginationConfig={"PageSize": 10}, ): knowledge_bases.extend(page["agentKnowledgeBaseSummaries"]) except ClientError as e: logger.error(f"Couldn't list knowledge bases. {e}") raise else: return knowledge_bases

다음 코드 예시에서는 ListAgents을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

계정에 속한 에이전트를 나열합니다.

def list_agents(self): """ List the available Amazon Bedrock Agents. :return: The list of available bedrock agents. """ try: all_agents = [] paginator = self.client.get_paginator("list_agents") for page in paginator.paginate(PaginationConfig={"PageSize": 10}): all_agents.extend(page["agentSummaries"]) except ClientError as e: logger.error(f"Couldn't list agents. {e}") raise else: return all_agents
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 ListAgents를 참조하세요.

다음 코드 예시에서는 ListAgents을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

계정에 속한 에이전트를 나열합니다.

def list_agents(self): """ List the available Amazon Bedrock Agents. :return: The list of available bedrock agents. """ try: all_agents = [] paginator = self.client.get_paginator("list_agents") for page in paginator.paginate(PaginationConfig={"PageSize": 10}): all_agents.extend(page["agentSummaries"]) except ClientError as e: logger.error(f"Couldn't list agents. {e}") raise else: return all_agents
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 ListAgents를 참조하세요.

다음 코드 예시에서는 PrepareAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

내부 테스트를 위해 에이전트를 준비합니다.

def prepare_agent(self, agent_id): """ Creates a DRAFT version of the agent that can be used for internal testing. :param agent_id: The unique identifier of the agent to prepare. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: prepared_agent_details = self.client.prepare_agent(agentId=agent_id) except ClientError as e: logger.error(f"Couldn't prepare agent. {e}") raise else: return prepared_agent_details
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 PrepareAgent를 참조하세요.

다음 코드 예시에서는 PrepareAgent을 사용하는 방법을 보여 줍니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

내부 테스트를 위해 에이전트를 준비합니다.

def prepare_agent(self, agent_id): """ Creates a DRAFT version of the agent that can be used for internal testing. :param agent_id: The unique identifier of the agent to prepare. :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception. """ try: prepared_agent_details = self.client.prepare_agent(agentId=agent_id) except ClientError as e: logger.error(f"Couldn't prepare agent. {e}") raise else: return prepared_agent_details
  • API 세부 정보는 AWS SDK for Python(Boto3) API 참조의 PrepareAgent를 참조하세요.

시나리오

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 에이전트에 대한 실행 역할을 생성합니다.

  • 에이전트를 생성하고 DRAFT 버전을 배포합니다.

  • 에이전트의 기능을 구현하는 Lambda 함수를 생성합니다.

  • 에이전트를 Lambda 함수에 연결하는 작업 그룹을 생성합니다.

  • 완전히 구성된 에이전트를 배포합니다.

  • 사용자가 제공한 프롬프트로 에이전트를 간접 호출합니다.

  • 생성된 모든 리소스를 삭제합니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 생성 및 간접 호출합니다.

REGION = "us-east-1" ROLE_POLICY_NAME = "agent_permissions" class BedrockAgentScenarioWrapper: """Runs a scenario that shows how to get started using Amazon Bedrock Agents.""" def __init__( self, bedrock_agent_client, runtime_client, lambda_client, iam_resource, postfix ): self.iam_resource = iam_resource self.lambda_client = lambda_client self.bedrock_agent_runtime_client = runtime_client self.postfix = postfix self.bedrock_wrapper = BedrockAgentWrapper(bedrock_agent_client) self.agent = None self.agent_alias = None self.agent_role = None self.prepared_agent_details = None self.lambda_role = None self.lambda_function = None def run_scenario(self): print("=" * 88) print("Welcome to the Amazon Bedrock Agents demo.") print("=" * 88) # Query input from user print("Let's start with creating an agent:") print("-" * 40) name, foundation_model = self._request_name_and_model_from_user() print("-" * 40) # Create an execution role for the agent self.agent_role = self._create_agent_role(foundation_model) # Create the agent self.agent = self._create_agent(name, foundation_model) # Prepare a DRAFT version of the agent self.prepared_agent_details = self._prepare_agent() # Create the agent's Lambda function self.lambda_function = self._create_lambda_function() # Configure permissions for the agent to invoke the Lambda function self._allow_agent_to_invoke_function() self._let_function_accept_invocations_from_agent() # Create an action group to connect the agent with the Lambda function self._create_agent_action_group() # If the agent has been modified or any components have been added, prepare the agent again components = [self._get_agent()] components += self._get_agent_action_groups() components += self._get_agent_knowledge_bases() latest_update = max(component["updatedAt"] for component in components) if latest_update > self.prepared_agent_details["preparedAt"]: self.prepared_agent_details = self._prepare_agent() # Create an agent alias self.agent_alias = self._create_agent_alias() # Test the agent self._chat_with_agent(self.agent_alias) print("=" * 88) print("Thanks for running the demo!\n") if q.ask("Do you want to delete the created resources? [y/N] ", q.is_yesno): self._delete_resources() print("=" * 88) print( "All demo resources have been deleted. Thanks again for running the demo!" ) else: self._list_resources() print("=" * 88) print("Thanks again for running the demo!") def _request_name_and_model_from_user(self): existing_agent_names = [ agent["agentName"] for agent in self.bedrock_wrapper.list_agents() ] while True: name = q.ask("Enter an agent name: ", self.is_valid_agent_name) if name.lower() not in [n.lower() for n in existing_agent_names]: break print( f"Agent {name} conflicts with an existing agent. Please use a different name." ) models = ["anthropic.claude-instant-v1", "anthropic.claude-v2"] model_id = models[ q.choose("Which foundation model would you like to use? ", models) ] return name, model_id def _create_agent_role(self, model_id): role_name = f"AmazonBedrockExecutionRoleForAgents_{self.postfix}" model_arn = f"arn:aws:bedrock:{REGION}::foundation-model/{model_id}*" print("Creating an an execution role for the agent...") try: role = self.iam_resource.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "bedrock.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } ), ) role.Policy(ROLE_POLICY_NAME).put( PolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "bedrock:InvokeModel", "Resource": model_arn, } ], } ) ) except ClientError as e: logger.error(f"Couldn't create role {role_name}. Here's why: {e}") raise return role def _create_agent(self, name, model_id): print("Creating the agent...") instruction = """ You are a friendly chat bot. You have access to a function called that returns information about the current date and time. When responding with date or time, please make sure to add the timezone UTC. """ agent = self.bedrock_wrapper.create_agent( agent_name=name, foundation_model=model_id, instruction=instruction, role_arn=self.agent_role.arn, ) self._wait_for_agent_status(agent["agentId"], "NOT_PREPARED") return agent def _prepare_agent(self): print("Preparing the agent...") agent_id = self.agent["agentId"] prepared_agent_details = self.bedrock_wrapper.prepare_agent(agent_id) self._wait_for_agent_status(agent_id, "PREPARED") return prepared_agent_details def _create_lambda_function(self): print("Creating the Lambda function...") function_name = f"AmazonBedrockExampleFunction_{self.postfix}" self.lambda_role = self._create_lambda_role() try: deployment_package = self._create_deployment_package(function_name) lambda_function = self.lambda_client.create_function( FunctionName=function_name, Description="Lambda function for Amazon Bedrock example", Runtime="python3.11", Role=self.lambda_role.arn, Handler=f"{function_name}.lambda_handler", Code={"ZipFile": deployment_package}, Publish=True, ) waiter = self.lambda_client.get_waiter("function_active_v2") waiter.wait(FunctionName=function_name) except ClientError as e: logger.error( f"Couldn't create Lambda function {function_name}. Here's why: {e}" ) raise return lambda_function def _create_lambda_role(self): print("Creating an execution role for the Lambda function...") role_name = f"AmazonBedrockExecutionRoleForLambda_{self.postfix}" try: role = self.iam_resource.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } ), ) role.attach_policy( PolicyArn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ) print(f"Created role {role_name}") except ClientError as e: logger.error(f"Couldn't create role {role_name}. Here's why: {e}") raise print("Waiting for the execution role to be fully propagated...") wait(10) return role def _allow_agent_to_invoke_function(self): policy = self.iam_resource.RolePolicy( self.agent_role.role_name, ROLE_POLICY_NAME ) doc = policy.policy_document doc["Statement"].append( { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": self.lambda_function["FunctionArn"], } ) self.agent_role.Policy(ROLE_POLICY_NAME).put(PolicyDocument=json.dumps(doc)) def _let_function_accept_invocations_from_agent(self): try: self.lambda_client.add_permission( FunctionName=self.lambda_function["FunctionName"], SourceArn=self.agent["agentArn"], StatementId="BedrockAccess", Action="lambda:InvokeFunction", Principal="bedrock.amazonaws.com", ) except ClientError as e: logger.error( f"Couldn't grant Bedrock permission to invoke the Lambda function. Here's why: {e}" ) raise def _create_agent_action_group(self): print("Creating an action group for the agent...") try: with open("./scenario_resources/api_schema.yaml") as file: self.bedrock_wrapper.create_agent_action_group( name="current_date_and_time", description="Gets the current date and time.", agent_id=self.agent["agentId"], agent_version=self.prepared_agent_details["agentVersion"], function_arn=self.lambda_function["FunctionArn"], api_schema=json.dumps(yaml.safe_load(file)), ) except ClientError as e: logger.error(f"Couldn't create agent action group. Here's why: {e}") raise def _get_agent(self): return self.bedrock_wrapper.get_agent(self.agent["agentId"]) def _get_agent_action_groups(self): return self.bedrock_wrapper.list_agent_action_groups( self.agent["agentId"], self.prepared_agent_details["agentVersion"] ) def _get_agent_knowledge_bases(self): return self.bedrock_wrapper.list_agent_knowledge_bases( self.agent["agentId"], self.prepared_agent_details["agentVersion"] ) def _create_agent_alias(self): print("Creating an agent alias...") agent_alias_name = "test_agent_alias" agent_alias = self.bedrock_wrapper.create_agent_alias( agent_alias_name, self.agent["agentId"] ) self._wait_for_agent_status(self.agent["agentId"], "PREPARED") return agent_alias def _wait_for_agent_status(self, agent_id, status): while self.bedrock_wrapper.get_agent(agent_id)["agentStatus"] != status: wait(2) def _chat_with_agent(self, agent_alias): print("-" * 88) print("The agent is ready to chat.") print("Try asking for the date or time. Type 'exit' to quit.") # Create a unique session ID for the conversation session_id = uuid.uuid4().hex while True: prompt = q.ask("Prompt: ", q.non_empty) if prompt == "exit": break response = asyncio.run(self._invoke_agent(agent_alias, prompt, session_id)) print(f"Agent: {response}") async def _invoke_agent(self, agent_alias, prompt, session_id): response = self.bedrock_agent_runtime_client.invoke_agent( agentId=self.agent["agentId"], agentAliasId=agent_alias["agentAliasId"], sessionId=session_id, inputText=prompt, ) completion = "" for event in response.get("completion"): chunk = event["chunk"] completion += chunk["bytes"].decode() return completion def _delete_resources(self): if self.agent: agent_id = self.agent["agentId"] if self.agent_alias: agent_alias_id = self.agent_alias["agentAliasId"] print("Deleting agent alias...") self.bedrock_wrapper.delete_agent_alias(agent_id, agent_alias_id) print("Deleting agent...") agent_status = self.bedrock_wrapper.delete_agent(agent_id)["agentStatus"] while agent_status == "DELETING": wait(5) try: agent_status = self.bedrock_wrapper.get_agent( agent_id, log_error=False )["agentStatus"] except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": agent_status = "DELETED" if self.lambda_function: name = self.lambda_function["FunctionName"] print(f"Deleting function '{name}'...") self.lambda_client.delete_function(FunctionName=name) if self.agent_role: print(f"Deleting role '{self.agent_role.role_name}'...") self.agent_role.Policy(ROLE_POLICY_NAME).delete() self.agent_role.delete() if self.lambda_role: print(f"Deleting role '{self.lambda_role.role_name}'...") for policy in self.lambda_role.attached_policies.all(): policy.detach_role(RoleName=self.lambda_role.role_name) self.lambda_role.delete() def _list_resources(self): print("-" * 40) print(f"Here is the list of created resources in '{REGION}'.") print("Make sure you delete them once you're done to avoid unnecessary costs.") if self.agent: print(f"Bedrock Agent: {self.agent['agentName']}") if self.lambda_function: print(f"Lambda function: {self.lambda_function['FunctionName']}") if self.agent_role: print(f"IAM role: {self.agent_role.role_name}") if self.lambda_role: print(f"IAM role: {self.lambda_role.role_name}") @staticmethod def is_valid_agent_name(answer): valid_regex = r"^[a-zA-Z0-9_-]{1,100}$" return ( answer if answer and len(answer) <= 100 and re.match(valid_regex, answer) else None, "I need a name for the agent, please. Valid characters are a-z, A-Z, 0-9, _ (underscore) and - (hyphen).", ) @staticmethod def _create_deployment_package(function_name): buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as zipped: zipped.write( "./scenario_resources/lambda_function.py", f"{function_name}.py" ) buffer.seek(0) return buffer.read() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") postfix = "".join( random.choice(string.ascii_lowercase + "0123456789") for _ in range(8) ) scenario = BedrockAgentScenarioWrapper( bedrock_agent_client=boto3.client( service_name="bedrock-agent", region_name=REGION ), runtime_client=boto3.client( service_name="bedrock-agent-runtime", region_name=REGION ), lambda_client=boto3.client(service_name="lambda", region_name=REGION), iam_resource=boto3.resource("iam"), postfix=postfix, ) try: scenario.run_scenario() except Exception as e: logging.exception(f"Something went wrong with the demo. Here's what: {e}")

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 에이전트에 대한 실행 역할을 생성합니다.

  • 에이전트를 생성하고 DRAFT 버전을 배포합니다.

  • 에이전트의 기능을 구현하는 Lambda 함수를 생성합니다.

  • 에이전트를 Lambda 함수에 연결하는 작업 그룹을 생성합니다.

  • 완전히 구성된 에이전트를 배포합니다.

  • 사용자가 제공한 프롬프트로 에이전트를 간접 호출합니다.

  • 생성된 모든 리소스를 삭제합니다.

SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

에이전트를 생성 및 간접 호출합니다.

REGION = "us-east-1" ROLE_POLICY_NAME = "agent_permissions" class BedrockAgentScenarioWrapper: """Runs a scenario that shows how to get started using Amazon Bedrock Agents.""" def __init__( self, bedrock_agent_client, runtime_client, lambda_client, iam_resource, postfix ): self.iam_resource = iam_resource self.lambda_client = lambda_client self.bedrock_agent_runtime_client = runtime_client self.postfix = postfix self.bedrock_wrapper = BedrockAgentWrapper(bedrock_agent_client) self.agent = None self.agent_alias = None self.agent_role = None self.prepared_agent_details = None self.lambda_role = None self.lambda_function = None def run_scenario(self): print("=" * 88) print("Welcome to the Amazon Bedrock Agents demo.") print("=" * 88) # Query input from user print("Let's start with creating an agent:") print("-" * 40) name, foundation_model = self._request_name_and_model_from_user() print("-" * 40) # Create an execution role for the agent self.agent_role = self._create_agent_role(foundation_model) # Create the agent self.agent = self._create_agent(name, foundation_model) # Prepare a DRAFT version of the agent self.prepared_agent_details = self._prepare_agent() # Create the agent's Lambda function self.lambda_function = self._create_lambda_function() # Configure permissions for the agent to invoke the Lambda function self._allow_agent_to_invoke_function() self._let_function_accept_invocations_from_agent() # Create an action group to connect the agent with the Lambda function self._create_agent_action_group() # If the agent has been modified or any components have been added, prepare the agent again components = [self._get_agent()] components += self._get_agent_action_groups() components += self._get_agent_knowledge_bases() latest_update = max(component["updatedAt"] for component in components) if latest_update > self.prepared_agent_details["preparedAt"]: self.prepared_agent_details = self._prepare_agent() # Create an agent alias self.agent_alias = self._create_agent_alias() # Test the agent self._chat_with_agent(self.agent_alias) print("=" * 88) print("Thanks for running the demo!\n") if q.ask("Do you want to delete the created resources? [y/N] ", q.is_yesno): self._delete_resources() print("=" * 88) print( "All demo resources have been deleted. Thanks again for running the demo!" ) else: self._list_resources() print("=" * 88) print("Thanks again for running the demo!") def _request_name_and_model_from_user(self): existing_agent_names = [ agent["agentName"] for agent in self.bedrock_wrapper.list_agents() ] while True: name = q.ask("Enter an agent name: ", self.is_valid_agent_name) if name.lower() not in [n.lower() for n in existing_agent_names]: break print( f"Agent {name} conflicts with an existing agent. Please use a different name." ) models = ["anthropic.claude-instant-v1", "anthropic.claude-v2"] model_id = models[ q.choose("Which foundation model would you like to use? ", models) ] return name, model_id def _create_agent_role(self, model_id): role_name = f"AmazonBedrockExecutionRoleForAgents_{self.postfix}" model_arn = f"arn:aws:bedrock:{REGION}::foundation-model/{model_id}*" print("Creating an an execution role for the agent...") try: role = self.iam_resource.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "bedrock.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } ), ) role.Policy(ROLE_POLICY_NAME).put( PolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "bedrock:InvokeModel", "Resource": model_arn, } ], } ) ) except ClientError as e: logger.error(f"Couldn't create role {role_name}. Here's why: {e}") raise return role def _create_agent(self, name, model_id): print("Creating the agent...") instruction = """ You are a friendly chat bot. You have access to a function called that returns information about the current date and time. When responding with date or time, please make sure to add the timezone UTC. """ agent = self.bedrock_wrapper.create_agent( agent_name=name, foundation_model=model_id, instruction=instruction, role_arn=self.agent_role.arn, ) self._wait_for_agent_status(agent["agentId"], "NOT_PREPARED") return agent def _prepare_agent(self): print("Preparing the agent...") agent_id = self.agent["agentId"] prepared_agent_details = self.bedrock_wrapper.prepare_agent(agent_id) self._wait_for_agent_status(agent_id, "PREPARED") return prepared_agent_details def _create_lambda_function(self): print("Creating the Lambda function...") function_name = f"AmazonBedrockExampleFunction_{self.postfix}" self.lambda_role = self._create_lambda_role() try: deployment_package = self._create_deployment_package(function_name) lambda_function = self.lambda_client.create_function( FunctionName=function_name, Description="Lambda function for Amazon Bedrock example", Runtime="python3.11", Role=self.lambda_role.arn, Handler=f"{function_name}.lambda_handler", Code={"ZipFile": deployment_package}, Publish=True, ) waiter = self.lambda_client.get_waiter("function_active_v2") waiter.wait(FunctionName=function_name) except ClientError as e: logger.error( f"Couldn't create Lambda function {function_name}. Here's why: {e}" ) raise return lambda_function def _create_lambda_role(self): print("Creating an execution role for the Lambda function...") role_name = f"AmazonBedrockExecutionRoleForLambda_{self.postfix}" try: role = self.iam_resource.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } ), ) role.attach_policy( PolicyArn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ) print(f"Created role {role_name}") except ClientError as e: logger.error(f"Couldn't create role {role_name}. Here's why: {e}") raise print("Waiting for the execution role to be fully propagated...") wait(10) return role def _allow_agent_to_invoke_function(self): policy = self.iam_resource.RolePolicy( self.agent_role.role_name, ROLE_POLICY_NAME ) doc = policy.policy_document doc["Statement"].append( { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": self.lambda_function["FunctionArn"], } ) self.agent_role.Policy(ROLE_POLICY_NAME).put(PolicyDocument=json.dumps(doc)) def _let_function_accept_invocations_from_agent(self): try: self.lambda_client.add_permission( FunctionName=self.lambda_function["FunctionName"], SourceArn=self.agent["agentArn"], StatementId="BedrockAccess", Action="lambda:InvokeFunction", Principal="bedrock.amazonaws.com", ) except ClientError as e: logger.error( f"Couldn't grant Bedrock permission to invoke the Lambda function. Here's why: {e}" ) raise def _create_agent_action_group(self): print("Creating an action group for the agent...") try: with open("./scenario_resources/api_schema.yaml") as file: self.bedrock_wrapper.create_agent_action_group( name="current_date_and_time", description="Gets the current date and time.", agent_id=self.agent["agentId"], agent_version=self.prepared_agent_details["agentVersion"], function_arn=self.lambda_function["FunctionArn"], api_schema=json.dumps(yaml.safe_load(file)), ) except ClientError as e: logger.error(f"Couldn't create agent action group. Here's why: {e}") raise def _get_agent(self): return self.bedrock_wrapper.get_agent(self.agent["agentId"]) def _get_agent_action_groups(self): return self.bedrock_wrapper.list_agent_action_groups( self.agent["agentId"], self.prepared_agent_details["agentVersion"] ) def _get_agent_knowledge_bases(self): return self.bedrock_wrapper.list_agent_knowledge_bases( self.agent["agentId"], self.prepared_agent_details["agentVersion"] ) def _create_agent_alias(self): print("Creating an agent alias...") agent_alias_name = "test_agent_alias" agent_alias = self.bedrock_wrapper.create_agent_alias( agent_alias_name, self.agent["agentId"] ) self._wait_for_agent_status(self.agent["agentId"], "PREPARED") return agent_alias def _wait_for_agent_status(self, agent_id, status): while self.bedrock_wrapper.get_agent(agent_id)["agentStatus"] != status: wait(2) def _chat_with_agent(self, agent_alias): print("-" * 88) print("The agent is ready to chat.") print("Try asking for the date or time. Type 'exit' to quit.") # Create a unique session ID for the conversation session_id = uuid.uuid4().hex while True: prompt = q.ask("Prompt: ", q.non_empty) if prompt == "exit": break response = asyncio.run(self._invoke_agent(agent_alias, prompt, session_id)) print(f"Agent: {response}") async def _invoke_agent(self, agent_alias, prompt, session_id): response = self.bedrock_agent_runtime_client.invoke_agent( agentId=self.agent["agentId"], agentAliasId=agent_alias["agentAliasId"], sessionId=session_id, inputText=prompt, ) completion = "" for event in response.get("completion"): chunk = event["chunk"] completion += chunk["bytes"].decode() return completion def _delete_resources(self): if self.agent: agent_id = self.agent["agentId"] if self.agent_alias: agent_alias_id = self.agent_alias["agentAliasId"] print("Deleting agent alias...") self.bedrock_wrapper.delete_agent_alias(agent_id, agent_alias_id) print("Deleting agent...") agent_status = self.bedrock_wrapper.delete_agent(agent_id)["agentStatus"] while agent_status == "DELETING": wait(5) try: agent_status = self.bedrock_wrapper.get_agent( agent_id, log_error=False )["agentStatus"] except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": agent_status = "DELETED" if self.lambda_function: name = self.lambda_function["FunctionName"] print(f"Deleting function '{name}'...") self.lambda_client.delete_function(FunctionName=name) if self.agent_role: print(f"Deleting role '{self.agent_role.role_name}'...") self.agent_role.Policy(ROLE_POLICY_NAME).delete() self.agent_role.delete() if self.lambda_role: print(f"Deleting role '{self.lambda_role.role_name}'...") for policy in self.lambda_role.attached_policies.all(): policy.detach_role(RoleName=self.lambda_role.role_name) self.lambda_role.delete() def _list_resources(self): print("-" * 40) print(f"Here is the list of created resources in '{REGION}'.") print("Make sure you delete them once you're done to avoid unnecessary costs.") if self.agent: print(f"Bedrock Agent: {self.agent['agentName']}") if self.lambda_function: print(f"Lambda function: {self.lambda_function['FunctionName']}") if self.agent_role: print(f"IAM role: {self.agent_role.role_name}") if self.lambda_role: print(f"IAM role: {self.lambda_role.role_name}") @staticmethod def is_valid_agent_name(answer): valid_regex = r"^[a-zA-Z0-9_-]{1,100}$" return ( answer if answer and len(answer) <= 100 and re.match(valid_regex, answer) else None, "I need a name for the agent, please. Valid characters are a-z, A-Z, 0-9, _ (underscore) and - (hyphen).", ) @staticmethod def _create_deployment_package(function_name): buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as zipped: zipped.write( "./scenario_resources/lambda_function.py", f"{function_name}.py" ) buffer.seek(0) return buffer.read() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") postfix = "".join( random.choice(string.ascii_lowercase + "0123456789") for _ in range(8) ) scenario = BedrockAgentScenarioWrapper( bedrock_agent_client=boto3.client( service_name="bedrock-agent", region_name=REGION ), runtime_client=boto3.client( service_name="bedrock-agent-runtime", region_name=REGION ), lambda_client=boto3.client(service_name="lambda", region_name=REGION), iam_resource=boto3.resource("iam"), postfix=postfix, ) try: scenario.run_scenario() except Exception as e: logging.exception(f"Something went wrong with the demo. Here's what: {e}")

다음 코드 예제는 Amazon Bedrock 및 Step Functions를 사용하여 생성형 AI 애플리케이션을 구축하고 오케스트레이션하는 방법을 보여줍니다.

SDK for Python(Boto3)

Amazon Bedrock 서버리스 프롬프트 체이닝 시나리오는 AWS Step Functions, Amazon Bedrockhttps://docs.aws.amazon.com/bedrock/latest/userguide/agents.html의 방법을 사용하여 복잡하고 확장성이 뛰어난 서버리스 생성형 AI 애플리케이션을 구축하고 오케스트레이션하는 방법을 보여줍니다. 여기에는 다음과 같은 작업 예제가 포함됩니다.

  • 문학 블로그에 특정 소설에 대한 분석을 작성합니다. 이 예제에서는 간단하고 순차적인 프롬프트 체인을 보여줍니다.

  • 주어진 주제에 대한 짧은 스토리를 생성합니다. 이 예제에서는 AI가 이전에 생성한 항목 목록을 어떻게 반복적으로 처리하는지 보여줍니다.

  • 주어진 목적지로 향하는 주말 휴가 일정을 생성합니다. 이 예제에서는 여러 개의 고유한 프롬프트를 병렬화하는 방법을 보여줍니다.

  • 영화 프로듀서인 사용자에게 영화 아이디어를 피칭합니다. 이 예제에서는 동일한 프롬프트를 서로 다른 추론 파라미터와 병렬화하는 방법, 체인의 이전 단계로 역추적하는 방법, 워크플로의 일부로 사람의 입력을 포함하는 방법을 보여줍니다.

  • 사용자가 가진 재료를 바탕으로 식사를 계획합니다. 이 예제에서는 프롬프트 체인이 두 개의 개별 AI 대화를 어떻게 통합하는지 보여줍니다. 두 AI 페르소나가 최종 결과를 개선하기 위해 서로 토론합니다.

  • 요즘 가장 화제가 되는 GitHub 리포지토리를 찾아 요약합니다. 이 예제에서는 외부 API와 상호 작용하는 여러 AI 에이전트를 연결하는 방법을 보여줍니다.

전체 소스 코드와 설정 및 실행 방법에 대한 지침은 GitHub에서 전체 프로젝트를 참조하세요.

이 예시에서 사용되는 서비스
  • Amazon Bedrock

  • Amazon Bedrock 런타임

  • Amazon Bedrock Agents

  • Amazon Bedrock Agents Runtime

  • Step Functions

다음 코드 예제는 Amazon Bedrock 및 Step Functions를 사용하여 생성형 AI 애플리케이션을 구축하고 오케스트레이션하는 방법을 보여줍니다.

SDK for Python(Boto3)

Amazon Bedrock 서버리스 프롬프트 체이닝 시나리오는 AWS Step Functions, Amazon Bedrockhttps://docs.aws.amazon.com/bedrock/latest/userguide/agents.html의 방법을 사용하여 복잡하고 확장성이 뛰어난 서버리스 생성형 AI 애플리케이션을 구축하고 오케스트레이션하는 방법을 보여줍니다. 여기에는 다음과 같은 작업 예제가 포함됩니다.

  • 문학 블로그에 특정 소설에 대한 분석을 작성합니다. 이 예제에서는 간단하고 순차적인 프롬프트 체인을 보여줍니다.

  • 주어진 주제에 대한 짧은 스토리를 생성합니다. 이 예제에서는 AI가 이전에 생성한 항목 목록을 어떻게 반복적으로 처리하는지 보여줍니다.

  • 주어진 목적지로 향하는 주말 휴가 일정을 생성합니다. 이 예제에서는 여러 개의 고유한 프롬프트를 병렬화하는 방법을 보여줍니다.

  • 영화 프로듀서인 사용자에게 영화 아이디어를 피칭합니다. 이 예제에서는 동일한 프롬프트를 서로 다른 추론 파라미터와 병렬화하는 방법, 체인의 이전 단계로 역추적하는 방법, 워크플로의 일부로 사람의 입력을 포함하는 방법을 보여줍니다.

  • 사용자가 가진 재료를 바탕으로 식사를 계획합니다. 이 예제에서는 프롬프트 체인이 두 개의 개별 AI 대화를 어떻게 통합하는지 보여줍니다. 두 AI 페르소나가 최종 결과를 개선하기 위해 서로 토론합니다.

  • 요즘 가장 화제가 되는 GitHub 리포지토리를 찾아 요약합니다. 이 예제에서는 외부 API와 상호 작용하는 여러 AI 에이전트를 연결하는 방법을 보여줍니다.

전체 소스 코드와 설정 및 실행 방법에 대한 지침은 GitHub에서 전체 프로젝트를 참조하세요.

이 예시에서 사용되는 서비스
  • Amazon Bedrock

  • Amazon Bedrock 런타임

  • Amazon Bedrock Agents

  • Amazon Bedrock Agents Runtime

  • Step Functions

프라이버시사이트 이용 약관쿠키 기본 설정
© 2025, Amazon Web Services, Inc. 또는 계열사. All rights reserved.