

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

# 자습서: 모기지 애플리케이션을 처리하는 흐름 생성
<a name="getting-started-mortgage-flow"></a>

Amazon Bedrock 리소스와 그 기능에 익숙해지기 위해 CloudFormation 템플릿을 사용하여 다양한 Amazon Bedrock과 기타 AWS 리소스를 결합하여 모기지 애플리케이션 프로세스 프로세스를 자동화하는 [흐름을](flows.md) 설정합니다.

**참고**  
이 자습서에서는 *us-east-1* 리전을 사용합니다. 에이전트, 흐름, 가드레일, 지식 기반 및 프롬프트 관리를 지원하는 리전이면 무엇이든 사용할 수 있습니다. 리전별 기능 지원 테이블은 [Amazon Bedrock AWS 리전 에서의 기능 지원](features-regions.md) 섹션을 참조하세요. 사용 중인 리전에서 Amazon S3, Amazon Bedrock, Lambda 및 DynamoDB 리소스를 생성할 수 있는 권한이 본인에게 있는지 확인합니다.

이 흐름은 배포용이 아니라 Amazon Bedrock 리소스를 이해하기 위한 자습서용입니다. 다음 이미지는 AWS Management Console의 흐름을 시각적으로 표현한 것입니다.

![\[모기지 처리 흐름\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/images/cloudformation/mortgage-processing-flow.png)


이 흐름은 Amazon Bedrock [에이전트](agents.md), [프롬프트](prompt-management.md) 및 [Lambda 함수](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)를 결합하여 고객 재무 정보를 수집하고 고객이 대출을 받을 자격이 있는지 여부를 처리하는 모기지 처리 흐름을 생성합니다. Amazon Bedrock [지식 기반](knowledge-base.md)과 [가드레일](guardrails.md)도 흐름의 에이전트에 연결되어 응답을 강화하고 보호 기능을 제공합니다. 흐름의 구성 요소에 대한 자세한 내용은 [모기지 처리 흐름에 대한 세부 정보](getting-started-mortgage-flow-details.md) 섹션을 참조하세요.

**Topics**
+ [사전 조건](#getting-started-mortgage-flow-prereqs)
+ [를 사용하여 모기지 처리 흐름 생성 CloudFormation](#getting-started-mortgage-flow-create)
+ [모기지 처리 흐름 테스트](#getting-started-mortgage-flow-test)
+ [정리: 리소스 삭제](#getting-started-mortgage-flow-delete)
+ [CloudFormation 템플릿](getting-started-mortgage-flow-template.md)
+ [모기지 처리 흐름에 대한 세부 정보](getting-started-mortgage-flow-details.md)

## 사전 조건
<a name="getting-started-mortgage-flow-prereqs"></a>

이 흐름을 생성하려면 .zip 파일을 다운로드하고 지침에 따라 리소스와 템플릿을 설정하는 스크립트를 실행합니다.

**중요**  
생성한 Amazon 리소스는 삭제될 때까지 요금이 청구됩니다.

다음 사전 조건을 완료합니다.

1. [cloudformation-mortgage-flow-setup.zip](samples/cloudformation-mortgage-flow-setup.zip) 파일을 다운로드합니다.

1. 파일 압축을 풉니다. 콘텐츠에 대한 자세한 내용은 [CloudFormation 템플릿](getting-started-mortgage-flow-template.md)에서 확인할 수 있습니다.

1. 다음을 수행하여 Amazon Bedrock 파운데이션 모델에 대한 액세스를 요청합니다.

   1. Amazon Bedrock 콘솔을 사용할 권한이 있는 IAM 자격 증명 AWS Management Console 으로에 로그인합니다. 그 다음 Amazon Bedrock 콘솔([https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock))을 엽니다.

   1. 오른쪽 상단 모서리에서 리전을 확인하여 **미국 동부(버지니아 북부)** 리전에 있는지 확인합니다. 그렇지 않은 경우 리전을 전환합니다.

   1. 왼쪽 탐색 창 하단에서 **모델 액세스**를 선택합니다.

   1. **모델 액세스 수정**을 선택합니다.

   1. 다음 중 하나를 수행하세요.
      + 모든 모델에 대한 액세스를 요청하려면 **모든 모델 활성화**를 선택합니다. 다음으로 나타나는 페이지에서 모든 모델 옆의 확인란이 채워집니다.
      + 특정 모델에 대한 액세스를 요청하려면 **특정 모델 활성화**를 선택합니다. 다음으로 나타나는 페이지에서 다음과 같은 옵션을 찾을 수 있습니다.
        + 제공업체의 모든 모델에 대한 액세스를 요청하려면 해당 제공업체 이름 옆의 확인란을 선택합니다.
        + 한 모델에 대한 액세스를 요청하려면 해당 모델 이름 옆의 확인란을 선택합니다.

   1. 다음 자습서의 목적상 최소한 **Titan Embeddings G1 - Text** 및 **Claude 3 Haiku** 모델에 대한 액세스를 요청해야 합니다. 그리고 **다음**을 선택합니다.

   1. 액세스를 요청하려는 모델과 **약관**을 검토합니다. 준비가 되면 **제출**을 선택하여 액세스를 요청합니다.

## 를 사용하여 모기지 처리 흐름 생성 CloudFormation
<a name="getting-started-mortgage-flow-create"></a>

모기지 처리 흐름과 관련 리소스를 생성하기 위해 CloudFormation 템플릿을 생성하고 이를 사용하여 Amazon Bedrock 리소스가 포함된 스택을 생성합니다.

**중요**  
생성한 Amazon 리소스는 삭제될 때까지 요금이 청구됩니다.

### 리소스 및 CloudFormation 템플릿 파일 생성
<a name="getting-started-mortgage-flow-file"></a>

먼저 .zip 파일의 스크립트를 사용하여 리소스를 S3 버킷에 업로드하고 CloudFormation 템플릿을 생성합니다.

1. 터미널에서 다음 명령을 실행하여 리소스를 Amazon S3 버킷에 복사하고 `main-stack.yaml` 및 `main-stack.json` 파일을 버킷 이름 파라미터의 기본값인 S3 버킷 이름으로 채웁니다.

   ```
   bash deploy.sh
   ```
**참고**  
스크립트 사용 형식은 `bash deploy.sh <region> <bucket-name>`이며, 여기서 *<region>* 및 *<bucket-name>*은 선택적 인수입니다. 값을 제공하지 않으면 다음 기본값이 사용됩니다.  
*<region>* - AWS 자격 증명 설정에 지정된 기본 AWS 리전입니다.
*<bucket-name>* - 버킷의 이름은 *mortgage-flow-deployment-<AccountId>-<Region>*입니다. 여기서 *<AccountId>*는 AWS 계정 ID이고 *<Region>*은 사용자가 제공한 값 또는 AWS 자격 증명 설정에 지정된 기본 AWS 리전과 일치합니다.

1. 프롬프트를 확인합니다. 배포가 완료되면 다음 단계를 위한 완전한 `main-stack.yaml` 및 `main-stack.json` 템플릿이 있어야 합니다.

**참고**  
스크립트가 실패하면 다음을 수행하여 리소스를 수동으로 준비할 수 있습니다.  
Amazon S3 콘솔([https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/))에서 압축 해제된 `cloudformation-mortgage-flow-setup` 폴더의 *콘텐츠*(폴더 자체는 포함하지 않음)를 미국 동부(버지니아 북부)에 있는 S3 버킷에 업로드합니다.
`templates/json/main-stack-tmp.yaml` 또는 `templates/json/main-stack-tmp.json` 파일을 찾아 다음을 수행합니다.  
`Q01pS3BucketName` 파라미터의 `Default` 값을 *MortgageFlowBucket*에서 S3 버킷 이름으로 변경합니다.
파일 이름에서 `-tmp`를 제거하여 `templates/json/main-stack.yaml` 또는 `templates/json/main-stack.json`이 되도록 합니다.

### CloudFormation 콘솔을 사용하여 스택 생성
<a name="getting-started-mortgage-flow-stack"></a>

다음으로, 저장한 템플릿을 사용하여 CloudFormation 스택을 프로비저닝합니다.

1. [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) CloudFormation 콘솔을 엽니다. 오른쪽 상단 모서리에서 리전을 확인하여 **미국 동부(버지니아 북부)** 리전에 있는지 확인합니다. 그렇지 않은 경우 리전을 전환합니다.

1. **스택** 페이지의 **스택 생성** 메뉴에서 **새 리소스 사용(표준)**을 선택합니다.

1. 템플릿을 지정합니다.

   1. **사전 조건**에서 **기존 템플릿 선택**을 선택합니다.

   1. **템플릿 지정**에서 **템플릿 파일 업로드**를 선택합니다.

   1. **파일 선택**을 선택하고 `main-stack.yaml` 또는 `main-stack.json` 템플릿으로 이동한 후 해당 템플릿을 선택합니다.

   1. **다음**을 선택합니다.

1. 스택 세부 정보를 다음과 같이 지정합니다.

   1. **스택 이름** 필드에 스택의 이름을 입력합니다.

   1. **파라미터** 필드에서 기본값을 그대로 둡니다.
**참고**  
`Q01pS3BucketName` 값은 이 템플릿의 리소스를 업로드해 놓은 S3 버킷의 이름과 일치해야 합니다. 나머지 인수는 지식 기반 구성과 관련이 있습니다. 이 인수를 수정하는 경우 구성이 서로 호환되는지 확인하세요. 자세한 내용은 [지식 기반에 대해 생성된 벡터 저장소 사용의 사전 조건](knowledge-base-setup.md) 단원을 참조하십시오.

   1. **다음**을 선택합니다.

1. 스택 옵션을 구성합니다.

   1. **스택 실패 옵션**에서 **새로 생성된 모든 리소스 삭제**를 선택합니다.
**참고**  
이 옵션을 선택하면 스택 생성에 실패하더라도 삭제 정책에서 보존하도록 지정한 리소스에 대해서는 요금이 청구되지 않습니다. 자세한 내용은 *CloudFormation 사용자 안내서*의 [`DeletionPolicy` 속성](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html)을 참조하세요.

   1. **기능**에서 CloudFormation이 계정에 IAM 리소스를 생성할 수 있음을 승인하는 확인란을 선택합니다.

   1. **다음**을 선택합니다.

1. 스택 세부 정보를 검토하고 **Submit**. CloudFormation creates the stack을 선택합니다. 생성하는 데 몇 분 정도 걸립니다. 스택 생성이 완료되면 스택 세부 정보 페이지의 **리소스** 탭을 사용하여 계정에 프로비저닝된 리소스를 볼 수 있습니다.

1. 스택 생성이 완료되면 다음을 수행하여 지식 기반을 쿼리할 수 있도록 지식 기반의 데이터 소스를 동기화합니다.

   1. Amazon Bedrock 콘솔을 사용할 권한이 있는 IAM 자격 증명 AWS Management Console 으로에 로그인합니다. 그 다음 Amazon Bedrock 콘솔([https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock))을 엽니다.

   1. 왼쪽 탐색 창에서 **지식 기반**을 선택한 다음, `AWSDocsTutorial-MortgageKB`라는 이름으로 생성된 지식 기반을 선택합니다.

   1. **데이터 소스** 섹션에서 `AWSDocsTutorial-MortgageKB-DS`라는 이름으로 생성된 데이터 소스 옆의 확인란을 선택합니다.

   1. **동기화**를 선택합니다. 동기화가 완료되면 흐름을 테스트할 수 있습니다.

## 모기지 처리 흐름 테스트
<a name="getting-started-mortgage-flow-test"></a>

모기지 처리 흐름이 생성되면 Amazon Bedrock 콘솔을 사용하여 흐름을 검사, 테스트 및 수정할 수 있습니다. 흐름의 개별 리소스를 검사, 테스트 및 수정할 수도 있습니다.

**흐름을 테스트하는 방법**

1. Amazon Bedrock 콘솔을 사용할 권한이 있는 IAM 자격 증명 AWS Management Console 으로에 로그인합니다. 그 다음 Amazon Bedrock 콘솔([https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock))을 엽니다.

1. 왼쪽 탐색 창에서 **흐름**을 선택합니다. 오른쪽 상단 모서리에서 리전을 확인하여 **미국 동부(버지니아 북부)** 리전에 있는지 확인합니다. 그렇지 않은 경우 리전을 전환합니다.

1. **흐름** 섹션에서 CloudFormation 템플릿에서 생성된 흐름을 선택합니다. 선택한 흐름은 `AWSDocsTutorial-MortgageFlow`일 것입니다.

1. **흐름 빌더에서 편집**을 선택합니다. 흐름의 개별 노드를 끌어 흐름의 시각적 표현을 수정할 수 있습니다.

1. **테스트 흐름** 창의 텍스트 필드에 다음을 입력한 다음 **실행**을 선택합니다.

   ```
   {
       "income": 80000, 
       "totalDebt": 5000, 
       "loanTerm": 30, 
       "loanAmount": 600000, 
       "creditScore": 750, 
       "mlsId": "MLS-5678"
   }
   ```

   계산된 최대 적정 대출 금액보다 대출 금액이 많으므로 **incomeDebt** 프롬프트가 트리거되고 흐름이 거부서를 생성합니다. **추적 표시**를 선택하면 흐름에서 실행된 노드를 볼 수 있습니다.

1. 다시 **흐름 테스트** 창의 텍스트 필드에 다음을 입력한 후 **실행**을 선택합니다.

   ```
   {
       "income": 120000, 
       "totalDebt": 5000, 
       "loanTerm": 30, 
       "loanAmount": 200000, 
       "creditScore": 650, 
       "mlsId": "MLS-3456"
   }
   ```

   계산된 최대 저렴한 대출 금액보다 대출 금액이 적으므로 **processApplication** 프롬프트가 트리거되어 **mortgageProcessingAgent**로 전송됩니다. 이 프롬프트는 연결된 지식 기반을 조회하고 입력 값에 따라 고객이 대출을 받을 자격이 있는지 여부를 평가하는 응답을 생성합니다.

1. (선택 사항) JSON 객체의 필드에 다른 값을 사용하여 흐름을 실행해 보세요. `mlsId` 값은 다중 나열 서비스에 나열된 속성에 해당합니다. 다음을 수행하여 유효한 `mlsId` 값을 찾을 수 있습니다.

   1. 에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) DynamoDB 콘솔을 엽니다.

   1. 왼쪽 탐색 창에서 **테이블**을 선택합니다.

   1. **AWSDocsTutorial-PropertyListing**이라는 테이블을 선택합니다.

   1. **테이블 항목 탐색**을 선택합니다.

   1. 흐름 입력의 **mls\$1id** 열에 있는 값 중 하나를 사용할 수 있습니다.

또한의 **에이전트**, **지식 기반**, **가드레일** 및 **프롬프트 관리** 페이지로 이동하여 흐름에 사용되는 각 Amazon Bedrock 리소스를 독립적으로 검사 AWS Management Console 할 수 있습니다. 흐름에 대해 자세히 알아보고 구성 요소를 자세히 이해하려면 [모기지 처리 흐름에 대한 세부 정보](getting-started-mortgage-flow-details.md) 섹션을 참조하세요.

## 정리: 리소스 삭제
<a name="getting-started-mortgage-flow-delete"></a>

리소스를 탐색하고 다양한 Amazon Bedrock 리소스의 기능을 더 정확히 이해한 후에는 스택과 스택에 포함된 리소스를 삭제합니다.

**중요**  
생성한 Amazon 리소스는 삭제될 때까지 요금이 청구됩니다.

1. [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)을 엽니다.

1. 왼쪽 탐색 창에서 **스택**을 선택합니다.

1. 템플릿에서 생성한 스택을 선택합니다. **삭제**를 선택한 다음 **삭제**를 확인합니다.

   CloudFormation은 기본 스택, 모든 중첩 스택 및 스택에 포함된 모든 리소스의 삭제를 시작합니다.

# CloudFormation 템플릿
<a name="getting-started-mortgage-flow-template"></a>

다운로드하는 `cloudformation-mortgage-flow-setup.zip` 파일에는 다음 파일이 포함됩니다.
+ `deploy.sh` - 리소스를 배포하고 사용할 기본 CloudFormation 템플릿을 준비하는 쉘 스크립트.
+ `artifacts` - 에이전트 및 지식 기반 템플릿에 대한 함수가 있는 .zip 파일이 포함된 폴더:
  + 에이전트의 작업 그룹에 대한 Lambda 함수
    + `agent_loan_calculator.zip`
    + `mls_lookup.zip`
    + `loader_deployment_package.zip`
  + 지식 기반을 설정하기 위한 함수
    + `custom-resource-lambda.zip`
    + `opensearchpy-layer.zip`
    + `provider-event-handler.zip`
+ `api-schema` - 작업 그룹에 대한 API 스키마가 포함된 폴더.
+ `knowledge-base-data-source` - [Fannie Mae의 판매 안내서](https://selling-guide.fanniemae.com/) PDF가 포함된 폴더.
+ `templates` - 이 흐름의 리소스를 위한 템플릿(JSON 및 YAML 두 형식으로 제공)이 포함된 폴더.
  + `main-stack-tmp` - 나머지 템플릿을 중첩 스택으로 배포하는 기본 템플릿. 이 파일은 배포 스크립트가 실행된 후 `main-stack`으로 전환됩니다.
  + `guardrails-template` - 에이전트와 연결할 가드레일의 템플릿.
  + `prompts-template` - 흐름에 사용할 프롬프트의 템플릿.
  + `kb-role-template` - OpenSearch 템플릿과 지식 기반 템플릿 모두에서 사용할 지식 기반 역할의 템플릿.
  + `oss-infra-template` - 지식 기반에 사용할 Amazon OpenSearch Serverless 벡터 스토어의 템플릿.
  + `kb-infra-template` - 에이전트와 연결할 모기지 대출 지식 기반의 템플릿.
  + `agent-template` - 흐름에 사용할 모기지 처리 에이전트의 템플릿.
  + `mortgage-flow-template` - 모든 리소스를 결합하는 모기지 처리 흐름의 템플릿.
+ `README.md` - 템플릿 사용 단계를 설명하는 README 파일.

다음 주제에서는 각 스택에 사용되는 CloudFormation 템플릿을 보여줍니다. 기본 스택은 나머지 스택을 [중첩 스택](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html)으로 배포합니다.

**Topics**
+ [기본 스택](#getting-started-mortgage-templates-main)
+ [Amazon Bedrock Guardrails 스택](#getting-started-mortgage-guardrail-templates)
+ [Amazon Bedrock Prompt Management 스택](#getting-started-mortgage-prompts-templates)
+ [Amazon Bedrock Knowledge Bases 스택](#getting-started-mortgage-kb-templates)

## 기본 스택
<a name="getting-started-mortgage-templates-main"></a>

기본 스택은 템플릿을 업로드할 때 정의할 수 있는 파라미터를 정의합니다. 이러한 값은 나머지 중첩 스택 각각에 전달됩니다. 배포 스크립트는 `Q01pS3BucketName` 파라미터의 기본값에 대한 *MortgageFlowBucket*을 스크립트에서 배포한 리소스가 포함된 실제 S3 버킷으로 바꿉니다.

------
#### [ YAML ]

```
AWSTemplateFormatVersion: '2010-09-09'
Description: "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow"

Parameters:
  Q01pS3BucketName:
    Type: String
    Description: Provide existing S3 bucket name where data is already stored
    Default: MortgageFlowBucket
  Q02pFlowName:
    Type: String
    Description: Name for the flow
    Default: MortgageFlow
  Q03pGuardrailName:
    Type: String
    Description: Name for guardrail to attach to agent
    Default: MortgageGR
  Q04pKnowledgeBaseName:
    Type: String
    Description: Name for knowledge base to associate with agent
    Default: MortgageKB
  Q05pAgentName:
    Type: String
    Description: Name for agent to create
    Default: MortgageAgent
  Q06pKBEmbedModel:
    Type: String
    Description: Select Embedding model
    Default: amazon.titan-embed-text-v1
  Q07pKBChunkingStrategy:
    Type: String
    Description: Select Chunking strategy
    AllowedValues:
      - Default chunking
      - Fixed-size chunking
      - No chunking
    Default: Default chunking
  Q08pKBMaxTokens:
    Type: Number
    Description: Maximum number of tokens in a chunk
    Default: 300
  Q09pKBOverlapPercentage:
    Type: Number
    Description: Percent overlap in each chunk
    Default: 20
  Q10pKBVectorStore:
    Type: String
    Description: Select vector store
    AllowedValues:
    - Open-Search-Serverless
    Default: Open-Search-Serverless
  Q11pOSSCollectionName:
    Type: String
    Description: Name of the Collection
    MinLength: 1
    MaxLength: 63
    Default: mortgage-kb-collection
    AllowedPattern: ^[a-z0-9](-*[a-z0-9])*
    ConstraintDescription: Must be lowercase or numbers with a length of 1-32 characters
  Q12pOSSIndexName:
    Type: String
    Description: Index name to be created in vector store
    MinLength: 1
    MaxLength: 63
    Default: mortgage-kb-index
    AllowedPattern: ^[a-z0-9](-*[a-z0-9])*
    ConstraintDescription: Must be lowercase or numbers with a length of 1-63 characters
  # Q13pVectorFieldName:
  #   Type: String
  #   Description: Vector field name
  #   Default: bedrock-knowledge-base-default-vector
  # Q14pMetaDataFieldName:
  #   Type: String
  #   Description: Metadata field name
  #   Default: AMAZON_BEDROCK_METADATA
  # Q15pTextFieldName:
  #   Type: String
  #   Description: Text field name
  #   Default: AMAZON_BEDROCK_TEXT_CHUNK
Resources:
  KBRoleStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/kb-role-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        Q01pS3BucketName:
          Ref: Q01pS3BucketName
  OSSStack:
    Type: AWS::CloudFormation::Stack
    DependsOn: KBRoleStack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/oss-infra-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        Q01pS3BucketName:
          Ref: Q01pS3BucketName
        Q06pKBEmbedModel:
          Ref: Q06pKBEmbedModel
        Q11pOSSCollectionName:
          Ref: Q11pOSSCollectionName
        Q12pOSSIndexName:
          Ref: Q12pOSSIndexName
        pKBRole:
          Fn::GetAtt:
          - KBRoleStack
          - Outputs.KBRole
        pKBRoleArn:
          Fn::GetAtt:
          - KBRoleStack
          - Outputs.KBRoleArn
  KBStack:
    Type: AWS::CloudFormation::Stack
    DependsOn: OSSStack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/kb-infra-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        KnowledgeBaseName:
          Ref: Q04pKnowledgeBaseName
        Q01pS3BucketName:
          Ref: Q01pS3BucketName
        Q06pKBEmbedModel:
          Ref: Q06pKBEmbedModel
        Q07pKBChunkingStrategy:
          Ref: Q07pKBChunkingStrategy
        Q08pKBMaxTokens:
          Ref: Q08pKBMaxTokens
        Q09pKBOverlapPercentage:
          Ref: Q09pKBOverlapPercentage
        Q11pOSSCollectionName:
          Ref: Q11pOSSCollectionName
        Q12pOSSIndexName:
          Ref: Q12pOSSIndexName
        # Q13pVectorFieldName:
        #   Ref: Q13pVectorFieldName
        # Q14pMetaDataFieldName:
        #   Ref: Q14pMetaDataFieldName
        # Q15pTextFieldName:
        #   Ref: Q15pTextFieldName
        pCollectionArn:
          Fn::GetAtt:
          - OSSStack
          - Outputs.CollectionArn
        pKBRoleArn:
          Fn::GetAtt:
          - KBRoleStack
          - Outputs.KBRoleArn
        pKBRole:
          Fn::GetAtt:
          - KBRoleStack
          - Outputs.KBRole
  GRStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/guardrails-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        GuardrailName:
          Ref: Q03pGuardrailName
  AgentStack:
    Type: AWS::CloudFormation::Stack
    DependsOn: 
      - KBStack
      - GRStack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/agent-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        Q01pS3BucketName:
          Ref: Q01pS3BucketName
        KnowledgeBaseId:
          Fn::GetAtt:
          - KBStack
          - Outputs.KBId
        GuardrailArn:
          Fn::GetAtt:
          - GRStack
          - Outputs.GuardrailArn
        GuardrailVersion:
          Fn::GetAtt:
          - GRStack
          - Outputs.GuardrailVersion
  PromptsStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/prompts-template.yaml
      TimeoutInMinutes: 15
  FlowStack:
    Type: AWS::CloudFormation::Stack
    DependsOn: 
      - AgentStack
      - PromptsStack
    Properties:
      TemplateURL: !Sub https://${Q01pS3BucketName}.s3.amazonaws.com/templates/yaml/mortgage-flow-template.yaml
      TimeoutInMinutes: 15
      Parameters:
        FlowName:
          Ref: Q02pFlowName
        Q01pS3BucketName:
          Ref: Q01pS3BucketName
        ProcessApplicationPromptArn:
          Fn::GetAtt:
          - PromptsStack
          - Outputs.ProcessApplicationPromptArn
        RejectionPromptArn:
          Fn::GetAtt:
          - PromptsStack
          - Outputs.RejectionPromptArn
        AgentId:
          Fn::GetAtt:
          - AgentStack
          - Outputs.AgentId
```

------
#### [ JSON ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow",
  "Parameters": {
    "Q01pS3BucketName": {
      "Type": "String",
      "Description": "Provide existing S3 bucket name where data is already stored",
      "Default": "MortgageFlowBucket"
    },
    "Q02pFlowName": {
      "Type": "String",
      "Description": "Name for the flow",
      "Default": "MortgageFlow"
    },
    "Q03pGuardrailName": {
      "Type": "String",
      "Description": "Name for guardrail to attach to agent",
      "Default": "MortgageGR"
    },
    "Q04pKnowledgeBaseName": {
      "Type": "String",
      "Description": "Name for knowledge base to associate with agent",
      "Default": "MortgageKB"
    },
    "Q05pAgentName": {
      "Type": "String",
      "Description": "Name for agent to create",
      "Default": "MortgageAgent"
    },
    "Q06pKBEmbedModel": {
      "Type": "String",
      "Description": "Select Embedding model",
      "Default": "amazon.titan-embed-text-v1"
    },
    "Q07pKBChunkingStrategy": {
      "Type": "String",
      "Description": "Select Chunking strategy",
      "AllowedValues": [
        "Default chunking",
        "Fixed-size chunking",
        "No chunking"
      ],
      "Default": "Default chunking"
    },
    "Q08pKBMaxTokens": {
      "Type": "Number",
      "Description": "Maximum number of tokens in a chunk",
      "Default": 300
    },
    "Q09pKBOverlapPercentage": {
      "Type": "Number",
      "Description": "Percent overlap in each chunk",
      "Default": 20
    },
    "Q10pKBVectorStore": {
      "Type": "String",
      "Description": "Select vector store",
      "AllowedValues": [
        "Open-Search-Serverless"
      ],
      "Default": "Open-Search-Serverless"
    },
    "Q11pOSSCollectionName": {
      "Type": "String",
      "Description": "Name of the Collection",
      "MinLength": 1,
      "MaxLength": 63,
      "Default": "mortgage-kb-collection",
      "AllowedPattern": "^[a-z0-9](-*[a-z0-9])*",
      "ConstraintDescription": "Must be lowercase or numbers with a length of 1-32 characters"
    },
    "Q12pOSSIndexName": {
      "Type": "String",
      "Description": "Index name to be created in vector store",
      "MinLength": 1,
      "MaxLength": 63,
      "Default": "mortgage-kb-index",
      "AllowedPattern": "^[a-z0-9](-*[a-z0-9])*",
      "ConstraintDescription": "Must be lowercase or numbers with a length of 1-63 characters"
    }
  },
  "Resources": {
    "KBRoleStack": {
      "Type": "AWS::CloudFormation::Stack",
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/kb-role-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "Q01pS3BucketName": {
            "Ref": "Q01pS3BucketName"
          }
        }
      }
    },
    "OSSStack": {
      "Type": "AWS::CloudFormation::Stack",
      "DependsOn": "KBRoleStack",
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/oss-infra-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "Q01pS3BucketName": {
            "Ref": "Q01pS3BucketName"
          },
          "Q06pKBEmbedModel": {
            "Ref": "Q06pKBEmbedModel"
          },
          "Q11pOSSCollectionName": {
            "Ref": "Q11pOSSCollectionName"
          },
          "Q12pOSSIndexName": {
            "Ref": "Q12pOSSIndexName"
          },
          "pKBRole": {
            "Fn::GetAtt": [
              "KBRoleStack",
              "Outputs.KBRole"
            ]
          },
          "pKBRoleArn": {
            "Fn::GetAtt": [
              "KBRoleStack",
              "Outputs.KBRoleArn"
            ]
          }
        }
      }
    },
    "KBStack": {
      "Type": "AWS::CloudFormation::Stack",
      "DependsOn": "OSSStack",
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/kb-infra-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "KnowledgeBaseName": {
            "Ref": "Q04pKnowledgeBaseName"
          },
          "Q01pS3BucketName": {
            "Ref": "Q01pS3BucketName"
          },
          "Q06pKBEmbedModel": {
            "Ref": "Q06pKBEmbedModel"
          },
          "Q07pKBChunkingStrategy": {
            "Ref": "Q07pKBChunkingStrategy"
          },
          "Q08pKBMaxTokens": {
            "Ref": "Q08pKBMaxTokens"
          },
          "Q09pKBOverlapPercentage": {
            "Ref": "Q09pKBOverlapPercentage"
          },
          "Q11pOSSCollectionName": {
            "Ref": "Q11pOSSCollectionName"
          },
          "Q12pOSSIndexName": {
            "Ref": "Q12pOSSIndexName"
          },
          "pCollectionArn": {
            "Fn::GetAtt": [
              "OSSStack",
              "Outputs.CollectionArn"
            ]
          },
          "pKBRoleArn": {
            "Fn::GetAtt": [
              "KBRoleStack",
              "Outputs.KBRoleArn"
            ]
          },
          "pKBRole": {
            "Fn::GetAtt": [
              "KBRoleStack",
              "Outputs.KBRole"
            ]
          }
        }
      }
    },
    "GRStack": {
      "Type": "AWS::CloudFormation::Stack",
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/guardrails-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "GuardrailName": {
            "Ref": "Q03pGuardrailName"
          }
        }
      }
    },
    "AgentStack": {
      "Type": "AWS::CloudFormation::Stack",
      "DependsOn": [
        "KBStack",
        "GRStack"
      ],
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/agent-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "Q01pS3BucketName": {
            "Ref": "Q01pS3BucketName"
          },
          "KnowledgeBaseId": {
            "Fn::GetAtt": [
              "KBStack",
              "Outputs.KBId"
            ]
          },
          "GuardrailArn": {
            "Fn::GetAtt": [
              "GRStack",
              "Outputs.GuardrailArn"
            ]
          },
          "GuardrailVersion": {
            "Fn::GetAtt": [
              "GRStack",
              "Outputs.GuardrailVersion"
            ]
          }
        }
      }
    },
    "PromptsStack": {
      "Type": "AWS::CloudFormation::Stack",
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/prompts-template.json"
        },
        "TimeoutInMinutes": 15
      }
    },
    "FlowStack": {
      "Type": "AWS::CloudFormation::Stack",
      "DependsOn": [
        "AgentStack",
        "PromptsStack"
      ],
      "Properties": {
        "TemplateURL": {
          "Fn::Sub": "https://${Q01pS3BucketName}.s3.amazonaws.com/templates/json/mortgage-flow-template.json"
        },
        "TimeoutInMinutes": 15,
        "Parameters": {
          "FlowName": {
            "Ref": "Q02pFlowName"
          },
          "Q01pS3BucketName": {
            "Ref": "Q01pS3BucketName"
          },
          "ProcessApplicationPromptArn": {
            "Fn::GetAtt": [
              "PromptsStack",
              "Outputs.ProcessApplicationPromptArn"
            ]
          },
          "RejectionPromptArn": {
            "Fn::GetAtt": [
              "PromptsStack",
              "Outputs.RejectionPromptArn"
            ]
          },
          "AgentId": {
            "Fn::GetAtt": [
              "AgentStack",
              "Outputs.AgentId"
            ]
          }
        }
      }
    }
  }
}
```

------

## Amazon Bedrock Guardrails 스택
<a name="getting-started-mortgage-guardrail-templates"></a>

이 스택은 다음과 같은 [가드레일](guardrails.md) 관련 리소스를 생성합니다.
+ AgentGuardrail([AWS::Bedrock::Guardrail](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-guardrail.html)) - 콘텐츠 필터링, 주제 정책 및 PII 보호를 제공하는 가드레일. 이 가드레일은 에이전트 스택의 에이전트에 연결됩니다.
+ AgentGuardrailVersion([AWS::Bedrock::GuardrailVersion](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-guardrailversion.html)) - 에이전트에 적용된 `AgentGuardrail` 리소스의 버전.

------
#### [ YAML ]

```
AWSTemplateFormatVersion: "2010-09-09"
Description: "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow"

