Strands による AgentCore Code Interpreter AWS の使用
以下のセクションでは、Amazon Bedrock AgentCore Code Interpreter を Strands SDK で使用する方法を示します。このセクションの例に進む前に、「前提条件」を参照してください。
ステップ 1: 依存関係をインストールする
プロジェクトフォルダを作成し、必要なパッケージをインストールします。
注記
Windows では、以下を使用します。 .venv\Scripts\activate
mkdir agentcore-tools-quickstart cd agentcore-tools-quickstart python3 -m venv .venv source .venv/bin/activate
必要なパッケージをインストールします。
pip install bedrock-agentcore strands-agents strands-agents-tools
これらのパッケージは以下を提供します。
-
bedrock-agentcore: AgentCore Code Interpreter を含む SDK for Amazon Bedrock AgentCore ツール -
strands-agents: Strands エージェントフレームワーク -
strands-agents-tools: Strands エージェントフレームワークが提供するツール
ステップ 2: AgentCore Code Interpreter を使用してエージェントを作成する
という名前のファイルを作成しcode_interpreter_agent.py、次のコードを追加します。
from strands import Agent from strands_tools.code_interpreter import AgentCoreCodeInterpreter # Initialize the Code Interpreter tool code_interpreter_tool = AgentCoreCodeInterpreter(region="<Region>") # Define the agent's system prompt SYSTEM_PROMPT = """You are an AI assistant that validates answers through code execution. When asked about code, algorithms, or calculations, write Python code to verify your answers.""" # Create an agent with the Code Interpreter tool agent = Agent( tools=[code_interpreter_tool.code_interpreter], system_prompt=SYSTEM_PROMPT ) # Test the agent with a sample prompt prompt = "Calculate the first 10 Fibonacci numbers." print(f"\n\nPrompt: {prompt}\n\n") response = agent(prompt) print(response.message["content"][0]["text"])
このコード:
-
リージョンの AgentCore Code Interpreter ツールを初期化します
-
検証にコード実行を使用するように設定されたエージェントを作成します。
-
フィボナッチ数を計算するようエージェントに求めるプロンプトを送信します
-
エージェントのレスポンスを出力します
ステップ 3: エージェントを実行する
スクリプトを実行します。
python code_interpreter_agent.py
予想される出力
最初の 10 個のフィボナッチ数を含むエージェントのレスポンスが表示されます。エージェントは Python コードを記述してシーケンスを計算し、コードと結果の両方を返します。
エラーが発生した場合は、以下を確認します。
-
IAM ロールに正しいアクセス許可と信頼ポリシーがある
-
Amazon Bedrock コンソールでモデルアクセスが有効になっている
-
AWS 認証情報が正しく設定されている