AgentCore Code Interpreter を直接使用する
以下のセクションでは、エージェントフレームワークなしで Amazon Bedrock AgentCore Code Interpreter を直接使用する方法について説明します。これは、特定のコードスニペットをプログラムで実行する場合に特に便利です。このセクションの例に進む前に、「前提条件」を参照してください。
ステップ 1: アプローチを選択し、依存関係をインストールする
Amazon Bedrock AgentCore には、高レベルの SDK クライアントを使用するか、boto3 を直接使用するという AgentCore 2 つの方法があります。
-
SDK クライアント : bedrock_agentcore SDK は、セッション管理の詳細を処理するシンプルなインターフェイスを提供します。このアプローチは、ほとんどのアプリケーションで使用します。
-
Boto3 クライアント: AWS SDK では、AgentCore Code Interpreter 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
これらのパッケージは以下を提供します。
ステップ 2: コードを実行する
AgentCore Code Interpreter でコードを実行するには、次のいずれかの方法を選択します。
を実際の AWS リージョン ( us-east-1や など) us-west-2 <Region>に置き換えます。
例
- SDK Client
-
-
という名前のファイルを作成し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 Code Interpreter クライアントを作成します。
-
セッションを開始します (コードを実行する前に必要)
-
Python コードを実行し、完全なイベント詳細で結果をストリーミングします
-
セッションを停止してリソースをクリーンアップします
スクリプトを実行する
次の コマンドを実行します。
python direct_code_execution_sdk.py
予想される出力
出力コンテンツに の実行結果を含む JSON Hello World!!! レスポンスが表示されます。
- Boto3
-
-
という名前のファイルを作成し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 Code Interpreter セッションを開始します
-
セッション ID を使用して Python コードを実行します。
-
ストリーミングレスポンスを解析してテキスト出力を抽出します
-
セッションを適切に停止してリソースを解放する
boto3 アプローチでは、明示的なセッション管理が必要です。コードを実行するstart_code_interpreter_session前と完了stop_code_interpreter_sessionしたら、 を呼び出す必要があります。
スクリプトを実行する
次の コマンドを実行します。
python direct_code_execution_boto3.py
予想される出力
コード実行の結果として、セッション ID 情報とともに Hello World!!! が表示されます。