【入門】Amazon Bedrock AgentCoreのCode Interpreterを動かしてみた

【入門】Amazon Bedrock AgentCoreのCode Interpreterを動かしてみた

Amazon Bedrock AgentCoreのCode Interpreter機能を初めて試してみました。 環境構築からHello World、Strands Agentsを使ったエージェント構築まで、公式ドキュメントのサンプルコードをベースに動かした手順を紹介します。
2025.10.03

こんにちは、AI事業本部の洲崎です。
今回は入門記事として、Amazon Bedrock AgentCoreのCode Interpreter機能を試してみました。公式ドキュメントのサンプルコードをベースに、実際に動かすまでの手順をまとめています。
まだ触ったことがない方にも、ハードルを低く始められるよう手順をまとめています。

参考ドキュメント:

対象読者

  • Amazon Bedrock AgentCore をまだ触ったことがない方
  • まずは環境構築して、Hello World!!! を実行してみたい方
  • Code Interpreterの推論を体験してみたい方

前提

Amazon Bedrock AgentCore を使用する権限を持つAWSアカウントがあること
AWS CLIが使える環境であること(ターミナルからAWSに接続できること)

Bedrock AgentCoreとは

Bedrock AgentCore は、LLMを活用したエージェントを安全かつスケーラブルにデプロイ・運用できるAWSの新しいサービスです。
https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html

Bedrock AgentCoreには様々な機能がありますが、以下の記事が分かりやすくまとまっています。
https://dev.classmethod.jp/articles/amazon-bedrock-agentcore-developersio-2025-osaka/

今回は、その中でもCode Interpreter機能に注目しました。
Code Interpreterは、コード実行・データ分析・計算処理をエージェントに組み込める機能で、生成AIに計算をさせたいというニーズは度々あり興味があったからです。

Bedrock AgentCoreの準備

作業ディレクトリの作成

まず、作業用のディレクトリを作成、移動します。

			
			mkdir bedrock-agentcore-tutorial
cd bedrock-agentcore-tutorial

		

最終的なディレクトリ構成は以下のようになります。

			
			bedrock-agentcore-tutorial/
├── myenv/                    # Python仮想環境(自動生成)
├── hello.py                  # Hello World サンプル
└── strands_ci_agent.py      # Code Interpreter サンプル

		

環境構築

ドキュメントに基づいて準備して、まずはhello.pyが実行できるか確認します。
ターミナルを開き、以下を実行します。

			
			# 1. 仮想環境を作成(任意のディレクトリ名を指定)
python3 -m venv myenv

# 2. 仮想環境を有効化
source myenv/bin/activate

# 3. パッケージをインストール
pip install boto3 bedrock-agentcore strands-agents strands-agents-tools

		

補足: AgentCoreと一緒にインストールするStrands Agentsは、わずか数行のコードでAIエージェントを構築できるAWSのオープンソースSDKです。モデル駆動型アプローチを採用しており、エージェント開発を大幅に簡素化できます。
詳細:Strands Agents – オープンソース AI エージェント SDK の紹介

Configure AWS credentials

aws configure でAWSの認証情報を設定します。
aws sts get-caller-identityを実行し以下のような出力が得られれば成功です。

			
			{
    "UserId": "AIDAXXXXXXXXXXXXX",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/your-user-name"
}

		

ちなみに私はAWSumeを使っています。この辺りはお好みで設定してください。
https://dev.classmethod.jp/articles/awsume/

サンプルコードをベースに、hello.pyを作成します。
region_nameは使用するリージョンに置き換えておきます。

hello_world.py
			
			import boto3
import json

code_to_execute = """
print("Hello World!!!")
"""

client = boto3.client(
    "bedrock-agentcore",
    region_name="us-west-2",  # 使用するリージョンを指定
    endpoint_url="https://bedrock-agentcore.us-west-2.amazonaws.com"
)

session_id = client.start_code_interpreter_session(
    codeInterpreterIdentifier="aws.codeinterpreter.v1",
    name="my-code-session",
    sessionTimeoutSeconds=900
)["sessionId"]

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'])

# Don't forget to stop the session when you're done
client.stop_code_interpreter_session(
    codeInterpreterIdentifier="aws.codeinterpreter.v1",
    sessionId=session_id
)

		

以下を実行します。

			
			python hello.py

		

以下の出力がでれば成功です。

			
			Hello World!!!

		

Code Interpreter を使ったエージェントの構築

エージェントコードの作成

以下のコードを strands_ci_agent.py として保存します。

strands_ci_agent.py
			
			import json
from strands import Agent, tool
from bedrock_agentcore.tools.code_interpreter_client import code_session
import asyncio