Parameters:
  GuardrailName:
    Type: String
    Description: Name for guardrail
    Default: MortgageGuardrail

Resources:
  AgentGuardrail:
    Type: AWS::Bedrock::Guardrail
    Properties:
      Name: !Sub AWSDocsTutorial-${GuardrailName}
      Description: Guardrail for mortgage processing with investment advice blocking, content filtering, and PII protection
      BlockedInputMessaging: "Sorry, the model cannot answer this question."
      BlockedOutputsMessaging: "Sorry, the model cannot answer this question."
      TopicPolicyConfig:
        TopicsConfig:
          - Name: InvestmentAdvice
            Definition: "Investment advice refers to inquires, guidance or recommendations regarding the management or allocation of fund or asset with the goal of generating returns or achieving specific financial objectives"
            Examples:
              - "Is investing in the stocks better than bonds?"
              - "Should I invest in gold?"
            Type: DENY
      ContentPolicyConfig:
        FiltersConfig:
          - Type: VIOLENCE
            InputStrength: HIGH
            OutputStrength: HIGH
          - Type: PROMPT_ATTACK
            InputStrength: HIGH
            OutputStrength: NONE
          - Type: MISCONDUCT
            InputStrength: HIGH
            OutputStrength: HIGH
          - Type: HATE
            InputStrength: HIGH
            OutputStrength: HIGH
          - Type: SEXUAL
            InputStrength: HIGH
            OutputStrength: HIGH
          - Type: INSULTS
            InputStrength: HIGH
            OutputStrength: HIGH
      WordPolicyConfig:
        WordsConfig:
          - Text: "crypto currency"
          - Text: "bitcoin"
        ManagedWordListsConfig:
          - Type: PROFANITY
      SensitiveInformationPolicyConfig:
        PiiEntitiesConfig:
          - Type: EMAIL
            Action: ANONYMIZE
          - Type: CREDIT_DEBIT_CARD_NUMBER
            Action: BLOCK
      ContextualGroundingPolicyConfig:
        FiltersConfig:
          - Type: GROUNDING
            Threshold: 0.85
          - Type: RELEVANCE
            Threshold: 0.5
            
  AgentGuardrailVersion:
    Type: AWS::Bedrock::GuardrailVersion
    Properties:
      GuardrailIdentifier: !Ref AgentGuardrail
      Description: Version 1 of the mortgage agent guardrail

