View a markdown version of this page

AgentCore 코드 인터프리터 직접 사용 - Amazon Bedrock AgentCore

AgentCore 코드 인터프리터 직접 사용

다음 섹션에서는 에이전트 프레임워크 없이 Amazon Bedrock AgentCore 코드 인터프리터를 직접 사용하는 방법을 보여줍니다. 이는 특정 코드 조각을 프로그래밍 방식으로 실행하려는 경우에 특히 유용합니다. 이 섹션의 예제를 살펴보기 전에 사전 조건을 참조하세요.

1단계: 접근 방식 선택 및 종속성 설치

Amazon Bedrock AgentCore는 AgentCore 코드 해석기와 상호 작용하는 두 가지 방법, 즉 상위 수준 SDK 클라이언트를 사용하거나 boto3를 직접 사용하는 방법을 제공합니다.

  • SDK 클라이언트: bedrock_agentcore SDK는 세션 관리 세부 정보를 처리하는 간소화된 인터페이스를 제공합니다. 대부분의 애플리케이션에이 접근 방식을 사용합니다.

  • Boto3 클라이언트: AWS SDK를 사용하면 AgentCore 코드 해석기 API 작업에 직접 액세스할 수 있습니다. 세션 구성을 세밀하게 제어해야 하거나 기존 boto3 기반 애플리케이션과 통합하려는 경우이 접근 방식을 사용합니다.

프로젝트 폴더를 생성하고(이전에 생성하지 않은 경우) 필요한 패키지를 설치합니다.

mkdir agentcore-tools-quickstart cd agentcore-tools-quickstart python3 -m venv .venv source .venv/bin/activate

Windows에서는 다음을 사용합니다. .venv\Scripts\activate

필수 패키지를 설치합니다.

pip install bedrock-agentcore boto3

이러한 패키지는 다음을 제공합니다.

  • bedrock-agentcore : AgentCore 코드 해석기를 포함한 Amazon Bedrock AgentCore용 SDK 도구

  • boto3 AWS 서비스를 생성, 구성 및 관리하기 위한 Python(Boto3)용 : AWS SDK

2단계: 코드 실행

다음 방법 중 하나를 선택하여 AgentCore 코드 해석기로 코드를 실행합니다.

참고

를 실제 AWS 리전(예: us-east-1 또는 us-west-2 )<Region>으로 바꿉니다.

SDK Client
  1. 라는 파일을 생성하고 다음 코드를 direct_code_execution_sdk.py 추가합니다.

    from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter import json # Initialize the Code Interpreter client for your region code_client = CodeInterpreter('<Region>') # Start a Code Interpreter session code_client.start() try: # Execute Python code response = code_client.invoke("executeCode", { "language": "python", "code": 'print("Hello World!!!")' }) # Process and print the response for event in response["stream"]: print(json.dumps(event["result"], indent=2)) finally: # Always clean up the session code_client.stop()

    이 코드는 다음과 같습니다.

    • 리전에 대한 AgentCore 코드 해석기 클라이언트를 생성합니다.

    • 세션을 시작합니다(코드를 실행하기 전에 필요).

    • Python 코드를 실행하고 전체 이벤트 세부 정보로 결과를 스트리밍합니다.

    • 세션을 중지하여 리소스를 정리합니다.

      스크립트 실행

      다음 명령을 실행합니다.

      python direct_code_execution_sdk.py

      예상 출력

      출력 콘텐츠에가 있는 실행 결과가 포함된 JSON 응답Hello World!!!이 표시됩니다.

Boto3
  1. 라는 파일을 생성하고 다음 코드를 direct_code_execution_boto3.py 추가합니다.

    import boto3 import json # Code to execute code_to_execute = """ print("Hello World!!!") """ # Initialize the bedrock-agentcore client client = boto3.client( "bedrock-agentcore", region_name="<Region>" ) # Start a Code Interpreter session session_response = client.start_code_interpreter_session( codeInterpreterIdentifier="aws.codeinterpreter.v1", name="my-code-session", sessionTimeoutSeconds=900 ) session_id = session_response["sessionId"] print(f"Started session: {session_id}\n\n") try: # Execute code in the session execute_response = client.invoke_code_interpreter( codeInterpreterIdentifier="aws.codeinterpreter.v1", sessionId=session_id, name="executeCode", arguments={ "language": "python", "code": code_to_execute } ) # Extract and print the text output from the stream for event in execute_response['stream']: if 'result' in event: result = event['result'] if 'content' in result: for content_item in result['content']: if content_item['type'] == 'text': print(content_item['text']) finally: # Stop the session when done client.stop_code_interpreter_session( codeInterpreterIdentifier="aws.codeinterpreter.v1", sessionId=session_id ) print(f"\n\nStopped session: {session_id}")

    이 코드는 다음과 같습니다.

    • bedrock-agentcore 서비스를 위한 boto3 클라이언트를 생성합니다.

    • 900초 제한 시간으로 AgentCore 코드 해석기 세션을 시작합니다.

    • 세션 ID를 사용하여 Python 코드를 실행합니다.

    • 스트리밍 응답을 구문 분석하여 텍스트 출력 추출

    • 리소스를 해제하기 위해 세션을 올바르게 중지합니다.

      boto3 접근 방식에는 명시적 세션 관리가 필요합니다. 코드를 실행하기 start_code_interpreter_session 전에를 호출하고 완료되면 stop_code_interpreter_session를 호출해야 합니다.

      스크립트 실행

      다음 명령을 실행합니다.

      python direct_code_execution_boto3.py

      예상 출력

      세션 ID 정보와 함께 코드 실행의 결과로 Hello World!!! 인쇄된가 표시되어야 합니다.