

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# AI 與機器學習
<a name="machinelearning-pattern-list"></a>

**Topics**
+ [將儲存 AWS CodeCommit 庫與另一個帳戶中 AWS 帳戶 的 Amazon SageMaker AI Studio Classic 建立關聯](associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.md)
+ [使用 Amazon Textract 從 PDF 檔案自動擷取內容](automatically-extract-content-from-pdf-files-using-amazon-textract.md)
+ [在 Amazon SageMaker AI Studio Lab 中將 DeepAR 用於時間序列，以建置冷啟動預測模型](build-a-cold-start-forecasting-model-by-using-deepar.md)
+ [使用 Amazon SageMaker AI 和 Azure DevOps 建置 MLOps 工作流程](build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops.md)
+ [使用 在 Amazon Bedrock 中設定模型調用記錄 AWS CloudFormation](configure-bedrock-invocation-logging-cloudformation.md)
+ [為 SageMaker 建立自訂 Docker 容器映像，並將其用於 AWS Step Functions 中的模型訓練](create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.md)
+ [使用 Amazon Bedrock 代理程式，透過文字型提示在 Amazon EKS 中自動建立存取項目控制項](using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.md)
+ [AWS 使用 Terraform 和 Amazon Bedrock 在 上部署 RAG 使用案例](deploy-rag-use-case-on-aws.md)
+ [使用 Amazon SageMaker 中的推論管道，將預先處理邏輯部署到單一端點中的 ML 模型](deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker.md)
+ [搭配 Kiro 和其他編碼助理使用 MCP 伺服器部署即時編碼安全驗證](deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.md)
+ [使用 RAG 和 ReAct 提示，開發進階生成式 AI 聊天式助理](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [使用 Amazon Bedrock 代理程式和知識庫開發全自動聊天式助理](develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases.md)
+ [使用 Amazon Bedrock 和 Amazon Transcribe 從語音輸入記錄機構知識](document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.md)
+ [使用 Amazon Personalize 產生個人化和重新排名的建議](generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.md)
+ [使用 SageMaker AI 和 hydra 簡化從本機開發到可擴展實驗的機器學習工作流程](streamline-machine-learning-workflows-by-using-amazon-sagemaker.md)
+ [將自然語言轉換為查詢 DSL for OpenSearch 和 Elasticsearch 查詢](translate-natural-language-query-dsl-opensearch-elasticsearch.md)
+ [使用 Amazon Q Developer 作為編碼助理，以提高您的生產力](use-q-developer-as-coding-assistant-to-increase-productivity.md)
+ [使用 SageMaker Processing 對 TB 級 ML 資料集進行分散式特徵工程](use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets.md)
+ [使用 Flask 和 AWS Elastic Beanstalk 視覺化 AI/ML 模型結果](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)
+ [更多模式](machinelearning-more-patterns-pattern-list.md)

# 將儲存 AWS CodeCommit 庫與另一個帳戶中 AWS 帳戶 的 Amazon SageMaker AI Studio Classic 建立關聯
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account"></a>

*Laurens van der Maas 和 Aubrey Oosthuizen，Amazon Web Services*

## 總結
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-summary"></a>

此模式提供如何將一個 AWS 帳戶 （帳戶 A) 中的 AWS CodeCommit 儲存庫與另一個 AWS 帳戶 （帳戶 B) 中的 Amazon SageMaker AI Studio Classic 建立關聯的說明和程式碼。若要設定關聯，您必須在帳戶 A 中建立 AWS Identity and Access Management (IAM) 政策和角色，並在帳戶 B 中建立 IAM 內嵌政策。然後，您可以使用 shell 指令碼，將 CodeCommit 儲存庫從帳戶 A 複製到帳戶 B 中的 Amazon SageMaker AI Classic。

## 先決條件和限制
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-prereqs"></a>

**先決條件 **
+ 兩個 [AWS 帳戶](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)，一個包含 CodeCommit 儲存庫，另一個包含具有使用者的 SageMaker AI 網域
+ 佈建的 [SageMaker AI 網域和使用者](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio-onboard.html)，可透過網際網路存取或透過虛擬私有網路 AWS Security Token Service (VPC AWS STS) 端點存取 CodeCommit 和 ()
+ 對 [IAM](https://docs.aws.amazon.com/iam/?id=docs_gateway) 的基本了解
+ 對 [SageMaker AI Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) 的基本了解
+ 對 [Git](https://git-scm.com/) 和 [CodeCommit ](https://docs.aws.amazon.com/codecommit/index.html)的基本了解

**限制 **

此模式僅適用於 SageMaker AI Studio Classic，不適用於 Amazon SageMaker AI 上的 RStudio。

## Architecture
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-architecture"></a>

**技術堆疊**
+ Amazon SageMaker AI
+ Amazon SageMaker AI Studio Classic
+ AWS CodeCommit
+ AWS Identity and Access Management (IAM) 
+ Git

**目標架構**

下圖顯示將 CodeCommit 儲存庫從帳戶 A 與帳戶 B 中的 SageMaker AI Studio Classic 建立關聯的架構。

![\[跨帳戶關聯的架構圖\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/d40df9eb-6ee2-4cb8-8257-051fa624e52a/images/abb89a66-fc8f-4e72-8f45-f0f44c2ec6ce.png)


該圖顯示以下工作流程：

1. 使用者透過角色擔任帳戶 A 中`MyCrossAccountRepositoryContributorRole`的角色`sts:AssumeRole`，同時使用帳戶 B 中 SageMaker AI Studio Classic 中的 SageMaker AI 執行角色。擔任的角色包含 CodeCommit 許可，可複製並與指定的儲存庫互動。

1. 使用者從 SageMaker AI Studio Classic 中的系統終端機執行 Git 命令。

**自動化和擴展**

此模式包含可使用 [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/?id=docs_gateway)、 [AWS CloudFormation](https://docs.aws.amazon.com/cloudformation/?id=docs_gateway)或 [Terraform](https://www.terraform.io/) 自動化的手動步驟。

## 工具
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-tools"></a>

**AWS 工具**
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon SageMaker AI Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) 是適用於機器學習的 Web 型整合開發環境 (IDE)，可讓您建置、訓練、偵錯、部署和監控機器學習模型。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一種版本控制服務，可協助您私下存放和管理 Git 儲存庫，而無需管理您自己的來源控制系統。

  **注意**： AWS CodeCommit 不再提供給新客戶。的現有客戶 AWS CodeCommit 可以繼續正常使用服務。[進一步了解](https://aws.amazon.com/blogs/devops/how-to-migrate-your-aws-codecommit-repository-to-another-git-provider/)
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。

**其他工具**
+ [Git](https://git-scm.com/) 是一種分散式版本控制系統，可在軟體開發期間追蹤原始程式碼的變更。

## 史詩
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-epics"></a>

### 在帳戶 A 中建立 IAM 政策和 IAM 角色
<a name="create-an-iam-policy-and-iam-role-in-account-a"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在帳戶 A 中建立儲存庫存取的 IAM 政策。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.html)最佳實務是將 IAM 政策的範圍限制為使用案例所需的最低許可。 | AWS DevOps | 
| 在帳戶 A 中建立儲存庫存取的 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.html) | AWS DevOps | 

### 在帳戶 B 中建立 IAM 內嵌政策
<a name="create-an-iam-inline-policy-in-account-b"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將內嵌政策連接至帳戶 B 中連接至 SageMaker 網域使用者的執行角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.html) | AWS DevOps | 

### 在帳戶 B 的 SageMaker AI Studio Classic 中複製儲存庫
<a name="clone-the-repository-in-sm-studio-classic-for-account-b"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在帳戶 B 的 SageMaker AI Studio Classic 中建立 shell 指令碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.html) | AWS DevOps | 
| 從系統終端機叫用 shell 指令碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.html)您已在 SageMaker AI Studio 跨帳戶中複製 CodeCommit 儲存庫。您現在可以從系統終端機執行所有 Git 命令。 | AWS DevOps | 

## 其他資訊
<a name="associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account-additional"></a>

**IAM 政策範例**

如果您使用此範例政策，請執行下列動作：
+ `<CodeCommit_Repository_Region>` 將 取代 AWS 區域 為 儲存庫的 。
+ `<Account_A_ID>` 將 取代為帳戶 A 的帳戶 ID。
+ `<CodeCommit_Repository_Name>` 將 取代為帳戶 A 中 CodeCommit 儲存庫的名稱。

```
{
"Version": "2012-10-17",		 	 	 
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "codecommit:BatchGet*",
            "codecommit:Create*",
            "codecommit:DeleteBranch",
            "codecommit:Get*",
            "codecommit:List*",
            "codecommit:Describe*",
            "codecommit:Put*",
            "codecommit:Post*",
            "codecommit:Merge*",
            "codecommit:Test*",
            "codecommit:Update*",
            "codecommit:GitPull",
            "codecommit:GitPush"
        ],
        "Resource": [
            "arn:aws:codecommit:<CodeCommit_Repository_Region>:<Account_A_ID>:<CodeCommit_Repository_Name>"
        ]
    }
]
}
```

**SageMaker AI shell 指令碼範例**

如果您使用此範例指令碼，請執行下列動作：
+ `<Account_A_ID>`將 取代為帳戶 A 的帳戶 ID。
+ `<Account_A_Role_Name>`將 取代為您先前建立的 IAM 角色名稱。
+ `<CodeCommit_Repository_Region>`將 取代 AWS 區域 為 儲存庫的 。
+ `<CodeCommit_Repository_Name>`將 取代為帳戶 A 中 CodeCommit 儲存庫的名稱。

```
#!/usr/bin/env bash
#Launch from system terminal
pip install --quiet git-remote-codecommit

mkdir -p ~/.aws
touch ~/.aws/config

echo "[profile CrossAccountAccessProfile]
region = <CodeCommit_Repository_Region>
credential_source=EcsContainer
role_arn = arn:aws:iam::<Account_A_ID>:role/<Account_A_Role_Name>
output = json" > ~/.aws/config

echo '[credential "https://git-codecommit.<CodeCommit_Repository_Region>.amazonaws.com"]
        helper = !aws codecommit credential-helper $@ --profile CrossAccountAccessProfile
        UseHttpPath = true' > ~/.gitconfig
        
git clone codecommit::<CodeCommit_Repository_Region>://CrossAccountAccessProfile@<CodeCommit_Repository_Name>
```

# 使用 Amazon Textract 從 PDF 檔案自動擷取內容
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract"></a>

*Tianxia Jia，Amazon Web Services*

## 總結
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-summary"></a>

許多組織需要從上傳到其商業應用程式的 PDF 檔案擷取資訊。例如，組織可能需要準確從稅務或醫療 PDF 檔案擷取資訊，以進行稅務分析或醫療索賠處理。