#Define the detailed system prompt for the assistant
SYSTEM_PROMPT = """You are a helpful AI assistant that validates all answers through code execution.

VALIDATION PRINCIPLES:
1. When making claims about code, algorithms, or calculations - write code to verify them
2. Use execute_python to test mathematical calculations, algorithms, and logic
3. Create test scripts to validate your understanding before giving answers
4. Always show your work with actual code execution
5. If uncertain, explicitly state limitations and validate what you can

APPROACH:
- If asked about a programming concept, implement it in code to demonstrate
- If asked for calculations, compute them programmatically AND show the code
- If implementing algorithms, include test cases to prove correctness
- Document your validation process for transparency
- The state is maintained between executions, so you can refer to previous results

TOOL AVAILABLE:
- execute_python: Run Python code and see output

RESPONSE FORMAT: The execute_python tool returns a JSON response with:
- sessionId: The code interpreter session ID
- id: Request ID
- isError: Boolean indicating if there was an error
- content: Array of content objects with type and text/data
- structuredContent: For code execution, includes stdout, stderr, exitCode, executionTime

For successful code execution, the output will be in content[0].text and also in structuredContent.stdout.
Check isError field to see if there was an error.

Be thorough, accurate, and always validate your answers when possible."""

#Define and configure the code interpreter tool 
@tool
def execute_python(code: str, description: str = "") -> str:
    """Execute Python code"""

    if description:
        code = f"# {description}\n{code}"

    #Print code to be executed
    print(f"\n Code: {code}")

    # Call the Invoke method and execute the generated code, within the initialized code interpreter session
    with code_session("<Region>") as code_client:
        response = code_client.invoke("executeCode", {
        "code": code,
        "language": "python",
        "clearContext": False
    })

    for event in response["stream"]:
        return json.dumps(event["result"])

#configure the strands agent including the tool(s)
agent=Agent(
        tools=[execute_python],
        system_prompt=SYSTEM_PROMPT,
        callback_handler=None)

query="Can all the planets in the solar system fit between the earth and moon?"

# Invoke the agent asynchcronously and stream the response
async def main():
    response_text = ""
    async for event in agent.stream_async(query):
        if "data" in event:
            # Stream text response
            chunk = event["data"]
            response_text += chunk
            print(chunk, end="")

asyncio.run(main())

		

サンプルの質問内容はqueryに含まれています。

			
			query="Can all the planets in the solar system fit between the earth and moon?"

日本語訳:
太陽系のすべての惑星は、地球と月の間に収まりますか?

		

3.実行と結果の確認

以下のコマンドを実行します。

			
			python strands_ci_agent.py

		

実行結果

			
			I'll calculate whether all the planets in our solar system can fit between Earth and the Moon by comparing their combined diameters to the Earth-Moon distance.
 Code: # Planet diameters in kilometers
planets = {
    'Mercury': 4879,
    'Venus': 12104,
    'Mars': 6792,
    'Jupiter': 142984,
    'Saturn': 120536,
    'Uranus': 51118,
    'Neptune': 49528
}

~省略~

Based on the known planetary diameters and Earth-Moon distance:

**Planet Diameters (km):**
- Mercury: 4,879 km
- Venus: 12,104 km  
- Mars: 6,792 km
- Jupiter: 142,984 km
- Saturn: 120,536 km
- Uranus: 51,118 km
- Neptune: 49,528 km

**Total diameter of all planets:** 387,941 km

**Earth-Moon distance:** 384,400 km (average)

**Answer: NO** - All the planets cannot fit between Earth and the Moon.

		

日本語訳

			
			地球と月の間に太陽系のすべての惑星が収まるかどうかを、惑星の直径の合計と地球と月の距離を比較して計算してみます。

コード:
```python
# 惑星の直径(キロメートル単位)
planets = {
    'Mercury': 4879,
    'Venus': 12104,
    'Mars': 6792,
    'Jupiter': 142984,
    'Saturn': 120536,
    'Uranus': 51118,
    'Neptune': 49528
}

~省略~

既知の惑星の直径と地球と月の距離に基づくと:

**惑星の直径(km):**
- 水星:4,879 km  
- 金星:12,104 km  
- 火星:6,792 km  
- 木星:142,984 km  
- 土星:120,536 km  
- 天王星:51,118 km  
- 海王星:49,528 km  

**すべての惑星の直径の合計:** 387,941 km

**地球と月の距離(平均):** 384,400 km

**答え:いいえ** — すべての惑星は地球と月の間には収まりません。

		

実際にコードを生成・実行し、数値をもとに論理的に回答してくれました。
Code Interpreterは以下のプロセスを自動で実行しています。

  • 問題を理解し、必要なデータを特定
  • Pythonコードを生成
  • コードを実行して計算
  • 結果を分かりやすく整形して回答

単なる知識の提示ではなく、実際に計算して検証するアプローチが取られていました。

設定が簡単だった

Amazon Bedrock AgentCoreのCode Interpreterを試してみました。
設定がシンプルで、Pythonから簡単に実行できるのが魅力的です。
計算も生成AIに任せたいケースは聞くので、次回はS3などの外部にあるデータをもとに計算ができるかを試してみたいと思います。

ではまた!AI事業本部の洲崎でした。

この記事をシェアする

FacebookHatena blogX

関連記事