Outputs:
  GuardrailArn:
    Value:
      Ref: AgentGuardrail
    Description: ARN of guardrail to associate with agent
  GuardrailVersion:
    Value:
      Fn::GetAtt:
      - AgentGuardrailVersion
      - Version
    Description: Version of guardrail to associate with agent
```

------
#### [ JSON ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow",
  "Parameters": {
    "GuardrailName": {
      "Type": "String",
      "Description": "Name for guardrail",
      "Default": "MortgageGuardrail"
    }
  },
  "Resources": {
    "AgentGuardrail": {
      "Type": "AWS::Bedrock::Guardrail",
      "Properties": {
        "Name": {
          "Fn::Sub": "AWSDocsTutorial-${GuardrailName}"
        },
        "Description": "Guardrail for mortgage processing with investment advice blocking, content filtering, and PII protection",
        "BlockedInputMessaging": "Sorry, the model cannot answer this question.",
        "BlockedOutputsMessaging": "Sorry, the model cannot answer this question.",
        "TopicPolicyConfig": {
          "TopicsConfig": [
            {
              "Name": "InvestmentAdvice",
              "Definition": "Investment advice refers to inquires, guidance or recommendations regarding the management or allocation of fund or asset with the goal of generating returns or achieving specific financial objectives",
              "Examples": [
                "Is investing in the stocks better than bonds?",
                "Should I invest in gold?"
              ],
              "Type": "DENY"
            }
          ]
        },
        "ContentPolicyConfig": {
          "FiltersConfig": [
            {
              "Type": "VIOLENCE",
              "InputStrength": "HIGH",
              "OutputStrength": "HIGH"
            },
            {
              "Type": "PROMPT_ATTACK",
              "InputStrength": "HIGH",
              "OutputStrength": "NONE"
            },
            {
              "Type": "MISCONDUCT",
              "InputStrength": "HIGH",
              "OutputStrength": "HIGH"
            },
            {
              "Type": "HATE",
              "InputStrength": "HIGH",
              "OutputStrength": "HIGH"
            },
            {
              "Type": "SEXUAL",
              "InputStrength": "HIGH",
              "OutputStrength": "HIGH"
            },
            {
              "Type": "INSULTS",
              "InputStrength": "HIGH",
              "OutputStrength": "HIGH"
            }
          ]
        },
        "WordPolicyConfig": {
          "WordsConfig": [
            {
              "Text": "crypto currency"
            },
            {
              "Text": "bitcoin"
            }
          ],
          "ManagedWordListsConfig": [
            {
              "Type": "PROFANITY"
            }
          ]
        },
        "SensitiveInformationPolicyConfig": {
          "PiiEntitiesConfig": [
            {
              "Type": "EMAIL",
              "Action": "ANONYMIZE"
            },
            {
              "Type": "CREDIT_DEBIT_CARD_NUMBER",
              "Action": "BLOCK"
            }
          ]
        },
        "ContextualGroundingPolicyConfig": {
          "FiltersConfig": [
            {
              "Type": "GROUNDING",
              "Threshold": 0.85
            },
            {
              "Type": "RELEVANCE",
              "Threshold": 0.5
            }
          ]
        }
      }
    },
    "AgentGuardrailVersion": {
      "Type": "AWS::Bedrock::GuardrailVersion",
      "Properties": {
        "GuardrailIdentifier": {
          "Ref": "AgentGuardrail"
        },
        "Description": "Version 1 of the mortgage agent guardrail"
      }
    }
  },
  "Outputs": {
    "GuardrailArn": {
      "Value": {
        "Ref": "AgentGuardrail"
      },
      "Description": "ARN of guardrail to associate with agent"
    },
    "GuardrailVersion": {
      "Value": {
        "Fn::GetAtt": [
          "AgentGuardrailVersion",
          "Version"
        ]
      },
      "Description": "Version of guardrail to associate with agent"
    }
  }
}
```

