

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# チュートリアル: 住宅ローン申請を処理するフローを作成する
<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 マネジメントコンソールのフローの視覚的表現です。

![\[住宅ローン処理フロー\]](http://docs.aws.amazon.com/ja_jp/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 ID AWS マネジメントコンソール を使用して にサインインします。Amazon Bedrock コンソール ([https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock)) を開きます。

   1. 右上隅にあるリージョンを確認して、**米国東部 (バージニア北部)** リージョンにいることを確かめます。そうでない場合は、リージョンを切り替えます。

   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` のテンプレートが完成します。

**注記**  
スクリプトが失敗した場合、以下を実行してリソースを手動で準備できます。  
解凍した `cloudformation-mortgage-flow-setup` フォルダの*中身* (フォルダ自体は含めないでください) を、[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/) 内の Amazon S3 コンソールの米国東部 (バージニア北部) の S3 バケットにアップロードします。
`templates/json/main-stack-tmp.yaml` ファイルまたは `templates/json/main-stack-tmp.json` ファイルを見つけて、以下を実行します。  
`Q01pS3BucketName` パラメータの `Default` 値を *MortgageFlowBucket* から S3 バケット名に変更します。
`templates/json/main-stack.yaml` または `templates/json/main-stack.json` になるように、ファイル名から `-tmp` を削除します。

### 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. **[Next]** (次へ) を選択します。

1. スタックオプションを設定します。

   1. **[スタック障害オプション]** で、**[新しく作成されたリソースをすべて削除]** を選択します。
**注記**  
このオプションを選択すると、スタックの作成に失敗した場合でも削除ポリシーで保持するように指定されているリソースに対して、課金される可能性を防ぐことができます。詳細については、「*CloudFormation ユーザーガイド*」の「[`DeletionPolicy` 属性](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html)」を参照してください。

   1. **[機能]** では、チェックボックスをオンにして、CloudFormation によってアカウントに IAM リソースが作成される場合があることを承認します。

   1. [**次へ**] を選択します。

1. スタックの詳細を確認し、**Submit**. CloudFormation creates を選択します。作成には数分かかります。スタックの作成が完了したら、スタックの詳細ページの **[リソース]** タブを使用して、アカウントにプロビジョニングされたリソースを表示できます。

1. スタックの作成が完了したら、以下を実行してナレッジベースのデータソースを同期し、ナレッジベースをクエリできるようにします。

   1. Amazon Bedrock コンソールを使用するアクセス許可を持つ IAM ID AWS マネジメントコンソール を使用して にサインインします。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 ID AWS マネジメントコンソール を使用して にサインインします。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` 値は、Multiple Listing Service にリストされているプロパティに対応しています。有効な `mlsId` 値を見つけるには、以下を実行します。

   1. にサインイン AWS マネジメントコンソール し、[https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) で DynamoDB コンソールを開きます。

   1. 左側のナビゲーションペインで、**[テーブル]** を選択します。

   1. **AWSDocsTutorial-PropertyListing** というテーブルを選択します。

   1. **[テーブルアイテムの探索]** を選択します。

   1. フロー入力では **mls\$1id** 列の任意の値を使用できます。

の **エージェント**、**ナレッジベース**、**ガードレール**、**プロンプト管理**ページに移動 AWS マネジメントコンソール して、フローで使用される各 Amazon Bedrock リソースを個別に調べることもできます。フローとコンポーネントの詳細については、「[住宅ローン処理フローの詳細](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 ガードレールのスタック](#getting-started-mortgage-guardrail-templates)
+ [Amazon Bedrock Prompt Management スタック](#getting-started-mortgage-prompts-templates)
+ [Amazon Bedrock ナレッジベースのスタック](#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 ガードレールのスタック
<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 ナレッジベースのスタック
<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 マネジメントコンソール は次のとおりです。

![\[住宅ローン処理フロー\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/images/cloudformation/mortgage-processing-flow.png)


## フローのステップ
<a name="getting-started-mortgage-flow-steps"></a>

このフローでは、次のステップが実行されます。

1. 入力された顧客の財務情報は `loanCalculator` Lambda 関数に送信され、関数は、顧客が返済可能な最大ローン額を計算します。

1. `loanCalculator` 関数 (`maximumAffordableLoan`) からの出力と入力からの `loanAmount` 値が条件ノードに送信され、以下のとおり評価されます。
   + `loanAmount` が `maximumAffordableLoan` より大きい場合、`incomeDebt` プロンプトがトリガーされ、ローンの却下通知が生成されます。
   + それ以外の場合、顧客の財務情報は `processApplication` プロンプトによって `mortgageProcessingAgent` に送信されます。エージェントは、ローン計算関数と Multiple Listing Service (MLS) 検索関数を適用して、DynamoDB テーブルを検索し、入力で指定された MLS 物件に基づいて顧客の情報を評価します。さらにエージェントは、Fannie Mae 販売ガイドなどのナレッジベースで情報を検索します。エージェントは、これらのすべての情報を利用して、リクエストされたローン金額に対する顧客の適格性を分析するレスポンスを生成します。