在 Amazon Web Services (AWS) 雲端上，Amazon Textract 會自動從 PDF 檔案擷取資訊 （例如，列印的文字、表單和資料表），並產生 JSON 格式的檔案，其中包含原始 PDF 檔案的資訊。您可以在 AWS 管理主控台中或透過實作 API 呼叫來使用 Amazon Textract。我們建議您使用[程式設計 API 呼叫](https://aws.amazon.com/textract/faqs/)來擴展和自動處理大量 PDF 檔案。

當 Amazon Textract 處理檔案時，會建立下列`Block`物件清單：頁面、行和文字、表單 （索引鍵/值對）、資料表和儲存格，以及選取元素。還包括其他物件資訊，例如[週框方塊](https://docs.aws.amazon.com/textract/latest/dg/API_BoundingBox.html)、可信度間隔、IDs和關係。Amazon Textract 會將內容資訊擷取為字串。正確識別和轉換的資料值是必要的，因為下游應用程式可以更輕鬆地使用這些值。 

此模式描述使用 Amazon Textract 自動從 PDF 檔案擷取內容並將其處理為乾淨輸出的step-by-step工作流程。模式使用範本比對技術來正確識別必要欄位、金鑰名稱和資料表，然後將後置處理更正套用至每個資料類型。您可以使用此模式來處理不同類型的 PDF 檔案，然後您可以擴展和自動化此工作流程，以處理格式相同的 PDF 檔案。  

## 先決條件和限制
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 現有的 Amazon Simple Storage Service (Amazon S3) 儲存貯體，用於儲存轉換為 JPEG 格式供 Amazon Textract 處理後的 PDF 檔案。如需 S3 儲存貯體的詳細資訊，請參閱 Amazon S3 文件中的[儲存貯體概觀](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)。
+ 已安裝和設定的 `Textract_PostProcessing.ipynb` Jupyter 筆記本 （已連接）。如需 Jupyter 筆記本的詳細資訊，請參閱 [Amazon SageMaker 文件中的建立 Jupyter 筆記本](https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-prepare.html)。 Amazon SageMaker 
+ 具有相同格式的現有 PDF 檔案。
+ 了解 Python。

**限制**
+ 您的 PDF 檔案必須品質良好且清晰可讀。建議使用原生 PDF 檔案，但如果所有個別單字都清晰，您可以使用轉換為 PDF 格式的掃描文件。如需詳細資訊，請參閱 AWS Machine Learning 部落格上的[使用 Amazon Textract：視覺效果偵測和移除進行 PDF 文件預先處理](https://aws.amazon.com/blogs/machine-learning/process-text-and-images-in-pdf-documents-with-amazon-textract/)。
+ 對於多頁檔案，您可以使用非同步操作，或將 PDF 檔案分割成單一頁面並使用同步操作。如需這兩個選項的詳細資訊，請參閱 Amazon Textract 文件[中的偵測和分析多頁文件中的文字](https://docs.aws.amazon.com/textract/latest/dg/async.html)[，以及偵測和分析單頁文件中的文字](https://docs.aws.amazon.com/textract/latest/dg/sync.html)。

## Architecture
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-architecture"></a>

此模式的工作流程會先在範例 PDF 檔案上執行 Amazon Textract (*第一次執行*)，然後在與第一個 PDF 格式相同的 PDF 檔案上執行它 (*重複執行*)。下圖顯示合併*的第一次執行*和*重複執行*工作流程，可自動且重複地從具有相同格式的 PDF 檔案擷取內容。

![\[使用 Amazon Textract 從 PDF 檔案擷取內容\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/2d724523-2cab-42c9-a773-65857014d9ec/images/9e20070f-3e0c-46aa-aa98-a8b1eb3395dc.png)


 

圖表顯示此模式的下列工作流程：

1. 將 PDF 檔案轉換為 JPEG 格式，並將其存放在 S3 儲存貯體中。 

1. 呼叫 Amazon Textract API 並剖析 Amazon Textract 回應 JSON 檔案。 

1. 透過為每個必要欄位新增正確的`KeyName:DataType`配對來編輯 JSON 檔案。建立*重複執行*階段`TemplateJSON`的檔案。

1. 定義每個資料類型 （例如浮點數、整數和日期） 的後製處理更正函數。

1. 準備與您第一個 PDF 檔案格式相同的 PDF 檔案。

1. 呼叫 Amazon Textract API 並剖析 Amazon Textract 回應 JSON。

1. 比對剖析的 JSON 檔案與 `TemplateJSON` 檔案。

1. 實作後製處理更正。

每個必要欄位的最終 JSON `Value` 輸出檔案都有正確的 `KeyName`和 。

**目標技術堆疊**
+ Amazon SageMaker 
+ Amazon S3 
+ Amazon Textract

**自動化和擴展**

您可以使用 AWS Lambda 函數來自動化*重複執行*工作流程，該函數會在新的 PDF 檔案新增至 Amazon S3 時啟動 Amazon Textract。然後，Amazon Textract 會執行處理指令碼，並將最終輸出儲存到儲存位置。如需詳細資訊，請參閱 [Lambda 文件中的使用 Amazon S3 觸發叫用 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html)。

## 工具
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-tools"></a>
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 是一項全受管 ML 服務，可協助您快速輕鬆地建置和訓練 ML 模型，然後將模型直接部署到生產就緒的託管環境中。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Textract](https://docs.aws.amazon.com/textract/latest/dg/what-is.html) 可讓您輕鬆地將文件文字偵測和分析新增至應用程式。

## 史詩
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-epics"></a>

### 第一次執行
<a name="first-time-run"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 轉換 PDF 檔案。 | 將 PDF 檔案分割為單一頁面並將其轉換為 JPEG 格式以進行 Amazon Textract [同步操作](https://docs.aws.amazon.com/textract/latest/dg/sync.html) ()，以準備初次執行的 PDF 檔案`Syn API`。您也可以將 Amazon Textract [非同步操作](https://docs.aws.amazon.com/textract/latest/dg/async.html) (`Asyn API`) 用於多頁 PDF 檔案。 | 資料科學家、開發人員 | 
| 剖析 Amazon Textract 回應 JSON。 | 開啟 `Textract_PostProcessing.ipynb` Jupyter 筆記本 （已連接），並使用下列程式碼呼叫 Amazon Textract API：<pre>response = textract.analyze_document(<br />Document={<br />        'S3Object': {<br />            'Bucket': BUCKET,<br />            'Name': '{}'.format(filename)<br />                    }<br />                },<br />        FeatureTypes=["TABLES", "FORMS"])</pre>使用下列程式碼，將回應 JSON 剖析為表單和資料表：<pre>parseformKV=form_kv_from_JSON(response)<br />parseformTables=get_tables_fromJSON(response)</pre> | 資料科學家、開發人員 | 
| 編輯 TemplateJSON 檔案。 | 編輯每個 `KeyName`和對應 `DataType`（例如，字串、浮點數、整數或日期） 和資料表標頭 （例如， `ColumnNames`和 ) 的剖析 JSON`RowNames`。此範本用於每個個別的 PDF 檔案類型，這表示範本可以重複使用於格式相同的 PDF 檔案。 | 資料科學家、開發人員 | 
| 定義後置處理校正函數。 | Amazon Textract 對 `TemplateJSON` 檔案的回應中的值為字串。日期、浮點數、整數或貨幣沒有差異。這些值必須轉換為下游使用案例的正確資料類型。 使用下列程式碼，根據`TemplateJSON`檔案修正每個資料類型：<pre>finalJSON=postprocessingCorrection(parsedJSON,templateJSON)</pre> | 資料科學家、開發人員 | 

### 重複執行
<a name="repeat-run"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 準備 PDF 檔案。 | 將 PDF 檔案分割成單一頁面，並將其轉換為 JPEG 格式以進行 Amazon Textract [同步操作](https://docs.aws.amazon.com/textract/latest/dg/sync.html) ()，以準備 PDF 檔案`Syn API`。您也可以將 Amazon Textract [非同步操作](https://docs.aws.amazon.com/textract/latest/dg/async.html) (`Asyn API`) 用於多頁 PDF 檔案。 | 資料科學家、開發人員 | 
| 呼叫 Amazon Textract API。 | 使用下列程式碼呼叫 Amazon Textract API：<pre>response = textract.analyze_document(<br />        Document={<br />        'S3Object': {<br />            'Bucket': BUCKET,<br />            'Name': '{}'.format(filename)<br />                    }<br />                },<br />        FeatureTypes=["TABLES", "FORMS"])</pre> | 資料科學家、開發人員 | 
| 剖析 Amazon Textract 回應 JSON。 | 使用下列程式碼，將回應 JSON 剖析為表單和資料表：<pre>parseformKV=form_kv_from_JSON(response)<br />parseformTables=get_tables_fromJSON(response)</pre> | 資料科學家、開發人員 | 
| 載入 TemplateJSON 檔案，並將其與剖析的 JSON 比對。 | 使用以下命令，使用 `TemplateJSON` 檔案擷取正確的鍵值對和資料表：<pre>form_kv_corrected=form_kv_correction(parseformKV,templateJSON)<br />form_table_corrected=form_Table_correction(parseformTables, templateJSON)<br />form_kv_table_corrected_final={**form_kv_corrected , **form_table_corrected}</pre> | 資料科學家、開發人員 | 
| 後置處理更正。 | 在 `TemplateJSON` 檔案和後置處理函數`DataType`中使用 ，透過使用下列程式碼來更正資料： <pre>finalJSON=postprocessingCorrection(form_kv_table_corrected_final,templateJSON)</pre> | 資料科學家、開發人員 | 

## 相關資源
<a name="automatically-extract-content-from-pdf-files-using-amazon-textract-resources"></a>
+ [使用 Amazon Textract 從文件中自動擷取文字和結構化資料](https://aws.amazon.com/blogs/machine-learning/automatically-extract-text-and-structured-data-from-documents-with-amazon-textract/)
+ [使用 Amazon Textract 擷取文字和結構化資料](https://aws.amazon.com/getting-started/hands-on/extract-text-with-amazon-textract/)
+ [Amazon Textract 資源](https://aws.amazon.com/textract/resources/?blog-posts-cards.sort-by=item.additionalFields.createdDate&blog-posts-cards.sort-order=desc)

## 附件
<a name="attachments-2d724523-2cab-42c9-a773-65857014d9ec"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/2d724523-2cab-42c9-a773-65857014d9ec/attachments/attachment.zip)

# 在 Amazon SageMaker AI Studio Lab 中將 DeepAR 用於時間序列，以建置冷啟動預測模型
<a name="build-a-cold-start-forecasting-model-by-using-deepar"></a>

*Ivan Cui 和 Eyal Shacham，Amazon Web Services*

## 摘要
<a name="build-a-cold-start-forecasting-model-by-using-deepar-summary"></a>

無論您是更有效率地為 Web 流量配置資源、預測患者對人員需求的需求，還是預測公司產品的銷售，預測都是不可或缺的工具。冷啟動預測會針對歷史資料很少的時間序列建置預測，例如剛進入零售市場的新產品。此模式使用 Amazon SageMaker AI DeepAR 預測演算法來訓練冷啟動預測模型，並示範如何對冷啟動項目執行預測。

 

[DeepAR](https://docs.aws.amazon.com/sagemaker/latest/dg/deepar.html) 是一種監督式學習演算法，可使用遞歸神經網路 (RNN) 預測純量 （一維） 時間序列。DeepAR 會針對相關產品的所有時間序列，採取聯合訓練單一模型的方法。

傳統的時間序列預測方法，例如自動迴歸整合移動平均值 (ARIMA) 或指數平滑 (ETS)，很大程度上依賴每個個別產品的歷史時間序列。因此，這些方法對冷啟動預測無效。當您的資料集包含數百個相關時間序列時，DeepAR 的執行效能會優於標準 ARIMA 和 ETS 方法。您也可以使用已訓練的模型，針對與其已訓練之時間序列類似的新時間序列產生預測。

## 先決條件和限制
<a name="build-a-cold-start-forecasting-model-by-using-deepar-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶。
+ Amazon SageMaker AI [網域。](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-studio-onboard.html)
+ [Amazon SageMaker AI Studio Lab](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-lab.html) 或 Jupiter 實驗室應用程式。
+ 具有讀取和寫入許可的 Amazon Simple Storage Service (Amazon S3) 儲存貯體。
+ Python 程式設計的知識。
+ 使用 Jupyter 筆記本的知識。

**限制**
+ 叫用預測模型而沒有任何歷史資料點，將會傳回錯誤。使用最少的歷史資料點調用模型將傳回不準確的預測，並具有高可信度。此模式建議解決冷啟動預測這些已知限制的方法。
+ 有些 AWS 服務 無法全部使用 AWS 區域。如需區域可用性，請參閱[依區域的 AWS 服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

**產品版本**
+ Python 3.10 版或更新版本。
+ 模式的筆記本已在 Amazon SageMaker AI Studio 中使用 Python 3 （資料科學） 核心在 ml.t3.medium 執行個體上進行測試。

## Architecture
<a name="build-a-cold-start-forecasting-model-by-using-deepar-architecture"></a>

下圖顯示此模式的工作流程和架構元件。

![\[使用 SageMaker 和 Amazon S3 建置冷啟動預測模型的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/98d021d3-96d2-40a9-b0ce-717934652173/images/d97d66a0-8eef-4d30-ac5f-4c6c79cf6c9f.png)


工作流程會執行下列任務：

1. 訓練和測試資料的輸入檔案會合成，然後上傳至 Amazon S3 儲存貯體。此資料包含具有分類和動態功能的多個時間序列，以及目標值 （要預測）。Jupyter 筆記本可視覺化資料，以進一步了解訓練資料的需求和預期的預測值。

1. 建立超參數調校器任務是為了訓練模型，並根據預先定義的指標尋找最佳模型。

1. 輸入檔案會從 Amazon S3 儲存貯體下載到超參數調校任務的每個執行個體。

1. 在調校器任務根據調校器的預先定義閾值選取最佳模型後，模型會部署為 SageMaker AI 端點。

1. 然後，部署的模型已準備好被叫用，其中它的預測會根據測試資料進行驗證。

筆記本示範當有足夠數量的歷史資料點可用時，模型預測目標值的能力。不過，當我們調用具有較少歷史資料點的模型時 （代表冷產品），即使模型的可信度範圍內，模型的預測也不符合原始測試資料。在 模式中，新模型是針對冷產品所建置，其中其初始內容長度 （預測點） 定義為可用的歷史點數量，而新模型會在取得新資料點時進行反覆訓練。筆記本顯示，只要歷史資料點的數量接近其內容長度，模型就會有準確的預測。

## 工具
<a name="build-a-cold-start-forecasting-model-by-using-deepar-tools"></a>

**AWS 服務**
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon SageMaker AI Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) 是適用於 ML 的 Web 型整合開發環境 (IDE)，可讓您建置、訓練、偵錯、部署和監控 ML 模型。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [DeepAR-ColdProduct-Pattern](https://github.com/aws-samples/DeepAR-ColdProduct-Pattern) 儲存庫中使用。

## 最佳實務
<a name="build-a-cold-start-forecasting-model-by-using-deepar-best-practices"></a>
+ 在虛擬環境中訓練您的模型，並一律使用版本控制進行最高的重現性工作。
+ 包含盡可能多的高品質分類功能，以獲得最高的預測模型。
+ 請確定中繼資料包含類似的分類項目，以便模型充分推斷冷啟動產品預測。
+ 執行超參數調校任務以取得最高的預測模型。
+ 在此模式中，您建置的模型內容長度為 24 小時，這表示它會預測接下來的 24 小時。如果您嘗試在歷史資料少於 24 小時時預測接下來的 24 小時，模型的預測準確性會根據歷史資料點數量線性下降。若要緩解此問題，請為每個歷史資料點組建立新的模型，直到此數字達到所需的預測 （內容） 長度。例如，從內容長度模型 2 小時開始，然後逐步將模型增加到 4 小時、8 小時、16 小時和 24 小時。

## 史詩
<a name="build-a-cold-start-forecasting-model-by-using-deepar-epics"></a>

### 啟動 SageMaker AI Studio Classic 應用程式
<a name="start-your-sm-studio-classic-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動您的筆記本環境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-cold-start-forecasting-model-by-using-deepar.html)如需詳細資訊，請參閱 [ SageMaker AI 文件中的啟動 Amazon SageMaker AI Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html)。 SageMaker  | 資料科學家 | 

### 建立和啟用筆記本
<a name="create-and-activate-the-notebook"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定虛擬環境以進行模型訓練。 | 若要設定虛擬環境以進行模型訓練，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-cold-start-forecasting-model-by-using-deepar.html)如需詳細資訊，請參閱 [ SageMaker AI 文件中的將檔案上傳至 SageMaker AI Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tasks-files.html)。 SageMaker  | 資料科學家 | 
| 建立和驗證預測模型。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-cold-start-forecasting-model-by-using-deepar.html) | 資料科學家 | 

## 相關資源
<a name="build-a-cold-start-forecasting-model-by-using-deepar-resources"></a>
+ [DeepAR 超參數](https://docs.aws.amazon.com/sagemaker/latest/dg/deepar_hyperparameters.html)
+ [使用 AWS 機器學習服務預測新產品簡介的需求](https://docs.aws.amazon.com/prescriptive-guidance/latest/forecast-demand-new-product/introduction.html)
+ [啟動 Amazon SageMaker AI Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-launch.html)
+ [使用 SageMaker AI DeepAR 預測演算法](https://docs.aws.amazon.com/sagemaker/latest/dg/deepar.html)

# 使用 Amazon SageMaker AI 和 Azure DevOps 建置 MLOps 工作流程
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops"></a>

*Deepika Kumar、Sara van de Moosdijk 和 Amazon Web Services 的 PHP Kokoh Prasetyo*

## 總結
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-summary"></a>

機器學習操作 (MLOps) 是一組可自動化和簡化機器學習 (ML) 工作流程和部署的實務。MLOps 著重於自動化 ML 生命週期。它有助於確保模型不僅經過開發，而且還會以系統化和重複的方式部署、監控和重新訓練。它將 DevOps 原則帶入 ML。MLOps 可加快 ML 模型的部署速度、提高一段時間內的準確度，以及更強大的保證，確保它們提供真正的商業價值。

在開始 MLOps 旅程之前，組織通常會有現有的 DevOps 工具和資料儲存解決方案。此模式展示如何利用 Microsoft Azure 和 的優勢 AWS。它可協助您將 Azure DevOps 與 Amazon SageMaker AI 整合，以建立 MLOps 工作流程。

解決方案可簡化 Azure 和 之間的工作 AWS。您可以使用 Azure 進行開發和 AWS 機器學習。它可提升從頭到尾建立機器學習模型的有效程序，包括資料處理、訓練和部署 AWS。為了提高效率，您可以透過 Azure DevOps 管道管理這些程序。此解決方案適用於生成式 AI 中的基礎模型操作 (FMOps) 和大型語言模型操作 (LLMOps)，其中包括微調、向量資料庫和提示管理。

## 先決條件和限制
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-prereqs"></a>

**先決條件**
+ **Azure 訂閱** – 存取 Azure DevOps 等 Azure 服務，用於設定持續整合和持續部署 (CI/CD) 管道。
+ **作用中 AWS 帳戶** – 在此 AWS 服務 模式中使用 的許可。
+ **資料** – 存取歷史資料以訓練機器學習模型。
+ **熟悉 ML 概念 – **了解 Python、Jupyter 筆記本和機器學習模型開發。
+ **安全組態** – 在 Azure 和 AWS 之間正確設定角色、政策和許可，以確保安全的資料傳輸和存取。
+ **（選用） 向量資料庫 **– 如果您為向量資料庫使用擷取增強生成 (RAG) 方法和第三方服務，則需要存取外部向量資料庫。

**限制**
+ 本指南不會討論安全的跨雲端資料傳輸。如需跨雲端資料傳輸的詳細資訊，請參閱[AWS 混合多雲端解決方案](https://aws.amazon.com/hybrid-multicloud/)。
+ 多雲端解決方案可能會增加即時資料處理和模型推論的延遲。
+ 本指南提供多帳戶 MLOps 架構的一個範例。必須根據您的機器學習和 AWS 策略進行調整。
+ 本指南不會描述使用 Amazon SageMaker AI 以外的 AI/ML 服務。
+ 有些 AWS 服務 完全無法使用 AWS 區域。如需區域可用性，請參閱[AWS 服務 依區域](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)頁面，然後選擇服務的連結。

## Architecture
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-architecture"></a>

**目標架構**

目標架構整合 Azure DevOps 與 Amazon SageMaker AI，建立跨雲端 ML 工作流程。它使用 Azure for CI/CD 流程和 SageMaker AI for ML 模型訓練和部署。它概述了透過模型建置和部署取得資料 （來自 Amazon S3、Snowflake 和 Azure Data Lake 等來源） 的程序。主要元件包括用於模型建置和部署、資料準備、基礎設施管理的 CI/CD 管道，以及用於訓練和微調、評估和部署 ML 模型的 Amazon SageMaker AI。此架構旨在跨雲端平台提供高效、自動化和可擴展的 ML 工作流程。

![\[使用 Azure Devops 和 SageMaker 的 MLOps 工作流程架構圖。 SageMaker\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/95fdf414-e561-4a93-9628-b41db39a577e/images/84ddcc36-54ef-473e-875f-154fae18cb13.png)


架構包含下列元件：

1. 資料科學家在開發帳戶中執行 ML 實驗，透過使用各種資料來源探索 ML 使用案例的不同方法。資料科學家執行單元測試和試驗，並追蹤他們的實驗，他們可以將 [Amazon SageMaker AI 與 MLflow](https://docs.aws.amazon.com/sagemaker/latest/dg/mlflow.html) 搭配使用。在生成式 AI 模型開發中，資料科學家從 Amazon SageMaker AI JumpStart 模型中微調基礎模型。在模型評估之後，資料科學家會將程式碼推送並合併到託管在 Azure DevOps 上的模型建置儲存庫。此儲存庫包含多步驟模型建置管道的程式碼。

1. 在 Azure DevOps 上，提供持續整合 (CI) 的模型建置管道可以在程式碼合併至主要分支時自動或手動啟動。在自動化帳戶中，這會啟用 SageMaker AI 管道，以根據準確性進行資料預先處理、模型訓練和微調、模型評估和條件式模型註冊。

1. 自動化帳戶是跨 ML 平台的中央帳戶，可託管 ML 環境 (Amazon ECR)、模型 (Amazon S3)、模型中繼資料 (SageMaker AI Model Registry)、功能 (SageMaker AI Feature Store)、自動化管道 (SageMaker AI Pipelines) 和 ML 日誌洞察 (CloudWatch)。對於生成式 AI 工作負載，您可能需要對下游應用程式中的提示進行額外的評估。提示管理應用程式有助於簡化和自動化程序。此帳戶允許 ML 資產的可重複使用性，並強制執行最佳實務來加速 ML 使用案例的交付。

1. 最新的模型版本會新增至 SageMaker AI 模型登錄檔以供檢閱。它會追蹤模型版本和個別成品 （系列和中繼資料）。它也會管理模型的狀態 （核准、拒絕或待定），並管理下游部署的 版本。

1. 在模型登錄檔中經過訓練的模型透過 Studio 界面或 API 呼叫核准後，事件可以分派至 Amazon EventBridge。EventBridge 會在 Azure DevOps 上啟動模型部署管道。

1. 模型部署管道提供持續部署 (CD)，可從模型部署儲存庫檢查來源。來源包含程式碼、模型部署的組態，以及品質基準測試的測試指令碼。模型部署管道可以根據您的推論類型量身打造。

1. 質量控制檢查後，模型部署管道會將模型部署到預備帳戶。預備帳戶是生產帳戶的副本，用於整合測試和評估。對於批次轉換，模型部署管道可以自動更新批次推論程序，以使用最新核准的模型版本。對於即時、無伺服器或非同步推論，它會設定或更新個別模型端點。

1. 在預備帳戶中成功測試後，可以透過模型部署管道手動核准，將模型部署到生產帳戶。此管道會在**部署至生產步驟中佈建生產**端點，包括模型監控和資料意見回饋機制。

1. 模型進入生產環境後，請使用 SageMaker AI Model Monitor 和 SageMaker AI Clarify 等工具來識別偏差、偵測偏離，並持續監控模型的效能。

**自動化和擴展**

使用基礎設施做為程式碼 (IaC) 自動部署到多個帳戶和環境。透過自動化設定 MLOps 工作流程的程序，可以區分 ML 團隊在不同專案中使用的環境。 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 會將基礎設施視為程式碼，協助您建立、佈建和管理 AWS 資源。

## 工具
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-tools"></a>

**AWS 服務**
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 是一種受管 ML 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一種全受管的擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。在此模式中，Amazon S3 用於資料儲存，並與 SageMaker AI 整合，用於模型訓練和模型物件。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。在此模式中，Lambda 用於資料預處理和後製處理任務。
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。在此模式中，它會存放 SageMaker AI 用於訓練和部署環境的 Docker 容器。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。在此模式中，EventBridge 會協調事件驅動型或時間型工作流程，以啟動自動模型重新訓練或部署。
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。 在此模式中，它會用來為 SageMaker AI 端點建立面向外部的單一進入點。
+ 對於 RAG 應用程式，您可以使用 [Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) 和 [Amazon RDS for PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html) AWS 服務等 來存放向 LLM 提供內部資料的向量內嵌。

**其他工具**
+ [Azure DevOps](https://learn.microsoft.com/en-us/azure/devops/user-guide/what-is-azure-devops) 可協助您管理 CI/CD 管道，並促進程式碼建置、測試和部署。
+ [Azure Data Lake Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction) 或 [Snowflake](https://docs.snowflake.com/en/) 是 ML 模型訓練資料的可能第三方來源。
+ [Pinecone](https://docs.pinecone.io/home)、[Milvus](https://milvus.io/docs/overview.md) 或 [ChromaDB](https://docs.trychroma.com/) 是儲存向量內嵌的可能第三方向量資料庫。

## 最佳實務
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-best-practices"></a>

在實作此多雲端 MLOps 工作流程的任何元件之前，請完成下列活動：
+ 定義並了解機器學習工作流程和支援它所需的工具。不同的使用案例需要不同的工作流程和元件。例如，功能存放區在個人化使用案例中可能需要重複使用功能和低延遲推論，但其他使用案例可能不需要。需要了解資料科學團隊的目標工作流程、使用案例要求和偏好的協作方法，才能成功自訂架構。
+ 為架構的每個元件建立明確的責任分離。將資料儲存分散到 Azure Data Lake Storage、Snowflake 和 Amazon S3 可能會增加複雜性和成本。如果可能，請選擇一致的儲存機制。同樣地，請避免使用 Azure 和 AWS DevOps 服務的組合，或 Azure 和 AWS ML 服務的組合。
+ 選擇一或多個現有模型和資料集，以執行 MLOps 工作流程的end-to-end測試。測試成品應反映資料科學團隊在平台進入生產環境時所開發的實際使用案例。

## 史詩
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-epics"></a>

### 設計您的 MLOps 架構
<a name="design-your-mlops-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 識別資料來源。 | 根據目前和未來的使用案例、可用的資料來源和資料類型 （例如機密資料），記錄需要與 MLOps 平台整合的資料來源。資料可以存放在 Amazon S3、Azure Data Lake Storage、Snowflake 或其他來源。對於生成式 AI 工作負載，資料也可能包含基於所產生回應的知識庫。此資料會以向量內嵌形式存放在向量資料庫中。建立整合這些來源與平台的計劃，並保護對正確資源的存取。 | 資料工程師、資料科學家、雲端架構師 | 
| 選擇適用的服務。 | 根據資料科學團隊所需的工作流程、適用的資料來源和現有的雲端架構，新增或移除服務，以自訂架構。例如，資料工程師和資料科學家可能會在 SageMaker AI AWS Glue或 Amazon EMR 中執行資料預先處理和特徵工程。不太可能需要這三種服務。 | AWS 管理員、資料工程師、資料科學家、ML 工程師 | 
| 分析安全需求。 | 收集並記錄安全需求。這包括判斷：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops.html)如需保護生成式 AI 工作負載的詳細資訊，請參閱[保護生成式 AI：生成式 AI 安全範圍矩陣簡介 ](https://aws.amazon.com/blogs/security/securing-generative-ai-an-introduction-to-the-generative-ai-security-scoping-matrix/)(AWS 部落格文章）。 | AWS 管理員、雲端架構師 | 

### 設定 AWS Organizations
<a name="set-up-aolong"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 AWS Organizations。 | 在根 AWS Organizations 目錄上設定 AWS 帳戶。這可協助您管理在多帳戶 MLOps 策略中建立的後續帳戶。如需詳細資訊，請參閱 [AWS Organizations 文件](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)。 | AWS 管理員 | 

### 設定開發環境和版本控制
<a name="set-up-the-development-environment-and-versioning"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 AWS 開發帳戶。 | 建立 AWS 帳戶 ，讓資料工程師和資料科學家具有實驗和建立 ML 模型的許可。如需說明，請參閱 AWS Organizations 文件中的[在組織中建立成員帳戶](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html)。 | AWS 管理員 | 
| 建立模型建置儲存庫。 | 在 Azure 中建立 Git 儲存庫，資料科學家可以在實驗階段完成後推送其模型建置和部署程式碼。如需說明，請參閱 Azure DevOps 文件中的[設定 Git 儲存庫](https://learn.microsoft.com/en-us/devops/develop/git/set-up-a-git-repository)。 | DevOps 工程師、ML 工程師 | 
| 建立模型部署儲存庫。 | 在 Azure 中建立 Git 儲存庫，以存放標準部署程式碼和範本。它應該包含組織使用的每個部署選項的程式碼，如設計階段中所識別。例如，它應該包含即時端點、非同步端點、無伺服器推論或批次轉換。如需說明，請參閱 Azure DevOps 文件中的[設定 Git 儲存庫](https://learn.microsoft.com/en-us/devops/develop/git/set-up-a-git-repository)。 | DevOps 工程師、ML 工程師 | 
| 建立 Amazon ECR 儲存庫。 | 設定 Amazon ECR 儲存庫，將核准的 ML 環境儲存為 Docker 影像。允許資料科學家和 ML 工程師定義新的環境。如需說明，請參閱 Amazon ECR 文件中的[建立私有儲存庫](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)。 | ML 工程師 | 
| 設定 SageMaker AI Studio。 | 根據先前定義的安全需求、偏好的資料科學工具 （例如 MLflow) 和偏好的整合式開發環境 (IDE)，在開發帳戶上設定 SageMaker AI Studio。使用生命週期組態來自動化關鍵功能的安裝，並為資料科學家建立統一的開發環境。如需詳細資訊，請參閱 [SageMaker AI 文件中的 Amazon SageMaker AI Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html) 和 [MLflow 追蹤伺服器](https://docs.aws.amazon.com/sagemaker/latest/dg/mlflow.html)。 SageMaker  | 資料科學家、ML 工程師、Prompt 工程師 | 

### 整合 CI/CD 管道
<a name="integrate-ci-cd-pipelines"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立自動化帳戶。 | 建立自動化管道和任務執行 AWS 帳戶 所在的 。您可以讓資料科學團隊讀取此帳戶的存取權。如需說明，請參閱 AWS Organizations 文件中的[在組織中建立成員帳戶](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html)。 | AWS 管理員 | 
| 設定模型登錄檔。 | 在自動化帳戶中設定 SageMaker AI 模型登錄檔。此登錄檔會存放 ML 模型的中繼資料，並協助特定資料科學家或團隊核准或拒絕模型。如需詳細資訊，請參閱 SageMaker AI 文件中的[使用模型登錄檔註冊和部署模型](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html)。 | ML 工程師 | 
| 建立模型建置管道。 | 在 Azure 中建立 CI/CD 管道，此管道會在程式碼推送至模型建置儲存庫時手動或自動啟動。管道應該檢查原始程式碼，並在自動化帳戶中建立或更新 SageMaker AI 管道。管道應將新模型新增至模型登錄檔。如需建立管道的詳細資訊，請參閱 [Azure Pipelines 文件](https://learn.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines)。 | DevOps 工程師、ML 工程師 | 

### 建置部署堆疊
<a name="build-the-deployment-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 AWS 預備和部署帳戶。 |  AWS 帳戶 為 ML 模型的預備和部署建立 。這些帳戶應該完全相同，以便在移至生產環境之前，允許在預備階段中準確測試模型。您可以讓資料科學團隊讀取臨時帳戶。如需說明，請參閱 AWS Organizations 文件[中的在組織中建立成員帳戶](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_create.html)。 | AWS 管理員 | 
| 設定 S3 儲存貯體以進行模型監控。 | 如果您想要為模型部署管道建立的已部署模型啟用模型監控，請完成此步驟。建立 Amazon S3 儲存貯體以存放輸入和輸出資料。如需建立 S3 儲存貯體的詳細資訊，請參閱 Amazon S3 文件中的[建立儲存貯體](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。設定跨帳戶許可，讓自動化模型監控任務在自動化帳戶中執行。如需詳細資訊，請參閱 SageMaker AI 文件中的[監控資料和模型品質](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html)。 | ML 工程師 | 
| 建立模型部署管道。 | 在 Azure 中建立 CI/CD 管道，該管道會在模型註冊表中核准模型時開始。管道應檢查原始程式碼和模型成品、建置基礎設施範本以在預備和生產帳戶中部署模型、在預備帳戶中部署模型、執行自動化測試、等待手動核准，以及將核准的模型部署到生產帳戶中。如需建立管道的詳細資訊，請參閱 [Azure Pipelines 文件](https://learn.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines)。 | DevOps 工程師、ML 工程師 | 

### （選用） 自動化 ML 環境基礎設施
<a name="optional-automate-ml-environment-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 組建 AWS CDK 或 CloudFormation 範本。 | 為所有需要自動部署的環境定義 AWS Cloud Development Kit (AWS CDK) 或 AWS CloudFormation 範本。這可能包括開發環境、自動化環境，以及預備和部署環境。如需詳細資訊，請參閱 [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html)和 [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 文件。 | AWS DevOps | 
| 建立 基礎設施管道。 | 在 Azure 中為基礎設施部署建立 CI/CD 管道。管理員可以啟動此管道來建立新的 ， AWS 帳戶 並設定 ML 團隊所需的環境。 | DevOps 工程師 | 

## 疑難排解
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| **監控不足和偏離偵測 **– 監控不足可能會導致錯過模型效能問題或資料偏離的偵測。 | 使用 Amazon CloudWatch、SageMaker AI Model Monitor 和 SageMaker AI Clarify 等工具強化監控架構。針對已識別的問題設定立即動作的提醒。 | 
| **CI 管道觸發錯誤 **– 由於組態錯誤，可能不會在程式碼合併時觸發 Azure DevOps 中的 CI 管道。** ** | 檢查 Azure DevOps 專案設定，以確保 Webhook 已正確設定並指向正確的 SageMaker AI 端點。 | 
| **控管 **–** **中央自動化帳戶可能無法跨 ML 平台強制執行最佳實務，導致工作流程不一致。 | 稽核自動化帳戶設定，確保所有 ML 環境和模型都符合預先定義的最佳實務和政策。 | 
| **模型登錄檔核准延遲 – **當檢查和核准模型有延遲時會發生這種情況，因為人員需要一些時間來檢閱模型，或是因為技術問題。 | 實作通知系統，以提醒利益相關者待核准的模型，並簡化審核程序。 | 
| **模型部署事件失敗 **– 傳送至啟動模型部署管道** **的事件可能會失敗，導致部署延遲。 | 確認 Amazon EventBridge 具有正確的許可和事件模式，以成功叫用 Azure DevOps 管道。 | 
| **生產部署瓶頸 **– ** **手動核准程序可能會產生瓶頸，進而延遲模型的生產部署。 | 最佳化模型部署管道中的核准工作流程，促進及時審核和清晰的溝通管道。 | 

## 相關資源
<a name="build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops-resources"></a>

**AWS 文件**
+ [Amazon SageMaker AI 文件](https://docs.aws.amazon.com/sagemaker/)
+ [Machine Learning Lens](https://docs.aws.amazon.com/wellarchitected/latest/machine-learning-lens/machine-learning-lens.html) (AWS Well Architected Framework)
+ [規劃成功的 MLOps](https://docs.aws.amazon.com/prescriptive-guidance/latest/ml-operations-planning/welcome.html) (AWS 方案指引）

**其他 AWS 資源**
+ [使用 Amazon SageMaker AI 的企業 MLOps 基礎藍圖](https://aws.amazon.com/blogs/machine-learning/mlops-foundation-roadmap-for-enterprises-with-amazon-sagemaker/) (AWS 部落格文章）
+ [AWS Summit ANZ 2022 - End-to-end MLOps ](https://www.youtube.com/watch?v=UnAN35gu3Rw)(YouTube 影片）
+ [FMOps/LLMOps：操作生成式 AI 和 MLOps 的差異](https://aws.amazon.com/blogs/machine-learning/fmops-llmops-operationalize-generative-ai-and-differences-with-mlops/) (AWS 部落格文章）
+ [使用 Amazon SageMaker AI Clarify 和 MLOps 服務大規模操作化 LLM 評估](https://aws.amazon.com/blogs/machine-learning/operationalize-llm-evaluation-at-scale-using-amazon-sagemaker-clarify-and-mlops-services/) (AWS 部落格文章）
+ [向量資料庫在生成式 AI 應用程式中的角色 ](https://aws.amazon.com/blogs/database/the-role-of-vector-datastores-in-generative-ai-applications/)(AWS 部落格文章）

**Azure 文件**
+ [Azure DevOps 文件](https://learn.microsoft.com/en-us/azure/devops/user-guide/what-is-azure-devops)
+ [Azure 管道文件](https://learn.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines)

# 使用 在 Amazon Bedrock 中設定模型調用記錄 AWS CloudFormation
<a name="configure-bedrock-invocation-logging-cloudformation"></a>

*Vikramaditya Bhatnagar，Amazon Web Services*

## 總結
<a name="configure-bedrock-invocation-logging-cloudformation-summary"></a>

您可以設定 Amazon Bedrock 為 中的所有模型調用收集調用日誌、模型輸入資料和模型輸出資料 AWS 帳戶。這是使用 Amazon Bedrock 建置強大生成式 AI 應用程式的[最佳實務](https://aws.amazon.com/blogs/machine-learning/best-practices-for-building-robust-generative-ai-applications-with-amazon-bedrock-agents-part-2/)。您可以將模型調用日誌存放在 Amazon CloudWatch Logs 日誌群組、Amazon Simple Storage Service (Amazon S3) 儲存貯體或兩者中。在 CloudWatch Logs 中擁有日誌資料可協助您建立自訂指標篩選條件、警示和儀表板。Amazon S3 非常適合用於跨資料複寫， AWS 區域 或用於長期儲存，這取決於您組織的政策。

此模式提供範例 AWS CloudFormation 範本，使用基礎設施做為程式碼 (IaC) 方法來設定 Amazon Bedrock 的模型調用記錄。範本會在 CloudWatch Logs 和 Amazon S3 中設定日誌儲存。

## 先決條件和限制
<a name="configure-bedrock-invocation-logging-cloudformation-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 下列許可：
  + 建立 CloudFormation 堆疊的[許可](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html) 
  + 存取 Amazon Bedrock [的許可](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html#security-iam-awsmanpol-updates) 
  + 建立和存取 Amazon S3 儲存貯體的[許可](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-policies-s3.html) 
  + 建立和存取 CloudWatch Logs 日誌群組的[許可](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-identity-based-access-control-cwl.html) 
  + 建立和存取 AWS Lambda 函數[的許可](https://docs.aws.amazon.com/lambda/latest/dg/security-iam-awsmanpol.html) 
  + 建立和存取 AWS Key Management Service (AWS KMS) 金鑰[的許可](https://docs.aws.amazon.com/kms/latest/developerguide/customer-managed-policies.html) 

**限制**

此模式會將模型調用記錄到 CloudWatch Logs 和 Amazon S3。它不支援僅選擇這兩個服務之一。

## Architecture
<a name="configure-bedrock-invocation-logging-cloudformation-architecture"></a>

**目標架構**

CloudFormation 範本會在您的目標中佈建下列資源 AWS 帳戶：
+ 用於儲存模型調用日誌的 CloudWatch Logs 日誌群組
+ 用於儲存模型調用日誌的 Amazon S3 儲存貯體和對應的儲存貯體政策
+ Amazon S3 儲存貯體，用於存放伺服器端存取日誌和對應的儲存貯體政策
+ 在 Amazon Bedrock 中設定記錄設定的 AWS Lambda 函數
+  AWS KMS key 和對應的金鑰別名
+ Amazon Bedrock 的 AWS Identity and Access Management (IAM) 服務角色

下圖顯示在您部署與此模式相關聯的 CloudFormation 堆疊後，如何存放叫用日誌。當基礎模型交付文字、影像、影片或內嵌資料時，Amazon Bedrock 會發佈日誌資料。如圖所示，Amazon S3 儲存貯體和 CloudWatch Logs 日誌群組會使用 加密 AWS KMS key。

![\[記錄 Amazon Bedrock 基礎模型調用的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/a55e7495-ec84-4d41-886e-5c37b37aac67/images/a958d52f-9072-40af-80cb-360f6c1c7fd5.png)


該圖顯示以下工作流程：

1. 使用者向 Amazon Bedrock 中的基礎模型提交查詢。

1. Amazon Bedrock 擔任 IAM 服務角色。

1. Amazon Bedrock 會產生日誌資料，並將其存放在 CloudWatch Logs 日誌群組和 Amazon S3 儲存貯體中。

1. 如果使用者讀取、上傳或刪除 Amazon S3 儲存貯體中包含模型叫用日誌的任何檔案，這些活動會記錄在另一個 Amazon S3 儲存貯體中做為伺服器端存取日誌。

**自動化和擴展**

若要擴展此解決方案，您可以將 CloudFormation 範本部署為堆疊設定為多個 AWS 區域 和 AWS 帳戶。如需詳細資訊，請參閱 CloudFormation 文件中的[使用 StackSets 管理跨帳戶和區域的堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)。

## 工具
<a name="configure-bedrock-invocation-logging-cloudformation-tools"></a>

**AWS 服務**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 公司和 Amazon 的高效能基礎模型 (FMs)。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) 可協助您集中所有系統、應用程式的日誌， AWS 服務 以便您可以監控日誌並將其安全地存檔。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可協助您建立和控制密碼編譯金鑰，以協助保護您的資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種物件儲存服務，可提供業界領先的可擴展性、資料可用性、安全性和效能。

**其他工具**
+ [Git](https://git-scm.com/docs) 是一種開放原始碼的分散式版本控制系統。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [enable-bedrock-logging-using-cloudformation](https://github.com/aws-samples/enable-bedrock-logging-using-cloudformation) 儲存庫中使用。

## 史詩
<a name="configure-bedrock-invocation-logging-cloudformation-epics"></a>

### 建立 CloudFormation 堆疊
<a name="create-the-cfnshort-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 下載 CloudFormation 範本。 | 從 GitHub 儲存庫下載 [CloudFormation 範本](https://github.com/aws-samples/enable-bedrock-logging-using-cloudformation/blob/main/enable-bedrock-logging-using-cloudformation.yaml)。 | 雲端架構師 | 
| 部署 範本。 | 在目標帳戶和區域中建立堆疊。在**參數**區段中，指定範本中定義的參數值。如需說明，請參閱 CloudFormation 文件中的[建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 | 雲端架構師 | 

### 測試解決方案
<a name="test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟用模型存取。 | 在 Amazon Bedrock 中，新增基礎模型的存取權。如需說明，請參閱 [Amazon Bedrock 文件中的新增或移除對 Amazon Bedrock 基礎模型的存取權](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html)。 | 雲端架構師 | 
| 執行範例提示。 | 在 Amazon Bedrock 遊樂場中，執行範例提示。如需說明，請參閱[《Amazon Bedrock 文件》中的使用遊樂場在主控台中產生回應](https://docs.aws.amazon.com/bedrock/latest/userguide/playgrounds.html)。 | 雲端架構師 | 
| 檢閱記錄組態。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/configure-bedrock-invocation-logging-cloudformation.html) | 雲端架構師 | 
| 檢閱 Amazon S3 儲存貯體。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/configure-bedrock-invocation-logging-cloudformation.html) | 雲端架構師 | 
| 檢閱日誌群組。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/configure-bedrock-invocation-logging-cloudformation.html) | 雲端架構師 | 

## 相關資源
<a name="configure-bedrock-invocation-logging-cloudformation-resources"></a>

**AWS 文件**
+ [存取 Amazon S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html)體 (Amazon S3 文件）
+ [建立和管理堆疊 ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html)(CloudFormation 文件）
+ [監控模型調用](https://docs.aws.amazon.com/bedrock/latest/userguide/model-invocation-logging.html) (Amazon Bedrock 文件）
+ [使用日誌群組和日誌串流 ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html)(CloudWatch Logs 文件）

**AWS 部落格文章**
+ [使用 Amazon Bedrock 和 Amazon CloudWatch 整合監控生成式 AI 應用程式](https://aws.amazon.com/blogs/mt/monitoring-generative-ai-applications-using-amazon-bedrock-and-amazon-cloudwatch-integration/)
+ [使用 Amazon Bedrock Agents 建置強大生成式 AI 應用程式的最佳實務 – 第 1 部分](https://aws.amazon.com/blogs/machine-learning/best-practices-for-building-robust-generative-ai-applications-with-amazon-bedrock-agents-part-1/)
+ [使用 Amazon Bedrock Agents 建置強大生成式 AI 應用程式的最佳實務 – 第 2 部分](https://aws.amazon.com/blogs/machine-learning/best-practices-for-building-robust-generative-ai-applications-with-amazon-bedrock-agents-part-2/)

# 為 SageMaker 建立自訂 Docker 容器映像，並將其用於 AWS Step Functions 中的模型訓練
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions"></a>

*Julia Bluszcz、Aubrey Oosthuizen、Mohan Gowda Purushothama、Neha Sharma 和 Mateusz Zaremba，Amazon Web Services*

## 總結
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-summary"></a>

此模式說明如何為 [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 建立 Docker 容器映像，並將其用於 [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 中的訓練模型。透過在容器中封裝自訂演算法，您可以在 SageMaker 環境中執行幾乎任何程式碼，無論程式設計語言、架構或相依性為何。

在提供的 [SageMaker 筆記本](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html)範例中，自訂 Docker 容器映像存放在 [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 中。Step Functions 接著會使用存放在 Amazon ECR 中的容器來執行 SageMaker 的 Python 處理指令碼。然後，容器會將模型匯出至 [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)。

## 先決條件和限制
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 具有 Amazon S3 [ S3 許可的 SageMaker AWS Identity and Access Management (IAM) 角色](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) 
+ [Step Functions 的 IAM 角色](https://sagemaker-examples.readthedocs.io/en/latest/step-functions-data-science-sdk/step_functions_mlworkflow_processing/step_functions_mlworkflow_scikit_learn_data_processing_and_model_evaluation.html#Create-an-Execution-Role-for-Step-Functions)
+ 熟悉 Python
+ 熟悉 Amazon SageMaker Python SDK
+ 熟悉 AWS Command Line Interface (AWS CLI)
+ 熟悉適用於 Python 的 AWS 開發套件 (Boto3)
+ 熟悉 Amazon ECR
+ 熟悉 Docker

**產品版本**
+ AWS Step Functions 資料科學 SDK 2.3.0 版
+ Amazon SageMaker Python SDK 2.78.0 版

## Architecture
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-architecture"></a>

下圖顯示為 SageMaker 建立 Docker 容器映像的範例工作流程，然後將其用於 Step Functions 中的訓練模型：

![\[為 SageMaker 建立 Docker 容器映像以用作 Step Functions 訓練模型的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/7857d57f-3077-4b06-8971-fb5846387693/images/37755e38-0bc4-4dd0-90c7-135d95b00053.png)


該圖顯示以下工作流程：

1. 資料科學家或 DevOps 工程師使用 Amazon SageMaker 筆記本來建立自訂 Docker 容器映像。

1. 資料科學家或 DevOps 工程師會將 Docker 容器映像存放在私有登錄檔中的 Amazon ECR 私有儲存庫中。

1. 資料科學家或 DevOps 工程師使用 Docker 容器在 Step Functions 工作流程中執行 Python SageMaker 處理任務。

**自動化和擴展**

此模式中的範例 SageMaker 筆記本使用`ml.m5.xlarge`筆記本執行個體類型。您可以變更執行個體類型以符合您的使用案例。如需 SageMaker 筆記本執行個體類型的詳細資訊，請參閱 [Amazon SageMaker 定價](https://aws.amazon.com/sagemaker/pricing/)。

## 工具
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-tools"></a>
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk) 是一個開放原始碼程式庫，用於在 SageMaker 上訓練和部署機器學習模型。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。
+ [AWS Step Functions 資料科學 Python SDK](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/index.html) 是一個開放原始碼程式庫，可協助您建立 Step Functions 工作流程來處理和發佈機器學習模型。

## 史詩
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-epics"></a>

### 建立自訂 Docker 容器映像並將其存放在 Amazon ECR 中
<a name="create-a-custom-docker-container-image-and-store-it-in-amazon-ecr"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Amazon ECR 並建立新的私有登錄檔。 | 如果您尚未設定 Amazon ECR，請遵循《Amazon ECR 使用者指南》中的[使用 Amazon ECR 設定中的指示來設定](https://docs.aws.amazon.com/AmazonECR/latest/userguide/get-set-up-for-amazon-ecr.html) Amazon ECR。 **每個 AWS 帳戶都會提供預設的私有 Amazon ECR 登錄檔。 | DevOps 工程師 | 
| 建立 Amazon ECR 私有儲存庫。 | 遵循《*Amazon ECR 使用者指南*》中[建立私有儲存庫](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)的指示。您建立的儲存庫是您存放自訂 Docker 容器映像的位置。 | DevOps 工程師 | 
| 建立 Dockerfile，其中包含執行 SageMaker 處理任務所需的規格。 | 建立 Dockerfile，其中包含透過設定 Dockerfile 執行 SageMaker 處理任務所需的規格。如需說明，請參閱《*Amazon SageMaker 開發人員指南*》中的[調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html)。如需 Dockerfiles 的詳細資訊，請參閱 [Docker 文件中的 Dockerfile 參考](https://docs.docker.com/engine/reference/builder/)。**建立 Dockerfile 的 Jupyter 筆記本程式碼儲存格範例***儲存格 1*<pre># Make docker folder<br />!mkdir -p docker</pre>*儲存格 2*<pre>%%writefile docker/Dockerfile<br /><br />FROM python:3.7-slim-buster<br /><br />RUN pip3 install pandas==0.25.3 scikit-learn==0.21.3<br />ENV PYTHONUNBUFFERED=TRUE<br /><br />ENTRYPOINT ["python3"]</pre> | DevOps 工程師 | 
| 建置 Docker 容器映像並將其推送至 Amazon ECR。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.html)如需詳細資訊，請參閱[在 GitHub 上建置您自己的演算法容器中的建置和註冊](https://sagemaker-examples.readthedocs.io/en/latest/advanced_functionality/scikit_bring_your_own/scikit_bring_your_own.html#Building-and-registering-the-container)*容器*。 GitHub**建置和註冊 Docker 映像的 Jupyter 筆記本程式碼儲存格範例**在執行下列儲存格之前，請確定您已建立 Dockerfile，並將其存放在名為 的目錄中`docker`。此外，請確定您已建立 Amazon ECR 儲存庫，並將第一個儲存格中的`ecr_repository`值取代為儲存庫的名稱。*儲存格 1*<pre>import boto3<br />tag = ':latest'<br />account_id = boto3.client('sts').get_caller_identity().get('Account')<br />region = boto3.Session().region_name<br />ecr_repository = 'byoc'<br /><br />image_uri = '{}.dkr.ecr.{}.amazonaws.com/{}'.format(account_id, region, ecr_repository + tag)</pre>*儲存格 2*<pre># Build docker image<br />!docker build -t $image_uri docker</pre>*儲存格 3*<pre># Authenticate to ECR<br />!aws ecr get-login-password --region {region} | docker login --username AWS --password-stdin {account_id}.dkr.ecr.{region}.amazonaws.com</pre>*儲存格 4*<pre># Push docker image<br />!docker push $image_uri</pre>您必須[向私有登錄檔驗證 Docker 用戶端](https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry_auth.html)，才能使用 `docker push`和 `docker pull`命令。這些命令會在登錄檔中的儲存庫中推送和提取映像。 | DevOps 工程師 | 

### 建立使用自訂 Docker 容器映像的 Step Functions 工作流程
<a name="create-a-step-functions-workflow-that-uses-your-custom-docker-container-image"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Python 指令碼，其中包含您的自訂處理和模型訓練邏輯。 | 撰寫要在資料處理指令碼中執行的自訂處理邏輯。然後，將其儲存為名為 的 Python 指令碼`training.py`。如需詳細資訊，請參閱[使用 GitHub 上的 SageMaker 指令碼模式使用您自己的模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-script-mode/sagemaker-script-mode.html)。 GitHub**包含自訂處理和模型訓練邏輯的範例 Python 指令碼**<pre>%%writefile training.py<br />from numpy import empty<br />import pandas as pd<br />import os<br />from sklearn import datasets, svm<br />from joblib import dump, load<br /><br /><br />if __name__ == '__main__':<br />    digits = datasets.load_digits()<br />    #create classifier object<br />    clf = svm.SVC(gamma=0.001, C=100.)<br />    <br />    #fit the model<br />    clf.fit(digits.data[:-1], digits.target[:-1])<br />    <br />    #model output in binary format<br />    output_path = os.path.join('/opt/ml/processing/model', "model.joblib")<br />    dump(clf, output_path)</pre> | 資料科學家 | 
| 建立 Step Functions 工作流程，其中包含您的 SageMaker Processing 任務作為其中一個步驟。 | 安裝並匯入 [AWS Step Functions 資料科學 SDK](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/readmelink.html)，並將 **training.py** 檔案上傳至 Amazon S3。然後，使用 [Amazon SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk) 在 Step Functions 中定義處理步驟。請確定您已在 AWS [帳戶中為 Step Functions 建立 IAM 執行角色](https://sagemaker-examples.readthedocs.io/en/latest/step-functions-data-science-sdk/step_functions_mlworkflow_processing/step_functions_mlworkflow_scikit_learn_data_processing_and_model_evaluation.html#Create-an-Execution-Role-for-Step-Functions)。**要上傳至 Amazon S3 的環境設定範例和自訂訓練指令碼**<pre>!pip install stepfunctions<br /><br />import boto3<br />import stepfunctions<br />import sagemaker<br />import datetime<br /><br />from stepfunctions import steps<br />from stepfunctions.inputs import ExecutionInput<br />from stepfunctions.steps import (<br />    Chain<br />)<br />from stepfunctions.workflow import Workflow<br />from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput<br /><br />sagemaker_session = sagemaker.Session()<br />bucket = sagemaker_session.default_bucket() <br />role = sagemaker.get_execution_role()<br />prefix = 'byoc-training-model'<br /><br /># See prerequisites section to create this role<br />workflow_execution_role = f"arn:aws:iam::{account_id}:role/AmazonSageMaker-StepFunctionsWorkflowExecutionRole"<br /><br />execution_input = ExecutionInput(<br />    schema={<br />        "PreprocessingJobName": str})<br /><br /><br />input_code = sagemaker_session.upload_data(<br />    "training.py",<br />    bucket=bucket,<br />    key_prefix="preprocessing.py",<br />)</pre>**使用自訂 Amazon ECR 映像和 Python 指令碼的 SageMaker 處理步驟定義範例**請務必使用 `execution_input` 參數來指定任務名稱。每次任務執行時， 參數的值必須是唯一的。此外，**training.py** 檔案的程式碼會做為 `input` 參數傳遞至 `ProcessingStep`，這表示它將在容器內複製。`ProcessingInput` 程式碼的目的地與 中的第二個引數相同`container_entrypoint`。<pre>script_processor = ScriptProcessor(command=['python3'],<br />                image_uri=image_uri,<br />                role=role,<br />                instance_count=1,<br />                instance_type='ml.m5.xlarge')<br /><br /><br />processing_step = steps.ProcessingStep(<br />    "training-step",<br />    processor=script_processor,<br />    job_name=execution_input["PreprocessingJobName"],<br />    inputs=[<br />        ProcessingInput(<br />            source=input_code,<br />            destination="/opt/ml/processing/input/code",<br />            input_name="code",<br />        ),<br />    ],<br />    outputs=[<br />        ProcessingOutput(<br />            source='/opt/ml/processing/model', <br />            destination="s3://{}/{}".format(bucket, prefix), <br />            output_name='byoc-example')<br />    ],<br />    container_entrypoint=["python3", "/opt/ml/processing/input/code/training.py"],<br />)</pre>**執行 SageMaker 處理任務的 Step Functions 工作流程範例**此範例工作流程僅包含 SageMaker 處理任務步驟，而非完整的 Step Functions 工作流程。如需完整的工作流程範例，請參閱 AWS Step Functions 資料科學 SDK 文件[中的 SageMaker 中的範例筆記本](https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/readmelink.html#example-notebooks-in-sagemaker)。<pre>workflow_graph = Chain([processing_step])<br /><br />workflow = Workflow(<br />    name="ProcessingWorkflow",<br />    definition=workflow_graph,<br />    role=workflow_execution_role<br />)<br /><br />workflow.create()<br /># Execute workflow<br />execution = workflow.execute(<br />    inputs={<br />        "PreprocessingJobName": str(datetime.datetime.now().strftime("%Y%m%d%H%M-%SS")),  # Each pre processing job (SageMaker processing job) requires a unique name,<br />    }<br />)<br />execution_output = execution.get_output(wait=True)</pre> | 資料科學家 | 

## 相關資源
<a name="create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions-resources"></a>
+ [程序資料](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html) (*Amazon SageMaker 開發人員指南*)
+ [調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html) (*Amazon SageMaker 開發人員指南*)

# 使用 Amazon Bedrock 代理程式，透過文字型提示在 Amazon EKS 中自動建立存取項目控制項
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks"></a>

*Keshav Ganesh 和 Sudhanshu Saurav，Amazon Web Services*

## 總結
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-summary"></a>

當多個團隊需要使用共用的 Amazon Elastic Kubernetes Service (Amazon EKS) 叢集時，組織在管理存取控制和資源佈建方面面臨挑戰。Amazon EKS 等受管 Kubernetes 服務可簡化叢集操作。不過，管理團隊存取和資源許可的管理開銷仍然複雜且耗時。

此模式顯示 Amazon Bedrock 代理程式如何協助您自動化 Amazon EKS 叢集存取管理。此自動化可讓開發團隊專注於其核心應用程式開發，而不是處理存取控制設定和管理。您可以自訂 Amazon Bedrock 代理程式，透過簡單的自然語言提示對各種任務執行動作。

透過使用 AWS Lambda 函數作為動作群組，Amazon Bedrock 代理程式可以處理任務，例如建立使用者存取項目和管理存取政策。此外，Amazon Bedrock 代理程式可以設定 Pod 身分關聯，允許存取叢集中執行之 Pod 的 AWS Identity and Access Management (IAM) 資源。使用此解決方案，組織可以使用簡單的文字提示來簡化其 Amazon EKS 叢集管理、減少手動額外負荷，並改善整體開發效率。

## 先決條件和限制
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶。
+ 建立部署程序的 IAM [角色和許可](https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html)。這包括存取 Amazon Bedrock 基礎模型 (FM)、建立 Lambda 函數，以及目標中任何其他必要資源的許可 AWS 帳戶。
+ 在作用中啟用 AWS 帳戶 對這些 Amazon Bedrock FMs[存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)：Amazon Titan Text Embeddings V2 和 Anthropic Claude 3 Haiku。
+ AWS Command Line Interface (AWS CLI) 2.9.11 版或更新版本，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。
+ eksctl 0.194.0 或更新版本，[已安裝](https://eksctl.io/installation/)。

**限制**
+ 可能需要訓練和文件，以協助確保這些技術的順利採用和有效使用。使用 Amazon Bedrock、Amazon EKS、Lambda、Amazon OpenSearch Service 和 [OpenAPI](https://www.openapis.org/what-is-openapi) 為開發人員和 DevOps 團隊帶來了重要的學習曲線。
+ 有些 AWS 服務 不適用於所有 AWS 區域。如需區域可用性，請參閱[依區域的 AWS 服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-architecture"></a>

下圖顯示此模式的工作流程和架構元件。

![\[使用 Amazon Bedrock 代理程式在 Amazon EKS 中建立存取控制的工作流程和元件。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/2c52b1ba-bbad-4a46-ab1e-10e69a0a66e7/images/c7981a86-f734-4c07-a2f7-63ad38b66ab6.png)


此解決方案會執行下列步驟：

1. 使用者透過提交提示或查詢來與 Amazon Bedrock 代理程式互動，做為代理程式處理和採取動作的輸入。

1. 根據提示，Amazon Bedrock 代理程式會檢查 OpenAPI 結構描述，以識別要鎖定的正確 API。如果 Amazon Bedrock 代理程式找到正確的 API 呼叫，請求會移至與實作這些動作的 Lambda 函數相關聯的動作群組。

1. 如果找不到相關 API，Amazon Bedrock 代理程式會查詢 OpenSearch 集合。OpenSearch 集合使用索引知識庫內容，這些內容來自包含 Amazon EKS 使用者指南的 Amazon S3 儲存貯體。 **

1. OpenSearch 集合會將相關內容資訊傳回給 Amazon Bedrock 代理程式。

1. 對於可行的請求 （符合 API 操作的請求），Amazon Bedrock 代理程式會在虛擬私有雲端 (VPC) 內執行，並觸發 Lambda 函數。

1. Lambda 函數會根據使用者在 Amazon EKS 叢集內的輸入來執行動作。

1. Lambda 程式碼的 Amazon S3 儲存貯體會存放為 Lambda 函數撰寫程式碼和邏輯的成品。

## 工具
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-tools"></a>

**AWS 服務**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 Kubernetes 控制平面或節點。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) 是一項受管服務，可協助您在 中部署、操作和擴展 OpenSearch 叢集 AWS 雲端。其集合功能可協助您整理資料，並建置 Amazon Bedrock 代理程式等 AI 助理可以使用的完整知識庫。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) 是一種命令列公用程式，用於在 Amazon EKS 上建立和管理 Kubernetes 叢集。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [eks-access-controls-bedrock-agent](https://github.com/aws-samples/eks-access-controls-bedrock-agent.git) 儲存庫中使用。

## 最佳實務
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-best-practices"></a>
+ 實作此模式時，請盡可能維持最高的安全性。確定 Amazon EKS 叢集是私有的、具有有限的存取許可，且所有資源都在虛擬私有雲端 (VPC) 內。如需詳細資訊，請參閱 Amazon EKS 文件中的[安全性最佳實務](https://docs.aws.amazon.com/eks/latest/best-practices/security.html)。
+ 盡可能使用 AWS KMS [客戶受管金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html)，並授予他們有限的存取許可。
+ 遵循最低權限原則，並授予執行任務所需的最低許可。如需詳細資訊，請參閱 IAM 文件中的[授予最低權限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。

## 史詩
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製此模式的儲存庫，請在本機工作站中執行下列命令：<pre>git clone https://github.com/aws-samples/eks-access-controls-bedrock-agent.git</pre> | AWS DevOps | 
| 取得 AWS 帳戶 ID。 | 若要取得 AWS 帳戶 ID，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)此命令會將您的 AWS 帳戶 ID 存放在 `AWS_ACCOUNT`變數中。 | AWS DevOps | 
| 建立 Lambda 程式碼的 S3 儲存貯體。 | 若要實作此解決方案，您必須建立三個提供不同用途的 Amazon S3 儲存貯體，如[架構](#using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-architecture)圖所示。S3 儲存貯體適用於 Lambda 程式碼、知識庫和 OpenAPI 結構描述。若要建立 Lambda 程式碼儲存貯體，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)套件命令會建立新的 CloudFormation 範本 (`eks-access-controls-template.yaml`)，其中包含：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 
| 建立知識庫的 S3 儲存貯體。 | 若要為知識庫建立 Amazon S3 儲存貯體，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 
| 建立 OpenAPI 結構描述的 S3 儲存貯體。 | 若要為 OpenAPI 結構描述建立 Amazon S3 儲存貯體，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 

### 部署 CloudFormation 堆疊
<a name="deploy-the-cfnshort-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 堆疊。 | 若要部署 CloudFormation 堆疊，請使用您先前建立`eks-access-controls-template.yaml`的 CloudFormation 範本檔案。如需更多詳細資訊，請參閱 [ CloudFormation 文件中的從 CloudFormation 主控台建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 CloudFormation 使用 CloudFormation 範本佈建 OpenSearch 索引大約需要 10 分鐘。建立堆疊之後，請記下 `VPC_ID`和 `PRIVATE_SUBNET ID`。 | AWS DevOps | 
| 建立 Amazon EKS 叢集。 | 若要在 VPC 內建立 Amazon EKS 叢集，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)預期的結果如下：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 

### 連接 Lambda 函數和 Amazon EKS 叢集
<a name="connect-the-lam-function-and-the-eks-cluster"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Amazon EKS 叢集和 Lambda 函數之間建立連線。 | 若要設定網路和 IAM 許可以允許 Lambda 函數與 Amazon EKS 叢集通訊，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 

### 測試解決方案
<a name="test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 測試 Amazon Bedrock 代理程式。 | 測試 Amazon Bedrock 代理程式之前，請務必執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)若要存取 Amazon Bedrock 代理程式，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html)您也可以要求代理程式對 EKS Pod 身分關聯執行動作。如需詳細資訊，請參閱《Amazon [EKS 文件》中的了解 EKS Pod Identity 如何授予 Pod 存取權 AWS 服務](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)。 | AWS DevOps | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要清除此模式建立的資源，請使用下列程序。等待每個刪除步驟完成，然後再繼續進行下一個步驟。此程序將永久刪除這些堆疊建立的所有資源。在繼續之前，請確定您已備份任何重要資料。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.html) | AWS DevOps | 

## 疑難排解
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 環境設定期間會傳回非零錯誤代碼。 | 執行任何命令來部署此解決方案時，請確認您使用的是正確的資料夾。如需詳細資訊，請參閱此模式儲存庫中的 [FIRST\$1DEPLOY.md](https://github.com/aws-samples/eks-access-controls-bedrock-agent/blob/main/FIRST_DEPLOY.md) 檔案。 | 
| Lambda 函數無法執行任務。 | 確定從 Lambda 函數到 Amazon EKS 叢集的連線設定正確。 | 
| 客服人員提示無法辨識 APIs。 | 重新部署解決方案。如需詳細資訊，請參閱此模式儲存庫中的 [RE\$1DEPLOY.md](https://github.com/aws-samples/eks-access-controls-bedrock-agent/blob/main/RE_DEPLOY.md) 檔案。 | 
| 堆疊無法刪除。 | 刪除堆疊的初始嘗試可能會失敗。此失敗可能是因為針對 OpenSearch 集合所建立之自訂資源的相依性問題，而該資源會執行知識庫的索引。若要刪除堆疊，請保留自訂資源以重試刪除操作。 | 

## 相關資源
<a name="using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks-resources"></a>

**AWS 部落格 **
+ [深入了解簡化的 Amazon EKS 存取控制](https://aws.amazon.com/blogs/containers/a-deep-dive-into-simplified-amazon-eks-access-management-controls/) 

**Amazon Bedrock 文件**
+ [使用 AI 代理器自動化應用程式中的任務](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) 
+ [Amazon Bedrock 代理程式的運作方式](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [測試代理程式行為並進行疑難排解](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-test.html)
+ [使用動作群組來定義代理程式要執行的動作](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html) 

**Amazon EKS 文件**
+ [了解存取控制在 Amazon EKS 中的運作方式](https://docs.aws.amazon.com/eks/latest/userguide/cluster-auth.html)

# AWS 使用 Terraform 和 Amazon Bedrock 在 上部署 RAG 使用案例
<a name="deploy-rag-use-case-on-aws"></a>

*Martin Maritsch、Nicolas Jacob Baer、Olivier Brique、Julian Ferdinand Grueber、Alice Morano 和 Nicola D Orazio、Amazon Web Services*

## 總結
<a name="deploy-rag-use-case-on-aws-summary"></a>

AWS 提供各種選項來建置支援[擷取增強生成 (RAG) 的](https://aws.amazon.com/what-is/retrieval-augmented-generation/)生成式 AI 使用案例。此模式為您提供以 LangChain 和 Amazon Aurora PostgreSQL 相容作為向量存放區之 RAG 型應用程式的解決方案。您可以使用 Terraform 直接將此解決方案部署到 ， AWS 帳戶 並實作下列簡單的 RAG 使用案例：

1. 使用者手動將檔案上傳至 Amazon Simple Storage Service (Amazon S3) 儲存貯體，例如 Microsoft Excel 檔案或 PDF 文件。（如需支援檔案類型的詳細資訊，請參閱[非結構化](https://docs.unstructured.io/open-source/core-functionality/partitioning)文件。)

1. 檔案的內容會解壓縮並內嵌至以無伺服器 Aurora PostgreSQL 相容為基礎的知識資料庫中，該資料庫支援近乎即時地將文件擷取至向量存放區。此方法可讓 RAG 模型存取和擷取低延遲之使用案例的相關資訊。

1. 當使用者與文字產生模型互動時，它會透過從先前上傳的檔案擷取相關內容擴增來增強互動。

模式使用 [Amazon Titan Text Embeddings v2](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html) 做為內嵌模型，而 [Anthropic Claude 3 Sonnet](https://aws.amazon.com/bedrock/claude/) 做為文字產生模型，兩者皆可在 Amazon Bedrock 上使用。

## 先決條件和限制
<a name="deploy-rag-use-case-on-aws-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶。
+ AWS Command Line Interface (AWS CLI) 已安裝並使用 設定 AWS 帳戶。如需安裝說明，請參閱 AWS CLI 文件[中的安裝或更新至最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) 。若要檢閱您的 AWS 登入資料和對帳戶的存取，請參閱 AWS CLI 文件中的[組態和登入資料檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。
+ 在 Amazon Bedrock 主控台中為所需的大型語言模型 (LLMs) 啟用的模型存取 AWS 帳戶。此模式需要下列 LLMs：
  + `amazon.titan-embed-text-v2:0`
  + `anthropic.claude-3-sonnet-20240229-v1:0`

**限制**
+ 此範例架構不包含使用向量資料庫進行程式設計問題回答的界面。如果您的使用案例需要 API，請考慮使用執行擷取和問答任務的 AWS Lambda 函數新增 [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide)。 
+ 此範例架構不包含已部署基礎設施的監控功能。如果您的使用案例需要監控，請考慮新增[AWS 監控服務](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/welcome.html)。
+ 如果您在短時間內將大量文件上傳至 Amazon S3 儲存貯體，Lambda 函數可能會遇到速率限制。作為解決方案，您可以將 Lambda 函數與 Amazon Simple Queue Service (Amazon SQS) 佇列分離，您可以在其中控制 Lambda 調用速率。
+ 有些 AWS 服務 完全無法使用 AWS 區域。如需區域可用性，請參閱[AWS 服務 依區域](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

**產品版本**
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 第 2 版或更新版本
+ [Docker](https://docs.docker.com/get-started/) 26.0.0 版或更新版本
+ [Poetry](https://pypi.org/project/poetry/) 1.7.1 版或更新版本
+ [Python](https://www.python.org/downloads/) 3.10 版或更新版本
+ [Terraform](https://developer.hashicorp.com/terraform/install) 1.8.4 版或更新版本

## Architecture
<a name="deploy-rag-use-case-on-aws-architecture"></a>

下圖顯示此模式的工作流程和架構元件。

![\[在 Amazon Bedrock 上使用 Aurora PostgreSQL 和 LLMs建立 RAG 型應用程式的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8f184945-7f17-4760-8806-6d0eaeef372a/images/3771b7a0-05bd-4eb3-ad5b-199e22f86184.png)


此圖表說明下列項目：

1. 在 Amazon S3 儲存貯體 中建立物件時`bedrock-rag-template-<account_id>`，[Amazon S3 通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html)會叫用 Lambda 函數 `data-ingestion-processor`。

1. Lambda 函數`data-ingestion-processor`是以存放在 Amazon Elastic Container Registry (Amazon ECR) 儲存庫 中的 Docker 映像為基礎`bedrock-rag-template`。

   函數使用 [LangChain S3FileLoader](https://python.langchain.com/v0.1/docs/integrations/document_loaders/aws_s3_file/) 將檔案讀取為 [LangChain 文件](https://api.python.langchain.com/en/v0.0.339/schema/langchain.schema.document.Document.html)。然後，[LangChain RecursiveCharacterTextSplitter](https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/recursive_text_splitter/) 會指定每個文件區塊，而 `CHUNK_SIZE`和 `CHUNK_OVERLAP`取決於 Amazon Titan Text Embedding V2 內嵌模型的最大字符大小。接著，Lambda 函數會叫用 Amazon Bedrock 上的內嵌模型，將區塊內嵌到數值向量表示法中。最後，這些向量會存放在 Aurora PostgreSQL 資料庫中。若要存取資料庫，Lambda 函數會先從中擷取使用者名稱和密碼 AWS Secrets Manager。

1. 在 Amazon SageMaker AI [筆記本執行個體](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html) 上`aws-sample-bedrock-rag-template`，使用者可以撰寫問題提示。此程式碼會在 Amazon Bedrock 上叫用 Claude 3，並將知識庫資訊新增至提示的內容。因此，Claude 3 會使用文件中的資訊提供回應。

此模式的聯網和安全性方法如下：
+ Lambda 函數`data-ingestion-processor`位於虛擬私有雲端 (VPC) 內的私有子網路中。由於 Lambda 函數的安全群組，因此不允許將流量傳送至公有網際網路。因此，流向 Amazon S3 和 Amazon Bedrock 的流量只會透過 VPC 端點路由。因此，流量不會周遊公有網際網路，這可減少延遲，並在聯網層級增加額外的安全層。
+ 適用時，所有資源和資料都會使用別名 的 AWS Key Management Service (AWS KMS) 金鑰進行加密`aws-sample/bedrock-rag-template`。

**自動化和擴展**

此模式使用 Terraform 將基礎設施從程式碼儲存庫部署到 AWS 帳戶。

## 工具
<a name="deploy-rag-use-case-on-aws-tools"></a>

**AWS 服務**
+ [Amazon Aurora PostgreSQL 相容版本](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraPostgreSQL.html)是完全受管的 ACID 相容關聯式資料庫引擎，可協助您設定、操作和擴展 PostgreSQL 部署。在此模式中，Aurora PostgreSQL 相容會使用 pgvector 外掛程式做為向量資料庫。
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。在此模式中，Amazon ECR 會託管 `data-ingestion-processor` Lambda 函數的 Docker 映像。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可協助您建立和控制密碼編譯金鑰，以協助保護您的資料。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。在此模式中，Lambda 會將資料擷取至向量存放區。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) 可協助您將程式碼中的硬式編碼憑證 (包括密碼) 取代為 Secrets Manager 的 API 呼叫，以便透過程式設計方法來擷取機密。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可協助您在已定義的虛擬網路中啟動 AWS 資源。此虛擬網路與您在自己的資料中心中操作的傳統網路相似，且具備使用 AWS可擴展基礎設施的優勢。VPC 包含子網路和路由表，以控制流量流程。

**其他工具**
+ [Docker](https://docs.docker.com/manuals/) 是一組平台即服務 (PaaS) 產品，可在作業系統層級使用虛擬化在容器中交付軟體。
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一種基礎設施即程式碼 (IaC) 工具，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。
+ [Poetry](https://pypi.org/project/poetry/) 是一種在 Python 中管理相依性和封裝的工具。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [terraform-rag-template-using-amazon-bedrock](https://github.com/aws-samples/terraform-rag-template-using-amazon-bedrock) 儲存庫中使用。

## 最佳實務
<a name="deploy-rag-use-case-on-aws-best-practices"></a>
+ 雖然此程式碼範例可以部署到任何 AWS 區域，但我們建議您使用美國東部 （維吉尼亞北部） – `us-east-1`或美國西部 （加利佛尼亞北部） – `us-west-1`。此建議是根據此模式發佈時 Amazon Bedrock 中基礎模型和內嵌模型的可用性。如需 中 up-to-date清單 AWS 區域，請參閱 Amazon Bedrock 文件中的 [模型支援 AWS 區域](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)。如需將此程式碼範例部署到其他區域的詳細資訊，請參閱[其他資訊](#deploy-rag-use-case-on-aws-additional)。
+ 此模式僅提供proof-of-concept(PoC) 或試行示範。如果您想要將程式碼帶入生產環境，請務必使用下列最佳實務：
  + 啟用 Amazon S3 的伺服器存取記錄。
  + 設定 Lambda 函數的[監控和提醒](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)。
  + 如果您的使用案例需要 API，請考慮使用執行擷取和問答任務的 Lambda 函數新增 Amazon API Gateway。
+ 遵循最低權限原則，並授予執行任務所需的最低許可。如需詳細資訊，請參閱 IAM 文件中的[授予最低權限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html)。

## 史詩
<a name="deploy-rag-use-case-on-aws-epics"></a>

### 在 中部署解決方案 AWS 帳戶
<a name="deploy-the-solution-in-an-aws-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製此模式隨附的 GitHub 儲存庫，請使用下列命令：<pre>git clone https://github.com/aws-samples/terraform-rag-template-using-amazon-bedrock</pre> | AWS DevOps | 
| 設定變數。 | 若要設定此模式的參數，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-rag-use-case-on-aws.html) | AWS DevOps | 
| 部署解決方案。 | 若要部署解決方案，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-rag-use-case-on-aws.html)基礎設施部署會在 VPC 內佈建 SageMaker AI 執行個體，並具有存取 Aurora PostgreSQL 資料庫的許可。 | AWS DevOps | 

### 測試解決方案
<a name="test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行示範。 | 先前的基礎設施部署成功後，請使用下列步驟在 Jupyter 筆記本中執行示範：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-rag-use-case-on-aws.html)Jupyter 筆記本會引導您完成下列程序：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-rag-use-case-on-aws.html) | 一般 AWS | 

### 清除基礎設施
<a name="clean-up-infrastucture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除基礎設施。 | 若要移除您不再需要的所有資源，請使用下列命令：<pre>terraform destroy -var-file=commons.tfvars</pre> | AWS DevOps | 

## 相關資源
<a name="deploy-rag-use-case-on-aws-resources"></a>

**AWS resources**
+ [使用 Python 建置 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ [基礎模型的推論參數](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)
+ [存取 Amazon Bedrock 基礎模型](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
+ [向量資料庫在生成式 AI 應用程式中的角色 ](https://aws.amazon.com/blogs/database/the-role-of-vector-datastores-in-generative-ai-applications/)(AWS 資料庫部落格）
+ [使用 Amazon Aurora PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraPostgreSQL.html)

**其他資源**
+ [pgvector 文件](https://github.com/pgvector/pgvector)

## 其他資訊
<a name="deploy-rag-use-case-on-aws-additional"></a>

**實作向量資料庫**

此模式使用 Aurora PostgreSQL 相容來實作 RAG 的向量資料庫。作為 Aurora PostgreSQL 的替代方案， 為 RAG AWS 提供其他功能和服務，例如 Amazon Bedrock 知識庫和 Amazon OpenSearch Service。您可以選擇最符合您特定需求的解決方案：
+ [Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) 提供分散式搜尋和分析引擎，您可以用來存放和查詢大量資料。
+ [Amazon Bedrock 知識庫](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)旨在建置和部署知識庫作為額外的抽象概念，以簡化 RAG 擷取和擷取程序。Amazon Bedrock 知識庫可以同時使用 Aurora PostgreSQL 和 Amazon OpenSearch Service。

**部署到其他 AWS 區域**

如[架構](#deploy-rag-use-case-on-aws-architecture)中所述，我們建議您使用美國東部 （維吉尼亞北部） – `us-east-1`或美國西部 `us-west-1` （加利佛尼亞北部） – 部署此程式碼範例。不過，有兩種可能的方法來將此程式碼範例部署到 `us-east-1`和 以外的區域`us-west-1`。您可以在 `commons.tfvars` 檔案中設定部署區域。對於跨區域基礎模型存取，請考慮下列選項：
+ **周遊公有網際網路** – 如果流量可以周遊公有網際網路，請將網際網路閘道新增至 VPC。然後，調整指派給 Lambda 函數`data-ingestion-processor`和 SageMaker AI 筆記本執行個體的安全群組，以允許輸出流量到公有網際網路。
+ **不周遊公有網際網路** – 若要將此範例部署到 `us-east-1`或 以外的任何區域`us-west-1`，請執行下列動作：

1. 在 `us-east-1`或 `us-west-1`區域中，建立額外的 VPC，包括 的 VPC 端點`bedrock-runtime`。

1. 使用 [VPC 對等互連或傳輸閘道至應用程式 VPC 來建立對等互連](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html)。 [https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)

1. 在 `bedrock-runtime` `us-east-1`或 之外的任何 Lambda 函數中設定 boto3 用戶端時`us-west-1`，請將 `bedrock-runtime` `us-east-1`或 us-west-1 中 VPC 端點的私有 DNS 名稱傳遞`endpoint_url`給 boto3 用戶端。

# 使用 Amazon SageMaker 中的推論管道，將預先處理邏輯部署到單一端點中的 ML 模型
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker"></a>

*Mohan Gowda Purushothama、Gabriel Rodriguez Garcia 和 Mateusz Zaremba，Amazon Web Services*

## 總結
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-summary"></a>

此模式說明如何在 Amazon SageMaker 中使用[推論管道，在單一端點中部署多個管道](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-pipelines.html)模型物件。管道模型物件代表不同的機器學習 (ML) 工作流程階段，例如預先處理、模型推論和後製處理。為了說明序列連線管道模型物件的部署，此模式示範如何根據內建於 [SageMaker 的線性學習程式演算法，部署預先處理 Scikit-learn](https://docs.aws.amazon.com/sagemaker/latest/dg/sklearn.html) 容器和迴歸模型。 [https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html](https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html) SageMaker 部署託管在 SageMaker 中的單一端點後方。

**注意**  
此模式中的部署會使用 ml.m4.2xlarge 執行個體類型。我們建議您使用符合您資料大小需求和工作流程複雜性的執行個體類型。如需更多資訊，請參閱 [Amazon SageMaker 定價](https://aws.amazon.com/sagemaker/pricing/)。此模式針對 [Scikit-learn 使用預先建置的 Docker 映像](https://docs.aws.amazon.com/sagemaker/latest/dg/pre-built-docker-containers-scikit-learn-spark.html)，但您可以使用自己的 Docker 容器，並將其整合到您的工作流程中。

## 先決條件和限制
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ [Python 3.9](https://www.python.org/downloads/release/python-390/)
+ [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/) 和 [Boto3 程式庫](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
+ 具有基本 SageMaker [許可](https://docs.aws.amazon.com/sagemaker/latest/dg/api-permissions-reference.html)和 Amazon Simple Storage Service (Amazon S3) 許可的 AWS Identity and Access Management (AWS IAM) [角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) [https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-policy-language-overview.html](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-policy-language-overview.html)

**產品版本**
+ [Amazon SageMaker Python SDK 2.49.2](https://sagemaker.readthedocs.io/en/v2.49.2/)

## Architecture
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-architecture"></a>

**目標技術堆疊**
+ Amazon Elastic Container Registry (Amazon ECR)
+ Amazon SageMaker
+ Amazon SageMaker Studio
+ Amazon Simple Storage Service (Amazon S3)
+ Amazon SageMaker 的[即時推論](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html)端點

**目標架構**

下圖顯示部署 Amazon SageMaker 管道模型物件的架構。

![\[部署 SageMaker 管道模型物件的架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/1105d51b-752f-46d7-962c-acef1fb3399f/images/12f06715-b1c2-4de0-b277-99ce87308152.png)


該圖顯示以下工作流程：

1. SageMaker 筆記本會部署管道模型。

1. S3 儲存貯體存放模型成品。

1. Amazon ECR 會從 S3 儲存貯體取得來源容器映像。

## 工具
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-tools"></a>

**AWS 工具**
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。
+ [Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) 是一項受管 ML 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。
+ [Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) 是適用於 ML 的 Web 型整合式開發環境 (IDE)，可讓您建置、訓練、偵錯、部署和監控 ML 模型。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**Code**

此模式的程式碼可在 GitHub [推論管道搭配 Scikit-learn 和線性學習程式](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-python-sdk/scikit_learn_inference_pipeline/Inference%20Pipeline%20with%20Scikit-learn%20and%20Linear%20Learner.ipynb)儲存庫中使用。

## 史詩
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-epics"></a>

### 準備資料集
<a name="prepare-the-dataset"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為您的迴歸任務準備資料集。 | 在 Amazon SageMaker Studio 中[開啟筆記本](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-create-open.html#notebooks-open)。若要匯入所有必要的程式庫並初始化您的工作環境，請在筆記本中使用下列範例程式碼：<pre>import sagemaker<br />from sagemaker import get_execution_role<br /><br />sagemaker_session = sagemaker.Session()<br /><br /># Get a SageMaker-compatible role used by this Notebook Instance.<br />role = get_execution_role()<br /><br /># S3 prefix<br />bucket = sagemaker_session.default_bucket()<br />prefix = "Scikit-LinearLearner-pipeline-abalone-example"</pre>若要下載範例資料集，請將下列程式碼新增至您的筆記本：<pre>! mkdir abalone_data<br />! aws s3 cp s3://sagemaker-sample-files/datasets/tabular/uci_abalone/abalone.csv ./abalone_data</pre>** **此模式中的範例使用 UCI Machine Learning 儲存庫中的[鮑魚資料集](https://archive.ics.uci.edu/ml/datasets/abalone)。 | 資料科學家 | 
| 將資料集上傳至 S3 儲存貯體。 | 在您先前準備資料集的筆記本中，新增下列程式碼，將範例資料上傳至 S3 儲存貯體：<pre>WORK_DIRECTORY = "abalone_data"<br /><br />train_input = sagemaker_session.upload_data(<br />    path="{}/{}".format(WORK_DIRECTORY, "abalone.csv"),<br />    bucket=bucket,<br />    key_prefix="{}/{}".format(prefix, "train"),<br />)</pre> | 資料科學家 | 

### 使用 SKLearn 建立資料預處理器
<a name="create-the-data-preprocessor-using-sklearn"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 準備 preprocessor.py 指令碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker.html) | 資料科學家 | 
| 建立 SKLearn 預處理器物件。 | 若要建立可納入最終推論管道的 SKLearn 預處理器物件 （稱為 SKLearn 估算器），請在 SageMaker 筆記本中執行下列程式碼：<pre>from sagemaker.sklearn.estimator import SKLearn<br /><br />FRAMEWORK_VERSION = "0.23-1"<br />script_path = "sklearn_abalone_featurizer.py"<br /><br />sklearn_preprocessor = SKLearn(<br />    entry_point=script_path,<br />    role=role,<br />    framework_version=FRAMEWORK_VERSION,<br />    instance_type="ml.c4.xlarge",<br />    sagemaker_session=sagemaker_session,<br />)<br />sklearn_preprocessor.fit({"train": train_input})</pre> | 資料科學家 | 
| 測試預處理器的推論。 | 若要確認您的預處理器已正確定義，請在 SageMaker 筆記本中輸入下列程式碼來啟動[批次轉換任務](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html)：<pre># Define a SKLearn Transformer from the trained SKLearn Estimator<br />transformer = sklearn_preprocessor.transformer(<br />    instance_count=1, instance_type="ml.m5.xlarge", assemble_with="Line", accept="text/csv"<br />)<br /><br /><br /># Preprocess training input<br />transformer.transform(train_input, content_type="text/csv")<br />print("Waiting for transform job: " + transformer.latest_transform_job.job_name)<br />transformer.wait()<br />preprocessed_train = transformer.output_path</pre> |  | 

### 建立機器學習模型
<a name="create-a-machine-learning-model"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立模型物件。 | 若要根據線性學習程式演算法建立模型物件，請在 SageMaker 筆記本中輸入下列程式碼：<pre>import boto3<br />from sagemaker.image_uris import retrieve<br /><br />ll_image = retrieve("linear-learner", boto3.Session().region_name)<br />s3_ll_output_key_prefix = "ll_training_output"<br />s3_ll_output_location = "s3://{}/{}/{}/{}".format(<br />    bucket, prefix, s3_ll_output_key_prefix, "ll_model"<br />)<br /><br />ll_estimator = sagemaker.estimator.Estimator(<br />    ll_image,<br />    role,<br />    instance_count=1,<br />    instance_type="ml.m4.2xlarge",<br />    volume_size=20,<br />    max_run=3600,<br />    input_mode="File",<br />    output_path=s3_ll_output_location,<br />    sagemaker_session=sagemaker_session,<br />)<br /><br />ll_estimator.set_hyperparameters(feature_dim=10, predictor_type="regressor", mini_batch_size=32)<br /><br />ll_train_data = sagemaker.inputs.TrainingInput(<br />    preprocessed_train,<br />    distribution="FullyReplicated",<br />    content_type="text/csv",<br />    s3_data_type="S3Prefix",<br />)<br /><br />data_channels = {"train": ll_train_data}<br />ll_estimator.fit(inputs=data_channels, logs=True)</pre>上述程式碼會從模型的公有 Amazon ECR 登錄檔擷取相關的 Amazon ECR Docker 影像、建立估算器物件，然後使用該物件來訓練迴歸模型。 | 資料科學家 | 

### 部署最終管道
<a name="deploy-the-final-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署管道模型。 | 若要建立管道模型物件 （即預處理器物件） 並部署物件，請在 SageMaker 筆記本中輸入下列程式碼：<pre>from sagemaker.model import Model<br />from sagemaker.pipeline import PipelineModel<br />import boto3<br />from time import gmtime, strftime<br /><br />timestamp_prefix = strftime("%Y-%m-%d-%H-%M-%S", gmtime())<br /><br />scikit_learn_inferencee_model = sklearn_preprocessor.create_model()<br />linear_learner_model = ll_estimator.create_model()<br /><br />model_name = "inference-pipeline-" + timestamp_prefix<br />endpoint_name = "inference-pipeline-ep-" + timestamp_prefix<br />sm_model = PipelineModel(<br />    name=model_name, role=role, models= [scikit_learn_inferencee_model, linear_learner_model]<br />)<br /><br />sm_model.deploy(initial_instance_count=1, instance_type="ml.c4.xlarge", endpoint_name=endpoint_name)</pre>您可以調整模型物件中使用的執行個體類型，以符合您的需求。 | 資料科學家 | 
| 測試推論。 | 若要確認端點是否正常運作，請在 SageMaker 筆記本中執行下列範例推論程式碼：<pre>from sagemaker.predictor import Predictor<br />from sagemaker.serializers import CSVSerializer<br /><br />payload = "M, 0.44, 0.365, 0.125, 0.516, 0.2155, 0.114, 0.155"<br />actual_rings = 10<br />predictor = Predictor(<br />    endpoint_name=endpoint_name, sagemaker_session=sagemaker_session, serializer=CSVSerializer()<br />)<br /><br />print(predictor.predict(payload))</pre> | 資料科學家 | 

## 相關資源
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-resources"></a>
+ [使用 Amazon SageMaker 推論管道和 Scikit-learn 進行預測之前，請先預先處理輸入資料](https://aws.amazon.com/blogs/machine-learning/preprocess-input-data-before-making-predictions-using-amazon-sagemaker-inference-pipelines-and-scikit-learn/) (AWS Machine Learning 部落格）
+ [使用 Amazon SageMaker (GitHub) 進行端對端Machine Learning ](https://github.com/aws-samples/amazon-sagemaker-build-train-deploy) GitHub

# 搭配 Kiro 和其他編碼助理使用 MCP 伺服器部署即時編碼安全驗證
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants"></a>

*Ivan Girardi 和 Iker Reina Fuente，Amazon Web Services*

## 摘要
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-summary"></a>

此模式說明如何實作模型內容通訊協定 (MCP) 伺服器，整合三種業界標準的安全性掃描工具，以提供全面的程式碼安全分析。伺服器可讓 AI 編碼助理 （例如 Kiro、Amazon Q Developer 和 Cline) 自動將程式碼片段和基礎設施掃描為程式碼 (IaC) 組態。透過這些掃描，編碼助理可協助識別安全漏洞、設定錯誤和違規。

在數百萬個程式碼片段上訓練的 AI 程式碼產生器會建立安全盲點，該訓練資料的安全性如何？ 此模式可在程式碼產生期間提供即時安全驗證，協助開發人員在程式碼過程中識別和了解潛在的安全問題。此方法可協助開發人員解決直接漏洞和來自相依性的繼承風險。透過彌補 AI 效率和安全合規之間的差距，此模式有助於安全採用 AI 驅動的開發工具。

此模式可協助組織透過 AI 輔助編碼工具增強其開發安全實務，提供跨多種程式設計語言和基礎設施定義的持續安全掃描功能。解決方案結合了下列工具的功能：
+ 用於掃描 IaC 檔案的 Checkov，包括 Terraform AWS CloudFormation和 Kubernetes 資訊清單
+ Semgrep 用於分析多種程式設計語言，例如 Python、JavaScript、Java 等
+ 專用 Python 安全性掃描的 Bandit 

此解決方案的主要功能包括下列項目：
+ Delta 掃描新的程式碼區段，降低運算開銷
+ 隔離的安全工具環境，防止跨工具污染
+ 與 AI 編碼助理 (Kiro、Amazon Q Developer、Cline 等） 無縫整合
+ 程式碼產生期間的即時安全意見回饋
+ 適用於組織合規的自訂掃描規則

模式為具有標準化回應格式的安全掃描提供統一界面，讓您更輕鬆地將安全檢查整合到開發工作流程中。模式使用 Python 和 MCP 架構來提供自動化安全意見回饋。此方法可協助開發人員在開發程序初期識別和解決安全問題，同時透過詳細的調查結果了解安全最佳實務。

## 先決條件和限制
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-prereqs"></a>

**先決條件**
+ 如果您想要使用其中一個編碼助理， AWS 帳戶 則具有使用 Kiro 或 Amazon Q Developer 之存取權的作用中
+ [已安裝](https://www.python.org/downloads/) Python 3.10 版或更新版本
+ `uv` 套件管理員[已安裝](https://docs.astral.sh/uv/getting-started/installation/)
+ 熟悉安全掃描工具和概念
+ 對 IaC 和應用程式安全性的基本了解

**限制**
+ Bandit 掃描僅限於 Python 檔案。
+ 即時掃描可能會影響大型程式碼基底的效能。
+ 工具特定的限制是以支援的檔案格式和語言為基礎。
+ 需要手動檢閱才能驗證安全性問題清單。
+ 安全掃描結果需要安全專業知識才能正確解譯。
+ 有些 AWS 服務 不適用於所有 AWS 區域。如需區域可用性，請參閱[AWS 依區域的服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

**產品版本**
+ Python 3.10 版或更新版本
+ Checkov 3.0.0 版或更新版本
+ Semgrep 1.45.0 版或更新版本
+ Bandit 1.7.5 版或更新版本
+ MCP【cli】 1.11.0 版或更新版本
+ Pydantic 1.10.0 版或更新版本
+ Loguru 0.6.0 版或更新版本

## Architecture
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-architecture"></a>

下圖顯示此解決方案的架構。

![\[AI 助理會將程式碼傳送至 MCP 安全掃描器伺服器，以路由至專用掃描器；掃描結果會傳送至開發人員。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/fa623544-4d54-48af-a4e4-9b6a0624e776/images/9c881f95-76d0-40f6-983e-d987fd2097b8.png)


該圖顯示以下工作流程：

1. 開發人員使用 AI 助理 （例如 Kiro、Cline、Amazon Q Developer 或 Roo Code) 來產生或分析程式碼。AI 助理會傳送程式碼以進行安全性掃描。

1. MCP 安全掃描器伺服器會透過將請求路由到適當的專用掃描器來處理請求：IaC 檔案的 Checkov、多個程式設計語言分析的 Semgrep，或 Python 特定安全性掃描的 Bandit。

1. 掃描器結果包含安全性調查結果、嚴重性等級、詳細說明和建議的修正，會透過 AI 助理傳回開發人員。

1. 建立持續的意見回饋迴圈，開發人員會在其中接收即時安全驗證，透過 AI 助理實現自動修正，並在開發期間提升安全最佳實務。

架構可降低下列常見的安全風險：
+ 命令注入
+ 提示注入
+ 路徑周遊
+ 相依性攻擊
+ 資源耗盡 

架構實作下列最佳實務，以降低這些常見的安全風險：
+ 所有使用者和 AI 模型輸入都會寫入暫存檔案。
+ 命令列界面 (CLI) 命令不會直接輸入。
+ 檔案系統存取僅限於暫時目錄和檔案。
+ 臨時檔案會自動清除。
+ 掃描回應已淨化。
+ 會強制執行限制程序功能的程序隔離。
+ 會記錄所有掃描活動。

**自動化和擴展**

模式透過下列功能支援自動化：
+ 與 AI 編碼助理整合，以進行自動程式碼掃描
+ 用於自動化處理的標準化 API 回應
+ 透過 MCP 組態檔案的組態
+ 支援批次處理多個檔案
+ 跨多種程式設計語言和 IaC 格式的可擴展掃描

掃描程序可以透過提供的 API 端點自動化：
+ `scan_with_checkov` 用於 IaC 掃描
+ `scan_with_semgrep` 適用於多語言程式碼掃描
+ `scan_with_bandit` 適用於 Python 特定掃描
+ `get_supported_formats` 用於格式驗證

擴充掃描工具時，請遵循本節先前所述的設計原則和最佳實務。另請參閱[最佳實務](#deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-best-practices)。

## 工具
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-tools"></a>

**AWS 服務**
+ [Kiro](https://aws.amazon.com/documentation-overview/kiro/) 是一種代理程式編碼服務，與開發人員一起將提示轉換為詳細規格，然後轉換為工作程式碼、文件和測試。Kiro 代理程式可協助開發人員解決具有挑戰性的問題，並自動化產生文件和單元測試等任務。
+ [Amazon Q Developer](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/what-is.html) 是採用生成式 AI 技術的對話式助理，可協助您了解、建置、擴展和操作 AWS 應用程式。

**其他工具**
+ [Bandit](https://bandit.readthedocs.io/en/latest/) 是一種專門的 Python 安全掃描器工具。它可偵測常見的 Python 安全問題，例如不安全的 函數、硬式編碼秘密和注入漏洞。Bandit 提供詳細的可信度和嚴重性評分。
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一種靜態程式碼分析工具，可檢查 IaC 的安全性和合規性設定錯誤。此外，Checkov 會偵測合規違規和安全最佳實務。
+ [Cline](https://cline.bot/) 是採用 AI 技術的編碼助理，可在 VS Code 中執行。
+ [Loguru](https://loguru.readthedocs.io/en/stable/) 是 Python 的資料驗證程式庫。
+ [模型內容通訊協定 (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) 是用於建置 AI 輔助開發工具的開放原始碼架構。
+ [Pydantic](https://docs.pydantic.dev/latest/) 是 Python 的資料驗證程式庫。
+ [Semgrep](https://semgrep.dev/docs/introduction) 會分析原始程式碼是否有安全漏洞和錯誤。它支援多種程式設計語言。Semgrep 使用以安全為重心的規則集進行全面分析。它提供詳細的可信度和嚴重性評分。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [MCP 安全掃描器：即時保護 AI 程式碼助理](https://github.com/aws-samples/sample-mcp-security-scanner)儲存庫中取得。儲存庫包含 MCP 伺服器實作、Kiro、Amazon Q Developer、Cline 等 MCP 組態的詳細資訊、組態範例和測試公用程式。

儲存庫結構包括：
+ `security_scanner_mcp_server/` - 主要伺服器實作
+ `docs/` - 文件和示範資料
+ `tests/` - 測試檔案
+ `mcp-config-example.json` - 範例 MCP 組態
+ `requirements.txt` - 專案相依性

## 最佳實務
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-best-practices"></a>

**安全性掃描實作**
+ 檢閱安全性調查結果，以驗證問題並排定優先順序。
+ 保持掃描工具 (Checkov、Semgrep 和 Bandit) 更新至最新版本。
+ 將此模式的 MCP 安全工具與其他安全措施和工具搭配使用。
+ 定期更新安全規則集和政策。

**組態管理**
+ 在官方版本控制來源中使用 MCP 組態檔案。
+ 記錄自訂規則和組態。

**整合**
+ 在開發週期的早期整合安全性掃描。
+ 在預先遞交勾點或持續整合和持續部署 (CI/CD) 管道中設定自動掃描。
+ 為您的環境設定適當的嚴重性閾值。
+ 建立明確的程序來處理安全問題清單。

**營運考量事項**
+ 監控掃描效能和資源用量。
+ 實作適當的錯誤處理和記錄。
+ 維護自訂組態的文件。
+ 建立檢閱和更新安全規則的程序。

此外，請記住下列最佳實務：
+ 一律在特定內容中驗證安全調查結果。
+ 將安全工具和相依性保持在最新狀態。
+ 使用多個安全工具進行全面涵蓋。
+ 遵循開發程序中的安全最佳實務。

## 史詩
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-epics"></a>

### (Kiro 使用者） 設定 MCP 安全掃描器伺服器
<a name="kiro-users-set-up-the-mcp-security-scanner-server"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 MCP 設定。 | 您可以使用 Kiro IDE，透過 （選項 1) 手動尋找組態檔案或 （選項 2) 在 Kiro 中編輯組態檔案。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html)<pre>{<br />  "mcpServers": {<br />    "security-scanner": {<br />      "command": "uvx",<br />      "args": [<br />        "--from",<br />        "git+https://github.com/aws-samples/sample-mcp-security-scanner.git@main",<br />        "security_scanner_mcp_server"<br />      ],<br />      "env": {<br />        "FASTMCP_LOG_LEVEL": "ERROR"<br />      },<br />      "disabled": false,<br />      "autoApprove": []<br />    }<br />  }<br />}</pre> | 應用程式開發人員 | 

### (Amazon Q Developer 使用者） 設定 MCP 安全掃描器伺服器
<a name="qdevlong-users-set-up-the-mcp-security-scanner-server"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 MCP 設定。 | 若要手動設定 MCP 設定，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html)<pre>{<br />  "mcpServers": {<br />    "security-scanner": {<br />      "command": "uvx",<br />      "args": [<br />        "--from",<br />        "git+https://github.com/aws-samples/sample-mcp-security-scanner.git@main",<br />        "security_scanner_mcp_server"<br />      ],<br />      "env": {<br />        "FASTMCP_LOG_LEVEL": "ERROR"<br />      }<br />    }<br />  }<br />}</pre> | 應用程式開發人員 | 

### (Cline 使用者） 設定 MCP 安全掃描器伺服器
<a name="cline-users-set-up-the-mcp-security-scanner-server"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 MCP 設定。 | 若要手動設定 MCP 設定，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html)<pre>{<br />  "mcpServers": {<br />    "security-scanner": {<br />      "command": "uvx",<br />      "args": [<br />        "--from",<br />        "git+https://github.com/aws-samples/sample-mcp-security-scanner.git@main",<br />        "security_scanner_mcp_server"<br />      ],<br />      "env": {<br />        "FASTMCP_LOG_LEVEL": "ERROR"<br />      },<br />      "disabled": false,<br />      "autoApprove": []<br />    }<br />  }<br />}</pre> | 應用程式開發人員 | 

### 使用 Python 和 Bandit 的程式碼分析範例
<a name="example-of-code-analysis-using-python-and-bandit"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行程式碼分析。 | 若要使用 Python 和 Bandit 執行程式碼分析，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 應用程式開發人員 | 

### 使用 Terraform 和 Checkov 的程式碼分析範例
<a name="example-of-code-analysis-using-terraform-and-checkov"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行程式碼分析。 | 若要使用 Terraform 和 Checkov 執行程式碼分析，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 應用程式開發人員 | 

### 進階掃描功能的範例
<a name="example-of-advanced-scanning-capabilities"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行目標掃描。 | 以下是可用來執行目標掃描的請求範例：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 應用程式開發人員 | 
| 使用安全掃描與程式碼產生。 | 若要使用程式碼產生迴圈來解決安全性問題清單，請使用下列步驟 （此範例使用 Kiro 作為編碼助理）：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 應用程式開發人員 | 

## 疑難排解
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 環境設定問題 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 
| 掃描器問題 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 
| 整合問題 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 
| 其他支援 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.html) | 

## 相關資源
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-resources"></a>

**AWS 文件**
+ [基礎設施即程式碼](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html) (AWS 白皮書*介紹 DevOps on AWS*)

**其他 AWS 資源**
+ [安全性、身分與合規的最佳實務](https://aws.amazon.com/architecture/security-identity-compliance/)

**其他資源**
+ [Bandit 文件](https://aws.amazon.com/architecture/security-identity-compliance/)
+ [Checkov 文件](https://aws.amazon.com/architecture/security-identity-compliance/)
+ [模型內容通訊協定 (MCP) 文件](https://aws.amazon.com/architecture/security-identity-compliance/)
+ [OWASP 安全編碼實務](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/) (OWASP Foundation 網站）
+ [Semgrep 文件](https://aws.amazon.com/architecture/security-identity-compliance/)

## 其他資訊
<a name="deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants-additional"></a>

**啟用自動核准的範例 MCP 組態**

如果未`autoApprove`設定，使用者必須授予許可，才能將程式碼傳送至 MCP 安全伺服器進行掃描。設定 `autoApprove` 時，程式碼助理無需使用者核准即可叫用工具。這些工具會在機器本機執行，不會傳送任何資料，而且只會執行程式碼掃描。

下列組態可自動執行所有安全掃描函數：

```
{
  "mcpServers": {
    "security-scanner": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/aws-samples/sample-mcp-security-scanner.git@main",
        "security_scanner_mcp_server"
      ],
      "env": {
        "FASTMCP_LOG_LEVEL": "ERROR"
      },
      "disabled": false,
      "autoApprove": [
        "scan_with_checkov",
        "scan_with_semgrep", 
        "scan_with_bandit",
        "get_supported_formats"
      ]
    }
  }
}
```

若要啟用偵錯記錄，請將 `"FASTMCP_LOG_LEVEL"`設定為 `"DEBUG"`。

**安全性掃描工具支援的檔案格式**

此解決方案中的每個安全掃描工具都支援下列檔案格式：

*Checkov (IaC)*
+ Terraform – .tf、.tfvars、.tfstate
+ CloudFormation – .yaml、.yml、.json、.template
+ Kubernetes – .yaml、.yml
+ Dockerfile – Dockerfile
+ ARM – .json (Azure Resource Manager)
+ Bicep – .bicep
+ 無伺服器 – .yml、.yaml
+ Helm – .yaml、.yml、.tpl
+ GitHub 動作 – .yml、.yaml
+ GitLab\$1ci – .yml、.yaml
+ Ansible – .yml、.yaml

*Semgrep （原始程式碼）*
+ Python – .py
+ JavaScript – .js
+ TypeScript – .ts
+ Java – .java
+ Go – .go
+ C – .c
+ C\$1\$1 – .cpp
+ C\$1 – .cs
+ Ruby – .rb
+ PHP – .php
+ Scala – .scala
+ Kotlin – .kt
+ Rust – .rs

*Bandit （僅限 Python)*
+ Python – .py

**示範**

針對程式碼掃描，請向 AI 助理嘗試下列範例提示：
+ 「掃描目前的指令碼並告訴我結果。」
+ 「掃描第 20-60 行並告訴我結果。」
+ 「掃描此 Amazon DynamoDB 資料表資源並告訴我結果。」

如需詳細資訊，請參閱此模式 GitHub 儲存庫中的此[程式碼掃描示範](https://github.com/aws-samples/sample-mcp-security-scanner/blob/main/docs/demo_code_scan.gif)。

若要產生安全程式碼，請嘗試下列範例提示：
+ 「產生 Terraform 組態以建立已啟用加密的 DynamoDB 資料表，並掃描是否有安全問題。」
+ 「建立寫入 DynamoDB 的 Python Lambda 函數，並掃描是否有漏洞。」
+ 「使用適當的安全性設定產生 S3 儲存貯體的 CloudFormation 範本，並確認它通過安全性檢查。」
+ 「撰寫 Python 指令碼以使用分頁查詢 DynamoDB，並掃描安全性最佳實務。」
+ 「為具有安全強化的微服務建立 Kubernetes 部署資訊清單並進行驗證。」

如需詳細資訊，請參閱此模式 GitHub 儲存庫中的此[程式碼產生與安全性掃描](https://github.com/aws-samples/sample-mcp-security-scanner/blob/main/docs/demo_code_generation.gif)示範。

# 使用 RAG 和 ReAct 提示，開發進階生成式 AI 聊天式助理
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting"></a>

*Praveen Kumar Jeyarajan、Shai Cao、Noah Hamilton、Kiowa Jackson、Jundong Qiao 和 Kara Yang、Amazon Web Services*

## 摘要
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-summary"></a>

典型的公司有 70% 的資料被困在孤立系統中。您可以使用生成式 AI 支援的聊天式助理，透過自然語言互動來釋放這些資料孤島之間的洞見和關係。為了充分利用生成式 AI，輸出必須值得信任、準確且包含可用的公司資料。成功的聊天式助理取決於下列項目：
+ 生成式 AI 模型 （例如 Anthropic Claude 2)
+ 資料來源向量化
+ 進階推理技巧，例如 [ReAct 架構](https://www.promptingguide.ai/techniques/react)，用於提示模型

此模式提供來自資料來源的資料擷取方法，例如 Amazon Simple Storage Service (Amazon S3) 儲存貯體、AWS Glue 和 Amazon Relational Database Service (Amazon RDS)。透過將[擷取增強生成 (RAG)](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html) 與chain-of-thought方法相交，從該資料中取得值。結果支援以聊天為基礎的複雜助理對話，這些對話會利用您公司儲存的所有資料。

此模式使用 Amazon SageMaker 手冊和定價資料表作為範例，以探索生成式 AI 聊天式助理的功能。您將建置聊天式助理，藉由回答有關定價和服務功能的問題，協助客戶評估 SageMaker 服務。解決方案使用 Streamlit 程式庫來建置前端應用程式，並使用 LangChain 架構來開發採用大型語言模型 (LLM) 的應用程式後端。

對聊天式助理的查詢會符合初始意圖分類，以路由至三個可能工作流程之一。最複雜的工作流程結合了一般諮詢指引與複雜的定價分析。您可以調整模式以符合企業、公司和工業使用案例。

## 先決條件和限制
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-prereqs"></a>

**先決條件**
+ [安裝並設定 AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 
+ [安裝和設定 AWS Cloud Development Kit (AWS CDK) Toolkit 2.114.1 或更新版本](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) 
+ Python 和 AWS CDK 的基本熟悉度
+ 已安裝 [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 
+ 已安裝 [Docker](https://docs.docker.com/get-docker/) 
+ [Python 3.11 或更新版本](https://www.python.org/downloads/)已安裝並設定 （如需詳細資訊，請參閱[工具](#develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-tools)一節）
+ 使用 [AWS CDK 引導的作用中 AWS 帳戶](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html) [https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)
+ Amazon Bedrock 服務中啟用了 Amazon Titan 和 Anthropic Claude [模型存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html#add-model-access) 
+ [在終端機環境中正確設定 AWS 安全登入](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html)資料，包括 。 `AWS_ACCESS_KEY_ID`

**限制**
+ LangChain 不支援每個 LLM 進行串流。支援 Anthropic Claude 模型，但不支援 AI21 實驗室的模型。
+ 此解決方案會部署到單一 AWS 帳戶。
+ 此解決方案只能在可使用 Amazon Bedrock 和 Amazon Kendra 的 AWS 區域中部署。如需可用性的詳細資訊，請參閱 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html#bedrock-regions) 和 [Amazon Kendra](https://docs.aws.amazon.com/general/latest/gr/kendra.html) 的文件。

**產品版本**
+ Python 3.11 版或更新版本
+ 串流 1.30.0 版或更新版本
+ Streamlit-chat 0.1.1 版或更新版本
+ LangChain 0.1.12 版或更新版本
+ AWS CDK 2.132.1 版或更新版本

## Architecture
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-architecture"></a>

**目標技術堆疊**
+ Amazon Athena
+ Amazon Bedrock
+ Amazon Elastic Container Service (Amazon ECS)
+ AWS Glue
+ AWS Lambda
+ Amazon S3
+ Amazon Kendra
+ Elastic Load Balancing

**目標架構**

AWS CDK 程式碼會部署在 AWS 帳戶中設定聊天式助理應用程式所需的所有資源。下圖中顯示的聊天式助理應用程式旨在回答來自使用者的 SageMaker 相關查詢。使用者透過 Application Load Balancer 連線至 VPC，其中包含託管 Streamlit 應用程式的 Amazon ECS 叢集。協同運作 Lambda 函數會連線至應用程式。S3 儲存貯體資料來源透過 Amazon Kendra 和 AWS Glue 將資料提供給 Lambda 函數。Lambda 函數會連線至 Amazon Bedrock，以回應聊天式助理使用者的查詢 （問題）。

![\[架構圖。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b4df6405-76ab-4493-a722-15ceca067254/images/4e5856cf-9489-41f8-a411-e3b8d8a50748.png)


1. 協同運作 Lambda 函數會將 LLM 提示請求傳送至 Amazon Bedrock 模型 (Claude 2)。

1. Amazon Bedrock 會將 LLM 回應傳回協調 Lambda 函數。

**協同運作 Lambda 函數內的邏輯流程**

當使用者透過 Streamlit 應用程式提出問題時，它會直接叫用協調 Lambda 函數。下圖顯示叫用 Lambda 函數時的邏輯流程。

![\[架構圖。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b4df6405-76ab-4493-a722-15ceca067254/images/70ae4736-06a6-4d3a-903a-edc5c10d78a0.png)

+ 步驟 1 – 輸入 `query`（問題） 分類為三個意圖之一：
  + 一般 SageMaker 指引問題
  + 一般 SageMaker 定價 （訓練/推論） 問題
  + 與 SageMaker 和定價相關的複雜問題
+ 步驟 2 – 輸入會`query`啟動以下三種服務之一：
  + `RAG Retrieval service`，它會從 [Amazon Kendra](https://aws.amazon.com/kendra/) 向量資料庫擷取相關內容，並透過 [Amazon Bedrock](https://aws.amazon.com/bedrock/) 呼叫 LLM，以摘要擷取的內容作為回應。
  + `Database Query service`，其使用 - 相關資料表的 LLM、資料庫中繼資料和範例資料列，將輸入轉換為 SQL `query` 查詢。資料庫查詢服務會透過 [Amazon Athena](https://aws.amazon.com/athena/) 對 SageMaker 定價資料庫執行 SQL 查詢，並將查詢結果摘要為回應。
  + `In-context ReACT Agent service`，這會先將輸入細分為`query`多個步驟，再提供回應。代理程式使用 `RAG Retrieval service`和 `Database Query service`做為工具，在推理過程中擷取相關資訊。推理和動作程序完成後，客服人員會產生最終答案作為回應。
+ 步驟 3 – 協同運作 Lambda 函數的回應會以輸出形式傳送至 Streamlit 應用程式。

## 工具
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-tools"></a>

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon Simple Storage Service (Amazon S3) 中分析資料。
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS 雲端開發套件 (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。
+ [Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) 是快速、可擴展的容器管理服務，可協助您執行、停止和管理叢集上的容器。
+ [AWS Glue](https://docs.aws.amazon.com/glue/) 是全受管的擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。此模式使用 AWS Glue 爬蟲程式和 AWS Glue Data Catalog 資料表。
+ [Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/what-is-kendra.html) 是一種智慧型搜尋服務，使用自然語言處理和進階機器學習演算法，傳回從資料搜尋問題的特定答案。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Elastic Load Balancing (ELB)](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) 會將傳入的應用程式或網路流量分散到多個目標。例如，您可以在一或多個可用區域中將流量分配到 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體、容器和 IP 地址。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [genai-bedrock-chatbot](https://github.com/awslabs/genai-bedrock-chatbot) 儲存庫中使用。

程式碼儲存庫包含下列檔案和資料夾：
+ `assets` 資料夾 – 架構圖表和公有資料集的靜態資產
+ `code/lambda-container` 資料夾 – 在 Lambda 函數中執行的 Python 程式碼
+ `code/streamlit-app` 資料夾 – 在 Amazon ECS 中做為容器映像執行的 Python 程式碼
+ `tests` 資料夾 – 執行以單元測試 AWS CDK 建構的 Python 檔案
+ `code/code_stack.py` – 用來建立 AWS 資源的 AWS CDK 建構 Python 檔案
+ `app.py` – 用於在目標 AWS 帳戶中部署 AWS 資源的 AWS CDK 堆疊 Python 檔案
+ `requirements.txt` – 必須為 AWS CDK 安裝的所有 Python 相依性清單
+ `requirements-dev.txt` – 必須安裝才能讓 AWS CDK 執行單元測試套件的所有 Python 相依性清單
+ `cdk.json` – 輸入檔案，用來提供啟動資源所需的值


| 
| 
| 注意：AWS CDK 程式碼使用 [L3 （第 3 層） 建構](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)和 [AWS Identity and Access Management (IAM) 政策來](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)部署解決方案。 | 
| --- |

## 最佳實務
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-best-practices"></a>
+ 此處提供的程式碼範例僅適用於proof-of-concept(PoC) 或試行示範。如果您想要將程式碼帶入生產環境，請務必使用下列最佳實務：
  + [Amazon S3 存取記錄已啟用](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html)。
  + [VPC 流程日誌已啟用](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)。
  + [Amazon Kendra Enterprise Edition 索引](https://docs.aws.amazon.com/whitepapers/latest/how-aws-pricing-works/amazon-kendra.html)已啟用。
+ 設定 Lambda 函數的監控和提醒。如需詳細資訊，請參閱[監控和疑難排解 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)。如需使用 Lambda 函數的一般最佳實務，請參閱 [AWS 文件](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)。

## 史詩
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-epics"></a>

### 在本機電腦上設定 AWS 登入資料
<a name="set-up-aws-credentials-on-your-local-machine"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 匯出要部署堆疊之帳戶和 AWS 區域的變數。 | 若要使用環境變數為 AWS CDK 提供 AWS 登入資料，請執行下列命令。<pre>export CDK_DEFAULT_ACCOUNT=<12 Digit AWS Account Number><br />export CDK_DEFAULT_REGION=<region></pre> | DevOps 工程師，AWS DevOps | 
| 設定 AWS CLI 設定檔。 | 若要設定帳戶的 AWS CLI 設定檔，請遵循 [AWS 文件](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/keys-profiles-credentials.html)中的指示。 | DevOps 工程師，AWS DevOps | 

### 設定您的環境
<a name="set-up-your-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在本機電腦上複製儲存庫。 | 若要複製儲存庫，請在終端機中執行下列命令。<pre>git clone https://github.com/awslabs/genai-bedrock-chatbot.git</pre> | DevOps 工程師，AWS DevOps | 
| 設定 Python 虛擬環境並安裝必要的相依性。 | 若要設定 Python 虛擬環境，請執行下列命令。<pre>cd genai-bedrock-chatbot<br />python3 -m venv .venv<br />source .venv/bin/activate</pre>若要設定所需的相依性，請執行下列命令。<pre>pip3 install -r requirements.txt</pre> | DevOps 工程師，AWS DevOps | 
| 設定 AWS CDK 環境並合成 AWS CDK 程式碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.html) | DevOps 工程師，AWS DevOps | 

### 設定和部署聊天式助理應用程式
<a name="configure-and-deploy-the-chat-based-assistant-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 佈建 Claude 模型存取。 | 若要為您的 AWS 帳戶啟用 Anthropic Claude 模型存取，請遵循 [Amazon Bedrock 文件](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html#add-model-access)中的指示。 | AWS DevOps | 
| 在帳戶中部署資源。 | 若要使用 AWS CDK 在 AWS 帳戶中部署資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.html)成功部署後，您可以使用 CloudFormation **Outputs** 區段中提供的 URL 來存取聊天式助理應用程式。 | AWS DevOps，DevOps 工程師 | 
| 執行 AWS Glue 爬蟲程式並建立資料目錄資料表。 | [AWS Glue 爬蟲程式](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)用於保持資料結構描述動態。解決方案會隨需執行爬蟲程式，在 [AWS Glue Data Catalog 資料表](https://docs.aws.amazon.com/athena/latest/ug/querying-glue-catalog.html)中建立和更新分割區。將 CSV 資料集檔案複製到 S3 儲存貯體後，請執行 AWS Glue 爬蟲程式並建立 Data Catalog 資料表結構描述以進行測試：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.html)AWS CDK 程式碼會將 AWS Glue 爬蟲程式設定為隨需執行，但您也可以[排定](https://docs.aws.amazon.com/glue/latest/dg/schedule-crawler.html)它定期執行。 | DevOps 工程師，AWS DevOps | 
| 啟動文件索引。 | 將檔案複製到 S3 儲存貯體後，請使用 Amazon Kendra 來編目和編製索引：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.html)AWS CDK 程式碼會將 Amazon Kendra 索引同步設定為隨需執行，但您也可以使用[排程參數](https://docs.aws.amazon.com/kendra/latest/dg/data-source.html#cron)定期執行。 | AWS DevOps，DevOps 工程師 | 

### 清除解決方案中的所有 AWS 資源
<a name="clean-up-all-aws-resources-in-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除 AWS 資源。 | 測試解決方案之後，請清除資源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.html) | DevOps 工程師，AWS DevOps | 

## 疑難排解
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| AWS CDK 傳回錯誤。 | 如需 AWS CDK 問題的協助，請參閱[疑難排解常見的 AWS CDK 問題](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)。 | 

## 相關資源
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-resources"></a>
+ Amazon Bedrock：
  + [模型存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
  + [基礎模型的推論參數](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)
+ [使用 Python 建置 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ [開始使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [在 Python 中使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [AWS 上的生成式 AI 應用程式建置器](https://docs.aws.amazon.com/solutions/latest/generative-ai-application-builder-on-aws/solution-overview.html)
+ [LangChain 文件](https://python.langchain.com/docs/get_started/introduction)
+ [串流文件](https://docs.streamlit.io/)

## 其他資訊
<a name="develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting-additional"></a>

**AWS CDK 命令**

使用 AWS CDK 時，請記住下列有用的命令：
+ 列出應用程式中的所有堆疊

  ```
  cdk ls
  ```
+ 發出合成的 AWS CloudFormation 範本

  ```
  cdk synth
  ```
+ 將堆疊部署到您的預設 AWS 帳戶和區域

  ```
  cdk deploy
  ```
+ 比較已部署堆疊與目前狀態

  ```
  cdk diff
  ```
+ 開啟 AWS CDK 文件

  ```
  cdk docs
  ```
+ 刪除 CloudFormation 堆疊並移除 AWS 部署的資源

  ```
  cdk destroy
  ```

# 使用 Amazon Bedrock 代理程式和知識庫開發全自動聊天式助理
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases"></a>

*Jundong Qiao、Shai Cao、Noah Hamilton、Kiowa Jackson、Praveen Kumar Jeyarajan 和 Kara Yang、Amazon Web Services*

## 摘要
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-summary"></a>

許多組織在建立能夠協調各種資料來源以提供完整答案的聊天式助理時，都會面臨挑戰。此模式提供一種解決方案，用於開發聊天式助理，能夠以直接的部署來回應文件和資料庫的查詢。

從 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 開始，這項全受管生成式人工智慧 (AI) 服務提供廣泛的進階基礎模型 (FMs)。這有助於高效建立生成式 AI 應用程式，並高度重視隱私權和安全性。在文件擷取的內容中，[擷取增強生成 (RAG)](https://docs.aws.amazon.com/sagemaker/latest/dg/jumpstart-foundation-models-customize-rag.html) 是一種樞紐功能。它使用[知識庫](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)，透過來自外部來源的內容相關資訊來增強 FM 提示。[Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html) 索引做為 Amazon Bedrock 知識庫後方的向量資料庫。此整合是透過仔細的提示詞工程來增強，以將不正確的情況降至最低，並確保回應錨定在實際文件中。對於資料庫查詢，Amazon Bedrock FMs 會將文字查詢轉換為結構化 SQL 查詢，並結合特定參數。這可讓您從資料庫管理的[AWS Glue 資料庫](https://docs.aws.amazon.com/glue/latest/dg/define-database.html)精確擷取資料。[Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 用於這些查詢。

為了處理更複雜的查詢，實現全面的答案需要來自文件和資料庫的資訊。[Amazon Bedrock 的代理](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)程式是一項生成式 AI 功能，可協助您建置自主代理程式，了解複雜的任務並將其分解為更簡單的協同運作任務。由 Amazon Bedrock 自動代理程式協助，從簡化任務中擷取的洞見組合可增強資訊的合成，進而產生更徹底且詳盡的答案。此模式示範如何在自動化解決方案中使用 Amazon Bedrock 和相關的生成式 AI 服務和功能來建置聊天式助理。

## 先決條件和限制
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ Docker，[已安裝](https://docs.docker.com/engine/install/)
+ AWS Cloud Development Kit (AWS CDK)，[已安裝](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_tools)並[引導](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_bootstrap)至 `us-east-1`或 `us-west-2` AWS 區域
+ AWS CDK [已安裝](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) Toolkit 2.114.1 版或更新版本
+ AWS Command Line Interface (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ Python 3.11 版或更新版本，[已安裝](https://www.python.org/downloads/)
+ 在 Amazon Bedrock 中，[啟用對 Claude 2、Claude 2.1、Claude Instant 和 Titan Embeddings G1 的存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) – 文字 G1 

**限制**
+ 此解決方案會部署到單一 AWS 帳戶。
+ 此解決方案只能在支援 Amazon Bedrock 和 Amazon OpenSearch Serverless AWS 區域 的 中部署。如需詳細資訊，請參閱 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-regions.html) 和 [Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html#serverless-regions) 的文件。

**產品版本**
+ Llama-index 0.10.6 版或更新版本
+ Sqlalchemy 2.0.23 版或更新版本
+ Opensearch-py 2.4.2 版或更新版本
+ Requests\$1aws4auth 1.2.3 版或更新版本
+ 適用於 Python (Boto3) 的 AWS SDK 1.34.57 版或更新版本

## Architecture
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-architecture"></a>

**目標技術堆疊 **

[AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是開放原始碼軟體開發架構，用於在程式碼中定義雲端基礎設施並透過其佈建 AWS CloudFormation。此模式中使用的 AWS CDK 堆疊會部署下列 AWS 資源： 
+ AWS Key Management Service (AWS KMS)
+ Amazon Simple Storage Service (Amazon S3)
+ AWS Glue Data Catalog，適用於 AWS Glue 資料庫元件
+ AWS Lambda
+ AWS Identity and Access Management (IAM)
+ Amazon OpenSearch Serverless
+ Amazon Elastic Container Registry (Amazon ECR) 
+ Amazon Elastic Container Service (Amazon ECS)
+ AWS Fargate
+ Amazon Virtual Private Cloud (Amazon VPC)
+ [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) 

**目標架構 **

![\[使用 Amazon Bedrock 知識庫和代理程式的架構圖\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/15372718-3a5d-4918-9cfa-422c455f288d/images/ff19152e-0bb6-4758-a6dd-4f6140e55113.png)


圖表顯示使用多個 AWS 區域的單一 AWS 中全面的雲端原生設定 AWS 服務。聊天式助理的主要界面是在 Amazon ECS 叢集上託管的 [Streamlit](https://docs.streamlit.io/) 應用程式。 [Application Load Balancer](https://aws.amazon.com/elasticloadbalancing/application-load-balancer/) 會管理可存取性。透過此界面進行的查詢會啟用 `Invocation` Lambda 函數，然後與 Amazon Bedrock 的代理程式連接。此代理程式會透過諮詢 Amazon Bedrock 的知識庫或叫用 `Agent executor` Lambda 函數來回應使用者查詢。此函數會在預先定義的 API 結構描述之後，觸發與代理程式相關聯的一組動作。Amazon Bedrock 的知識庫使用 OpenSearch Serverless 索引作為向量資料庫基礎。此外，`Agent executor`函數會產生透過 Amazon Athena 針對 AWS Glue 資料庫執行的 SQL 查詢。

## 工具
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-tools"></a>

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon Simple Storage Service (Amazon S3) 中分析資料。
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。
+ [Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) 是快速、可擴展的容器管理服務，可協助您執行、停止和管理叢集上的容器。
+ [Elastic Load Balancing ](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)會將傳入的應用程式或網路流量分散到多個目標。例如，您可以將流量分散到一或多個可用區域中的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體、容器和 IP 地址。
+ [AWS Glue](https://docs.aws.amazon.com/glue/) 是全受管擷取、轉換和載入 (ETL) 服務。它可協助您可靠地分類、清理、擴充和移動資料存放區和資料串流之間的資料。此模式使用 AWS Glue 爬蟲程式和 AWS Glue Data Catalog 資料表。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html) 是 Amazon OpenSearch Service 的隨需無伺服器組態。在此模式中，OpenSearch Serverless 索引可做為 Amazon Bedrock 知識庫的向量資料庫。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [Streamlit](https://docs.streamlit.io/) 是一種開放原始碼 Python 架構，可用來建立資料應用程式。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [genai-bedrock-agent-chatbot](https://github.com/awslabs/genai-bedrock-agent-chatbot/) 儲存庫中使用。程式碼儲存庫包含下列檔案和資料夾：
+ `assets` 資料夾 – 靜態資產，例如架構圖表和公有資料集。
+ `code/lambdas/action-lambda` 資料夾 – Lambda 函數的 Python 程式碼，可做為 Amazon Bedrock 代理程式的動作。
+ `code/lambdas/create-index-lambda` 資料夾 – 建立 OpenSearch Serverless 索引之 Lambda 函數的 Python 程式碼。
+ `code/lambdas/invoke-lambda` 資料夾 – 叫用 Amazon Bedrock 代理程式的 Lambda 函數的 Python 程式碼，該代理程式直接從 Streamlit 應用程式呼叫。
+ `code/lambdas/update-lambda` 資料夾 – Lambda 函數的 Python 程式碼，會在透過 部署資源之後更新或刪除 AWS 資源 AWS CDK。
+ `code/layers/boto3_layer` 資料夾 – 建立 Boto3 layer 的 AWS CDK 堆疊，在所有 Lambda 函數之間共用。
+ `code/layers/opensearch_layer` 資料夾 – 建立 OpenSearch Serverless layer 的 AWS CDK 堆疊，會安裝所有相依性來建立索引。
+ `code/streamlit-app` 資料夾 – 在 Amazon ECS 中做為容器映像執行的 Python 程式碼。
+ `code/code_stack.py` – AWS CDK 建立 AWS 資源的建構 Python 檔案。
+ `app.py` – 在目標 AWS 帳戶中部署 AWS 資源的 AWS CDK 堆疊 Python 檔案。
+ `requirements.txt` – 必須為 安裝的所有 Python 相依性清單 AWS CDK。
+ `cdk.json` – 輸入檔案，用來提供建立資源所需的值。此外，您可以在`context/config`欄位中相應地自訂解決方案。如需自訂的詳細資訊，請參閱[其他資訊](#develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-additional)一節。

## 最佳實務
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-best-practices"></a>
+ 此處提供的程式碼範例僅用於proof-of-concept(PoC) 或試行目的。如果您想要將程式碼帶入生產環境，請務必使用下列最佳實務：
  + 啟用 [Amazon S3 存取記錄](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html)
  + 啟用 [VPC 流程日誌](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)
+ 設定 Lambda 函數的監控和提醒。如需詳細資訊，請參閱[監控和疑難排解 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)。如需最佳實務，請參閱[使用 AWS Lambda 函數的最佳實務](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)。

## 史詩
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-epics"></a>

### 在本機工作站上設定 AWS 登入資料
<a name="set-up-aws-credentials-on-your-local-workstation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 匯出帳戶和區域的變數。 | 若要使用環境變數提供 的 AWS 登入 AWS CDK 資料，請執行下列命令。<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number><br />export CDK_DEFAULT_REGION=<Region></pre> | AWS DevOps，DevOps 工程師 | 
| 設定 AWS CLI 具名設定檔。 | 若要為帳戶設定 AWS CLI 具名設定檔，請遵循[組態和登入資料檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)中的指示。 | AWS DevOps，DevOps 工程師 | 

### 設定您的環境
<a name="set-up-your-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將儲存庫複製到您的本機工作站。 | 若要複製儲存庫，請在終端機中執行下列命令。<pre>git clone https://github.com/awslabs/genai-bedrock-agent-chatbot.git</pre> | DevOps 工程師，AWS DevOps | 
| 設定 Python 虛擬環境。 | 若要設定 Python 虛擬環境，請執行下列命令。<pre>cd genai-bedrock-agent-chatbot<br />python3 -m venv .venv<br />source .venv/bin/activate</pre>若要設定所需的相依性，請執行下列命令。<pre>pip3 install -r requirements.txt</pre> | DevOps 工程師，AWS DevOps | 
| 設定 AWS CDK 環境。 | 若要將程式碼轉換為 AWS CloudFormation 範本，請執行命令 `cdk synth`。 | AWS DevOps，DevOps 工程師 | 

### 設定和部署應用程式
<a name="configure-and-deploy-the-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在帳戶中部署資源。 | 若要 AWS 帳戶 使用 在 中部署資源 AWS CDK，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases.html)成功部署後，您可以使用 CloudFormation 主控台的**輸出**索引標籤上提供的 URL 來存取聊天式助理應用程式。 | DevOps 工程師，AWS DevOps | 

### 清除解決方案中的所有 AWS 資源
<a name="clean-up-all-aws-resources-in-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除 AWS 資源。 | 測試解決方案之後，若要清除資源，請執行命令 `cdk destroy`。 | AWS DevOps，DevOps 工程師 | 

## 相關資源
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-resources"></a>

**AWS 文件**
+ Amazon Bedrock 資源：
  + [模型存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
  + [基礎模型的推論參數](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)
  + [Amazon Bedrock 的代理程式](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)
  + [Amazon Bedrock 的知識庫](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)
+ [使用 Python 建置 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ AWS CDK 資源：
  + [開始使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
  + [對 AWS CDK 常見問題進行故障診斷](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)
  + [在 Python AWS CDK 中使用](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [上的生成式 AI 應用程式建置器 AWS](https://docs.aws.amazon.com/solutions/latest/generative-ai-application-builder-on-aws/solution-overview.html)

**其他 AWS 資源**
+ [Amazon OpenSearch Serverless 的向量引擎](https://aws.amazon.com/opensearch-service/serverless-vector-engine/)

**其他資源**
+ [LlamaIndex 文件](https://docs.llamaindex.ai/en/stable/)
+ [串流文件](https://docs.streamlit.io/)

## 其他資訊
<a name="develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases-additional"></a>

**使用您自己的資料自訂聊天式助理**

若要整合自訂資料以部署解決方案，請遵循這些結構化準則。這些步驟旨在確保無縫且有效率的整合程序，讓您能夠使用自訂資料有效地部署解決方案。

*用於知識庫資料整合*

**資料準備**

1. 找到 `assets/knowledgebase_data_source/`目錄。

1. 將資料集放在此資料夾中。

**組態調整**

1. 開啟 `cdk.json` 檔案。

1. 導覽至 `context/configure/paths/knowledgebase_file_name` 欄位，然後相應地更新。

1. 導覽至 `bedrock_instructions/knowledgebase_instruction` 欄位，然後更新它，以準確反映新資料集的細微差別和內容。

*用於結構資料整合*

**資料組織**

1. 在 `assets/data_query_data_source/`目錄中，建立子目錄，例如 `tabular_data`。

1. 將您的結構化資料集 （可接受的格式包括 CSV、JSON、ORC 和 Parquet) 放入這個新建立的子資料夾。

1. 如果您要連線到現有的資料庫，請在 `create_sql_engine()`中更新 函數`code/lambda/action-lambda/build_query_engine.py`以連線到您的資料庫。

**組態和程式碼更新**

1. 在 `cdk.json` 檔案中，更新 `context/configure/paths/athena_table_data_prefix` 欄位以符合新的資料路徑。

1. 透過整合與資料集對應的新text-to-SQL範例`code/lambda/action-lambda/dynamic_examples.csv`進行修訂。

1. 修改`code/lambda/action-lambda/prompt_templates.py`以鏡像結構化資料集的屬性。

1. 在 `cdk.json` 檔案中，更新 `context/configure/bedrock_instructions/action_group_description` 欄位以解釋 `Action group` Lambda 函數的目的和功能。

1. 在 `assets/agent_api_schema/artifacts_schema.json` 檔案中，說明 `Action group` Lambda 函數的新功能。

*一般更新*

在 `cdk.json` 檔案中，在 `context/configure/bedrock_instructions/agent_instruction`區段中，提供 Amazon Bedrock 代理程式預期功能和設計用途的完整描述，並將新整合的資料納入考量。

# 使用 Amazon Bedrock 和 Amazon Transcribe 從語音輸入記錄機構知識
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe"></a>

*Praveen Kumar Jeyarajan、Jundong Qiao、Rajiv Upadhyay 和 Megan Wu，Amazon Web Services*

## 總結
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-summary"></a>

擷取機構知識對於確保組織成功和彈性至關重要。機構知識代表員工隨著時間累積的集體智慧、洞見和經驗，通常在性質上隱含，並以非正式方式傳遞。這種豐富的資訊包含獨特的方法、最佳實務和解決方案，可處理可能未記錄在其他地方的複雜問題。透過正式化和記錄這些知識，公司可以保留機構記憶體、促進創新、增強決策過程，並加速新員工的學習曲線。此外，它可促進協作、賦予個人能力，並培養持續改善的文化。最後，利用機構知識可協助公司使用其最寶貴的資產，也就是人力資源的集體智慧，在動態商業環境中應對挑戰、推動成長並維持競爭優勢。

此模式說明如何透過資深員工的語音錄音來擷取機構知識。它使用 [Amazon Transcribe](https://docs.aws.amazon.com/transcribe/latest/dg/what-is.html) 和 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 進行系統性文件和驗證。透過記錄這種非正式知識，您可以保留它並與後續的員工群組共用。此工作支援卓越營運，並透過整合透過直接體驗取得的實際知識來改善訓練計劃的有效性。

## 先決條件和限制
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ Docker，[已安裝](https://docs.docker.com/engine/install/)
+ AWS 雲端開發套件 (AWS CDK) 2.114.1 版或更新版本，[已安裝](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_tools)並[引導](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_bootstrap)至 `us-east-1`或 `us-west-2` AWS 區域
+ AWS CDK Toolkit 2.114.1 版或更新版本，[已安裝](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)
+ AWS 命令列界面 (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ Python 3.12 版或更新版本，[已安裝](https://www.python.org/downloads/)
+ 建立 Amazon Transcribe、Amazon Bedrock、Amazon Simple Storage Service (Amazon S3) 和 AWS Lambda 資源的許可

**限制**
+ 此解決方案會部署到單一 AWS 帳戶。
+ 此解決方案只能在可使用 Amazon Bedrock 和 Amazon Transcribe 的 AWS 區域中部署。如需可用性的相關資訊，請參閱 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-regions.html) 和 [Amazon Transcribe](https://docs.aws.amazon.com/transcribe/latest/dg/what-is.html#tsc-regions) 的文件。
+ 音訊檔案的格式必須是 Amazon Transcribe 支援的格式。如需支援的格式清單，請參閱轉錄文件中的[媒體格式](https://docs.aws.amazon.com/transcribe/latest/dg/how-input.html#how-input-audio)。

**產品版本**
+ 適用於 Python (Boto3) 的 AWS 開發套件 1.34.57 版或更新版本
+ LangChain 0.1.12 版或更新版本

## Architecture
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-architecture"></a>

架構代表 AWS 上的無伺服器工作流程。[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 協調 Lambda 函數以進行音訊處理、文字分析和文件產生。下圖顯示 Step Functions 工作流程，也稱為*狀態機器*。

![\[產生文件的 Step Functions 狀態機器的架構圖\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/f1e0106d-b046-4adc-9718-c299efb7b436/images/e90298ca-1b7f-4c3e-97bd-311a9d5a4997.png)


狀態機器中的每個步驟都由不同的 Lambda 函數處理。以下是文件產生程序中的步驟：

1. `preprocess` Lambda 函數會驗證傳遞至 Step Functions 的輸入，並列出所提供 Amazon S3 URI 資料夾路徑中的所有音訊檔案。工作流程中的下游 Lambda 函數會使用檔案清單來驗證、摘要和產生文件。

1. `transcribe` Lambda 函數使用 Amazon Transcribe 將音訊檔案轉換為文字記錄。此 Lambda 函數負責啟動轉錄程序，並將語音準確轉換為文字，然後存放以供後續處理。

1. `validate` Lambda 函數會分析文字文字記錄，判斷回應與初始問題之間的相關性。透過 Amazon Bedrock 使用大型語言模型 (LLM)，可以識別主題上的答案，並將其與主題外回應分開。

1. `summarize` Lambda 函數使用 Amazon Bedrock 產生主題上答案的一致性和簡潔摘要。

1. `generate` Lambda 函數會將摘要組合成結構良好的文件。它可以根據預先定義的範本格式化文件，並包含任何其他必要的內容或資料。

1. 如果任何 Lambda 函數失敗，您會透過 Amazon Simple Notification Service (Amazon SNS) 收到電子郵件通知。

在此過程中，AWS Step Functions 會確保以正確的順序啟動每個 Lambda 函數。此狀態機器具有可平行處理的容量，可提高效率。Amazon S3 儲存貯體做為中央儲存儲存庫，透過管理涉及的各種媒體和文件格式來支援工作流程。

## 工具
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-tools"></a>

**AWS 服務**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可協助您協調和管理發佈者和用戶端之間的訊息交換，包括 Web 伺服器和電子郵件地址。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。 
+ [Amazon Transcribe](https://docs.aws.amazon.com/transcribe/latest/dg/what-is.html) 是一種自動語音辨識服務，使用機器學習模型將音訊轉換為文字。

**其他工具**
+ [LangChain](https://python.langchain.com/docs/get_started/introduction/) 是一種架構，用於開發採用大型語言模型 (LLMs的應用程式。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [genai-knowledge-capture](https://github.com/aws-samples/genai-knowledge-capture) 儲存庫中使用。

程式碼儲存庫包含下列檔案和資料夾：
+ `assets` 資料夾 – 解決方案的靜態資產，例如架構圖表和公有資料集
+ `code/lambdas` 資料夾 – 所有 Lambda 函數的 Python 程式碼
  + `code/lambdas/generate` 資料夾 - 從 S3 儲存貯體中的摘要資料產生文件的 Python 程式碼
  + `code/lambdas/preprocess` 資料夾 - 處理 Step Functions 狀態機器輸入的 Python 程式碼
  + `code/lambdas/summarize` 資料夾 - 使用 Amazon Bedrock 服務摘要轉錄資料的 Python 程式碼
  + `code/lambdas/transcribe` 資料夾 - 使用 Amazon Transcribe 將語音資料 （音訊檔案） 轉換為文字的 Python 程式碼
  + `code/lambdas/validate` 資料夾 - 驗證所有答案是否與相同主題相關的 Python 程式碼
+ `code/code_stack.py` – 用來建立 AWS 資源的 AWS CDK 建構 Python 檔案
+ `app.py` – 用於在目標 AWS 帳戶中部署 AWS 資源的 AWS CDK 應用程式 Python 檔案
+ `requirements.txt` – 必須為 AWS CDK 安裝的所有 Python 相依性清單
+ `cdk.json` – 提供建立資源所需的值的輸入檔案

## 最佳實務
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-best-practices"></a>

提供的程式碼範例僅用於proof-of-concept(PoC) 或試行目的。如果您想要將解決方案用於生產環境，請使用下列最佳實務：
+ 啟用 [Amazon S3 存取記錄](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html)
+ 啟用 [VPC 流程日誌](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)

## 史詩
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-epics"></a>

### 在本機工作站上設定 AWS 登入資料
<a name="set-up-aws-credentials-on-your-local-workstation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 匯出帳戶和 AWS 區域的變數。 | 若要使用環境變數提供 AWS CDK 的 AWS 登入資料，請執行下列命令。<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number><br />export CDK_DEFAULT_REGION=<Region></pre> | AWS DevOps，DevOps 工程師 | 
| 設定名為 的 AWS CLI 設定檔。 | 若要設定帳戶的 AWS CLI 命名設定檔，請遵循[組態和登入資料檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)中的指示。 | AWS DevOps，DevOps 工程師 | 

### 設定您的環境
<a name="set-up-your-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將儲存庫複製到您的本機工作站。 | 若要複製 [genai-knowledge-capture](https://github.com/aws-samples/genai-knowledge-capture) 儲存庫，請在終端機中執行下列命令。<pre>git clone https://github.com/aws-samples/genai-knowledge-capture</pre> | AWS DevOps，DevOps 工程師 | 
| （選用） 取代音訊檔案。 | 若要自訂範例應用程式以整合您自己的資料，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.html) | AWS DevOps，DevOps 工程師 | 
| 設定 Python 虛擬環境。 | 若要設定 Python 虛擬環境，請執行下列命令。<pre>cd genai-knowledge-capture<br />python3 -m venv .venv<br />source .venv/bin/activate<br />pip install -r requirements.txt</pre> | AWS DevOps，DevOps 工程師 | 
| 合成 AWS CDK 程式碼。 | 若要將程式碼轉換為 AWS CloudFormation 堆疊組態，請執行下列命令。<pre>cdk synth</pre> | AWS DevOps，DevOps 工程師 | 

### 設定和部署解決方案
<a name="configure-and-deploy-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 佈建基礎模型存取。 | 啟用存取您 AWS 帳戶的 Anthropic Claude 3 Sonnet 模型。如需說明，請參閱 Bedrock 文件中的[新增模型存取權](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html#model-access-add)。 | AWS DevOps | 
| 在帳戶中部署資源。 | 若要使用 AWS CDK 在 AWS 帳戶中部署資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.html) | AWS DevOps，DevOps 工程師 | 
| 訂閱 Amazon SNS 主題。 | 若要訂閱 Amazon SNS 主題以進行通知，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.html) | 一般 AWS | 

### 測試解決方案
<a name="test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行狀態機器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.html) | 應用程式開發人員，一般 AWS | 

### 清除解決方案中的所有 AWS 資源
<a name="clean-up-all-aws-resources-in-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除 AWS 資源。 | 測試解決方案之後，請清除資源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe.html) | AWS DevOps，DevOps 工程師 | 

## 相關資源
<a name="document-institutional-knowledge-from-voice-inputs-by-using-amazon-bedrock-and-amazon-transcribe-resources"></a>

**AWS 文件**
+ Amazon Bedrock 資源：
  + [模型存取](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
  + [基礎模型的推論參數](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)
+ AWS CDK 資源：
  + [開始使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
  + [在 Python 中使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
  + [疑難排解常見的 AWS CDK 問題](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)
  + [工具組命令](https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-commands)
+ AWS Step Functions 資源：
  + [AWS Step Functions 入門](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)
  + [疑難排解](https://docs.aws.amazon.com/step-functions/latest/dg/troubleshooting.html)
+ [使用 Python 建置 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ [AWS 上的生成式 AI 應用程式建置器](https://docs.aws.amazon.com/solutions/latest/generative-ai-application-builder-on-aws/solution-overview.html)

**其他資源**
+ [LangChain 文件](https://python.langchain.com/docs/get_started/introduction)

# 使用 Amazon Personalize 產生個人化和重新排名的建議
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize"></a>

*Mason Cahill、Matthew Chasse 和 Tayo Olajide，Amazon Web Services*

## 總結
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-summary"></a>

此模式說明如何使用 Amazon Personalize，根據從這些使用者擷取即時使用者互動資料，為您的使用者產生個人化建議，包括重新排名的建議。此模式中使用的範例案例是以寵物採用網站為基礎，該網站會根據其互動為其使用者產生建議 （例如，使用者造訪哪些寵物）。遵循範例案例，您將學習如何使用 Amazon Kinesis Data Streams 擷取互動資料、AWS Lambda 產生建議並重新排名建議，以及 Amazon Data Firehose 將資料存放在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中。您也會學習使用 AWS Step Functions 來建置狀態機器，以管理產生建議的解決方案版本 （即訓練過的模型）。

## 先決條件和限制
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-prereqs"></a>

**先決條件**
+ 具有[引導式](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) [AWS 雲端開發套件 (AWS CDK) 的作用中 AWS 帳戶](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/) 
+ 具有已設定登入資料的 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 
+ [Python 3.9](https://www.python.org/downloads/release/python-390/)

**產品版本**
+ Python 3.9
+ AWS CDK 2.23.0 或更新版本
+ AWS CLI 2.7.27 或更新版本

## Architecture
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-architecture"></a>

**技術堆疊**
+ Amazon Data Firehose
+ Amazon Kinesis Data Streams
+ Amazon Personalize
+ Amazon Simple Storage Service (Amazon S3)
+ AWS 雲端開發套件 (AWS CDK)
+ AWS 命令列界面 (AWS CLI)
+ AWS Lambda
+ AWS Step Functions

**目標架構**

下圖說明將即時資料擷取至 Amazon Personalize 的管道。然後，管道會使用該資料為使用者產生個人化和重新排名的建議。

![\[Amazon Personalize 的資料擷取架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/42eb193b-2347-408a-8b25-46beeb3b29ca/images/786dbd56-7d7f-41bb-90f6-d4485d73fe15.png)


該圖顯示以下工作流程：

1. Kinesis Data Streams 會擷取即時使用者資料 （例如，造訪寵物等事件），以供 Lambda 和 Firehose 處理。

1. Lambda 函數會處理來自 Kinesis Data Streams 的記錄，並發出 API 呼叫，將記錄中的使用者互動新增至 Amazon Personalize 中的事件追蹤器。

1. 以時間為基礎的規則會叫用 Step Functions 狀態機器，並使用 Amazon Personalize 中事件追蹤器的事件，為建議產生新的解決方案版本並重新排序模型。

1. 狀態機器會更新 Amazon Personalize [行銷活動](https://docs.aws.amazon.com/personalize/latest/dg/campaigns.html)，以使用新的[解決方案版本](https://docs.aws.amazon.com/personalize/latest/dg/creating-a-solution-version.html)。

1. Lambda 透過呼叫 Amazon Personalize 重新排名行銷活動來重新排名建議項目清單。

1. Lambda 會透過呼叫 Amazon Personalize 建議行銷活動來擷取建議項目的清單。

1. Firehose 會將事件儲存到 S3 儲存貯體，以做為歷史資料存取。

## 工具
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-tools"></a>

**AWS 工具**
+ [AWS 雲端開發套件 (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。
+ [Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) 可協助您將即時[串流資料](https://aws.amazon.com/streaming-data/)交付至其他 AWS 服務、自訂 HTTP 端點，以及受支援的第三方服務供應商所擁有的 HTTP 端點。
+ [Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) 可協助您即時收集和處理大型資料記錄串流。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而不需要佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Personalize](https://docs.aws.amazon.com/personalize/latest/dg/what-is-personalize.html) 是一項全受管機器學習 (ML) 服務，可協助您根據您的資料為使用者產生項目建議。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。

**其他工具**
+ [pytest ](https://docs.pytest.org/en/7.2.x/index.html)是一種 Python 架構，用於撰寫小型且可讀取的測試。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**Code**

此模式的程式碼可在 GitHub [Animal Recommender](https://github.com/aws-samples/personalize-pet-recommendations) 儲存庫中使用。您可以從此儲存庫使用 AWS CloudFormation 範本來部署範例解決方案的資源。

**注意**  
Amazon Personalize 解決方案版本、事件追蹤器和行銷活動由在原生 CloudFormation 資源上擴展的[自訂資源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) （基礎設施內） 提供支援。

## 史詩
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-epics"></a>

### 建立基礎設施
<a name="create-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立隔離的 Python 環境。 | **Mac/Linux 設定**[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.html)**Windows 設定**若要手動建立虛擬環境，請從終端機執行 `% .venv\Scripts\activate.bat`命令。 | DevOps 工程師 | 
| 合成 CloudFormation 範本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.html)在步驟 2 中， `CDK_ENVIRONMENT` 是指 `config/{env}.yml` 檔案。 | DevOps 工程師 | 
| 部署資源並建立基礎設施。 | 若要部署解決方案資源，請從終端機執行 `./deploy.sh`命令。此命令會安裝所需的 Python 相依性。Python 指令碼會建立 S3 儲存貯體和 AWS Key Management Service (AWS KMS) 金鑰，然後新增初始模型建立的種子資料。最後，指令碼會執行 `cdk deploy`來建立剩餘的基礎設施。初始模型訓練會在堆疊建立期間進行。堆疊最多可能需要兩個小時才能完成建立。 | DevOps 工程師 | 

## 相關資源
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-resources"></a>
+ [Animal Recommender](https://github.com/aws-samples/personalize-pet-recommendations) (GitHub)
+ [AWS CDK 參考文件](https://docs.aws.amazon.com/cdk/api/v2/)
+ [Boto3 文件](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
+ [使用 Amazon Personalize 最佳化您選擇的業務指標的個人化建議 ](https://aws.amazon.com/blogs/machine-learning/optimize-personalized-recommendations-for-a-business-metric-of-your-choice-with-amazon-personalize/)(AWS Machine Learning 部落格）

## 其他資訊
<a name="generate-personalized-and-re-ranked-recommendations-using-amazon-personalize-additional"></a>

**範例承載和回應**

*建議 Lambda 函數*

若要擷取建議，請使用下列格式的承載向建議 Lambda 函數提交請求：

```
{
  "userId": "3578196281679609099",
  "limit": 6
}
```

下列範例回應包含動物群組的清單：

```
[{"id": "1-domestic short hair-1-1"},
{"id": "1-domestic short hair-3-3"},
{"id": "1-domestic short hair-3-2"},
{"id": "1-domestic short hair-1-2"},
{"id": "1-domestic short hair-3-1"},
{"id": "2-beagle-3-3"},
```

如果您離開 `userId` 欄位，函數會傳回一般建議。

*重新排序 Lambda 函數*

若要使用重新排名，請提交請求至重新排名的 Lambda 函數。承載包含要重新排名的所有項目 IDs`userId`的 及其中繼資料。下列範例資料使用適用於 `animal_species_id`(1=貓，2=狗） 的 Oxford Pets 類別，以及適用於 `animal_age_id`和 的整數 1-5`animal_size_id`：

```
{
   "userId":"12345",
   "itemMetadataList":[
      {
         "itemId":"1",
         "animalMetadata":{
            "animal_species_id":"2",
            "animal_primary_breed_id":"Saint_Bernard",
            "animal_size_id":"3",
            "animal_age_id":"2"
         }
      },
      {
         "itemId":"2",
         "animalMetadata":{
            "animal_species_id":"1",
            "animal_primary_breed_id":"Egyptian_Mau",
            "animal_size_id":"1",
            "animal_age_id":"1"
         }
      },
      {
         "itemId":"3",
         "animalMetadata":{
            "animal_species_id":"2",
            "animal_primary_breed_id":"Saint_Bernard",
            "animal_size_id":"3",
            "animal_age_id":"2"
         }
      }
   ]
}
```

Lambda 函數會重新排序這些項目，然後傳回排序清單，其中包含項目 IDs 和來自 Amazon Personalize 的直接回應。這是項目所在的動物群組及其分數的排名清單。Amazon Personalize [使用使用者個人化](https://docs.aws.amazon.com/personalize/latest/dg/native-recipe-new-item-USER_PERSONALIZATION.html)和[個人化排名](https://docs.aws.amazon.com/personalize/latest/dg/native-recipe-search.html)配方，在建議中包含每個項目的分數。這些分數代表 Amazon Personalize 針對使用者接下來將選擇的項目所擁有的相對確定性。分數越高代表確定性越高。

```
{
   "ranking":[
      "1",
      "3",
      "2"
   ],
   "personalizeResponse":{
      "ResponseMetadata":{
         "RequestId":"a2ec0417-9dcd-4986-8341-a3b3d26cd694",
         "HTTPStatusCode":200,
         "HTTPHeaders":{
            "date":"Thu, 16 Jun 2022 22:23:33 GMT",
            "content-type":"application/json",
            "content-length":"243",
            "connection":"keep-alive",
            "x-amzn-requestid":"a2ec0417-9dcd-4986-8341-a3b3d26cd694"
         },
         "RetryAttempts":0
      },
      "personalizedRanking":[
         {
            "itemId":"2-Saint_Bernard-3-2",
            "score":0.8947961
         },
         {
            "itemId":"1-Siamese-1-1",
            "score":0.105204
         }
      ],
      "recommendationId":"RID-d97c7a87-bd4e-47b5-a89b-ac1d19386aec"
   }
}
```

*Amazon Kinesis 承載*

要傳送至 Amazon Kinesis 的承載格式如下：

```
{
    "Partitionkey": "randomstring",
    "Data": {
        "userId": "12345",
        "sessionId": "sessionId4545454",
        "eventType": "DetailView",
        "animalMetadata": {
            "animal_species_id": "1",
            "animal_primary_breed_id": "Russian_Blue",
            "animal_size_id": "1",
            "animal_age_id": "2"
        },
        "animal_id": "98765"
        
    }
}
```

**注意**  
未驗證的使用者會移除 `userId` 欄位。

# 使用 SageMaker AI 和 hydra 簡化從本機開發到可擴展實驗的機器學習工作流程
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker"></a>

*David Sauerwein、Marco Geiger 和 Julian Ferdinand Grueber，Amazon Web Services*

## 摘要
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-summary"></a>

此模式提供統一的方法，以設定和執行從本機測試到 Amazon SageMaker AI 生產的機器學習 (ML) 演算法。ML 演算法是此模式的重點，但其方法延伸到特徵工程、推論和整個 ML 管道。此模式示範透過範例使用案例，從本機指令碼開發轉換至 SageMaker AI 訓練任務。

典型的 ML 工作流程是在本機機器上開發和測試解決方案、在雲端執行大規模實驗 （例如，使用不同的參數），以及在雲端部署已核准的解決方案。然後，必須監控和維護部署的解決方案。如果沒有統一的工作流程方法，開發人員通常需要在每個階段重構程式碼。如果解決方案依賴於此工作流程的任何階段可能變更的大量參數，則保持組織和一致性可能會變得越來越困難。

此模式可解決這些挑戰。首先，它提供統一的工作流程，無論在本機機器、容器還是 SageMaker AI 上執行，都不需要在環境之間進行程式碼重構。其次，它透過 Hydra 的組態系統簡化參數管理，其中參數是在不同的組態檔案中定義，可輕鬆修改和合併，並自動記錄每個執行的組態。如需此模式如何處理這些挑戰的詳細資訊，請參閱[其他資訊](#streamline-machine-learning-workflows-by-using-amazon-sagemaker-additional)。

## 先決條件和限制
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 部署和啟動 SageMaker AI 訓練任務的 AWS Identity and Access Management (IAM) [使用者角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html) 
+ AWS Command Line Interface (AWS CLI) 2.0 版或更新版本[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ 已安裝 [Poetry](https://python-poetry.org/) 1.8 版或更新版本，但早於 2.0 版
+ 已安裝 [Docker](https://www.docker.com/) 
+ Python [3.10.x 版](https://www.python.org/downloads/release/python-31011/)

**限制**
+ 此程式碼目前僅鎖定 SageMaker AI 訓練任務。將其擴展到處理任務和整個 SageMaker AI 管道非常簡單。
+ 若要進行完全生產的 SageMaker AI 設定，必須備妥其他詳細資訊。範例可以是用於運算和儲存的自訂 AWS Key Management Service (AWS KMS) 金鑰，或聯網組態。您也可以在 `config` 資料夾的專用子資料夾中使用 hydra 來設定這些額外的選項。
+ 有些 AWS 服務 無法全部使用 AWS 區域。如需區域可用性，請參閱[AWS 依區域的服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-architecture"></a>

下圖說明解決方案的架構。

![\[建立和執行 SageMaker AI 訓練或 HPO 任務的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/1db57484-f85c-49a6-b870-471dade02b26/images/d80e7474-a975-4d92-8f66-2d34e33053fd.png)


該圖顯示以下工作流程：

1. 資料科學家可以在本機環境中以小規模迭代演算法、調整參數，以及快速測試訓練指令碼，而不需要 Docker 或 SageMaker AI。（如需詳細資訊，請參閱《[Epics](#streamline-machine-learning-workflows-by-using-amazon-sagemaker-epics)》中的「在本機執行以進行快速測試」任務。)

1. 滿足演算法後，資料科學家會建置 Docker 映像並將其推送至名為 的 Amazon Elastic Container Registry (Amazon ECR) 儲存庫`hydra-sm-artifact`。（如需詳細資訊，請參閱《[Epics](#streamline-machine-learning-workflows-by-using-amazon-sagemaker-epics)》中的「在 SageMaker AI 上執行工作流程」。)

1. 資料科學家使用 Python 指令碼啟動 SageMaker AI 訓練任務或超參數最佳化 (HPO) 任務。對於一般訓練任務，調整後的組態會寫入名為 的 Amazon Simple Storage Service (Amazon S3) 儲存貯體`hydra-sample-config`。對於 HPO 任務，會套用位於 `config` 資料夾中的預設組態集。

1. SageMaker AI 訓練任務會提取 Docker 映像、從 Amazon S3 儲存貯體 讀取輸入資料`hydra-sample-data`，以及從 Amazon S3 儲存貯體擷取組態`hydra-sample-config`或使用預設組態。訓練後，任務會將輸出資料儲存至 Amazon S3 儲存貯體 `hydra-sample-data`。

**自動化和擴展**
+ 對於自動訓練、重新訓練或推論，您可以將 AWS CLI 程式碼與 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)、 [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)或 [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 等服務整合。
+ 可以透過變更執行個體大小的組態或新增分散式訓練的組態來實現擴展。

## 工具
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-tools"></a>

**AWS 服務**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。對於此模式， AWS CLI 適用於初始資源組態和測試。
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一種受管容器映像登錄服務，安全、可擴展且可靠。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/?id=docs_gateway) 是一種受管機器學習 (ML) 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。SageMaker AI Training 是 SageMaker AI 內的全受管 ML 服務，可大規模訓練 ML 模型。該工具可以有效地處理訓練模型的運算需求，利用內建的可擴展性和與其他模型的整合 AWS 服務。SageMaker AI Training 也支援自訂演算法和容器，因此可靈活用於各種 ML 工作流程。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [Docker](https://www.docker.com/) 是一組平台即服務 (PaaS) 產品，可在作業系統層級使用虛擬化在容器中交付軟體。它用於此模式，以確保從開發到部署，以及可靠地封裝相依性和程式碼等各種階段的環境一致。允許 Docker 的容器化，以便在整個工作流程中輕鬆擴展和控制版本。
+ [Hydra](https://hydra.cc/) 是一種組態管理工具，可為處理多個組態和動態資源管理提供彈性。它有助於管理環境組態，允許在不同環境中無縫部署。如需 Hydra 的詳細資訊，請參閱[其他資訊](#streamline-machine-learning-workflows-by-using-amazon-sagemaker-additional)。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。Python 用於撰寫 ML 程式碼和部署工作流程。
+ [Poetry](https://python-poetry.org/) 是一種在 Python 中管理相依性和封裝的工具。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [configuring-sagemaker-training-jobs-with-hydra](https://github.com/aws-samples/configuring-sagemaker-training-jobs-with-hydra) 儲存庫中使用。

## 最佳實務
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-best-practices"></a>
+ 選擇 IAM 角色以部署和啟動遵循最低權限原則的 SageMaker AI 訓練任務，並授予執行任務所需的最低許可。如需詳細資訊，請參閱 IAM 文件中的[授予最低權限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。
+ 使用暫時登入資料來存取終端機中的 IAM 角色。

## 史詩
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立和啟用虛擬環境。 | 若要建立和啟用虛擬環境，請在儲存庫的根目錄中執行下列命令：<pre>poetry install <br />poetry shell</pre> | 一般 AWS | 
| 部署基礎設施。 | 若要使用 CloudFormation 部署基礎設施，請執行下列命令：<pre>aws cloudformation deploy --template-file infra/hydra-sagemaker-setup.yaml --stack-name hydra-sagemaker-setup  --capabilities CAPABILITY_NAMED_IAM</pre> | 一般 AWS，DevOps 工程師 | 
| 下載範例資料。 | 若要將輸入資料從 [openml](https://www.openml.org/) 下載到本機電腦，請執行下列命令：<pre>python scripts/download_data.py</pre> | 一般 AWS | 
| 在本機執行 以進行快速測試。 | 若要在本機執行訓練程式碼進行測試，請執行下列命令：<pre>python mypackage/train.py data.train_data_path=data/train.csv evaluation.base_dir_path=data</pre>所有執行的日誌會依執行時間儲存在名為 的資料夾中`outputs`。如需詳細資訊，請參閱 [GitHub 儲存庫](https://github.com/aws-samples/configuring-sagemaker-training-jobs-with-hydra)中的「輸出」一節。您也可以使用 `--multirun`功能，以不同的參數平行執行多個訓練。如需詳細資訊，請參閱 [Hydra 文件](https://hydra.cc/docs/tutorials/basic/running_your_app/multi-run/)。 | 資料科學家 | 

### 在 SageMaker AI 上執行工作流程
<a name="run-workflows-on-sm"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定環境變數。 | 若要在 SageMaker AI 上執行任務，請設定下列環境變數，並提供您的 AWS 區域 和 AWS 帳戶 ID：<pre>export ECR_REPO_NAME=hydra-sm-artifact<br />export image_tag=latest<br />export AWS_REGION="<your_aws_region>" # for instance, us-east-1<br />export ACCOUNT_ID="<your_account_id>"<br />export BUCKET_NAME_DATA=hydra-sample-data-$ACCOUNT_ID<br />export BUCKET_NAME_CONFIG=hydra-sample-config-$ACCOUNT_ID<br />export AWS_DEFAULT_REGION=$AWS_REGION<br />export ROLE_ARN=arn:aws:iam::${ACCOUNT_ID}:role/hydra-sample-sagemaker<br />export INPUT_DATA_S3_PATH=s3://$BUCKET_NAME_DATA/hydra-on-sm/input/<br />export OUTPUT_DATA_S3_PATH=s3://$BUCKET_NAME_DATA/hydra-on-sm/output/</pre> | 一般 AWS | 
| 建立並推送 Docker 映像。 | 若要建立 Docker 映像並將其推送至 Amazon ECR 儲存庫，請執行下列命令：<pre>chmod +x scripts/create_and_push_image.sh<br />scripts/create_and_push_image.sh $ECR_REPO_NAME $image_tag $AWS_REGION $ACCOUNT_ID</pre>此任務假設您在環境中擁有有效的登入資料。Docker 映像會推送到先前任務中環境變數中指定的 Amazon ECR 儲存庫，並用於啟用訓練任務將在其中執行的 SageMaker AI 容器。 | ML 工程師，一般 AWS | 
| 將輸入資料複製到 Amazon S3。 | SageMaker AI 訓練任務需要接收輸入資料。若要將輸入資料複製到 Amazon S3 儲存貯體以取得資料，請執行下列命令：<pre>aws s3 cp data/train.csv "${INPUT_DATA_S3_PATH}train.csv" </pre> | 資料工程師，一般 AWS | 
| 提交 SageMaker AI 訓練任務。 | 若要簡化指令碼的執行，請在 `default.yaml` 檔案中指定預設組態參數。除了確保跨執行的一致性之外，此方法還提供視需要輕鬆覆寫預設設定的彈性。請參閱下列範例：<pre>python scripts/start_sagemaker_training_job.py sagemaker.role_arn=$ROLE_ARN sagemaker.config_s3_bucket=$BUCKET_NAME_CONFIG sagemaker.input_data_s3_path=$INPUT_DATA_S3_PATH sagemaker.output_data_s3_path=$OUTPUT_DATA_S3_PATH</pre> | 一般 AWS、ML 工程師、資料科學家 | 
| 執行 SageMaker AI 超參數調校。 | 執行 SageMaker AI 超參數調校類似於提交 SageMaker AII 訓練任務。不過，執行指令碼在一些重要方面有所不同，如您在 [start\$1sagemaker\$1hpo\$1job.py](https://github.com/aws-samples/configuring-sagemaker-training-jobs-with-hydra/blob/main/scripts/start_sagemaker_hpo_job.py) 檔案中所見。要調校的超參數必須透過 boto3 承載傳遞，而不是訓練任務的通道。若要啟動超參數最佳化 (HPO) 任務，請執行下列命令：<pre>python scripts/start_sagemaker_hpo_job.py sagemaker.role_arn=$ROLE_ARN sagemaker.config_s3_bucket=$BUCKET_NAME_CONFIG sagemaker.input_data_s3_path=$INPUT_DATA_S3_PATH sagemaker.output_data_s3_path=$OUTPUT_DATA_S3_PATH</pre> | 資料科學家 | 

## 疑難排解
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 權杖過期 | 匯出新的 AWS 登入資料。 | 
| 缺少 IAM 許可 | 請務必匯出具備所有必要 IAM 許可的 IAM 角色憑證，以部署 CloudFormation 範本並啟動 SageMaker AI 訓練任務。 | 

## 相關資源
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-resources"></a>
+ [使用 Amazon SageMaker AI 訓練模型](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html) (AWS 文件）
+ [什麼是超參數調校？](https://aws.amazon.com/what-is/hyperparameter-tuning/#:~:text=Hyperparameter%20tuning%20allows%20data%20scientists,the%20model%20as%20a%20hyperparameter.)

## 其他資訊
<a name="streamline-machine-learning-workflows-by-using-amazon-sagemaker-additional"></a>

此模式可解決下列挑戰：

**從本機開發到大規模部署的一致性** – 透過此模式，開發人員可以使用相同的工作流程，無論他們是使用本機 Python 指令碼、執行本機 Docker 容器、在 SageMaker AI 上執行大型實驗，還是在 SageMaker AI 的生產環境中部署。由於下列原因，此一致性很重要：
+ **更快速的反覆運算** – 它允許快速的本機實驗，而不需要在擴展時進行重大調整。
+ **不重構** – 在 SageMaker AI 上轉換到更大的實驗是無縫的，不需要對現有設定進行大修。
+ **持續改進** – 開發新功能並持續改進演算法非常簡單，因為程式碼在環境中保持不變。

**組態管理** – 此模式使用組態管理工具 [hydra](https://hydra.cc/) 來提供下列優點：
+ 參數是在組態檔案中定義，與程式碼分開。
+ 您可以輕鬆交換或組合不同的參數集。
+ 實驗追蹤會簡化，因為每個執行的組態都會自動記錄。
+ 雲端實驗可以使用與本機執行相同的組態結構，以確保一致性。

使用 Hydra，您可以有效管理組態，啟用下列功能：
+ **分割組態** – 將您的專案組態分成可獨立修改的較小、可管理的部分。這種方法可讓您更輕鬆地處理複雜的專案。
+ **輕鬆調整預設值** – 快速變更基準組態，讓您更輕鬆地測試新想法。
+ **對齊 CLI 輸入和組態檔案** – 順暢地將命令列輸入與您的組態檔案合併。這種方法可減少雜亂和混淆，讓您的專案隨著時間更易於管理。

 

# 將自然語言轉換為查詢 DSL for OpenSearch 和 Elasticsearch 查詢
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch"></a>

*Tabby Ward、Nicholas Switzer 和 Breanne Warner，Amazon Web Services*

## 總結
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-summary"></a>

此模式示範如何使用大型語言模型 (LLMs) 將自然語言查詢轉換為查詢網域特定的語言 （查詢 DSL)，讓使用者更輕鬆地與搜尋服務互動，例如 OpenSearch 和 Elasticsearch，而無需對查詢語言有廣泛的了解。對於想要使用自然語言查詢功能增強以搜尋為基礎的應用程式，最終改善使用者體驗和搜尋功能的開發人員和資料科學家來說，此資源特別有用。

模式說明了提示性工程、反覆精簡和納入專業知識的技術，這些技術對於合成資料產生至關重要。雖然此方法主要著重於查詢轉換，但隱含地展示了資料擴增和可擴展性合成資料生產的可能性。此基礎可以擴展到更全面的合成資料產生任務，以強調 LLMs使用結構化、應用程式特定的輸出橋接非結構化自然語言輸入的能力。

此解決方案在傳統意義上不涉及遷移或部署工具。相反地，它著重於示範使用 LLMs概念驗證 (PoC)。
+ 模式使用 Jupyter 筆記本做為step-by-step指南。 text-to-query 
+ 它使用 Amazon Bedrock 存取 LLMs，這對於解譯自然語言和產生適當的查詢至關重要。
+ 解決方案旨在與 Amazon OpenSearch Service 搭配使用。您可以遵循 Elasticsearch 的類似程序，而產生的查詢可能會適應類似的搜尋引擎。

[查詢 DSL](https://opensearch.org/docs/latest/query-dsl/) 是一種靈活的 JSON 型搜尋語言，用於在 Elasticsearch 和 OpenSearch 中建構複雜的查詢。它可讓您在搜尋操作的查詢參數中指定查詢，並支援各種查詢類型。DSL 查詢包含分葉查詢和複合查詢。分葉查詢會搜尋特定欄位中的特定值，並包含全文、術語層級、地理、聯結、跨度和特殊化查詢。複合查詢可做為多個分葉或複合子句的包裝函式，並結合其結果或修改其行為。查詢 DSL 支援建立複雜的搜尋，範圍從簡單的所有相符查詢，到產生高度特定結果的複雜多子句查詢。對於需要進階搜尋功能、彈性查詢建構和 JSON 型查詢結構的專案，查詢 DSL 特別有價值。

此模式使用技術，例如少量擷取提示、系統提示、結構化輸出、提示鏈結、內容佈建，以及text-to-query DSL 轉換的任務特定提示。如需這些技術的定義和範例，請參閱[其他資訊](#translate-natural-language-query-dsl-opensearch-elasticsearch-additional)一節。

## 先決條件和限制
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-prereqs"></a>

**先決條件**

若要有效地使用 Jupyter 筆記本將自然語言查詢轉換為查詢 DSL 查詢，您需要：
+ **熟悉 Jupyter 筆記本**。對如何在 Jupyter 筆記本環境中導覽和執行程式碼的基本了解。
+ **Python 環境**。運作中的 Python 環境，最好是 Python 3.x，並已安裝必要的程式庫。
+ **Elasticsearch 或 OpenSearch 知識**。Elasticsearch 或 OpenSearch 的基本知識，包括其架構以及如何執行查詢。
+ **AWS 帳戶**。 AWS 帳戶 用於存取 Amazon Bedrock 和其他相關服務的作用中 。
+ **程式庫和相依性**。安裝筆記本中提及的特定程式庫，例如`boto3` AWS 互動，以及 LLM 整合所需的任何其他相依性。
+ **Amazon Bedrock 內的模型存取**。此模式使用來自 Anthropic LLMs。開啟 [Amazon Bedrock 主控台](https://console.aws.amazon.com/bedrock/)，然後選擇**模型存取**。在下一個畫面上，選擇**啟用特定模型**，然後選取這三個模型：
  + Claude 3 Sonnet
  + Claude 3.5 Sonnet
  + Claude 3 Haiku
+ **適當的 IAM 政策和 IAM 角色**。若要在 中執行筆記本 AWS 帳戶，您的 AWS Identity and Access Management (IAM) 角色需要 `SagemakerFullAccess` 政策以及[其他資訊](#translate-natural-language-query-dsl-opensearch-elasticsearch-additional)區段中提供的政策，您可以將其命名為 `APGtext2querydslpolicy`。此政策包含訂閱列出的三個 Claude 模型。

備妥這些先決條件可確保在使用筆記本時獲得順暢的體驗，並實作text-to-query功能。

**限制**
+ **概念狀態證明**。此專案主要用於概念驗證 (PoC)。它示範了使用 LLMs 將自然語言查詢轉換為查詢 DSL 的可能性，但它可能尚未完全最佳化或可供生產使用。
+ **模型限制**：

  **內容視窗限制***條件。*使用 Amazon Bedrock 上可用的 LLMs 時，請注意內容時段限制：

  Claude 模型 （截至 2024 年 9 月）：
  + Claude 3 Opus：200，000 個字符
  + Claude 3 Sonnet：200，000 個字符
  + Claude 3 Haiku：200，000 個字符

  Amazon Bedrock 上的其他模型可能會有不同的內容視窗大小。請務必檢查最新的文件以取得最新資訊。

  **模型可用性***。 *Amazon Bedrock 上特定模型的可用性可能會有所不同。在實作此解決方案之前，請確定您能夠存取所需的模型。
+ **其他限制**
  + **查詢複雜性**。查詢 DSL 轉換的自然語言有效性可能會因輸入查詢的複雜性而有所不同。
  + **版本相容性**。產生的查詢 DSL 可能需要根據您使用的 Elasticsearch 或 OpenSearch 特定版本進行調整。
  + **效能**。此模式提供 PoC 實作，因此查詢產生速度和準確性可能不最適合大規模生產使用。
  + **成本**：在 Amazon Bedrock 中使用 LLMs 會產生成本。請注意所選模型的定價結構。如需詳細資訊，請參閱 [Amazon Bedrock 定價](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-pricing.html)。
  + **維護**。為了跟上 LLM 技術的進展和查詢 DSL 語法的變更，可能需要定期更新提示和模型選擇。

**產品版本**

此解決方案已在 Amazon OpenSearch Service 中測試。如果您想要使用 Elasticsearch，您可能需要進行一些變更，才能複寫此模式的確切功能。
+ **OpenSearch 版本相容性**。** **OpenSearch 在主要版本中維持回溯相容性。例如：
  + OpenSearch 1.x 用戶端通常與 OpenSearch 1.x 叢集相容。
  + OpenSearch 2.x 用戶端通常與 OpenSearch 2.x 叢集相容。

  不過，最好盡可能同時針對用戶端和叢集使用相同的次要版本。
+ **OpenSearch API 相容性**。** **OpenSearch 針對大多數操作維持與 Elasticsearch OSS 7.10.2 的 API 相容性。不過，存在一些差異，特別是在較新的版本中。
+ **OpenSearch 升級考量**事項：
  + 不支援直接降級。視需要使用快照進行轉返。
  + 升級時，請檢查[相容性矩陣和版本備註](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/supported-operations.html)是否有任何重大變更。

**Elasticsearch 考量事項**
+ **Elasticsearch 版本**。您使用的 Elasticsearch 主要版本至關重要，因為查詢語法和功能可能會在主要版本之間變更。目前，最新的穩定版本是 Elasticsearch 8.x。請確定您的查詢與您的特定 Elasticsearch 版本相容。
+ **Elasticsearch 查詢 DSL 程式庫版本**。如果您使用的是 Elasticsearch 查詢 DSL Python 程式庫，請確定其版本與您的 Elasticsearch 版本相符。例如：
  + 對於 Elasticsearch 8.x，請使用大於或等於 8.0.0 但小於 9.0.0 的`elasticsearch-dsl`版本。
  + 對於 Elasticsearch 7.x，請使用大於或等於 7.0.0 但小於 8.0.0 的`elasticsearch-dsl`版本。
+ **用戶端程式庫版本**。無論您是使用官方 Elasticsearch 用戶端還是特定語言用戶端，請確定它與您的 Elasticsearch 版本相容。
+ **查詢 DSL 版本**。查詢 DSL 會隨著 Elasticsearch 版本而演進。某些查詢類型或參數可能會遭到取代，或在不同的版本中引入。
+ **映射版本**。定義索引映射和版本之間變更的方式。請務必檢查特定 Elasticsearch 版本的映射文件。
+ **分析工具版本**。如果您使用的是分析器、權杖化器或其他文字分析工具，其行為或可用性可能會在版本之間變更。

## Architecture
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-architecture"></a>

**目標架構**

下圖說明此模式的架構。

![\[用於翻譯自然語言以在 Amazon Bedrock 中查詢 DSL 的架構。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/75296405-2893-4328-9551-9bcc6ec7fd3e/images/ffb1b893-d23c-4e1c-b679-8063b4f85a8a.png)


其中：

1. 使用者輸入和系統提示，其中包含少量的提示範例。程序從提供自然語言查詢或產生結構描述請求的使用者開始。

1. Amazon Bedrock。輸入會傳送到 Amazon Bedrock，做為存取 Claude LLM 的界面。

1. Claude 3 Sonnet LLM。Amazon Bedrock 使用來自 Claude 3 系列 LLMs Claude 3 Sonnet 來處理輸入。它會解譯並產生適當的 Elasticsearch 或 OpenSearch 查詢 DSL。對於結構描述請求，它會產生合成 Elasticsearch 或 OpenSearch 映射。

1. 查詢 DSL 產生。對於自然語言查詢，應用程式會取得 LLM 的輸出，並將其格式化為有效的 Elasticsearch 或 OpenSearch Service 查詢 DSL。

1. 合成資料產生。應用程式也會採用結構描述來建立合成 Elasticsearch 或 OpenSearch 資料，以載入 OpenSearch Serverless 集合進行測試。

1. OpenSearch 或 Elasticsearch。產生的查詢 DSL 會針對所有索引上的 OpenSearch Serverless 集合進行查詢。JSON 輸出包含來自 OpenSearch Serverless 集合中資料的相關資料和*命*中次數。

**自動化和擴展**

此模式提供的程式碼專為 PoC 用途而建置。以下清單提供一些建議，讓您進一步自動化和擴展解決方案，並將程式碼移至生產環境。這些增強功能超出此模式的範圍。
+ 容器化：
  + Dockerize 應用程式以確保不同環境的一致性。
  + 使用 Amazon Elastic Container Service (Amazon ECS) 或 Kubernetes 等容器協同運作平台進行可擴展的部署。
+ 無伺服器架構：
  + 將核心功能轉換為 AWS Lambda 函數。
  + 使用 Amazon API Gateway 為自然語言查詢輸入建立 RESTful 端點。
+ 非同步處理：
  + 實作 Amazon Simple Queue Service (Amazon SQS) 將傳入的查詢排入佇列。
  + 使用 AWS Step Functions 來協調處理查詢和產生查詢 DSL 的工作流程。
+ 快取：
  + 實作機制以快取提示。
+ 監控和記錄：
  + 使用 Amazon CloudWatch 進行監控和提醒。
  + 使用 Amazon CloudWatch Logs 或 Amazon OpenSearch Service 實作集中式日誌記錄，以進行日誌分析。
+ 安全性增強功能：
  + 實作 IAM 角色以進行精細存取控制。
  + 使用 AWS Secrets Manager 安全地存放和管理 API 金鑰和登入資料。
+ 多區域部署：
  + 請考慮在多個 之間部署解決方案 AWS 區域 ，以改善延遲和災難復原。
  + 使用 Amazon Route 53 進行智慧型請求路由。

透過實作這些建議，您可以將此 PoC 轉換為強大、可擴展且可供生產使用的解決方案。我們建議您在完全部署之前徹底測試每個元件和整個系統。

## 工具
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-tools"></a>

**工具**
+ [Amazon SageMaker AI 筆記本](https://aws.amazon.com/sagemaker/notebooks/)是全受管的 Jupyter 筆記本，用於機器學習開發。此模式使用筆記本做為互動式環境，在 Amazon SageMaker AI 中進行資料探索、模型開發和實驗。筆記本可與其他 SageMaker AI 功能 和 無縫整合 AWS 服務。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。此模式使用 Python 做為核心語言來實作解決方案。
+ [Amazon Bedrock](https://aws.amazon.com/bedrock/) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。Amazon Bedrock 提供 LLMs的存取權，以進行自然語言處理。此模式使用 Anthropic Claude 3 模型。
+ [適用於 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) 是一種軟體開發套件，可協助您整合 Python 應用程式、程式庫或指令碼 AWS 服務，包括 Amazon Bedrock。
+ [Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) 是一項受管服務，可協助您在 AWS 雲端中部署、操作和擴展 OpenSearch Service 叢集。此模式使用 OpenSearch Service 做為產生查詢 DSL 的目標系統。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [Prompt Engineering Text-to-QueryDSL 中使用 Claude 3 Models](https://github.com/aws-samples/text-to-queryDSL/blob/main/text2ES_prompting_guide.ipynb) 儲存庫。此範例使用運作狀態社交媒體應用程式，為與運作狀態應用程式相關聯的使用者和使用者設定檔建立貼文。

## 最佳實務
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-best-practices"></a>

使用此解決方案時，請考慮下列事項：
+ 需要適當的 AWS 登入資料和許可才能存取 Amazon Bedrock
+ 與使用 AWS 服務 和 LLMs相關的潛在成本
+ 了解查詢 DSL 驗證並可能修改所產生查詢的重要性

## 史詩
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-epics"></a>

### 設定環境並準備資料
<a name="set-up-the-environment-and-prepare-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定開發環境。 | 如需此模式和此模式中其他步驟的詳細說明和程式碼，請參閱 [GitHub 儲存庫](https://github.com/aws-samples/text-to-queryDSL/blob/main/text2ES_prompting_guide.ipynb)中的完整演練。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/translate-natural-language-query-dsl-opensearch-elasticsearch.html) | Python、pip、AWS 開發套件 | 
| 設定 AWS 存取權。 | 設定 Amazon Bedrock 用戶端和 SageMaker AI 工作階段。擷取 SageMaker AI 執行角色的 Amazon Resource Name (ARN)，以供日後建立 OpenSearch Serverless 集合時使用。 | IAM、AWS CLI、Amazon Bedrock、Amazon SageMaker | 
| 載入運作狀態應用程式結構描述。 | 從預先定義的檔案讀取和剖析運作狀態文章和使用者設定檔的 JSON 結構描述。將結構描述轉換為字串以供稍後在提示中使用。 | DevOps 工程師、一般 AWS、Python、JSON | 

### 產生合成資料
<a name="generate-synthetic-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 LLM 型資料產生器。 | 實作 **generate\$1data()** 函數，以 Claude 3 模型呼叫 Amazon Bedrock Converse API。設定 Sonnet、Sonnet 3.5 和 Haiku IDs：<pre>model_id_sonnet3_5 = "anthropic.claude-3-5-sonnet-20240620-v1:0" <br />model_id_sonnet = "anthropic.claude-3-sonnet-20240229-v1:0" <br />model_id_haiku = "anthropic.claude-3-haiku-20240307-v1:0"</pre> | Python、Amazon Bedrock API、LLM 提示 | 
| 建立合成運作狀態文章。 | 使用 **generate\$1data()** 函數搭配特定訊息提示，根據提供的結構描述建立合成運作狀態文章項目。函數呼叫如下所示：<pre>health_post_data = generate_data(bedrock_rt, model_id_sonnet, system_prompt, message_healthpost, inference_config)</pre> | Python、JSON | 
| 建立合成使用者設定檔。 | 使用 **generate\$1data()** 函數搭配特定訊息提示，根據提供的結構描述建立合成使用者設定檔項目。這類似於產生運作狀態文章，但使用不同的提示。 | Python、JSON | 

### 設定 OpenSearch 和擷取資料
<a name="set-up-opensearch-and-ingest-data"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 OpenSearch Serverless 集合。 | 使用 Boto3 建立具有適當加密、網路和存取政策的 OpenSearch Serverless 集合。集合建立如下所示：<pre>collection = aoss_client.create_collection(name=es_name, type='SEARCH')</pre> 如需 OpenSearch Serverless 的詳細資訊，請參閱 [AWS 文件](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless.html)。 | OpenSearch Serverless、IAM | 
| 定義 OpenSearch 索引。 | 根據預先定義的結構描述映射，使用 OpenSearch 用戶端建立運作狀態文章和使用者設定檔的 indiexe。索引建立如下所示：<pre>response_health = oss_client.indices.create(healthpost_index, body=healthpost_body)</pre> | OpenSearch、JSON | 
| 將資料載入 OpenSearch。 | 執行 **ingest\$1data()** 函數，將合成運作狀態文章和使用者設定檔大量插入各自的 OpenSearch 索引。函數使用來自 的大量協助程式`opensearch-py`：<pre>success, failed = bulk(oss_client, actions)</pre> | Python、OpenSearch API、大量資料操作 | 

### 產生和執行查詢
<a name="generate-and-run-queries"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設計少量擷取提示範例。 | 使用 Claude 3 模型產生範例查詢和對應的自然語言問題，做為產生查詢的少量範例。系統提示包含下列範例：<pre>system_prompt_query_generation = [{"text": f"""You are an expert query dsl generator. ... Examples: {example_prompt} ..."""}]</pre> | LLM 提示、查詢 DSL | 
| 建立text-to-query DSL 轉換器。 | 實作系統提示，其中包含結構描述、資料和少量擷取範例，以產生查詢。使用系統提示將自然語言查詢轉換為查詢 DSL。函數呼叫如下所示：<pre>query_response = generate_data(bedrock_rt, model_id, system_prompt_query_generation, query, inference_config)</pre> | Python、Amazon Bedrock API、LLM 提示 | 
| 在 OpenSearch 上測試查詢 DSL。 | 執行 **query\$1oss()** 函數，針對 OpenSearch Serverless 集合執行產生的查詢 DSL，並傳回結果。函數使用 OpenSearch 用戶端的搜尋方法：<pre>response = oss_client.search(index="_all", body=temp)</pre> | Python、OpenSearch API、查詢 DSL | 

### 測試和評估
<a name="test-and-evaluate"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立測試查詢集。 | 使用 Claude 3 根據合成資料和結構描述產生一組不同的測試問題：<pre>test_queries = generate_data(bedrock_rt, model_id_sonnet, query_system_prompt, query_prompt, inference_config)</pre> | LLM 提示 | 
| 評估查詢 DSL 轉換的準確性。 | 對 OpenSearch 執行查詢，並分析傳回的結果相關性和準確性，以測試產生的查詢 DSL。這包括執行查詢和檢查命中：<pre>output = query_oss(response1) print("Response after running query against Opensearch") print(output)</pre> | Python、資料分析、查詢 DSL | 
| 基準 Claude 3 模型。 | 比較不同 Claude 3 模型 (Haiku、Sonnet、Sonnet 3.5) 在準確性和延遲方面產生查詢的效能。若要比較，請在呼叫 **generate\$1data()** `model_id` 時變更 並測量執行時間。 | Python、效能基準測試 | 

### 清除和記錄
<a name="clean-up-and-document"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 開發清除程序。 | 使用後從 OpenSearch Serverless 集合中刪除所有索引。 | Python、AWS 開發套件、OpenSearch API | 

## 相關資源
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-resources"></a>
+ [查詢 DSL](https://opensearch.org/docs/latest/query-dsl/) (OpenSearch 文件）
+ [Amazon OpenSearch Service 文件](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html)
+ [OpenSearch Serverless 集合](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-manage.html)
+ [Amazon Bedrock 文件](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
+ [Amazon SageMaker AI 文件](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html)
+ [適用於 Python (Boto3) 的 AWS SDK 文件](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)

## 其他資訊
<a name="translate-natural-language-query-dsl-opensearch-elasticsearch-additional"></a>

**IAM 政策**

以下是此模式中所用 IAM 角色`APGtext2querydslpolicy`的政策：

```
{
  "Version": "2012-10-17",		 	 	  
  "Statement": [
    { "Effect": "Allow", 
      "Action": [ 
        "bedrock:InvokeModel", 
        "bedrock:InvokeModelWithResponseStream"
      ], 
      "Resource": "*" 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "s3:GetObject", 
        "s3:PutObject", 
        "s3:ListBucket"
      ], 
      "Resource": [
        "arn:aws:s3:::sagemaker-*", 
        "arn:aws:s3:::sagemaker-*/*" 
      ] 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "logs:CreateLogGroup", 
        "logs:CreateLogStream", 
        "logs:PutLogEvents" 
      ], 
      "Resource": "arn:aws:logs:*:*:log-group:/aws/sagemaker/*" 
    }, 
    { "Effect": "Allow", 
      "Action": [
        "ec2:CreateNetworkInterface", 
        "ec2:DescribeNetworkInterfaces", 
        "ec2:DeleteNetworkInterface" 
      ], 
      "Resource": "*" 
    }, 
    { "Effect": "Allow", 
      "Action": [
        "aoss:*" 
      ], 
      "Resource": "*" 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "iam:PassRole", 
        "sagemaker:*" 
      ], 
      "Resource": [ 
        "arn:aws:iam::*:role/*", "*" 
      ], 
      "Condition": { 
        "StringEquals": { 
          "iam:PassedToService": "sagemaker.amazonaws.com" 
          } 
      } 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "codecommit:GetBranch", 
        "codecommit:GetCommit", 
        "codecommit:GetRepository", 
        "codecommit:ListBranches", 
        "codecommit:ListRepositories" 
      ], 
      "Resource": "*" 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "aws-marketplace:Subscribe" 
      ], 
      "Resource": "*", 
      "Condition": {
        "ForAnyValue:StringEquals": { 
          "aws-marketplace:ProductId": [ 
            "prod-6dw3qvchef7zy", 
            "prod-m5ilt4siql27k", 
            "prod-ozonys2hmmpeu" 
          ]
        } 
      } 
    }, 
    { "Effect": "Allow", 
      "Action": [ 
        "aws-marketplace:Unsubscribe", 
        "aws-marketplace:ViewSubscriptions" 
      ], 
      "Resource": "*" 
    }, 
    { "Effect": "Allow", 
      "Action": "iam:*", 
      "Resource": "*" 
    } 
  ] 
}
```

**Anthropic Claude 3 模型的提示技術**

此模式示範使用 Claude 3 模型進行text-to-query DSL 轉換的下列提示技術。
+ **Few-shot 提示：**Few-shot 提示是改善 Amazon Bedrock 上 Claude 3 模型效能的強大技術。此方法涉及為模型提供少量範例，示範所需的輸入/輸出行為，然後再要求它執行類似的任務。當您在 Amazon Bedrock 上使用 Claude 3 模型時，對於需要特定格式、推理模式或網域知識的任務，少量擷取提示特別有效。若要實作此技術，您通常會使用兩個主要元件來建構提示：範例區段和實際查詢。範例區段包含一或多個說明任務的輸入/輸出對，而查詢區段會顯示您想要回應的新輸入。此方法有助於 Claude 3 了解內容和預期的輸出格式，通常會導致更準確且一致的回應。

  範例：

  ```
  "query": {
    "bool": {
      "must": [
        {"match": {"post_type": "recipe"}},
        {"range": {"likes_count": {"gte": 100}}},
        {"exists": {"field": "media_urls"}}
      ]
    }
  }
  Question: Find all recipe posts that have at least 100 likes and include media URLs.
  ```
+ **系統提示：**除了少量擷取提示之外，Amazon Bedrock 上的 Claude 3 模型也支援使用系統提示。系統提示是在向模型提供特定使用者輸入之前，提供模型整體內容、指示或指導方針的方法。它們特別適用於設定音調、定義模型的角色，或建立整個對話的限制。若要在 Amazon Bedrock 上使用 Claude 3 的系統提示，請在 API 請求的 `system` 參數中包含它。這與使用者訊息分開，並套用於整個互動。詳細的系統提示用於設定內容並提供模型的指導方針。

  範例：

  ```
  You are an expert query dsl generator. Your task is to take an input question and generate a query dsl to answer the question. Use the schemas and data below to generate the query.
  
  Schemas: [schema details]
  Data: [sample data]
  Guidelines: 
  - Ensure the generated query adheres to DSL query syntax
  - Do not create new mappings or other items that aren't included in the provided schemas.
  ```
+ **結構化輸出**：您可以指示模型以特定格式提供輸出，例如 JSON 或在 XML 標籤內。

  範例：

  ```
  Put the query in json tags
  ```
+ **提示鏈結**：筆記本使用一個 LLM 呼叫的輸出做為另一個 LLM 呼叫的輸入，例如使用產生的合成資料來建立範例問題。
+ **內容佈建**：相關內容，包括結構描述和範例資料，會在提示中提供。

  範例：

  ```
  Schemas: [schema details]
  Data: [sample data]
  ```
+ **任務特定的提示**：針對特定任務製作不同的提示，例如產生合成資料、建立範例問題，以及將自然語言查詢轉換為查詢 DSL。

  產生測試問題的範例：

  ```
  Your task is to generate 5 example questions users can ask the health app based on provided schemas and data. Only include the questions generated in the response.
  ```

# 使用 Amazon Q Developer 作為編碼助理，以提高您的生產力
<a name="use-q-developer-as-coding-assistant-to-increase-productivity"></a>

*Ram Kandaswamy，Amazon Web Services*

## 總結
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-summary"></a>

此模式使用 tic-tac-toe 遊戲，示範如何在各種開發任務中套用 Amazon Q Developer。它會產生 tic-tac-toe 遊戲的程式碼做為單頁應用程式 (SPA)，增強其 UI，並建立指令碼來部署應用程式 AWS。

Amazon Q Developer 做為編碼助理，協助加速軟體開發工作流程，並增強開發人員和非開發人員的生產力。無論您的技術專業知識為何，都可協助您為業務問題建立架構和設計解決方案、引導您的工作環境、協助您實作新功能，以及產生測試案例以進行驗證。它使用自然語言指示和 AI 功能，以確保一致的高品質程式碼，並緩解編碼挑戰，無論您的程式設計技能為何。

Amazon Q Developer 的主要優點是能夠讓您擺脫重複的編碼任務。當您使用`@workspace`註釋時，Amazon Q Developer 會擷取整合開發環境 (IDE) 中的所有程式碼檔案、組態和專案結構，並提供量身打造的回應，協助您專注於創意問題解決。您可以花更多時間設計創新解決方案並增強使用者體驗。如果您不是技術，則可以使用 Amazon Q Developer 來簡化工作流程，並與開發團隊更有效地協作。Amazon Q Developer **Explain 程式碼**功能提供詳細說明和摘要，因此您可以導覽複雜的程式碼庫。

此外，Amazon Q Developer 提供與語言無關的方法，可協助初階和中階開發人員擴展技能集。您可以專注於核心概念和商業邏輯，而不是語言特定的語法。當您切換技術時，這會減少學習曲線。

## 先決條件和限制
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-prereqs"></a>

**先決條件**
+ 安裝 Amazon Q Developer 外掛程式的 IDE （例如 WebStorm 或 Visual Studio Code)。如需說明，請參閱[《Amazon Q Developer 文件》中的在 IDE 中安裝 Amazon Q Developer 延伸模組或外掛程式](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/q-in-IDE-setup.html)。
+ 使用 Amazon Q Developer 的作用中 AWS 帳戶 設定。如需說明，請參閱 Amazon Q Developer 文件中的[入門](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/getting-started-q-dev.html)。
+ **npm** 已安裝。如需說明，請參閱 [npm 文件](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。此模式已使用 npm 10.8 版進行測試。
+ AWS Command Line Interface (AWS CLI) 已安裝。如需說明，請參閱 [AWS CLI 文件](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

**限制**
+ Amazon Q Developer 一次只能執行一個開發任務。
+ 有些 AWS 服務 完全無法使用 AWS 區域。如需區域可用性，請參閱[AWS 服務 依區域](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)頁面，然後選擇服務的連結。

## 工具
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-tools"></a>
+ 此模式需要 IDE，例如 Visual Studio Code 或 WebStorm。如需支援的 IDEs 清單，請參閱 [Amazon Q Developer 文件](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/q-in-IDE.html#supported-ides-features)。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。

## 最佳實務
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-best-practices"></a>

請參閱 AWS 方案指引中的[使用 Amazon Q Developer 進行最佳編碼實務](https://docs.aws.amazon.com/prescriptive-guidance/latest/best-practices-code-generation/best-practices-coding.html)。此外：
+ 當您向 Amazon Q Developer 提供提示時，請確定您的指示清楚明確。新增程式碼片段和註釋，例如 `@workspace`到提示中，為您的提示提供更多內容。
+ 包含相關的程式庫並進行匯入，以避免系統發生衝突或不正確的猜測。
+ 如果產生的程式碼不正確或如預期，請使用**提供意見回饋和重新產生**選項。嘗試將提示分成較小的指示。

## 史詩
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-epics"></a>

### 設定工作環境
<a name="set-up-the-working-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立新專案。 | 若要在工作環境中建立新的專案，請執行下列命令，並接受所有問題的預設設定：<pre>npx create-next-app@latest</pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 測試基礎應用程式。 | 執行下列命令，並確認基礎應用程式在瀏覽器中成功載入：<pre>npm run dev </pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 清除基本程式碼。 | 導覽至 `src/app` 資料夾中`page.tsx`的檔案，並刪除預設內容以取得空白頁面。刪除後，檔案應如下所示：<pre>export default function Home() {<br />  return (<div></div><br />      );<br />}</pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 

### 使用 Amazon Q Developer 設計 tic-tac-toe 遊戲專案
<a name="use-qdevlong-to-design-a-tic-tac-toe-game-project"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 取得步驟概觀。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-q-developer-as-coding-assistant-to-increase-productivity.html) | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 產生 tic-tac-toe 的程式碼。 | 在聊天面板中，使用 `/dev`命令啟動開發任務，後面接著任務的描述。例如：<pre>/dev Create a React-based single-page application  written in TypeScript for a tic-tac-toe game with the following specifications:<br />1. Design an aesthetically pleasing interface with the game grid centered vertically and <br />horizontally on the page. <br />2. Include a heading and clear instructions on how to play the game.<br />3. Implement color-coding for X and O marks to distinguish them easily. </pre>Amazon Q Developer 會根據您的指示產生程式碼。 | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 檢查並接受產生的程式碼。 | 目測檢查程式碼，然後選擇**接受程式碼**以自動取代`page.tsx`檔案。如果您遇到問題，請選擇**提供意見回饋並重新產生**並描述您遇到的問題。 | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 修正 lint 錯誤。 | 範例 tic-tac-toe 遊戲包含網格。Amazon Q Developer 產生的程式碼可能會使用預設類型 `any`。您可以提示 Amazon Q Developer 來新增類型安全，如下所示：<pre>/dev Ensure proper TypeScript typing for the onSquare Click event handler <br />to resolve any 'any' type issues.</pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 新增視覺效果吸引力。 | 您可以將原始需求分成較小的片段。例如，您可以在開發任務中使用下列提示來改善遊戲 UI。此提示可增強串聯樣式表 (CSS) 樣式，並匯出應用程式以進行部署。<pre>/dev Debug and fix any CSS issues to correctly display the game grid and overall layout. <br /><br />Simplify the code by removing game history functionality and related components. <br /><br />Implement static file export to an 'out' directory for easy deployment. The solution <br />should be fully functional, visually appealing, and free of typing errors or layout issues. </pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 再次測試。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-q-developer-as-coding-assistant-to-increase-productivity.html) | 應用程式開發人員、程式設計師、軟體開發人員 | 

### 將應用程式部署到 AWS 雲端
<a name="deploy-the-application-to-the-aws-cloud"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立要部署的資料夾和檔案。 | 在工作環境中的專案中，建立部署資料夾和其中的兩個檔案： `pushtos3.sh`和 `cloudformation.yml`：<pre>mkdir deployment && cd deployment<br />touch pushtos3.sh && chmod +x pushtos3.sh<br />touch cloudformation.yml</pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 產生自動化程式碼。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-q-developer-as-coding-assistant-to-increase-productivity.html) | AWS 管理員、AWS DevOps、應用程式開發人員 | 
| 產生指令碼內容。 | 若要建立部署指令碼，請使用下列提示：<pre>/dev Modify the pushtos3 shell script so that it can use AWS CLI commands to create a <br />CloudFormation stack named tictactoe-stack if it does not exist already, and use <br />cloudformation.yml as the source template. Wait for the stack to complete and sync the <br />contents from the out folder to the S3 bucket. Perform invalidation of the CloudFront <br />origin.</pre> | 應用程式開發人員、程式設計師、軟體開發人員 | 
| 將應用程式部署到 AWS 雲端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/use-q-developer-as-coding-assistant-to-increase-productivity.html) | AWS 管理員、AWS DevOps、雲端架構師、應用程式開發人員 | 

## 疑難排解
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 組建不會建立單頁應用程式或將其匯出至輸出資料夾。 | 查看 `next.config.mjs` 檔案的內容。如果程式碼具有下列預設組態：<pre>const nextConfig = {};</pre>修改如下：<pre>const nextConfig = {<br />  output: 'export',<br />  distDir: 'out',<br />};</pre> | 

## 相關資源
<a name="use-q-developer-as-coding-assistant-to-increase-productivity-resources"></a>
+ [建立新的 React 專案](https://react.dev/learn/start-a-new-react-project) (React 文件）
+ [Amazon Q Developer 概觀](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/what-is.html) (AWS 文件）
+ [Amazon Q Developer 最佳實務 ](https://docs.aws.amazon.com/prescriptive-guidance/latest/best-practices-code-generation/introduction.html)(AWS 方案指引）
+ [搭配 JetBrains IDEs 安裝、設定和使用 Amazon Q Developer ](https://www.youtube.com/watch?v=-iQfIhTA4J0&pp=ygUSYW1hem9uIHEgZGV2ZWxvcGVy)(YouTube 影片）
+ [為命令列安裝 Amazon Q](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-getting-started-installing.html) (AWS 文件）

# 使用 SageMaker Processing 對 TB 級 ML 資料集進行分散式特徵工程
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets"></a>

*Chris Boomhower，Amazon Web Services*

## 總結
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-summary"></a>

許多 TB 級或更大的資料集通常由階層式資料夾結構組成，而且資料集中的檔案有時會共用相互依存性。因此，機器學習 (ML) 工程師和資料科學家必須做出深思熟慮的設計決策，以準備此類資料進行模型訓練和推論。此模式示範如何結合 Amazon SageMaker Processing 和虛擬 CPU (vCPU) 平行處理，使用手動巨集分片和微分技術，以有效率地擴展複雜大數據 ML 資料集的特徵工程程序。 

此模式將*巨集碎片*定義為跨多部機器處理的資料目錄分割，並將*微碎片*定義為跨多個處理執行緒分割每部機器上的資料。模式透過使用 Amazon SageMaker 搭配 [PhysioNet MIMIC-III](https://physionet.org/content/mimic3wdb/1.0/) 資料集中的範例時間序列波形記錄來示範這些技術。透過在此模式中實作技術，您可以將特徵工程的處理時間和成本降至最低，同時最大化資源使用率和輸送量效率。這些最佳化仰賴 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體和 vCPUs 上的分散式 SageMaker Processing 進行類似的大型資料集，無論資料類型為何。

## 先決條件和限制
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-prereqs"></a>

**先決條件**
+ 如果您想要為自己的資料集實作此模式，請存取 SageMaker 筆記本執行個體或 SageMaker Studio。如果您是第一次使用 Amazon SageMaker，請參閱 AWS 文件中的[開始使用 Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/gs.html)。
+ SageMaker Studio，如果您想要使用 [PhysioNet MIMIC-III](https://physionet.org/content/mimic3wdb/1.0/) 範例資料實作此模式。 
+ 模式使用 SageMaker Processing，但不需要任何執行 SageMaker Processing 任務的經驗。

**限制**
+ 此模式非常適合包含相互依存檔案的 ML 資料集。這些相互依存性受益於手動巨集分割和平行執行多個單一執行個體 SageMaker Processing 任務。對於不存在此類相互依存性的資料集，SageMaker Processing 中的`ShardedByS3Key`功能可能是巨集碎片的更佳替代方案，因為它會將碎片資料傳送至由相同處理任務管理的多個執行個體。不過，您可以在這兩種情況下實作此模式的微分策略，以充分利用執行個體 vCPUs。

**產品版本**
+ Amazon SageMaker Python SDK 第 2 版

## Architecture
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-architecture"></a>

**目標技術堆疊**
+ Amazon Simple Storage Service (Amazon S3)
+ Amazon SageMaker

**目標架構**

*巨集控制和分散式 EC2 執行個體*

此架構中表示的 10 個平行程序會反映 MIMIC-III 資料集的結構。（程序會以省略符號表示，以簡化圖表。) 當您使用手動巨集分片時，類似的架構會套用至任何資料集。在 MIMIC-III 的情況下，您可以盡可能分別處理每個病患群組資料夾，藉此善用資料集的原始結構。在下圖中，記錄群組區塊會出現在左側 (1)。鑑於資料的分散式本質，依病患群組碎片是合理的。

![\[微分和分散式 EC2 執行個體的架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e7a90b31-de8f-41fd-bb3f-c7c6100fc306/images/c19a8f87-ac59-458e-89cb-50be17ca4a0c.png)


不過，依病患群組手動分片表示每個病患群組資料夾都需要單獨的處理任務，如圖表 (2) 中間區段所示，而不是具有多個 EC2 執行個體的單一處理任務。由於 MIMIC-III 的資料同時包含二進位波形檔案和相符的文字型標頭檔案，而且需要依賴 [wfdb 程式庫](https://wfdb.readthedocs.io/en/latest/)才能擷取二進位資料，因此必須在同一執行個體上提供特定病患的所有記錄。唯一可以確定每個二進位波形檔案的關聯標頭檔案也存在的方法，是實作手動碎片，在其自己的處理任務中執行每個碎片，並指定`s3_data_distribution_type='FullyReplicated'`何時定義處理任務輸入。或者，如果所有資料在單一目錄中可用，而且檔案之間不存在相依性，則更合適的選項可能是啟動具有多個 EC2 執行個體且`s3_data_distribution_type='ShardedByS3Key'`指定的單一處理任務。將 指定`ShardedByS3Key `為 Amazon S3 資料分佈類型，會指示 SageMaker 自動管理跨執行個體的資料分片。 

為每個資料夾啟動處理任務是一種經濟實惠的方式來預先處理資料，因為同時執行多個執行個體可節省時間。為了節省額外的成本和時間，您可以在每個處理任務中使用微分。 

*微分和平行 vCPUs*

在每個處理任務中，分組的資料會進一步分割，以最大限度地使用 SageMaker 全受管 EC2 執行個體上所有可用的 vCPUs。圖表 (2) 中間區段中的區塊描述了每個主要處理任務中發生的情況。會根據執行個體上可用的 vCPUs 數量，將病患記錄資料夾的內容扁平化並平均分割。分割資料夾內容後，平均大小的檔案集會分散到所有 vCPUs以進行處理。處理完成時，每個 vCPU 的結果會合併為每個處理任務的單一資料檔案。 

在連接的程式碼中，這些概念會呈現在 `src/feature-engineering-pass1/preprocessing.py` 檔案的下一節中。

```
def chunks(lst, n):
    """
    Yield successive n-sized chunks from lst.
    
    :param lst: list of elements to be divided
    :param n: number of elements per chunk
    :type lst: list
    :type n: int
    :return: generator comprising evenly sized chunks
    :rtype: class 'generator'
    """
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
 
 
# Generate list of data files on machine
data_dir = input_dir
d_subs = next(os.walk(os.path.join(data_dir, '.')))[1]
file_list = []
for ds in d_subs:
    file_list.extend(os.listdir(os.path.join(data_dir, ds, '.')))
dat_list = [os.path.join(re.split('_|\.', f)[0].replace('n', ''), f[:-4]) for f in file_list if f[-4:] == '.dat']
 
# Split list of files into sub-lists
cpu_count = multiprocessing.cpu_count()
splits = int(len(dat_list) / cpu_count)
if splits == 0: splits = 1
dat_chunks = list(chunks(dat_list, splits))
 
# Parallelize processing of sub-lists across CPUs
ws_df_list = Parallel(n_jobs=-1, verbose=0)(delayed(run_process)(dc) for dc in dat_chunks)
 
# Compile and pickle patient group dataframe
ws_df_group = pd.concat(ws_df_list)
ws_df_group = ws_df_group.reset_index().rename(columns={'index': 'signal'})
ws_df_group.to_json(os.path.join(output_dir, group_data_out))
```

函數 `chunks`會先定義為透過將指定清單分割為平均大小的長度區塊`n `，並將這些結果傳回為產生器，來使用指定的清單。接下來，透過編譯存在的所有二進位波形檔案清單，將資料扁平化到病患資料夾。完成後，會取得 EC2 執行個體上可用的 vCPUs 數量。透過呼叫 將二進位波形檔案的清單平均分割到這些 vCPUs`chunks`，然後使用 [joblib 的平行類別](https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html)在自己的 vCPU 上處理每個波形子清單。處理任務會自動將結果合併為單一資料影格清單，然後 SageMaker 會在任務完成時進一步處理，再寫入 Amazon S3。在此範例中，處理任務寫入 Amazon S3 的檔案有 10 個 （每個任務一個）。

當所有初始處理任務完成時，次要處理任務會顯示在圖表 (3) 右側的 區塊中，結合每個主要處理任務產生的輸出檔案，並將合併的輸出寫入 Amazon S3 (4)。

## 工具
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-tools"></a>

**工具**
+ [Python](https://www.python.org/) – 用於此模式的範例程式碼為 Python （第 3 版）。
+ [SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) – Amazon SageMaker Studio 是適用於機器學習的 Web 型整合式開發環境 (IDE)，可讓您建置、訓練、偵錯、部署和監控機器學習模型。您可以在 SageMaker Studio 中使用 Jupyter 筆記本來執行 SageMaker Processing 任務。
+ [SageMaker Processing](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html) – Amazon SageMaker Processing 提供執行資料處理工作負載的簡化方法。在此模式中，使用 SageMaker Processing 任務大規模實作特徵工程程式碼。

**Code**

連接的 .zip 檔案提供此模式的完整程式碼。下一節說明為此模式建置架構的步驟。每個步驟都由附件中的範例程式碼說明。

## 史詩
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-epics"></a>

### 設定 SageMaker Studio 環境
<a name="set-up-your-sagemaker-studio-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 存取 Amazon SageMaker Studio。 | 遵循 Amazon SageMaker 文件中提供的指示，在您的 AWS 帳戶中加入 SageMaker Studio。[Amazon SageMaker ](https://docs.aws.amazon.com/sagemaker/latest/dg/onboard-quick-start.html) | 資料科學家、ML 工程師 | 
| 安裝 wget 公用程式。 | 如果您使用新的 SageMaker Studio 組態加入，或從未在 SageMaker Studio 中使用這些公用程式，請安裝 *wget*。 若要安裝，請在 SageMaker Studio 主控台中開啟終端機視窗，然後執行下列命令：<pre>sudo yum install wget</pre> | 資料科學家、ML 工程師 | 
| 下載並解壓縮範例程式碼。 | 在*附件*區段中下載 `attachments.zip` 檔案。在終端機視窗中，導覽至您下載檔案的資料夾，並解壓縮其內容：<pre>unzip attachment.zip</pre>導覽至您解壓縮 .zip 檔案的資料夾，並解壓縮`Scaled-Processing.zip`檔案的內容。<pre>unzip Scaled-Processing.zip</pre> | 資料科學家、ML 工程師 | 
| 從 physionet.org 下載範例資料集，並將其上傳至 Amazon S3。 | 在包含`Scaled-Processing`檔案的資料夾中執行 `get_data.ipynb` Jupyter 筆記本。此筆記本會從 [physionet.org](https://physionet.org) 下載範例 MIMIC-III 資料集，並將其上傳至 Amazon S3 中的 SageMaker Studio 工作階段儲存貯體。 | 資料科學家、ML 工程師 | 

### 設定第一個預先處理指令碼
<a name="configure-the-first-preprocessing-script"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 扁平化所有子目錄的檔案階層。 | 在 MIMIC-III 等大型資料集中，檔案通常分佈於多個子目錄，即使在邏輯父群組內也是如此。您的指令碼應設定為在所有子目錄中扁平化所有群組檔案，如下列程式碼所示。<pre># Generate list of .dat files on machine<br />data_dir = input_dir<br />d_subs = next(os.walk(os.path.join(data_dir, '.')))[1]<br />file_list = []<br />for ds in d_subs:<br />    file_list.extend(os.listdir(os.path.join(data_dir, ds, '.')))<br />dat_list = [os.path.join(re.split('_|\.', f)[0].replace('n', ''), f[:-4]) for f in file_list if f[-4:] == '.dat']</pre>    此範例程式碼片段的範例來自 檔案，該`src/feature-engineering-pass1/preprocessing.py`檔案在附件中提供。 | 資料科學家、ML 工程師 | 
| 根據 vCPU 計數將檔案分成子群組。 | 根據執行指令碼的執行個體上存在vCPUs 數量，檔案應分為大小均勻的子組或區塊。在此步驟中，您可以實作類似如下的程式碼。<pre># Split list of files into sub-lists<br />cpu_count = multiprocessing.cpu_count()<br />splits = int(len(dat_list) / cpu_count)<br />if splits == 0: splits = 1<br />dat_chunks = list(chunks(dat_list, splits))</pre> | 資料科學家、ML 工程師 | 
| 平行處理跨 vCPUs的子群組。 | 指令碼邏輯應設定為平行處理所有子群組。若要這樣做，請使用 Joblib 程式庫的`Parallel `類別和`delayed `方法，如下所示。 <pre># Parallelize processing of sub-lists across CPUs<br />ws_df_list = Parallel(n_jobs=-1, verbose=0)(delayed(run_process)(dc) for dc in dat_chunks)</pre> | 資料科學家、ML 工程師 | 
| 將單一檔案群組輸出儲存至 Amazon S3。 | 當平行 vCPU 處理完成時，每個 vCPU 的結果應合併並上傳至檔案群組的 S3 儲存貯體路徑。在此步驟中，您可以使用類似如下的程式碼。<pre># Compile and pickle patient group dataframe<br />ws_df_group = pd.concat(ws_df_list)<br />ws_df_group = ws_df_group.reset_index().rename(columns={'index': 'signal'})<br />ws_df_group.to_json(os.path.join(output_dir, group_data_out))</pre> | 資料科學家、ML 工程師 | 

### 設定第二個預先處理指令碼
<a name="configure-the-second-preprocessing-script"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 合併執行第一個指令碼的所有處理任務所產生的資料檔案。 | 先前的指令碼會為每個 SageMaker Processing 任務輸出單一檔案，該任務會從資料集處理一組檔案。 接著，您需要將這些輸出檔案合併為單一物件，並將單一輸出資料集寫入 Amazon S3。這是在 檔案中示範的，該`src/feature-engineering-pass1p5/preprocessing.py`檔案在附件中提供，如下所示。<pre>def write_parquet(wavs_df, path):<br />    """<br />    Write waveform summary dataframe to S3 in parquet format.<br />    <br />    :param wavs_df: waveform summary dataframe<br />    :param path: S3 directory prefix<br />    :type wavs_df: pandas dataframe<br />    :type path: str<br />    :return: None<br />    """<br />    extra_args = {"ServerSideEncryption": "aws:kms"}<br />    wr.s3.to_parquet(<br />        df=wavs_df,<br />        path=path,<br />        compression='snappy',<br />        s3_additional_kwargs=extra_args)<br /> <br /> <br />def combine_data():<br />    """<br />    Get combined data and write to parquet.<br />    <br />    :return: waveform summary dataframe<br />    :rtype: pandas dataframe<br />    """<br />    wavs_df = get_data()<br />    wavs_df = normalize_signal_names(wavs_df)<br />    write_parquet(wavs_df, "s3://{}/{}/{}".format(bucket_xform, dataset_prefix, pass1p5out_data))<br /> <br />    return wavs_df<br /> <br /> <br />wavs_df = combine_data()</pre> | 資料科學家、ML 工程師 | 

### 執行處理任務
<a name="run-processing-jobs"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行第一個處理任務。 | 若要執行巨集分割，請為每個檔案群組執行個別的處理任務。Microsharding 會在每個處理任務內執行，因為每個任務都會執行您的第一個指令碼。下列程式碼示範如何在下列程式碼片段 （包含在 中`notebooks/FeatExtract_Pass1.ipynb`) 中為每個檔案群組目錄啟動處理任務。<pre>pat_groups = list(range(30,40))<br />ts = str(int(time.time()))<br /> <br />for group in pat_groups:<br />    sklearn_processor = SKLearnProcessor(framework_version='0.20.0',<br />                                     role=role,<br />                                     instance_type='ml.m5.4xlarge',<br />                                     instance_count=1,<br />                                     volume_size_in_gb=5)<br />    sklearn_processor.run(<br />        code='../src/feature-engineering-pass1/preprocessing.py',<br />        job_name='-'.join(['scaled-processing-p1', str(group), ts]),<br />        arguments=[<br />            "input_path", "/opt/ml/processing/input",<br />            "output_path", "/opt/ml/processing/output",<br />            "group_data_out", "ws_df_group.json"<br />        ],<br />        inputs=<br />        [<br />            ProcessingInput(<br />                source=f's3://{sess.default_bucket()}/data_inputs/{group}',<br />                destination='/opt/ml/processing/input',<br />                s3_data_distribution_type='FullyReplicated'<br />            )<br />        ],<br />        outputs=<br />        [<br />            ProcessingOutput(<br />                source='/opt/ml/processing/output',<br />                destination=f's3://{sess.default_bucket()}/data_outputs/{group}'<br />            )<br />        ],<br />        wait=False<br />    )</pre> | 資料科學家、ML 工程師 | 
| 執行第二個處理任務。 | 若要合併第一組處理任務產生的輸出並執行任何額外的預先處理運算，您可以使用單一 SageMaker Processing 任務來執行第二個指令碼。下列程式碼示範這一點 （包含在 中`notebooks/FeatExtract_Pass1p5.ipynb`)。<pre>ts = str(int(time.time()))<br />bucket = sess.default_bucket()<br />     <br />sklearn_processor = SKLearnProcessor(framework_version='0.20.0',<br />                                 role=role,<br />                                 instance_type='ml.t3.2xlarge',<br />                                 instance_count=1,<br />                                 volume_size_in_gb=5)<br />sklearn_processor.run(<br />    code='../src/feature-engineering-pass1p5/preprocessing.py',<br />    job_name='-'.join(['scaled-processing', 'p1p5', ts]),<br />    arguments=['bucket', bucket,<br />               'pass1out_prefix', 'data_outputs',<br />               'pass1out_data', 'ws_df_group.json',<br />               'pass1p5out_data', 'waveform_summary.parquet',<br />               'statsdata_name', 'signal_stats.csv'],<br />    wait=True<br />)</pre> | 資料科學家、ML 工程師 | 

## 相關資源
<a name="use-sagemaker-processing-for-distributed-feature-engineering-of-terabyte-scale-ml-datasets-resources"></a>
+ [使用 Quick Start 加入 Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/onboard-quick-start.html) (SageMaker 文件）
+ [處理資料](https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html) (SageMaker 文件） 
+ [使用 scikit-learn 的資料處理](https://docs.aws.amazon.com/sagemaker/latest/dg/use-scikit-learn-processing-container.html) (SageMaker 文件） 
+ [joblib.Parallel 文件](https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html)
+ Moody、B.、Moody、G.、Villanerroel、M.、Clifford、G. D. 和 Silva、I. (2020)。[MIMIC-III 波形資料庫](https://doi.org/10.13026/c2607m) (1.0 版）。*PhysioNet*。
+ Johnson， A. E. W.， Pollard， T. J.， Shen， L.， Lehman， L. H.， Feng， M.， Ghassemi， M.， Moody， B.， Sezovits， P.， Celi， L. A.， & Mark， R. G. (2016)。[MIMIC-III，可免費存取的關鍵護理資料庫](https://dx.doi.org/10.1038/sdata.2016.35)。科學資料，3， 160035。
+ [MIMIC-III Waveform 資料庫授權](https://physionet.org/content/mimic3wdb/1.0/LICENSE.txt)

## 附件
<a name="attachments-e7a90b31-de8f-41fd-bb3f-c7c6100fc306"></a>

若要存取與本文件相關聯的其他內容，請解壓縮下列檔案： [attachment.zip](samples/p-attach/e7a90b31-de8f-41fd-bb3f-c7c6100fc306/attachments/attachment.zip)

# 使用 Flask 和 AWS Elastic Beanstalk 視覺化 AI/ML 模型結果
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk"></a>

*Chris Caudill 和 Durga Sury，Amazon Web Services*

## 摘要
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-summary"></a>

視覺化人工智慧和機器學習 (AI/ML) 服務的輸出通常需要複雜的 API 呼叫，必須由您的開發人員和工程師自訂。如果您的分析師想要快速探索新的資料集，這可能是個缺點。

您可以使用 Web 型使用者介面 (UI)，讓使用者能夠上傳自己的資料，並在儀表板中視覺化模型結果，藉此增強服務的可存取性，並提供更互動式的資料分析形式。

此模式使用 [Flask](https://flask.palletsprojects.com/en/2.0.x/) 和 [Plotly](https://plotly.com/) 將 Amazon Comprehend 與自訂 Web 應用程式整合，並從使用者提供的資料視覺化情緒和實體。模式也提供使用 AWS Elastic Beanstalk 部署應用程式的步驟。您可以使用 [Amazon Web Services (AWS) AI 服務或](https://aws.amazon.com/machine-learning/ai-services/)託管在端點 （例如，[Amazon SageMaker 端點](https://docs.aws.amazon.com/sagemaker/latest/dg/deploy-model.html)) 上的自訂訓練模型來調整應用程式。

## 先決條件和限制
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶 
+ AWS Command Line Interface (AWS CLI)，安裝在本機機器上並進行設定。如需詳細資訊，請參閱 AWS CLI 文件中的[組態基本概念](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)。您也可以使用 AWS Cloud9 整合開發環境 (IDE)；如需詳細資訊，請參閱 [ AWS Cloud9 文件中的 AWS Cloud9 的 Python 教學](https://docs.aws.amazon.com/cloud9/latest/user-guide/sample-python.html)課程和[在 AWS Cloud9 IDE 中預覽執行中的應用程式](https://docs.aws.amazon.com/cloud9/latest/user-guide/app-preview.html)。 AWS Cloud9 

  **注意**： AWS Cloud9 不再提供給新客戶。的現有客戶 AWS Cloud9 可以繼續正常使用服務。[進一步了解](https://aws.amazon.com/blogs/devops/how-to-migrate-from-aws-cloud9-to-aws-ide-toolkits-or-aws-cloudshell/)
+ 了解 Flask 的 Web 應用程式架構。如需 Flask 的詳細資訊，請參閱 Flask 文件中的 [Quickstart](https://flask.palletsprojects.com/en/1.1.x/quickstart)。
+ Python 3.6 版或更新版本，已安裝並設定。您可以依照 AWS Elastic Beanstalk 文件中[設定 Python 開發環境的指示來安裝 Python](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/python-development-environment.html)。
+ Elastic Beanstalk 命令列界面 (EB CLI)，已安裝並設定。如需詳細資訊，請參閱 AWS Elastic Beanstalk 文件中的[安裝 EB CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html) 和[設定 EB CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-configuration.html)。

**限制**
+ 此模式的 Flask 應用程式旨在使用使用單一文字資料欄且限制為 200 列的 .csv 檔案。應用程式程式碼可以調整為處理其他檔案類型和資料磁碟區。
+ 應用程式不會考慮資料保留，並繼續彙總上傳的使用者檔案，直到手動刪除為止。您可以將應用程式與用於持久性物件儲存的 Amazon Simple Storage Service (Amazon S3) 整合，或使用 Amazon DynamoDB 等資料庫進行無伺服器金鑰值儲存。
+ 應用程式只會考慮英文的文件。不過，您可以使用 Amazon Comprehend 來偵測文件的主要語言。如需每個動作支援語言的詳細資訊，請參閱 Amazon Comprehend 文件中的 [API 參考](https://docs.aws.amazon.com/comprehend/latest/dg/API_Reference.html)。
+ *其他資訊 *區段提供包含常見錯誤及其解決方案的故障診斷清單。

## Architecture
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-architecture"></a>

**Flask 應用程式架構**

Flask 是一種輕量型架構，可用於在 Python 中開發 Web 應用程式。它旨在結合 Python 的強大資料處理與豐富的 Web 使用者介面。模式的 Flask 應用程式說明如何建置 Web 應用程式，讓使用者上傳資料、將資料傳送至 Amazon Comprehend 進行推論，然後視覺化結果。  應用程式具有下列結構：
+ `static` – 包含支援 Web UI 的所有靜態檔案 （例如 JavaScript、CSS 和映像）
+ `templates` – 包含應用程式的所有 HTML 頁面
+ `userData` – 存放上傳的使用者資料
+ `application.py` – Flask 應用程式檔案
+ `comprehend_helper.py` – 對 Amazon Comprehend 進行 API 呼叫的函數
+ `config.py` – 應用程式組態檔案
+ `requirements.txt` – 應用程式所需的 Python 相依性

`application.py` 指令碼包含 Web 應用程式的核心功能，其中包含四個 Flask 路由。下圖顯示這些 Flask 路由。

![\[構成 Web 應用程式核心功能的四個 Flask 路由。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/03d80cf1-ec97-43f7-adb5-2746a9ec70e6/images/9ca6bad1-26e2-4262-98d0-d54c172336bf.png)


 
+ `/` 是應用程式的根目錄，將使用者導向 `upload.html`頁面 （存放在 `templates`目錄中）。
+ `/saveFile` 是在使用者上傳檔案後呼叫的路由。此路由會透過 HTML 表單接收`POST`請求，其中包含使用者上傳的檔案。檔案會儲存在 `userData`目錄中，而路由會將使用者重新導向至`/dashboard`路由。
+ `/dashboard` 會將使用者傳送至 `dashboard.html`頁面。在此頁面的 HTML 中，它會在 中執行 JavaScript 程式碼`static/js/core.js`，從`/data`路由讀取資料，然後建置頁面的視覺化效果。
+ `/data` 是一種 JSON API，提供要在儀表板中視覺化的資料。此路由會讀取使用者提供的資料，並使用 中的 函數將使用者資料`comprehend_helper.py`傳送至 Amazon Comprehend，以進行情緒分析和具名實體辨識 (NER)。Amazon Comprehend 的回應會格式化並傳回為 JSON 物件。

**部署架構**

![\[使用 Flask 和 Elastic Beanstalk 視覺化 AI/ML 模型結果的架構圖。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/03d80cf1-ec97-43f7-adb5-2746a9ec70e6/images/d691bfd2-e2ec-4830-8bff-ffa1e3a95c4a.png)


[設計考量事項](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.concepts.design.html)

 如需在 AWS 雲端上使用 Elastic Beanstalk 部署之應用程式的設計考量詳細資訊，請參閱 AWS Elastic Beanstalk 文件中的 。

**技術堆疊**
+ Amazon Comprehend 
+ Elastic Beanstalk 
+ Flask 

**自動化和擴展**

Elastic Beanstalk 部署會自動設定負載平衡器和自動擴展群組。如需更多組態選項，請參閱 AWS Elastic Beanstalk [Elastic Beanstalk 文件中的設定 Elastic Beanstalk 環境](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers.html)。

## 工具
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-tools"></a>
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種統一的工具，可提供與 AWS 所有部分互動的一致界面。
+ [Amazon Comprehend](https://docs.aws.amazon.com/comprehend/latest/dg/comprehend-general.html) 使用自然語言處理 (NLP) 擷取文件內容的洞見，而不需要特殊的預先處理。
+ [AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html) 可協助您在 AWS 雲端中快速部署和管理應用程式，而無需了解執行這些應用程式的基礎設施。
+ [Elastic Beanstalk CLI (EB CLI)](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3.html) 是 AWS Elastic Beanstalk 的命令列界面，提供互動式命令，以簡化從本機儲存庫建立、更新和監控環境。
+ [Flask](https://flask.palletsprojects.com/en/2.0.x/) 框架使用 Python 執行資料處理和 API 呼叫，並透過 Plotly 提供互動式 Web 視覺化。

**Code**

此模式的程式碼可在使用 Flask 和 AWS Elastic Beanstalk 儲存庫的 GitHub 視覺化 AI/ML 模型結果中取得。 [ AWS Elastic Beanstalk](https://github.com/aws-samples/aws-comprehend-elasticbeanstalk-for-flask) 

## 史詩
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-epics"></a>

### 設定 Flask 應用程式
<a name="set-up-the-flask-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 GitHub 儲存庫。 | 執行下列命令，從使用 Flask 和 AWS Elastic Beanstalk 儲存庫的 GitHub 視覺化 AI/ML 模型結果提取應用程式程式碼： [ AWS Elastic Beanstalk](https://github.com/aws-samples/aws-comprehend-elasticbeanstalk-for-flask) `git clone git@github.com:aws-samples/aws-comprehend-elasticbeanstalk-for-flask.git`請務必使用 GitHub 設定 SSH 金鑰。 | 開發人員 | 
| 安裝 Python 模組。 | 複製儲存庫之後，會建立新的本機`aws-comprehend-elasticbeanstalk-for-flask`目錄。在該目錄中， `requirements.txt` 檔案包含執行應用程式的 Python 模組和版本。使用下列命令來安裝模組：`cd aws-comprehend-elasticbeanstalk-for-flask``pip install -r requirements.txt` | Python 開發人員 | 
| 在本機測試應用程式。 | 執行下列命令來啟動 Flask 伺服器：`python application.py`這會傳回執行中伺服器的相關資訊。您應該可以透過開啟瀏覽器並造訪 http：//localhost：5000 來存取應用程式如果您在 AWS Cloud9 IDE 中執行應用程式，則需要將 `application.py` 檔案中的 `application.run()`命令取代為下列行：`application.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))`您必須在部署之前還原此變更。 | Python 開發人員 | 

### 將應用程式部署至 Elastic Beanstalk
<a name="deploy-the-application-to-elastic-beanstalk"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動 Elastic Beanstalk 應用程式。 | 若要以 Elastic Beanstalk 應用程式的形式啟動專案，請從應用程式的根目錄執行下列命令：`eb init -p python-3.6 comprehend_flask --region us-east-1`[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.html)執行 `eb init -i`命令以取得更多部署組態選項。 | 架構師、開發人員 | 
| 部署 Elastic Beanstalk 環境。 | 從應用程式的根目錄執行下列命令：`eb create comprehend-flask-env``comprehend-flask-env` 是 Elastic Beanstalk 環境的名稱，可根據您的需求進行變更。名稱只能包含字母、數字和破折號。 | 架構師、開發人員 | 
| 授權您的部署以使用 Amazon Comprehend。 | 雖然您的應用程式可能已成功部署，但您也應該為部署提供 Amazon Comprehend 的存取權。 `ComprehendFullAccess` 是一種 AWS 受管政策，可為部署的應用程式提供對 Amazon Comprehend 進行 API 呼叫的許可。執行下列命令，將`ComprehendFullAccess`政策連接至 `aws-elasticbeanstalk-ec2-role`（此角色會自動為您部署的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體建立）：`aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/ComprehendFullAccess --role-name aws-elasticbeanstalk-ec2-role``aws-elasticbeanstalk-ec2-role` 會在您的應用程式部署時建立。您必須先完成部署程序，才能連接 AWS Identity and Access Management (IAM) 政策。 | 開發人員、安全架構師 | 
| 造訪您部署的應用程式。 | 在應用程式成功部署後，您可以執行 `eb open`命令來造訪它。您也可以執行 `eb status`命令來接收部署的詳細資訊。部署 URL 列在 下`CNAME`。 | 架構師、開發人員 | 

### （選用） 根據您的 ML 模型自訂應用程式
<a name="optional-customize-the-application-to-your-ml-model"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 授權 Elastic Beanstalk 存取新模型。 | 確定 Elastic Beanstalk 具有新模型端點所需的存取許可。例如，如果您使用 Amazon SageMaker 端點，您的部署需要具有叫用端點的許可。 如需詳細資訊，請參閱 Amazon SageMaker 文件中的 [InvokeEndpoint](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html)。 | 開發人員、安全架構師 | 
| 將使用者資料傳送至新模型。 | 若要變更此應用程式中的基礎 ML 模型，您必須變更下列檔案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.html) | 資料科學家 | 
| 更新儀表板視覺效果。 | 一般而言，整合新的 ML 模型表示必須更新視覺化以反映新的結果。這些變更會在下列檔案中進行：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.html) | Web 開發人員 | 

### （選用） 部署更新的應用程式
<a name="optional-deploy-the-updated-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新應用程式的需求檔案。 | 將變更傳送至 Elastic Beanstalk 之前，請在應用程式的根目錄中執行下列命令，來更新 `requirements.txt` 檔案以反映任何新的 Python 模組：`pip freeze > requirements.txt` | Python 開發人員 | 
| 重新部署 Elastic Beanstalk 環境。 | 若要確保您的應用程式變更反映在您的 Elastic Beanstalk 部署中，請導覽至應用程式的根目錄並執行下列命令：`eb deploy`這會將最新版的應用程式程式碼傳送至您現有的 Elastic Beanstalk 部署。 | 系統管理員、架構師 | 

## 相關資源
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-resources"></a>
+ [使用 Amazon API Gateway 和 AWS Lambda 呼叫 Amazon SageMaker 模型端點 Amazon API Gateway AWS Lambda](https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/)
+ [將 Flask 應用程式部署至 Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html)
+ [EB CLI 命令參考 ](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-cmd-commands.html)
+ [設定您的 Python 開發環境](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/python-development-environment.html)

## 其他資訊
<a name="visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk-additional"></a>

**故障診斷清單**

以下是六個常見的錯誤及其解決方案。

***錯誤 1 * **

```
Unable to assume role "arn:aws:iam::xxxxxxxxxx:role/aws-elasticbeanstalk-ec2-role". Verify that the role exists and is configured correctly.
```

**解決方案**：如果在您執行 時發生此錯誤`eb create`，請在 Elastic Beanstalk 主控台上建立範例應用程式，以建立預設執行個體描述檔。如需詳細資訊，請參閱 AWS Elastic Beanstalk [Elastic Beanstalk 文件中的建立 Elastic Beanstalk 環境](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.environments.html)。

***錯誤 2***

```
Your WSGIPath refers to a file that does not exist.
```

**解決方案： **此錯誤發生在部署日誌中，因為 Elastic Beanstalk 預期 Flask 程式碼會命名為 `application.py`。如果您選擇不同的名稱，請執行`eb config`並編輯 WSGIPath，如下列程式碼範例所示：

```
aws:elasticbeanstalk:container:python:
     NumProcesses: '1'
     NumThreads: '15'
     StaticFiles: /static/=static/
     WSGIPath: application.py
```

請確定您使用檔案名稱`application.py`取代 。

您也可以利用 Gunicorn 和 Procfile。如需此方法的詳細資訊，請參閱 AWS Elastic Beanstalk [Elastic Beanstalk 文件中的使用 Procfile 設定 WSGI 伺服器](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/python-configuration-procfile.html)。

***錯誤 3***

```
Target WSGI script '/opt/python/current/app/application.py' does not contain WSGI application 'application'.
```

**解決方案： **Elastic Beanstalk 預期代表 Flask 應用程式的變數會命名為 `application`。請確定`application.py`檔案使用 `application`做為變數名稱：

```
application = Flask(__name__)
```

***錯誤 4***

```
The EB CLI cannot find your SSH key file for keyname
```

**解決方案：**使用 EB CLI 指定要使用的金鑰對，或為部署的 EC2 執行個體建立金鑰對。若要解決錯誤，請執行 `eb init -i`，其中一個選項會詢問：

```
Do you want to set up SSH for your instances?
```

回應 `Y` 以建立金鑰對或指定現有的金鑰對。

***錯誤 5***

*我已更新程式碼並重新部署，但我的部署並未反映我的變更。*

**解決方案**：如果您在部署中使用 Git 儲存庫，請務必在重新部署之前新增並遞交變更。

***錯誤 6***

*您正在從 AWS Cloud9 IDE 預覽 Flask 應用程式並發生錯誤。*

**解決方案： **如需詳細資訊，請參閱 [ AWS Cloud9 文件中的在 AWS Cloud9 IDE 中預覽執行中的應用程式](https://docs.aws.amazon.com/cloud9/latest/user-guide/app-preview.html)。 AWS Cloud9 

 

 

**使用 Amazon Comprehend 的自然語言處理**

透過選擇使用 Amazon Comprehend，您可以透過執行即時分析或非同步批次任務來偵測個別文字文件中的自訂實體。Amazon Comprehend 也可讓您透過建立端點，即時訓練自訂實體辨識和文字分類模型。

此模式使用非同步批次任務，從包含多個文件的輸入檔案中偵測情緒和實體。此模式提供的範例應用程式旨在讓使用者上傳包含單一資料欄的 .csv 檔案，每列包含一個文字文件。GitHub 中的 `comprehend_helper.py` 檔案[使用 Flask 和 AWS Elastic Beanstalk 儲存庫視覺化 AI/ML 模型結果](https://github.com/aws-samples/aws-comprehend-elasticbeanstalk-for-flask)會讀取輸入檔案，並將輸入傳送至 Amazon Comprehend 進行處理。

*BatchDetectEntities*

Amazon Comprehend 會檢查一批文件的文字是否有具名實體，並傳回偵測到的實體、位置、[實體類型](https://docs.aws.amazon.com/comprehend/latest/dg/how-entities.html)，以及指出 Amazon Comprehend 可信度的分數。一次 API 呼叫最多可傳送 25 個文件，每個文件的大小小於 5，000 個位元組。您可以篩選結果，根據使用案例僅顯示特定實體。例如，您可以略過`‘quantity’`實體類型，並為偵測到的實體設定閾值分數 （例如 0.75)。建議您先探索特定使用案例的結果，再選擇閾值。如需詳細資訊，請參閱 Amazon Comprehend 文件中的 [BatchDetectEntities](https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectEntities.html)。

*BatchDetectSentiment*

Amazon Comprehend 會檢查一批傳入文件，並傳回每個文件 (`POSITIVE`、`MIXED`、 `NEUTRAL`或 ) 的現行情緒`NEGATIVE`。一次 API 呼叫最多可傳送 25 個文件，每個文件的大小小於 5，000 個位元組。分析情緒非常簡單，您可以選擇要在最終結果中顯示最高分數的情緒。如需詳細資訊，請參閱 Amazon Comprehend 文件中的 [BatchDetectSentiment](https://docs.aws.amazon.com/comprehend/latest/dg/API_BatchDetectSentiment.html)。

 

 

**Flask 組態處理**

Flask 伺服器使用一系列[的組態變數](https://flask.palletsprojects.com/en/1.1.x/config/)來控制伺服器的執行方式。這些變數可包含偵錯輸出、工作階段字符或其他應用程式設定。您也可以定義可在應用程式執行時存取的自訂變數。設定組態變數的方法有多種。

在此模式中，組態是在 中定義`config.py`，並在 中繼承`application.py`。
+ 
**注意**  
`config.py` 包含在應用程式啟動時設定的組態變數。在此應用程式中，會定義`DEBUG`變數，指示應用程式以[偵錯模式](https://flask.palletsprojects.com/en/1.1.x/config/#DEBUG)執行伺服器。：在生產環境中執行應用程式時，不應使用偵錯模式。 `UPLOAD_FOLDER` 是自訂變數，定義為稍後在應用程式中參考，並通知應存放上傳使用者資料的位置。
+ `application.py` 會啟動 Flask 應用程式，並繼承 中定義的組態設定`config.py`。這由下列程式碼執行：

```
application = Flask(__name__)
application.config.from_pyfile('config.py')
```

# 更多模式
<a name="machinelearning-more-patterns-pattern-list"></a>

**Topics**
+ [使用後台和自助式 Amazon SageMaker AI 範本加速 MLOps](accelerate-mlops-with-backstage-and-sagemaker-templates.md)
+ [使用 Amazon Bedrock 自動化 AWS 基礎設施操作](automate-aws-infrastructure-operations-by-using-amazon-bedrock.md)
+ [使用 Terraform 在 Amazon Bedrock 上部署代理程式系統，搭配CrewAI 架構](deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.md)
+ [在聊天應用程式自訂動作和 中使用 Amazon Q Developer 部署 ChatOps 解決方案來管理 SAST 掃描結果 CloudFormation](deploy-chatops-solution-to-manage-sast-scan-results.md)
+ [在 Quick Sight 中使用 AWS Mainframe Modernization 和 Amazon Q 產生資料洞見](generate-data-insights-by-using-aws-mainframe-modernization-and-amazon-q-in-quicksight.md)
+ [使用 Quick Sight 中的 AWS Mainframe Modernization 和 Amazon Q 產生 Db2 z/OS 資料洞見](generate-db2-zos-data-insights-aws-mainframe-modernization-amazon-q-in-quicksight.md)
+ [讓 SageMaker 筆記本執行個體暫時存取另一個 AWS 帳戶中的 CodeCommit 儲存庫](give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.md)
+ [使用 AWS CodePipeline 和 Amazon Bedrock 以程式碼形式管理 AWS Organizations 政策](manage-organizations-policies-as-code.md)
+ [使用 現代化 CardDemo 大型主機應用程式 AWS Transform](modernize-carddemo-mainframe-app.md)
+ [使用 和 Terraform 現代化 AWS Transform 和部署大型主機應用程式](modernize-mainframe-app-transform-terraform.md)
+ [使用 Amazon Redshift ML 執行進階分析](perform-advanced-analytics-using-amazon-redshift-ml.md)
+ [使用 Amazon Bedrock 代理程式和 簡化 Amazon EC2 合規管理 AWS Config](streamline-amazon-ec2-compliance-management-with-amazon-bedrock-agents-and-aws-config.md)
+ [使用自動化工作流程簡化 Amazon Lex 機器人開發和部署](streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.md)
+ [AWS Step Functions 使用 Amazon Bedrock 對 中的狀態進行故障診斷](troubleshooting-states-in-aws-step-functions.md)