# Amazon Bedrock Workshop for FSI (4. Agents) ## 目錄 - [實驗環境準備](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/HkjF3MBcge) - [1. Amazon Bedrock Foundation Model 使用概覽](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/B1PFXXHcex) - [2. Amazon Bedrock Knowledge Bases (Vector Store) for RAG](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/ByyeB7r5eg) - [3. Amazon Bedrock Knowledge Bases (Vector Store) for GraphRag](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/HJmVw7S9gl) - [4. Amazon Bedrock Agents](#4-Amazon-Bedrock-Agents) - [4-1. 建立 Agent](#4-1-建立-Agent) - [4-2. 建立動作群組 (API 整合)](#4-2-建立動作群組-API-整合) - [4-3. 調整 API 程式](#4-3-調整-API-程式) - [4-4. 整合知識庫](#4-4-整合知識庫) - [4-5. 測試 Agent](#4-5-測試-Agent) - [5. Amazon Bedrock Flows](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/B1eEw7H5gl) - [6. Amazon Bedrock Guardrails](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/SJ0XvmH5lx) - [其他相關參考資料](https://hackmd.io/@6g-86IJuRWiQ17aprBneGQ/B1Dw5XBclg) --- ## 4. Amazon Bedrock Agents ### 4-1. 建立 Agent 1. 進入 **Amazon Bedrock** 服務 ![圖片](https://hackmd.io/_uploads/S1YeGJiJyl.png =500x) 2. 點擊 **代理程式 (Agents)** 來快速建立 RAG 與 API 整合應用 ![image](https://hackmd.io/_uploads/Sy_DMwUcgg.png =100x) 3. 點擊 **建立代理程式 (Create Agent)** ![圖片](https://hackmd.io/_uploads/Skhrbls1yg.png =500x) - **名稱 (Name):** `cloud-advisor` ![image](https://hackmd.io/_uploads/B1knMPLcle.png =400x) - **選取模型 (Select model):** `Claude 3.7 Sonnet v1` - **代理程式指示 (Agent Prompt):** ``` 你是一位金融上雲諮詢助手,提供以下服務: <服務> - 解答有關金融上雲法規的問題 - 處理上雲遷移申請 - 查詢上雲遷移申請狀態 </服務> 對於任何其他無關的問題,請回答:「抱歉,我沒有這方面的知識。」 在處理客戶查詢時,請遵循以下規則: <規則> - 當用戶的問題過於籠統,引導其提供更明確的問題 - 所有的對答都需要使用台灣中文 </規則> ``` - 其他設定 (Additional settings) - **使用者輸入 (User input):** `已啟用 (Enabled)` - 上述完成後,先點擊 **儲存 (Save)** 以建立 Agent [**[ ⤴️ 回到目錄]**](#目錄) --- ### 4-2. 建立動作群組 (API 整合) 1. 前往 **動作群組 (Action groups)** 並點擊 **新增 (Add)** ![圖片](https://hackmd.io/_uploads/H1qPfejJJg.png =300x) - **輸入動作群組名稱 (Enter Action group name):** `cloud-application` - **描述 (Description):** `處理上雲相關申請作業` - **動作群組類型 (Action group type):** `使用函數詳細資訊進行定義` - **動作群組調用 (Action group invocation):** `快速建立一個新的 Lambda 函數 - 建議值` - **動作群組函數 (Action group function) 1:** ![圖片](https://hackmd.io/_uploads/SyrCWZ2gyx.png) :::spoiler **JSON 格式** { "name": "apply-cloud-migration", "description": "提供上雲遷移申請", "parameters": [ { "name": "cloud_provider", "description": "Cloud Provider", "required": "True", "type": "String", "tableIndex": 0 }, { "name": "department_name", "description": "Department Name", "required": "True", "type": "String", "tableIndex": 1 }, { "name": "services_required", "description": "Services Required", "required": "True", "type": "Array", "tableIndex": 2 }, { "name": "workload_name", "description": "Workload Name", "required": "True", "type": "String", "tableIndex": 3 }, { "name": "kickoff_date", "description": "Kickoff Date (YYYYMMDD)", "required": "True", "type": "String", "tableIndex": 4 } ], "requireConfirmation": "DISABLED" } ::: - 名稱 (Name): `apply-cloud-migration` - 描述 (Description): `提供上雲遷移申請` - 參數 (Parameters): - 名稱 (Name): `cloud_provider` - 描述 (Description): `Cloud Provider` - 類型 (Type): `String` - 必要 (Required): `True` - 名稱 (Name): `department_name` - 描述 (Description): `Department Name` - 類型 (Type): `String` - 必要 (Required): `True` - 名稱 (Name): `services_required` - 描述 (Description): `Services Required` - 類型 (Type): `Array` - 必要 (Required): `True` - 名稱 (Name): `workload_name` - 描述 (Description): `Workload Name` - 類型 (Type): `String` - 必要 (Required): `True` - 名稱 (Name): `kickoff_date` - 描述 (Description): `Kickoff Date (YYYYMMDD)` - 類型 (Type): `String` - 必要 (Required): `True` - **動作群組函數 (Action group function) 2:** ![圖片](https://hackmd.io/_uploads/rJ78gZnlyx.png) :::spoiler **JSON 格式** { "name": "check-approval-status", "description": "查詢上雲遷移申請的核准狀態", "parameters": [ { "name": "department_name", "description": "Department Name", "required": "True", "type": "String", "tableIndex": 0 }, { "name": "workload_name", "description": "Workload Name", "required": "True", "type": "String", "tableIndex": 1 } ], "requireConfirmation": "DISABLED" } ::: - 名稱 (Name): `check-approval-status` - 描述 (Description): `查詢上雲遷移申請的核准狀態` - 參數 (Parameters): - 名稱 (Name): `department_name` - 描述 (Description): `Department Name` - 類型 (Type): `String` - 必要(Required): `True` - 名稱 (Name): `workload_name` - 描述 (Description): `Workload Name` - 類型 (Type): `String` - 必要(Required): `True` - **動作群組函數 (Action group function) 3:** ![圖片](https://hackmd.io/_uploads/r1KHp_D3kg.png) :::spoiler **JSON 格式** { "name": "get-current-datetime", "description": "取得現在日期時間", "parameters": {}, "requireConfirmation": "DISABLED" } ::: - 名稱 (Name): `get-current-datetime` - 描述 (Description): `取得現在日期時間` 2. 上述完成後請點擊 **建立 (Create)** ![圖片](https://hackmd.io/_uploads/BJxdQ-nxyx.png) [**[ ⤴️ 回到目錄]**](#目錄) --- ### 4-3. 調整 API 程式 1. 前往 **Amazon Lambda** 服務 ![圖片](https://hackmd.io/_uploads/H1YY8liykg.png) 2. 點擊自動生成的 Lambda function (函數): `函數名稱為 cloud-application 開頭` ![圖片](https://hackmd.io/_uploads/Sy0iIlsyJl.png =500x) 3. 取代程式碼 **dummy_lambda.py** ```python import logging from typing import Dict, Any from http import HTTPStatus import json from datetime import datetime, timedelta logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]: """ AWS Lambda handler for processing Bedrock agent requests. Args: event (Dict[str, Any]): The Lambda event containing action details context (Any): The Lambda context object Returns: Dict[str, Any]: Response containing the action execution results Raises: KeyError: If required fields are missing from the event """ try: action_group = event['actionGroup'] function = event['function'] message_version = event.get('messageVersion',1) parameters = event.get('parameters', []) print(json.dumps(event)) # Execute your business logic here. For more information, # refer to: https://docs.aws.amazon.com/bedrock/latest/userguide/agents-lambda.html response_text = "" match function: case "apply-cloud-migration": response_text = "The function {} was called successfully!".format(function) case "check-approval-status": response_text = "Your request is still under process." case "get-current-datetime": current_time = datetime.utcnow() + timedelta(hours=8) response_text = "The current date and time is: " + current_time.strftime("%Y-%m-%d %H:%M:%S") case _: pass response_body = { "TEXT": { "body": response_text } } action_response = { 'actionGroup': action_group, 'function': function, 'functionResponse': { 'responseBody': response_body } } response = { 'response': action_response, 'messageVersion': message_version } logger.info('Response: %s', response) return response except KeyError as e: logger.error('Missing required field: %s', str(e)) return { 'statusCode': HTTPStatus.BAD_REQUEST, 'body': f'Error: {str(e)}' } except Exception as e: logger.error('Unexpected error: %s', str(e)) return { 'statusCode': HTTPStatus.INTERNAL_SERVER_ERROR, 'body': 'Internal server error' } ``` ![圖片](https://hackmd.io/_uploads/H14dyIqxxx.png) 4. 完成後點擊左方的 ![圖片](https://hackmd.io/_uploads/HkyhumT1yx.png =50x) [**[ ⤴️ 回到目錄]**](#目錄) --- ### 4-4. 整合知識庫 1. 進入 **Amazon Bedrock** 服務 ![圖片](https://hackmd.io/_uploads/S1YeGJiJyl.png) 2. 點擊 **代理程式 (Agents)** 並進入 `cloud-advisor` ![圖片](https://hackmd.io/_uploads/Byfl8Z3gJe.png) 3. 點擊 **在代理程式建置器中編輯** ![圖片](https://hackmd.io/_uploads/HkqGUbngyg.png) 4. 前往 **知識庫 (Knowledge bases)** 並點擊 **新增 (Add)** ![圖片](https://hackmd.io/_uploads/ry-oEgskke.png) - **選取知識庫 (Select knowledge base):** `regulation-document-rag-semantic` - **代理程式的知識庫指示 (Knowledge base instructions for Agent):** `查詢及回應有關金融業上雲的相關法規` 5. 完成後點擊 **Add** 以整合知識庫 ![圖片](https://hackmd.io/_uploads/S1VAXWhxyg.png) [**[ ⤴️ 回到目錄]**](#目錄) --- ### 4-5. 測試 Agent 1. 點擊 **儲存 (Save)** 以保存 Agent 相關設定 2. 點擊 **準備 (Prepare)** 以準備進行 Agent 測試,並嘗試測試以下問題: ![圖片](https://hackmd.io/_uploads/BJZf_xs1yl.png) ``` 上雲 金融業上雲需要注意哪些事項? 我要申請系統上雲 我要查詢系統上雲申請狀態 我要請假 ``` :::spoiler **回應結果示範** - `上雲` ![image](https://hackmd.io/_uploads/r19ltDUqgl.png) - `金融業上雲需要注意哪些事項?` ![image](https://hackmd.io/_uploads/HJo2uw89ex.png) - `我要申請系統上雲` ![image](https://hackmd.io/_uploads/H1K7Fw89gx.png) - `我要查詢系統上雲申請狀態` ![image](https://hackmd.io/_uploads/SkALYvLcgx.png) - `我要請假` ![image](https://hackmd.io/_uploads/B1o9FDIcel.png) ::: [**[ ⤴️ 回到目錄]**](#目錄) ---