------

## Amazon Bedrock Prompt Management 스택
<a name="getting-started-mortgage-prompts-templates"></a>

이 스택은 흐름에 추가되는 다음 [프롬프트](prompt-management.md)([AWS::IAM::Prompt](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                     /aws-resource-bedrock-prompt.html)) 리소스를 생성합니다.
+ RejectionPrompt - 금융 정보를 기반으로 생성된 거부 서신을 반환하는 프롬프트.
+ ProcessApplicationPrompt - 에이전트에게 고객의 금융 정보를 보내고 고객이 대출을 받을 자격이 있는지 평가하라는 메시지를 보내는 프롬프트.

------
#### [ YAML ]

```
AWSTemplateFormatVersion: "2010-09-09"
Description: "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow"

Resources:
  RejectionPrompt:
    Type: AWS::Bedrock::Prompt
    Properties:
      Name: !Sub AWSDocsTutorial-RejectionPrompt
      Description: "Use this prompt to generate a rejection letter triggered by an unsatisfactory income to debt ratio"
      DefaultVariant: variantOne
      Variants:
        - Name: variantOne
          TemplateType: TEXT
          ModelId: anthropic.claude-3-haiku-20240307-v1:0
          TemplateConfiguration:
            Text:
              Text: |
                Write a mortgage loan rejection letter for a candiate with income {{income}}, totalDebt {{totalDebt}}, loanAmount {{loanAmount}}. 
                The reason for rejection is their income to debt ratio. 
                Do not mention any other reason. 
                Make the letter as concise as possible. 
                Treat all numeric inputs as whole numbers.
                Let the general structure be like the below:

                Dear [Applicant's Name],
                We appreciate your interest in obtaining a mortgage loan with our institution...
                The primary reason for this decision is that ...
                While we understand that this news may be disappointing, ...
                Thank you again for your interest, and we wish you the best in your future endeavors...

                Sincerely,
                [Your Institution's Name]
              InputVariables:
                - Name: income
                - Name: totalDebt
                - Name: loanAmount
          InferenceConfiguration:
            Text:
              MaxTokens: 2000
              Temperature: 0.0
              TopP: 0.999
              StopSequences:
                - "\n\nHuman:"
          AdditionalModelRequestFields:
            top_k: 250

  ProcessApplicationPrompt:
    Type: AWS::Bedrock::Prompt
    Properties:
      Name: !Sub AWSDocsTutorial-ProcessApplicationPrompt
      Description: "Use this prompt to generate a question for an agent to process the mortgage application"
      DefaultVariant: variantOne
      Variants:
        - Name: variantOne
          TemplateType: TEXT
          ModelId: anthropic.claude-3-haiku-20240307-v1:0
          TemplateConfiguration:
            Text:
              Text: |
                Generate a question asking if the user will qualify for a loan for the specified criteria. 

                Include instruction to base the answer on key features of the property retrieved from MLS listing. 

                Start with "will an applicant...".

                { "income": {{income}}, "creditScore": {{creditScore}}, "totalDebt": {{totalDebt}}, "loanAmount": {{loanAmount}}, "mlsId": {{mlsId}} }

                Include a second question on loan requirements an applicant with the below attributes should consider for a Fannie Mae backed loan (other than debt to income).
              InputVariables:
                - Name: income
                - Name: creditScore
                - Name: totalDebt
                - Name: loanAmount
                - Name: mlsId
          InferenceConfiguration:
            Text:
              MaxTokens: 2000
              Temperature: 0.0
              TopP: 0.999
              StopSequences:
                - "\n\nHuman:"
          AdditionalModelRequestFields:
            top_k: 250

Outputs:
  ProcessApplicationPromptArn:
    Value:
      Ref: ProcessApplicationPrompt
    Description: ARN of the prompt to process a mortgage application
  RejectionPromptArn:
    Value:
      Ref: RejectionPrompt
    Description: ARN of the prompt to reject a mortgage application
```

