

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Tutorial: Erstellen eines Flows, der Hypothekenanträge verarbeitet
<a name="getting-started-mortgage-flow"></a>

Um uns mit den Ressourcen von Amazon Bedrock und ihren Funktionen vertraut zu machen, verwenden wir eine CloudFormation Vorlage, um einen [Ablauf](flows.md) einzurichten, der die Prozesse zur Beantragung einer Hypothek automatisiert, indem verschiedene Amazon Bedrock- und andere Ressourcen kombiniert werden. AWS 

**Anmerkung**  
Für dieses Tutorial verwenden wir die Region. *us-east-1* Sie können jede beliebige Region verwenden, die Agenten, Flows, Integritätsschutz, Wissensdatenbanken und Prompt-Management unterstützt. Eine Tabelle der unterstützten Features nach Regionen finden Sie unter [Funktionsunterstützung von AWS-Region in Amazon Bedrock](features-regions.md). Vergewissern Sie sich, dass Sie berechtigt sind, Amazon-S3-, Amazon-Bedrock-, Lambda- und DynamoDB-Ressourcen in der Region zu erstellen, die Sie verwenden.

Dieser Flow ist nicht für Bereitstellungszwecke gedacht, sondern soll als Tutorial dienen, um die Ressourcen von Amazon Bedrock kennenzulernen und zu verstehen. Die folgende Abbildung zeigt die visuelle Darstellung des Flows in der AWS-Managementkonsole:

