View a markdown version of this page

透過 AWS Strands 使用 AgentCore Code Interpreter - Amazon Bedrock AgentCore

透過 AWS Strands 使用 AgentCore Code Interpreter

下列各節說明如何搭配 Strands SDK 使用 Amazon Bedrock AgentCore Code Interpreter。在完成本節中的範例之前,請參閱先決條件

步驟 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 :適用於 Amazon Bedrock AgentCore 的工具開發套件,包括 AgentCore Code Interpreter

  • 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 工具

  • 建立設定為使用程式碼執行進行驗證的代理程式

  • 傳送提示,要求客服人員計算 Fibonacci 號碼

  • 列印客服人員的回應

步驟 3:執行代理程式

執行指令碼:

python code_interpreter_agent.py

預期的輸出

您應該會看到客服人員的回應,其中包含前 10 個 Fibonacci 號碼。代理程式將編寫 Python 程式碼來計算序列,並同時傳回程式碼和結果。

如果您遇到錯誤,請驗證:

  • 您的 IAM 角色具有正確的許可和信任政策

  • 您已在 Amazon Bedrock 主控台中啟用模型存取

  • 您的 AWS 登入資料已正確設定