------
#### [ JSON ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow",
  "Resources": {
    "RejectionPrompt": {
      "Type": "AWS::Bedrock::Prompt",
      "Properties": {
        "Name": {
          "Fn::Sub": "AWSDocsTutorial-RejectionPrompt"
        },
        "Description": "Use this prompt to generate a rejection letter triggered by an unsatisfactory income to debt ratio",
        "DefaultVariant": "variantOne",
        "Variants": [
          {
            "Name": "variantOne",
            "TemplateType": "TEXT",
            "ModelId": "anthropic.claude-3-haiku-20240307-v1:0",
            "TemplateConfiguration": {
              "Text": {
                "Text": "Write a mortgage loan rejection letter for a candiate with income {{income}}, totalDebt {{totalDebt}}, loanAmount {{loanAmount}}. \nThe reason for rejection is their income to debt ratio. \nDo not mention any other reason. \nMake the letter as concise as possible. \nTreat all numeric inputs as whole numbers.\nLet the general structure be like the below:\n\nDear [Applicant's Name],\nWe appreciate your interest in obtaining a mortgage loan with our institution...\nThe primary reason for this decision is that ...\nWhile we understand that this news may be disappointing, ...\nThank you again for your interest, and we wish you the best in your future endeavors...\n\nSincerely,\n[Your Institution's Name]\n",
                "InputVariables": [
                  {
                    "Name": "income"
                  },
                  {
                    "Name": "totalDebt"
                  },
                  {
                    "Name": "loanAmount"
                  }
                ]
              }
            },
            "InferenceConfiguration": {
              "Text": {
                "MaxTokens": 2000,
                "Temperature": 0.0,
                "TopP": 0.999,
                "StopSequences": [
                  "\n\nHuman:"
                ]
              }
            },
            "AdditionalModelRequestFields": {
              "top_k": 250
            }
          }
        ]
      }
    },
    "ProcessApplicationPrompt": {
      "Type": "AWS::Bedrock::Prompt",
      "Properties": {
        "Name": {
          "Fn::Sub": "AWSDocsTutorial-ProcessApplicationPrompt"
        },
        "Description": "Use this prompt to generate a question for an agent to process the mortgage application",
        "DefaultVariant": "variantOne",
        "Variants": [
          {
            "Name": "variantOne",
            "TemplateType": "TEXT",
            "ModelId": "anthropic.claude-3-haiku-20240307-v1:0",
            "TemplateConfiguration": {
              "Text": {
                "Text": "Generate a question asking if the user will qualify for a loan for the specified criteria. \n\nInclude instruction to base the answer on key features of the property retrieved from MLS listing. \n\nStart with \"will an applicant...\".\n\n{ \"income\": {{income}}, \"creditScore\": {{creditScore}}, \"totalDebt\": {{totalDebt}}, \"loanAmount\": {{loanAmount}}, \"mlsId\": {{mlsId}} }\n\nInclude a second question on loan requirements an applicant with the below attributes should consider for a Fannie Mae backed loan (other than debt to income).\n",
                "InputVariables": [
                  {
                    "Name": "income"
                  },
                  {
                    "Name": "creditScore"
                  },
                  {
                    "Name": "totalDebt"
                  },
                  {
                    "Name": "loanAmount"
                  },
                  {
                    "Name": "mlsId"
                  }
                ]
              }
            },
            "InferenceConfiguration": {
              "Text": {
                "MaxTokens": 2000,
                "Temperature": 0.0,
                "TopP": 0.999,
                "StopSequences": [
                  "\n\nHuman:"
                ]
              }
            },
            "AdditionalModelRequestFields": {
              "top_k": 250
            }
          }
        ]
      }
    }
  },
  "Outputs": {
    "ProcessApplicationPromptArn": {
      "Value": {
        "Ref": "ProcessApplicationPrompt"
      },
      "Description": "ARN of the prompt to process a mortgage application"
    },
    "RejectionPromptArn": {
      "Value": {
        "Ref": "RejectionPrompt"
      },
      "Description": "ARN of the prompt to reject a mortgage application"
    }
  }
}
```

------

## Amazon Bedrock Knowledge Bases 스택
<a name="getting-started-mortgage-kb-templates"></a>

이 템플릿은 대출 지침이 포함된 [지식 기반](knowledge-base.md)과 해당 데이터 소스를 생성합니다.
+ KnowledgeBase([AWS::Bedrock::KnowledgeBase](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-knowledgebase.html))
+ KnowledgeBaseDataSource([AWS::Bedrock::DataSource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-datasource.html))

------
#### [ YAML ]

```
AWSTemplateFormatVersion: '2010-09-09'
Description: "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow"
Parameters:
  KnowledgeBaseName:
    Type: String
    Description: Name of knowledge base
    Default: MortgageKB
  Q01pS3BucketName:
    Type: String
    Description: Name of S3 bucket where knowledge base data is stored
  Q06pKBEmbedModel:
    Type: String
    Description: Selected Embedding model
  Q07pKBChunkingStrategy:
    Type: String
    Description: Selected Chunking strategy
  Q08pKBMaxTokens:
    Type: Number
    Description: Maximum number of tokens in a chunk
  Q09pKBOverlapPercentage:
    Type: Number
    Description: Percent overlap in each chunk
  Q11pOSSCollectionName:
    Type: String
    Description: Name of the Collection
  Q12pOSSIndexName:
    Type: String
    Description: Index name to be created in vector store
  Q13pVectorFieldName:
    Type: String
    Description: Vector field name
    Default: bedrock-knowledge-base-default-vector
  Q14pMetaDataFieldName:
    Type: String
    Description: Metadata field name
    Default: AMAZON_BEDROCK_METADATA
  Q15pTextFieldName:
    Type: String
    Description: Text field name
    Default: AMAZON_BEDROCK_TEXT_CHUNK
  pCollectionArn:
    Type: String
    Description: Name of the Collection Arn
  pKBRole:
    Type: String
    Description: KB role for e2e RAG
  pKBRoleArn:
    Type: String
    Description: KB role Arn for e2e RAG
