選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

與 Amazon Bedrock 流程交談

焦點模式
與 Amazon Bedrock 流程交談 - Amazon Bedrock

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

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

下列程式碼範例示範如何使用 InvokeFlow 與包含代理程式節點的 Amazon Bedrock 流程進行對話。

如需詳細資訊,請參閱與 Amazon Bedrock 流程進行衝突

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

""" Shows how to run an Amazon Bedrock flow with InvokeFlow and handle muli-turn interaction for a single conversation. For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-multi-turn-invocation.html. """ import logging import boto3 import botocore import botocore.exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def invoke_flow(client, flow_id, flow_alias_id, input_data, execution_id): """ Invoke an Amazon Bedrock flow and handle the response stream. Args: client: Boto3 client for Amazon Bedrock agent runtime. flow_id: The ID of the flow to invoke. flow_alias_id: The alias ID of the flow. input_data: Input data for the flow. execution_id: Execution ID for continuing a flow. Use the value None on first run. Returns: Dict containing flow_complete status, input_required info, and execution_id """ response = None request_params = None if execution_id is None: # Don't pass execution ID for first run. request_params = { "flowIdentifier": flow_id, "flowAliasIdentifier": flow_alias_id, "inputs": [input_data], "enableTrace": True } else: request_params = { "flowIdentifier": flow_id, "flowAliasIdentifier": flow_alias_id, "executionId": execution_id, "inputs": [input_data], "enableTrace": True } response = client.invoke_flow(**request_params) if "executionId" not in request_params: execution_id = response['executionId'] input_required = None flow_status = "" # Process the streaming response for event in response['responseStream']: # Check if flow is complete. if 'flowCompletionEvent' in event: flow_status = event['flowCompletionEvent']['completionReason'] # Check if more input us needed from user. elif 'flowMultiTurnInputRequestEvent' in event: input_required = event # Print the model output. elif 'flowOutputEvent' in event: print(event['flowOutputEvent']['content']['document']) # Log trace events. elif 'flowTraceEvent' in event: logger.info("Flow trace: %s", event['flowTraceEvent']) return { "flow_status": flow_status, "input_required": input_required, "execution_id": execution_id } def converse_with_flow(bedrock_agent_client, flow_id, flow_alias_id): """ Run a conversation with the supplied flow. Args: bedrock_agent_client: Boto3 client for Amazon Bedrock agent runtime. flow_id: The ID of the flow to run. flow_alias_id: The alias ID of the flow. """ flow_execution_id = None finished = False # Get the intial prompt from the user. user_input = input("Enter input: ") # Use prompt to create input data. flow_input_data = { "content": { "document": user_input }, "nodeName": "FlowInputNode", "nodeOutputName": "document" } try: while not finished: # Invoke the flow until successfully finished. result = invoke_flow( bedrock_agent_client, flow_id, flow_alias_id, flow_input_data, flow_execution_id) status = result['flow_status'] flow_execution_id = result['execution_id'] more_input = result['input_required'] if status == "INPUT_REQUIRED": # The flow needs more information from the user. logger.info("The flow %s requires more input", flow_id) user_input = input( more_input['flowMultiTurnInputRequestEvent']['content']['document'] + ": ") flow_input_data = { "content": { "document": user_input }, "nodeName": more_input['flowMultiTurnInputRequestEvent']['nodeName'], "nodeInputName": "agentInputText" } elif status == "SUCCESS": # The flow completed successfully. finished = True logger.info("The flow %s successfully completed.", flow_id) except botocore.exceptions.ClientError as e: print(f"Client error: {str(e)}") logger.error("Client error: %s", {str(e)}) except Exception as e: print(f"An error occurred: {str(e)}") logger.error("An error occurred: %s", {str(e)}) logger.error("Error type: %s", {type(e)}) def main(): """ Main entry point for the script. """ # Replace these with your actual flow ID and flow alias ID. FLOW_ID = 'YOUR_FLOW_ID' FLOW_ALIAS_ID = 'YOUR_FLOW_ALIAS_ID' logger.info("Starting conversation with FLOW: %s ID: %s", FLOW_ID, FLOW_ALIAS_ID) # Get the Bedrock agent runtime client. session = boto3.Session(profile_name='default') bedrock_agent_client = session.client('bedrock-agent-runtime') # Start the conversation. converse_with_flow(bedrock_agent_client, FLOW_ID, FLOW_ALIAS_ID) logger.info("Conversation with FLOW: %s ID: %s finished", FLOW_ID, FLOW_ALIAS_ID) if __name__ == "__main__": main()
  • 如需 API 詳細資訊,請參閱 SDK AWS for Python (Boto3) API 參考中的 InvokeFlow

SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

""" Shows how to run an Amazon Bedrock flow with InvokeFlow and handle muli-turn interaction for a single conversation. For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-multi-turn-invocation.html. """ import logging import boto3 import botocore import botocore.exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def invoke_flow(client, flow_id, flow_alias_id, input_data, execution_id): """ Invoke an Amazon Bedrock flow and handle the response stream. Args: client: Boto3 client for Amazon Bedrock agent runtime. flow_id: The ID of the flow to invoke. flow_alias_id: The alias ID of the flow. input_data: Input data for the flow. execution_id: Execution ID for continuing a flow. Use the value None on first run. Returns: Dict containing flow_complete status, input_required info, and execution_id """ response = None request_params = None if execution_id is None: # Don't pass execution ID for first run. request_params = { "flowIdentifier": flow_id, "flowAliasIdentifier": flow_alias_id, "inputs": [input_data], "enableTrace": True } else: request_params = { "flowIdentifier": flow_id, "flowAliasIdentifier": flow_alias_id, "executionId": execution_id, "inputs": [input_data], "enableTrace": True } response = client.invoke_flow(**request_params) if "executionId" not in request_params: execution_id = response['executionId'] input_required = None flow_status = "" # Process the streaming response for event in response['responseStream']: # Check if flow is complete. if 'flowCompletionEvent' in event: flow_status = event['flowCompletionEvent']['completionReason'] # Check if more input us needed from user. elif 'flowMultiTurnInputRequestEvent' in event: input_required = event # Print the model output. elif 'flowOutputEvent' in event: print(event['flowOutputEvent']['content']['document']) # Log trace events. elif 'flowTraceEvent' in event: logger.info("Flow trace: %s", event['flowTraceEvent']) return { "flow_status": flow_status, "input_required": input_required, "execution_id": execution_id } def converse_with_flow(bedrock_agent_client, flow_id, flow_alias_id): """ Run a conversation with the supplied flow. Args: bedrock_agent_client: Boto3 client for Amazon Bedrock agent runtime. flow_id: The ID of the flow to run. flow_alias_id: The alias ID of the flow. """ flow_execution_id = None finished = False # Get the intial prompt from the user. user_input = input("Enter input: ") # Use prompt to create input data. flow_input_data = { "content": { "document": user_input }, "nodeName": "FlowInputNode", "nodeOutputName": "document" } try: while not finished: # Invoke the flow until successfully finished. result = invoke_flow( bedrock_agent_client, flow_id, flow_alias_id, flow_input_data, flow_execution_id) status = result['flow_status'] flow_execution_id = result['execution_id'] more_input = result['input_required'] if status == "INPUT_REQUIRED": # The flow needs more information from the user. logger.info("The flow %s requires more input", flow_id) user_input = input( more_input['flowMultiTurnInputRequestEvent']['content']['document'] + ": ") flow_input_data = { "content": { "document": user_input }, "nodeName": more_input['flowMultiTurnInputRequestEvent']['nodeName'], "nodeInputName": "agentInputText" } elif status == "SUCCESS": # The flow completed successfully. finished = True logger.info("The flow %s successfully completed.", flow_id) except botocore.exceptions.ClientError as e: print(f"Client error: {str(e)}") logger.error("Client error: %s", {str(e)}) except Exception as e: print(f"An error occurred: {str(e)}") logger.error("An error occurred: %s", {str(e)}) logger.error("Error type: %s", {type(e)}) def main(): """ Main entry point for the script. """ # Replace these with your actual flow ID and flow alias ID. FLOW_ID = 'YOUR_FLOW_ID' FLOW_ALIAS_ID = 'YOUR_FLOW_ALIAS_ID' logger.info("Starting conversation with FLOW: %s ID: %s", FLOW_ID, FLOW_ALIAS_ID) # Get the Bedrock agent runtime client. session = boto3.Session(profile_name='default') bedrock_agent_client = session.client('bedrock-agent-runtime') # Start the conversation. converse_with_flow(bedrock_agent_client, FLOW_ID, FLOW_ALIAS_ID) logger.info("Conversation with FLOW: %s ID: %s finished", FLOW_ID, FLOW_ALIAS_ID) if __name__ == "__main__": main()
  • 如需 API 詳細資訊,請參閱 SDK AWS for Python (Boto3) API 參考中的 InvokeFlow

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 搭配 AWS SDK 使用 Amazon Bedrock。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。

下一個主題:

動作

上一個主題:

基本概念
隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。