Serverless Operations, inc

>_cd /blog/id_sl-peiw9_-o

title

Amazon Bedrock AgentCore (4) Code Interpreter :自然言語からのコードの記述・実行・デバッグ

今日は Code Interpreter を触っていきます。

Code Interpreter は、エージェントが安全なサンドボックス環境内でコードを記述・実行・デバッグできるツールです。これにより、自然言語理解とプログラム実行をシームレスに統合できます。複数のプログラミング言語(Python, JavaScript, TypeScriptなど)に対応し、インタラクティブな処理が可能です。

以下の様な特徴を備えています。

  • セキュアなコード実行

    実行はコンテナ化されたサンドボックス内で行われ、外部への影響を制限することができます。ネットワーク設定(Sandbox/Publicなど)や IAM ロールによる権限制御が可能です。

  • 多言語・高度な構成

    Python や JavaScript, TypeScript 等複数言語に対応し大きなファイル(インラインアップロードで最大100MB、S3経由なら最大5GB)も扱うことが可能です。

  • ログとモニタリング

    CloudTrail により操作ログを取得でき、トレースや監査にも対応することができます 。

  • 実行時間の柔軟性

    デフォルトで15分、最大8時間までの長時間実行に対応しています 。

  • 構造化データ処理

    CSV、Excel、JSONなどの形式を読み込み、データクリーニングや解析が可能です。

  • 複雑なワークフロー支援

    複数ステップの推論や反復的なデバッグ・開発もサポートしています。

さっそくやってみる

ではStarterkitのサンプルをやっていきます。

まず codeinterpreter.py を作成時実行してCode Interpreter のセッションを作成します。

from bedrock_agentcore.tools.code_interpreter_client import code_session

# Code Interpreter セッションを作成
with code_session("us-west-2") as client:
    print("Code interpreter session created")
    
    # セッションIDを取得
    print(f"Session ID: {client.session_id}")

    # 例: listFiles を呼び出し
    result = client.invoke("listFiles")
    for event in result["stream"]:
        print(event["result"]["content"])
python3 codeinterpreter.py
Code interpreter session created
Session ID: 01K37RFWXTETE17P4GRGS2XZXK
[{'type': 'resource_link', 'uri': 'file:///log', 'name': 'log', 'description': 'Directory'}, {'type': 'resource_link', 'uri': 'file:///.ipython', 'name': '.ipython', 'description': 'Directory'}]

次にCode Interpreter 経由でPythonコードを実行します。

from bedrock_agentcore.tools.code_interpreter_client import code_session

with code_session("us-west-2") as client:
    # 実行するPythonコード
    code_to_execute = """
import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.show()

print("Code execution completed successfully!")
"""

    # コードを実行
    result = client.invoke("executeCode", {"language": "python", "code": code_to_execute})

    # ストリーミング結果をそのまま出力
    print("=== Raw Events ===")
    for event in result["stream"]:
        print(event)
python3 codeexecute.py
=== Raw Events ===
{'result': {'content': [{'type': 'text', 'text': '<Figure size 1000x600 with 1 Axes>\nCode execution completed successfully!'}], 'structuredContent': {'stdout': '<Figure size 1000x600 with 1 Axes>\nCode execution completed successfully!', 'stderr': '', 'exitCode': 0, 'executionTime': 0.8740293979644775}, 'isError': False}}

'isError': False となっておりコードが異常なく実行されたことがわかります。

次にPythonコードを意図的にバグがある状態に書き換えます。

plt.xlabel('x')plt.label(x)として再度実行します。