Conditions:
  IsChunkingStrategyFixed:
    Fn::Equals:
      - Ref: Q07pKBChunkingStrategy
      - Fixed-size chunking
  IsChunkingStrategyDefault:
    Fn::Equals:
      - Ref: Q07pKBChunkingStrategy
      - Default chunking
  IsChunkingStrategyNoChunking:
    Fn::Equals:
      - Ref: Q07pKBChunkingStrategy
      - No chunking
  IsChunkingStrategyFixedOrDefault:
    Fn::Or:
      - Condition: IsChunkingStrategyFixed
      - Condition: IsChunkingStrategyDefault
Resources:
  KnowledgeBase:
    Type: AWS::Bedrock::KnowledgeBase
    Properties:
      Description: Test KB Deployment
      KnowledgeBaseConfiguration:
        Type: VECTOR
        VectorKnowledgeBaseConfiguration:
          EmbeddingModelArn:
            Fn::Sub: arn:aws:bedrock:${AWS::Region}::foundation-model/${Q06pKBEmbedModel}
      Name: !Sub AWSDocsTutorial-${KnowledgeBaseName}
      RoleArn:
        Ref: pKBRoleArn
      StorageConfiguration:
        OpensearchServerlessConfiguration:
          CollectionArn:
            Ref: pCollectionArn
          FieldMapping:
            MetadataField:
              Ref: Q14pMetaDataFieldName
            TextField:
              Ref: Q15pTextFieldName
            VectorField:
              Ref: Q13pVectorFieldName
          VectorIndexName:
            Ref: Q12pOSSIndexName
        Type: OPENSEARCH_SERVERLESS

  KnowledgeBaseDataSource:
    Type: AWS::Bedrock::DataSource
    DependsOn:
    - KnowledgeBase
    Properties:
      DataSourceConfiguration:
        Type: S3
        S3Configuration:
          BucketArn:
            Fn::Sub: arn:aws:s3:::${Q01pS3BucketName}
          InclusionPrefixes:
            - knowledge-base-data-source/
      Description: Knowledge base data source
      KnowledgeBaseId:
        Ref: KnowledgeBase
      Name: !Sub AWSDocsTutorial-${KnowledgeBaseName}-DS
      VectorIngestionConfiguration:
        ChunkingConfiguration:
          Fn::If:
            - IsChunkingStrategyFixed
            - ChunkingStrategy: FIXED_SIZE
              FixedSizeChunkingConfiguration:
                MaxTokens: !Ref Q08pKBMaxTokens
                OverlapPercentage: !Ref Q09pKBOverlapPercentage
            - Fn::If:
                - IsChunkingStrategyDefault
                - ChunkingStrategy: FIXED_SIZE
                  FixedSizeChunkingConfiguration:
                    MaxTokens: 300
                    OverlapPercentage: 20
                - Fn::If:
                    - IsChunkingStrategyNoChunking
                    - ChunkingStrategy: NONE
                    - !Ref AWS::NoValue
