프롬프트 플로우 실행 코드 샘플 - Amazon Bedrock

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

프롬프트 플로우 실행 코드 샘플

참고

프롬프트 플로우는 미리 보기 중이며 변경될 수 있습니다.

다음 코드 샘플은 다음과 같은 사전 요구 사항을 충족했다고 가정합니다.

  1. Amazon Bedrock 작업에 대한 권한을 갖도록 역할을 설정합니다. 아직 확인하지 않았다면 을 참조하십시오. 아마존 베드락 시작하기

  2. 를 사용하려면 자격 증명을 설정하십시오 AWS API. 아직 확인하지 않았다면 을 참조하십시오AWS API 사용하기 시작하기.

  3. 사용자 대신 즉각적인 흐름 관련 작업을 수행할 서비스 역할을 생성하세요. 아직 확인하지 않았다면 을 참조하십시오. Amazon Bedrock에서 프롬프트 플로우에 대한 서비스 역할 생성

Prompt flow의 일부 코드 샘플을 시험해 보려면 선택한 방법에 해당하는 탭을 선택하고 단계를 따르세요.

Python
  1. 다음 노드가 있는 Amazon Bedrock용 에이전트 빌드 타임 엔드포인트에서 요청을 사용하여 프롬프트 플로우를 생성합니다 (요청 및 응답 형식과 필드 세부 정보는 링크 참조). CreateFlow

    • 입력 노드.

    • 프롬프트가 인라인으로 정의되어 있는 프롬프트 노드로, 두 변수 (genrenumber) 를 사용하여 음악 재생 목록을 만듭니다.

    • 모델 완성을 반환하는 출력 노드입니다.

    다음 코드 스니펫을 실행하여 Amazon Bedrock 클라이언트를 로드하고, 노드가 포함된 프롬프트 플로우를 생성합니다 (executionRoleArn필드를 프롬프트 플로우에 대해 생성한 서비스 ARN 역할의 필드로 대체). AWS SDK for Python (Boto3)

    # Import Python SDK and create client import boto3 client = boto3.client(service_name='bedrock-agent') # Replace with the service role that you created. For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html FLOWS_SERVICE_ROLE = "arn:aws:iam::123456789012:role/MyPromptFlowsRole" # Define each node # The input node validates that the content of the InvokeFlow request is a JSON object. input_node = { "type": "Input", "name": "FlowInput", "outputs": [ { "name": "document", "type": "Object" } ] } # This prompt node defines an inline prompt that creates a music playlist using two variables. # 1. {{genre}} - The genre of music to create a playlist for # 2. {{number}} - The number of songs to include in the playlist # It validates that the input is a JSON object that minimally contains the fields "genre" and "number", which it will map to the prompt variables. # The output must be named "modelCompletion" and be of the type "String". prompt_node = { "type": "Prompt", "name": "MakePlaylist", "configuration": { "prompt": { "sourceConfiguration": { "inline": { "modelId": "amazon.titan-text-express-v1", "templateType": "TEXT", "inferenceConfiguration": { "text": { "temperature": 0.8 } }, "templateConfiguration": { "text": { "text": "Make me a {{genre}} playlist consisting of the following number of songs: {{number}}." } } } } } }, "inputs": [ { "name": "genre", "type": "String", "expression": "$.data.genre" }, { "name": "number", "type": "Number", "expression": "$.data.number" } ], "outputs": [ { "name": "modelCompletion", "type": "String" } ] } # The output node validates that the output from the last node is a string and returns it as is. The name must be "document". output_node = { "type": "Output", "name": "FlowOutput", "inputs": [ { "name": "document", "type": "String", "expression": "$.data" } ] } # Create connections between the nodes connections = [] # First, create connections between the output of the flow input node and each input of the prompt node for input in prompt_node["inputs"]: connections.append( { "name": "_".join([input_node["name"], prompt_node["name"], input["name"]]), "source": input_node["name"], "target": prompt_node["name"], "type": "Data", "configuration": { "data": { "sourceOutput": input_node["outputs"][0]["name"], "targetInput": input["name"] } } } ) # Then, create a connection between the output of the prompt node and the input of the flow output node connections.append( { "name": "_".join([prompt_node["name"], output_node["name"]]), "source": prompt_node["name"], "target": output_node["name"], "type": "Data", "configuration": { "data": { "sourceOutput": prompt_node["outputs"][0]["name"], "targetInput": output_node["inputs"][0]["name"] } } } ) # Create the flow from the nodes and connections response = client.create_flow( name="FlowCreatePlaylist", description="A flow that creates a playlist given a genre and number of songs to include in the playlist.", executionRoleArn=FLOWS_SERVICE_ROLE, definition={ "nodes": [input_node, prompt_node, output_node], "connections": connections } ) flow_id = response.get("id")
  2. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 ListFlows요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 방금 생성한 것을 포함하여 계정의 프롬프트 흐름을 나열합니다.

    client.list_flows()
  3. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 GetFlow요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 방금 생성한 프롬프트 흐름에 대한 정보를 얻을 수 있습니다.

    client.get_flow(flowIdentifier=flow_id)
  4. 작업 초안의 최신 변경 사항이 적용되고 버전을 작성할 준비가 되도록 프롬프트 흐름을 준비하십시오. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 PrepareFlow요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하십시오.

    client.prepare_flow(flowIdentifier=flow_id)
  5. 프롬프트 흐름의 작업 초안 버전을 지정하여 프롬프트 흐름의 정적 스냅샷을 생성한 다음 다음 작업을 통해 관련 정보를 검색하십시오.

    1. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 CreateFlowVersion요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 버전을 생성합니다.

      response = client.create_flow_version(flowIdentifier=flow_id) flow_version = response.get("version")
    2. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 ListFlowVersions요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 모든 버전의 프롬프트 흐름을 나열합니다.

      client.list_flow_versions(flowIdentifier=flow_id)
    3. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 GetFlowVersion요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 버전에 대한 정보를 얻으십시오.

      client.get_flow_version(flowIdentifier=flow_id, flowVersion=flow_version)
  6. 생성한 프롬프트 흐름의 버전을 가리키는 별칭을 생성한 다음 다음 작업을 통해 해당 정보를 검색하십시오.

    1. 별칭을 생성하고 다음 코드 스니펫을 실행하여 Agents for Amazon Bedrock 빌드 타임 엔드포인트로 CreateFlowAlias요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 방금 생성한 버전을 가리키도록 지정합니다.

      response = client.create_flow_alias( flowIdentifier="FLOW123456", name="latest", description="Alias pointing to the latest version of the flow.", routingConfiguration=[ { "flowVersion": flow_version } ] ) flow_alias_id = response.get("id")
    2. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 ListFlowAliass요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 프롬프트 흐름의 모든 별칭을 나열합니다.

      client.list_flow_aliases(flowIdentifier=flow_id)
    3. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 GetFlowAlias요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 방금 생성한 별칭에 대한 정보를 얻을 수 있습니다.

      client.get_flow_alias(flowIdentifier=flow_id, aliasIdentifier=flow_alias_id)
  7. 다음 코드 스니펫을 실행하여 Amazon Bedrock Runtime 클라이언트용 에이전트를 생성하고 흐름을 호출합니다. 요청은 프롬프트 흐름의 프롬프트에 변수를 채우고 모델의 응답을 반환하여 Amazon Bedrock InvokeFlowAgents 런타임 엔드포인트에 요청을 보냅니다 (요청 및 응답 형식과 필드 세부 정보는 링크 참조).

    client_runtime = boto3.client('bedrock-agent-runtime') response = client_runtime.invoke_flow( flowIdentifier=flow_id, flowAliasIdentifier=flow_alias_id, inputs=[ { "content": { "document": { "genre": "pop", "number": 3 } }, "nodeName": "FlowInput", "nodeOutputName": "document" } ] ) result = {} for event in response.get("responseStream"): result.update(event) if result['flowCompletionEvent']['completionReason'] == 'SUCCESS': print("Prompt flow invocation was successful! The output of the prompt flow is as follows:\n") print(result['flowOutputEvent']['content']['document']) else: print("The prompt flow invocation completed because of the following reason:", result['flowCompletionEvent']['completionReason'])

    응답은 세 곡이 포함된 팝 음악 재생 목록을 반환해야 합니다.

  8. 다음 작업을 수행하여 만든 별칭, 버전 및 프롬프트 플로우를 삭제합니다.

    1. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 DeleteFlowAlias요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 별칭을 삭제합니다.

      client.delete_flow_alias(flowIdentifier=flow_id, aliasIdentifier=flow_alias_id)
    2. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 DeleteFlowVersion요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 버전을 삭제합니다.

      client.delete_flow_version(flowIdentifier=flow_id, flowVersion=flow_version)
    3. Amazon Bedrock용 에이전트 빌드 타임 엔드포인트로 다음 코드 스니펫을 실행하여 DeleteFlow요청 (요청 및 응답 형식과 필드 세부 정보는 링크 참조) 하여 흐름을 삭제합니다.

      client.delete_flow(flowIdentifier=flow_id)