python3 codeexecute.py
=== Raw Events ===
{'result': {'content': [{'type': 'text', 'text': '<Figure size 1000x600 with 1 Axes>'}, {'type': 'text', 'text': "---------------------------------------------------------------------------\nAttributeError                            Traceback (most recent call last)\nCell In[2], line 12\n     10 plt.plot(x, y, 'b-', linewidth=2)\n     11 plt.title('Sine Wave')\n---> 12 plt.label(x)\n     13 plt.ylabel('sin(x)')\n     14 plt.grid(True)\n\nAttributeError: module 'matplotlib.pyplot' has no attribute 'label'"}], 'structuredContent': {'stdout': '<Figure size 1000x600 with 1 Axes>', 'stderr': "---------------------------------------------------------------------------\nAttributeError                            Traceback (most recent call last)\nCell In[2], line 12\n     10 plt.plot(x, y, 'b-', linewidth=2)\n     11 plt.title('Sine Wave')\n---> 12 plt.label(x)\n     13 plt.ylabel('sin(x)')\n     14 plt.grid(True)\n\nAttributeError: module 'matplotlib.pyplot' has no attribute 'label'", 'exitCode': 1, 'executionTime': 1.0843472480773926}, 'isError': True}}

このようにエラーとなります。このままではエラー出力が改行されず見づらいため codeexecute.py を以下に置換して再度実行します。

import json
from bedrock_agentcore.tools.code_interpreter_client import code_session

with code_session("us-west-2") as client:
    # わざとエラーを起こすコード
    code_to_execute = """
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Sine Wave')

# 存在しないメソッドを呼んでエラーを出す
plt.label(x)

plt.ylabel('sin(x)')
plt.grid(True)
plt.show()
"""

    result = client.invoke("executeCode", {"language": "python", "code": code_to_execute})

    print("=== Formatted Events ===")
    for event in result["stream"]:
        result_obj = event.get("result", {})
        content = result_obj.get("content", [])
        structured = result_obj.get("structuredContent", {})
        is_error = result_obj.get("isError", False)

        if content:
            print("\n-- Content --")
            for item in content:
                if item["type"] == "text":
                    print(item["text"])

        if structured:
            print("\n-- Structured Content --")
            print(json.dumps(structured, indent=2, ensure_ascii=False))

        if is_error:
            print("\n[!] Error occurred")
python3 codeexecute.py
=== Formatted Events ===

-- Content --
<Figure size 1000x600 with 1 Axes>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 12
      9 plt.title('Sine Wave')
     11 # 存在しないメソッドを呼んでエラーを出す
---> 12 plt.label(x)
     14 plt.ylabel('sin(x)')
     15 plt.grid(True)

AttributeError: module 'matplotlib.pyplot' has no attribute 'label'

-- Structured Content --
{
  "stdout": "<Figure size 1000x600 with 1 Axes>",
  "stderr": "---------------------------------------------------------------------------\nAttributeError                            Traceback (most recent call last)\nCell In[2], line 12\n      9 plt.title('Sine Wave')\n     11 # 存在しないメソッドを呼んでエラーを出す\n---> 12 plt.label(x)\n     14 plt.ylabel('sin(x)')\n     15 plt.grid(True)\n\nAttributeError: module 'matplotlib.pyplot' has no attribute 'label'",
  "exitCode": 1,
  "executionTime": 1.0242962837219238
}

[!] Error occurred

まとめ

今回は、Amazon Bedrock AgentCore Code Interpreterを動かしてみましたが、「セキュアな環境で自然言語 → コード実行 → 結果取得」 の流れがスムーズに実現できることが分かりました。感想として、自然言語理解とプログラム実行の環境がこれだけ簡単に準備できるのは驚きでした。例えば今後、以下のようなユースケースが考えられそうです。

  • S3に蓄積された数GB単位のCSVやログデータを直接読み込み、クレンジング・集計・可視化までをエージェントが担う
  • 既存のREST APIやLambdaをMCP対応ツールとして公開、自然言語からシームレスに呼び出し、外部システムから必要に応じたデータを取得
  • CloudTrailやログを自動解析し、異常検知や監査レポート作成をエージェントが支援

このように、自然言語で複雑な処理を実行して様々な業務が自動化できることは、さらにAIの使い所を広げていってくれそうです。

Written by
編集部

亀田 治伸

Kameda Harunobu

  • Facebook->
  • X->
  • GitHub->

Share

Facebook->X->
Back
to list
<-