Outputs:
  KBId:
    Value:
      Ref: KnowledgeBase
    Description: KnowledgeBase ID
  DS:
    Value:
      Ref: KnowledgeBaseDataSource
    Description: KnowledgeBase Datasource
```

------
#### [ JSON ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "[AWSDocs] AmazonBedrockDocs: getting-started-mortgage-flow",
  "Parameters": {
    "KnowledgeBaseName": {
      "Type": "String",
      "Description": "Name of knowledge base",
      "Default": "MortgageKB"
    },
    "Q01pS3BucketName": {
      "Type": "String",
      "Description": "Name of S3 bucket where knowledge base data is stored"
    },
    "Q06pKBEmbedModel": {
      "Type": "String",
      "Description": "Selected Embedding model"
    },
    "Q07pKBChunkingStrategy": {
      "Type": "String",
      "Description": "Selected Chunking strategy"
    },
    "Q08pKBMaxTokens": {
      "Type": "Number",
      "Description": "Maximum number of tokens in a chunk"
    },
    "Q09pKBOverlapPercentage": {
      "Type": "Number",
      "Description": "Percent overlap in each chunk"
    },
    "Q11pOSSCollectionName": {
      "Type": "String",
      "Description": "Name of the Collection"
    },
    "Q12pOSSIndexName": {
      "Type": "String",
      "Description": "Index name to be created in vector store"
    },
    "Q13pVectorFieldName": {
      "Type": "String",
      "Description": "Vector field name",
      "Default": "bedrock-knowledge-base-default-vector"
    },
    "Q14pMetaDataFieldName": {
      "Type": "String",
      "Description": "Metadata field name",
      "Default": "AMAZON_BEDROCK_METADATA"
    },
    "Q15pTextFieldName": {
      "Type": "String",
      "Description": "Text field name",
      "Default": "AMAZON_BEDROCK_TEXT_CHUNK"
    },
    "pCollectionArn": {
      "Type": "String",
      "Description": "Name of the Collection Arn"
    },
    "pKBRole": {
      "Type": "String",
      "Description": "KB role for e2e RAG"
    },
    "pKBRoleArn": {
      "Type": "String",
      "Description": "KB role Arn for e2e RAG"
    }
  },
  "Conditions": {
    "IsChunkingStrategyFixed": {
      "Fn::Equals": [
        {
          "Ref": "Q07pKBChunkingStrategy"
        },
        "Fixed-size chunking"
      ]
    },
    "IsChunkingStrategyDefault": {
      "Fn::Equals": [
        {
          "Ref": "Q07pKBChunkingStrategy"
        },
        "Default chunking"
      ]
    },
    "IsChunkingStrategyNoChunking": {
      "Fn::Equals": [
        {
          "Ref": "Q07pKBChunkingStrategy"
        },
        "No chunking"
      ]
    },
    "IsChunkingStrategyFixedOrDefault": {
      "Fn::Or": [
        {
          "Condition": "IsChunkingStrategyFixed"
        },
        {
          "Condition": "IsChunkingStrategyDefault"
        }
      ]
    }
  },
  "Resources": {
    "KnowledgeBase": {
      "Type": "AWS::Bedrock::KnowledgeBase",
      "Properties": {
        "Description": "Test KB Deployment",
        "KnowledgeBaseConfiguration": {
          "Type": "VECTOR",
          "VectorKnowledgeBaseConfiguration": {
            "EmbeddingModelArn": {
              "Fn::Sub": "arn:aws:bedrock:${AWS::Region}::foundation-model/${Q06pKBEmbedModel}"
            }
          }
        },
        "Name": {
          "Fn::Sub": "AWSDocsTutorial-${KnowledgeBaseName}"
        },
        "RoleArn": {
          "Ref": "pKBRoleArn"
        },
        "StorageConfiguration": {
          "OpensearchServerlessConfiguration": {
            "CollectionArn": {
              "Ref": "pCollectionArn"
            },
            "FieldMapping": {
              "MetadataField": {
                "Ref": "Q14pMetaDataFieldName"
              },
              "TextField": {
                "Ref": "Q15pTextFieldName"
              },
              "VectorField": {
                "Ref": "Q13pVectorFieldName"
              }
            },
            "VectorIndexName": {
              "Ref": "Q12pOSSIndexName"
            }
          },
          "Type": "OPENSEARCH_SERVERLESS"
        }
      }
    },
    "KnowledgeBaseDataSource": {
      "Type": "AWS::Bedrock::DataSource",
      "DependsOn": [
        "KnowledgeBase"
      ],
      "Properties": {
        "DataSourceConfiguration": {
          "Type": "S3",
          "S3Configuration": {
            "BucketArn": {
              "Fn::Sub": "arn:aws:s3:::${Q01pS3BucketName}"
            },
            "InclusionPrefixes": [
              "knowledge-base-data-source/"
            ]
          }
        },
        "Description": "Knowledge base data source",
        "KnowledgeBaseId": {
          "Ref": "KnowledgeBase"
        },
        "Name": {
          "Fn::Sub": "AWSDocsTutorial-${KnowledgeBaseName}-DS"
        },
        "VectorIngestionConfiguration": {
          "ChunkingConfiguration": {
            "Fn::If": [
              "IsChunkingStrategyFixed",
              {
                "ChunkingStrategy": "FIXED_SIZE",
                "FixedSizeChunkingConfiguration": {
                  "MaxTokens": {
                    "Ref": "Q08pKBMaxTokens"
                  },
                  "OverlapPercentage": {
                    "Ref": "Q09pKBOverlapPercentage"
                  }
                }
              },
              {
                "Fn::If": [
                  "IsChunkingStrategyDefault",
                  {
                    "ChunkingStrategy": "FIXED_SIZE",
                    "FixedSizeChunkingConfiguration": {
                      "MaxTokens": 300,
                      "OverlapPercentage": 20
                    }
                  },
                  {
                    "Fn::If": [
                      "IsChunkingStrategyNoChunking",
                      {
                        "ChunkingStrategy": "NONE"
                      },
                      {
                        "Ref": "AWS::NoValue"
                      }
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }
  },
  "Outputs": {
    "KBId": {
      "Value": {
        "Ref": "KnowledgeBase"
      },
      "Description": "KnowledgeBase ID"
    },
    "DS": {
      "Value": {
        "Ref": "KnowledgeBaseDataSource"
      },
      "Description": "KnowledgeBase Datasource"
    }
  }
}
```