![\[Verarbeitungs-Flow für Hypotheken\]](http://docs.aws.amazon.com/de_de/bedrock/latest/userguide/images/cloudformation/mortgage-processing-flow.png)


Der Flow kombiniert einen Amazon-Bedrock-[Agenten](agents.md), [Prompts](prompt-management.md) und eine [Lambda-Funktion](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html), um einen Verarbeitungs-Flow für Hypotheken zu erstellen, der Finanzinformationen eines Kunden aufnimmt und dahingehend verarbeitet, ob der Kunde für einen Kredit infrage kommt. Eine Amazon-Bedrock-[Wissensdatenbank](knowledge-base.md) und ein Amazon-Bedrock-[Integritätsschutz](guardrails.md) sind ebenfalls an den Agenten des Flows angefügt, um die Antworten zu verbessern und Schutz zu bieten. Weitere Informationen zu den Komponenten des Flows finden Sie unter [Der Verarbeitungs-Flow für Hypotheken im Detail](getting-started-mortgage-flow-details.md).

**Topics**
+ [

## Voraussetzungen
](#getting-started-mortgage-flow-prereqs)
+ [

## Erstellen Sie den Hypotheken-Verarbeitungsablauf mit CloudFormation
](#getting-started-mortgage-flow-create)
+ [

## Testen des Verarbeitungs-Flows für Hypotheken
](#getting-started-mortgage-flow-test)
+ [

## Bereinigung: Löschen von Ressourcen
](#getting-started-mortgage-flow-delete)
+ [

# CloudFormation Vorlagen
](getting-started-mortgage-flow-template.md)
+ [

# Der Verarbeitungs-Flow für Hypotheken im Detail
](getting-started-mortgage-flow-details.md)

## Voraussetzungen
<a name="getting-started-mortgage-flow-prereqs"></a>

Um diesen Flow zu erstellen, laden Sie eine ZIP-Datei herunter und folgen den Anleitungen zum Ausführen eines Skripts, das Ihre Ressourcen und Ihre Vorlage für Sie einrichtet.

**Wichtig**  
Die Amazon-Ressourcen, die Sie erstellen, werden Ihnen in Rechnung gestellt, bis Sie sie löschen.

Erfüllen Sie anschließend die folgenden Voraussetzungen:

1. Laden Sie die [cloudformation-mortgage-flow-setupZIP-Datei](samples/cloudformation-mortgage-flow-setup.zip) herunter.

1. Entpacken Sie die Datei. Weitere Informationen zum Inhalt finden Sie unter [CloudFormation Vorlagen](getting-started-mortgage-flow-template.md).

1. Fordern Sie wie folgt den Zugriff auf Amazon-Bedrock-Basismodelle an:

   1. Melden Sie sich bei der AWS-Managementkonsole mit einer IAM-Identität an, die berechtigt ist, die Amazon Bedrock-Konsole zu verwenden. Öffnen Sie dann die Amazon Bedrock-Konsole unter [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

   1. Vergewissern Sie sich, dass Sie sich in der Region **USA Ost (Nord-Virginia)** befinden, indem Sie Ihre Region oben rechts überprüfen. Falls nicht, wechseln Sie die Region.

   1. Wählen Sie unten im linken Navigationsbereich **Modellzugriff** aus.

   1. Wählen Sie **Modellzugriff ändern**.

   1. Führen Sie eine der folgenden Aktionen aus:
      + Um Zugriff auf alle Modelle anzufordern, wählen Sie **Alle Modelle aktivieren**. Auf der Seite, zu der Sie weitergeleitet werden, werden die Kontrollkästchen neben allen Modellen ausgefüllt.
      + Um Zugriff auf bestimmte Modelle anzufordern, wählen Sie **Bestimmte Modelle aktivieren**. Auf der Seite, zu der Sie weitergeleitet werden, haben Sie folgende Optionen:
        + Um den Zugriff auf alle Modelle eines Anbieters anzufordern, aktivieren Sie das Kontrollkästchen neben dem betreffenden Anbieternamen.
        + Um Zugriff auf ein Modell anzufordern, aktivieren Sie das Kontrollkästchen neben dem Modellnamen.

   1. Für die Zwecke des folgenden Tutorials sollten Sie mindestens Zugriff auf die Modelle **Titan Embeddings G1 - Text** und **Claude 3 Haiku** anfordern. Klicken Sie anschließend auf **Weiter**.

   1. Sehen Sie sich die Modelle an, für die Sie den Zugriff anfordern, und lesen Sie die **Nutzungsbedingungen**. Sobald Sie bereit sind, klicken Sie auf **Senden**, um den Zugriff anzufordern.

## Erstellen Sie den Hypotheken-Verarbeitungsablauf mit CloudFormation
<a name="getting-started-mortgage-flow-create"></a>

Um den Hypotheken-Verarbeitungsablauf und die zugehörigen Ressourcen zu erstellen, erstellen wir eine CloudFormation Vorlage und verwenden sie, um einen Stapel mit Amazon Bedrock-Ressourcen zu erstellen.

**Wichtig**  
Die Amazon-Ressourcen, die Sie erstellen, werden Ihnen in Rechnung gestellt, bis Sie sie löschen.

### Erstellen Sie die Ressourcen- und CloudFormation Vorlagendatei
<a name="getting-started-mortgage-flow-file"></a>

Verwenden Sie zunächst das Skript aus der ZIP-Datei, um die Ressourcen in einen S3-Bucket hochzuladen und die CloudFormation Vorlagen zu erstellen.

1. Führen Sie in einem Terminal den folgenden Befehl aus, um die Ressourcen in einen Amazon-S3-Bucket zu kopieren und die Dateien `main-stack.yaml` und `main-stack.json` mit dem Namen des S3-Buckets als Standardwert für den Parameter des Bucket-Namens zu füllen.

   ```
   bash deploy.sh
   ```
**Anmerkung**  
Die Verwendung des Skripts ist`bash deploy.sh <region> <bucket-name>`, where *<region>* und *<bucket-name>* sind optionale Argumente. Wenn Sie sie nicht angeben, werden die folgenden Standardwerte verwendet:  
*<region>*— Die AWS Standardregion, die in Ihrem AWS Anmeldeinformations-Setup angegeben wurde.
*<bucket-name>*— Der Bucket wird benannt*mortgage-flow-deployment-<AccountId>-<Region>*, wobei sich Ihre AWS Konto-ID *<AccountId>* befindet und dem von Ihnen angegebenen Wert oder der AWS Standardregion *<Region>* entspricht, die in Ihrem AWS Anmeldedaten-Setup angegeben wurde.

1. Bestätigen Sie die Prompts. Nach Abschluss der Bereitstellung sollten Sie über eine vollständige `main-stack.yaml`- und `main-stack.json`-Vorlage für den nächsten Schritt verfügen.

**Anmerkung**  
Wenn das Skript fehlschlägt, können Sie die Ressourcen wie folgt manuell vorbereiten:  
Laden Sie den *Inhalt* (ohne den Ordner selbst) des entpackten `cloudformation-mortgage-flow-setup` Ordners in einen S3-Bucket in der Region USA Ost (Nord-Virginia) in der Amazon S3 S3-Konsole unter hoch. [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)
Suchen Sie die Datei `templates/json/main-stack-tmp.yaml` oder `templates/json/main-stack-tmp.json` und gehen Sie folgendermaßen vor:  
Ändern Sie den `Default` Wert des `Q01pS3BucketName` Parameters von in *MortgageFlowBucket* Ihren S3-Bucket-Namen.
Entfernen Sie `-tmp` aus dem Dateinamen, sodass er zu `templates/json/main-stack.yaml` oder `templates/json/main-stack.json` wird.

### Erstellen Sie den Stack mithilfe der CloudFormation Konsole
<a name="getting-started-mortgage-flow-stack"></a>

Verwenden Sie als Nächstes die Vorlage, die Sie gespeichert haben, um einen CloudFormation Stack bereitzustellen.

1. Öffnen Sie die CloudFormation Konsole unter [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/). Vergewissern Sie sich, dass Sie sich in der Region **USA Ost (Nord-Virginia)** befinden, indem Sie Ihre Region oben rechts überprüfen. Falls nicht, wechseln Sie die Region.

1. Auf der Seite **Stacks** wählen Sie im Menü **Stack erstellen** die Option **Mit neuen Ressourcen (Standard)** aus.

1. Legen Sie die Vorlage fest:

   1. Wählen Sie unter **Voraussetzung** die Option **Vorhandene Vorlage wählen** aus.

   1. Wählen Sie unter **Vorlage angeben** die Option **Eine Vorlagendatei hochladen** aus.

   1. Klicken Sie auf **Datei auswählen**, navigieren Sie zur Vorlage `main-stack.yaml` oder `main-stack.json` und wählen Sie sie aus.

   1. Klicken Sie auf **Weiter**.

1. Geben Sie die Stack-Details ein:

   1. Geben Sie unter **Stack-Name** einen Namen für den Stack ein.

   1. Übernehmen Sie die Standardwerte im Feld **Parameter**.
**Anmerkung**  
Der Wert `Q01pS3BucketName` sollte dem Namen des S3-Buckets entsprechen, in den Sie die Ressourcen für diese Vorlage hochgeladen haben. Die verbleibenden Argumente beziehen sich auf die Konfigurationen der Wissensdatenbank. Wenn Sie eine davon ändern, müssen Sie sicherstellen, dass die Konfigurationen miteinander kompatibel sind. Weitere Informationen finden Sie unter [Voraussetzungen für die Verwendung eines Vektorspeichers, den Sie für eine Wissensdatenbank erstellt haben](knowledge-base-setup.md).

   1. Wählen Sie **Weiter** aus.

1. Konfigurieren Sie die Stack-Optionen:

   1. Wählen Sie unter **Optionen für Stack-Fehler** die Option **Löschen aller neu erstellten Ressourcen** aus.
**Anmerkung**  
Durch Auswahl dieser Option vermeiden Sie möglicherweise anfallende Kosten für Ressourcen, deren Löschrichtlinie die Beibehaltung auch vorsieht, wenn die Stack-Erstellung fehlschlägt. Weitere Informationen finden Sie unter [`DeletionPolicy`-Attribut](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html) im *Benutzerhandbuch zu CloudFormation *.

   1. Markieren Sie unter **Funktionen** das Kästchen, um zu bestätigen, dass dadurch IAM-Ressourcen in Ihrem Konto erstellt werden CloudFormation könnten.

   1. Wählen Sie **Weiter** aus.

1. Überprüfen Sie die Stack-Details und wählen Sie **Senden** aus. CloudFormation erstellt den Stapel. Die Erstellung dauert mehrere Minuten. Nach erfolgter Stack-Erstellung können Sie auf der Registerkarte **Ressourcen** der Seite „Stack-Details“ die in Ihrem Konto bereitgestellten Ressourcen anzeigen.

1. Gehen Sie nach Abschluss der Stack-Erstellung wie folgt vor, um die Datenquelle für die Wissensdatenbank zu synchronisieren, damit die Wissensdatenbank abgefragt werden kann:

   1. Melden Sie sich bei der AWS-Managementkonsole mit einer IAM-Identität an, die berechtigt ist, die Amazon Bedrock-Konsole zu verwenden. Öffnen Sie dann die Amazon Bedrock-Konsole unter [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

   1. Klicken Sie im linken Navigationsbereich auf **Wissensdatenbank** und wählen Sie die erstellte Wissensdatenbank mit dem Namen `AWSDocsTutorial-MortgageKB` aus.

   1. Aktivieren Sie im Abschnitt **Datenquelle** das Kontrollkästchen neben der Datenquelle, die erstellt wurde: `AWSDocsTutorial-MortgageKB-DS`.

   1. Klicken Sie auf **Synchronisieren**. Nach Abschluss der Synchronisierung können Sie den Flow testen.

## Testen des Verarbeitungs-Flows für Hypotheken
<a name="getting-started-mortgage-flow-test"></a>

Sobald der Verarbeitungs-Flow für Hypotheken erstellt wurde, können Sie ihn mit der Amazon-Bedrock-Konsole untersuchen, testen und ändern. Sie können auch die einzelnen Ressourcen im Flow untersuchen, testen und ändern.

**So testen Sie den Flow**

1. Melden Sie sich bei der AWS-Managementkonsole mit einer IAM-Identität an, die berechtigt ist, die Amazon Bedrock-Konsole zu verwenden. Öffnen Sie dann die Amazon Bedrock-Konsole unter [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. Wählen Sie im linken Navigationsbereich die Option **Flows** aus. Vergewissern Sie sich, dass Sie sich in der Region **USA Ost (Nord-Virginia)** befinden, indem Sie Ihre Region oben rechts überprüfen. Falls nicht, wechseln Sie die Region.

1. Wählen Sie im Abschnitt **Flows** den Flow aus, der anhand der Vorlage erstellt wurde. CloudFormation Dies sollte `AWSDocsTutorial-MortgageFlow` sein.

1. Wählen Sie **Im Flow-Builder bearbeiten** aus. Sie können einzelne Knoten im Flow ziehen, um die visuelle Darstellung des Flows zu ändern.

1. Geben Sie im Bereich **Flow testen** Folgendes in das Textfeld ein und klicken Sie dann auf **Ausführen**.

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

   Da der Kreditbetrag den berechneten Höchstbetrag für einen bezahlbaren Kredit übersteigt, wird der Prompt **incomeDebt** ausgelöst und der Flow generiert ein Ablehnungsschreiben. Sie können **Nachverfolgung anzeigen** wählen, um die Knoten zu sehen, die im Flow ausgeführt wurden.

1. Geben Sie auch hier im Bereich **Flow testen** Folgendes in das Textfeld ein und klicken Sie dann auf **Ausführen**.

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

   Da der Kreditbetrag unter dem berechneten Höchstbetrag für einen bezahlbaren Kredit liegt, wird die **ProcessApplication-Aufforderung** ausgelöst und an die **mortgageProcessingAgent**gesendet. Diese sucht in der angehängten Wissensdatenbank und generiert eine Antwort, mit der anhand der Eingabewerte bewertet wird, ob der Kunde für einen Kredit in Frage kommt.

1. (Optional) Versuchen Sie, den Flow auszuführen, indem Sie unterschiedliche Werte für die Felder im JSON-Objekt verwenden. Die Werte `mlsId` entsprechen den Immobilien, die im Multiple Listing Service aufgeführt sind. Gehen Sie wie folgt vor, um gültige `mlsId`-Werte zu finden:

   1. Melden Sie sich bei der an AWS-Managementkonsole und öffnen Sie die DynamoDB-Konsole unter. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

   1. Wählen Sie im linken Navigationsbereich **Tabellen** aus.

   1. Wählen Sie die Tabelle mit der Aufschrift. **AWSDocsTutorial-PropertyListing**

   1. Wählen Sie **Tabellenelemente erkunden** aus.

   1. Sie können jeden der Werte in der Spalte **mls\$1id** in der Flow-Eingabe verwenden.

Sie können auch zu den **Verwaltungsseiten **Agents**, **Knowledge Bases**, **Guardrails** und Prompt** in der navigieren, AWS-Managementkonsole um jede Amazon Bedrock-Ressource, die im Flow verwendet wird, unabhängig voneinander zu untersuchen. Weitere Informationen zum Flow und ein detailliertere Erläuterung der Komponenten finden Sie unter [Der Verarbeitungs-Flow für Hypotheken im Detail](getting-started-mortgage-flow-details.md).

## Bereinigung: Löschen von Ressourcen
<a name="getting-started-mortgage-flow-delete"></a>

Nachdem Sie sich mit den Ressourcen befasst haben und die Funktionen der verschiedenen Amazon-Bedrock-Ressourcen nun besser verstehen, löschen wir den Stack und die darin enthaltenen Ressourcen.

**Wichtig**  
Die Amazon-Ressourcen, die Sie erstellen, werden Ihnen in Rechnung gestellt, bis Sie sie löschen.

1. [Öffnen Sie die Datei /cloudformation. https://console.aws.amazon.com](https://console.aws.amazon.com/cloudformation/)

1. Wählen Sie im linken Navigationsbereich **Stacks** aus.

1. Wählen Sie den Stack aus, den Sie aus der Vorlage erstellt haben. Wählen Sie **Löschen** und bestätigen Sie das **Löschen**.

   CloudFormation initiiert das Löschen des Hauptstapels, aller seiner verschachtelten Stacks und aller in den Stacks enthaltenen Ressourcen.

# CloudFormation Vorlagen
<a name="getting-started-mortgage-flow-template"></a>

Der Download-Datei `cloudformation-mortgage-flow-setup.zip` enthält die folgenden Dateien:
+ `deploy.sh`— Ein Shell-Skript, das Ihre Ressourcen bereitstellt und die CloudFormation Hauptvorlage vorbereitet, die Sie verwenden werden.
+ `artifacts` – Einen Ordner, der ZIP-Dateien mit Funktionen für den Agenten und Vorlagen für die Wissensdatenbank enthält:
  + Lambda-Funktionen für die Aktionsgruppen des Agenten
    + `agent_loan_calculator.zip`
    + `mls_lookup.zip`
    + `loader_deployment_package.zip`
  + Funktionen zum Einrichten der Wissensdatenbank
    + `custom-resource-lambda.zip`
    + `opensearchpy-layer.zip`
    + `provider-event-handler.zip`
+ `api-schema` – Einen Ordner, der API-Schemas für Aktionsgruppen enthält
+ `knowledge-base-data-source` – Einen Ordner, der die PDF-Datei für [Fannie Mae's Selling Guide](https://selling-guide.fanniemae.com/) enthält
+ `templates` – Einen Ordner, der die Vorlagen für die Ressourcen in diesem Flow sowohl im JSON- als auch im YAML-Format enthält:
  + `main-stack-tmp` – Die Hauptvorlage, die die verbleibenden Vorlagen als verschachtelten Stack bereitstellt. Diese Datei wird in `main-stack` konvertiert, nachdem das Bereitstellungsskript ausgeführt wurde.
  + `guardrails-template` – Die Vorlage für den Integritätsschutz, der mit dem Agenten verknüpft werden soll
  + `prompts-template` – Die Vorlage für die Prompts, die im Flow verwendet werden sollen
  + `kb-role-template`— Die Vorlage für die Wissensdatenbank-Rolle, die sowohl von der OpenSearch Vorlage als auch von der Wissensdatenbank-Vorlage verwendet werden soll.
  + `oss-infra-template`— Die Vorlage für den Amazon OpenSearch Serverless Vector Store, die für die Wissensdatenbank verwendet werden soll.
  + `kb-infra-template` – Die Vorlage für die Wissensdatenbank des Hypothekenkredits, die mit dem Agenten verknüpft werden soll
  + `agent-template` – Die Vorlage für den Verarbeitungsagenten der Hypothek, der im Flow verwendet werden soll
  + `mortgage-flow-template` – Die Vorlage für den Verarbeitungs-Flow der Hypothek, der alle Ressourcen kombiniert
+ `README.md` – Eine README-Datei, in der die Schritte zur Verwendung der Vorlage beschrieben werden

Die folgenden Themen zeigen die CloudFormation Vorlagen, die für jeden Stapel verwendet werden. Der Haupt-Stack stellt die übrigen Stacks als [verschachtelte Stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) bereit.

**Topics**
+ [

## Haupt-Stack
](#getting-started-mortgage-templates-main)
+ [

## Integritätsschutz-Stack für Amazon Bedrock
](#getting-started-mortgage-guardrail-templates)
+ [

## Amazon-Bedrock-Prompt-Management-Stack
](#getting-started-mortgage-prompts-templates)
+ [

## Amazon-Bedrock-Wissensdatenbank-Stack
](#getting-started-mortgage-kb-templates)

## Haupt-Stack
<a name="getting-started-mortgage-templates-main"></a>

Der Haupt-Stack definiert die Parameter, die Sie beim Hochladen der Vorlage definieren können. Diese Werte werden an jeden der verbleibenden verschachtelten Stacks weitergegeben. Das Bereitstellungsskript ersetzt *MortgageFlowBucket* den Standardwert des `Q01pS3BucketName` Parameters durch Ihren tatsächlichen S3-Bucket, der die vom Skript bereitgestellten Ressourcen enthält.

------
#### [ 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"
            ]
          }
        }
      }
    }
  }
}
```

------

## Integritätsschutz-Stack für Amazon Bedrock
<a name="getting-started-mortgage-guardrail-templates"></a>

Dieser Stack erstellt die folgenden Ressourcen in Bezug auf den [Integritätsschutz](guardrails.md):
+ AgentGuardrail ([AWS::Bedrock::Guardrail](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-guardrail.html)) — Eine Leitplanke, die Inhaltsfilterung, Themenrichtlinien und Schutz personenbezogener Daten bietet. Dieser Integritätsschutz wird an den Agenten im Agenten-Stack angefügt.
+ AgentGuardrailVersion ([AWS::Bedrock::GuardrailVersion](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                         /aws-resource-bedrock-guardrailversion.html)) — Die Version der `AgentGuardrail` Ressource, die auf den Agenten angewendet wurde.

------
#### [ 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-Stack
<a name="getting-started-mortgage-prompts-templates"></a>

Dieser Stapel erstellt die folgenden [prompt](prompt-management.md) ([AWS::IAM::Prompt](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide                     /aws-resource-bedrock-prompt.html)) -Ressourcen, die dem Flow hinzugefügt werden:
+ RejectionPrompt — Eine Aufforderung, die ein generiertes Ablehnungsschreiben zurückgibt, das auf Finanzinformationen basiert.
+ ProcessApplicationPrompt — Eine Aufforderung, bei der die Finanzinformationen eines Kunden an einen Makler gesendet werden und dieser aufgefordert wird, zu beurteilen, ob der Kunde für ein Darlehen in Frage kommt.

------
#### [ 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-Wissensdatenbank-Stack
<a name="getting-started-mortgage-kb-templates"></a>

Diese Vorlage erstellt die [Wissensdatenbank](knowledge-base.md) und ihre Datenquelle, die die Kreditrichtlinien enthält:
+ 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"
    }
  }
}
```

------

# Der Verarbeitungs-Flow für Hypotheken im Detail
<a name="getting-started-mortgage-flow-details"></a>

Die visuelle Darstellung des Hypothekenverarbeitungsablaufs in der AWS-Managementkonsole lautet wie folgt:

![\[Verarbeitungs-Flow für Hypotheken\]](http://docs.aws.amazon.com/de_de/bedrock/latest/userguide/images/cloudformation/mortgage-processing-flow.png)


## Schritte im Flow
<a name="getting-started-mortgage-flow-steps"></a>

Die folgenden Schritte finden im Flow statt:

1. Die Finanzinformationen des Kunden aus der Eingabe werden an die Lambda-Funktion `loanCalculator` gesendet, die den Kredit berechnet, den sich der Kunde maximal leisten kann.

1. Die Ausgabe der Funktion `loanCalculator` (`maximumAffordableLoan`) und der Wert `loanAmount` der Eingabe werden an den Bedingungsknoten gesendet, der dann wie folgt evaluiert wird:
   + Wenn der `loanAmount` größer als der `maximumAffordableLoan` ist, wird der Prompt `incomeDebt` ausgelöst und ein Ablehnungsschreiben für den Kredit generiert.
   + Andernfalls werden die Finanzinformationen des Kunden per `processApplication`-Prompt an den `mortgageProcessingAgent` gesendet. Der Agent wendet eine Kreditrechnerfunktion sowie eine MLS-Nachschlagefunktion (Multiple Listing Service) an, um in einer DynamoDB-Tabelle nachzuschlagen und die Kundeninformationen in Bezug auf die in der Eingabe angegebene MLS-Immobilie zu bewerten. Darüber hinaus sucht der Agent nach Informationen in einer Wissensdatenbank, die den Fannie Mae Selling Guide enthält. Der Agent verwendet all diese Informationen, um eine Antwort zu generieren, in der die Eignung des Kunden für den angeforderten Kreditbetrag analysiert wird.