------

# 모기지 처리 흐름에 대한 세부 정보
<a name="getting-started-mortgage-flow-details"></a>

에서 모기지 처리 흐름의 시각적 표현 AWS Management Console 은 다음과 같습니다.

![\[모기지 처리 흐름\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/images/cloudformation/mortgage-processing-flow.png)


## 흐름의 단계
<a name="getting-started-mortgage-flow-steps"></a>

흐름에서 다음 단계가 수행됩니다.

1. 입력에서 얻은 고객의 재무 정보는 `loanCalculator` Lambda 함수로 전송되며, Lambda 함수는 고객에게 맞는 최대 저렴한 대출을 계산합니다.

1. `loanCalculator` 함수(`maximumAffordableLoan`)의 출력과 입력의 `loanAmount` 값은 조건 노드로 전송되며, 조건 노드는 다음과 같이 평가됩니다.
   + `loanAmount`가 `maximumAffordableLoan`보다 크면 `incomeDebt` 프롬프트가 트리거되고 대출에 대한 거부서가 생성됩니다.
   + 그렇지 않으면 `processApplication` 프롬프트를 통해 고객의 재무 정보가 `mortgageProcessingAgent`로 전송됩니다. 에이전트는 대출 계산기 함수와 다중 목록 서비스(MLS) 조회 함수를 적용하여 DynamoDB 테이블을 조회하고 입력에 지정된 MLS 속성과 관련된 고객 정보를 평가합니다. 또한 에이전트는 Fannie Mae 판매 안내서가 포함된 지식 기반에서 정보를 조회합니다. 에이전트는 이 모든 정보를 사용하여 요청된 대출 금액에 대한 고객의 자격을 분석하는 응답을 생성합니다.