通过以下方式使用 AgentCore 代码解释器 AWS Strands
以下各节将向您展示如何将 Amazon Bedrock AgentCore 代码解释器与 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: 适用于 Amazon Bedrock 的 SDK AgentCore 工具,包括 AgentCore 代码解释器 -
strands-agents: Strands 代理框架 -
strands-agents-tools: Strands 代理框架提供的工具
第 2 步:使用 AgentCore 代码解释器创建代理
创建一个名为的文件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 代码解释器工具
-
创建配置为使用代码执行进行验证的代理
-
发送提示,要求代理计算斐波那契数字
-
打印代理的响应
步骤 3:运行代理
执行脚本:
python code_interpreter_agent.py
预期产出
您应该会看到代理的回复中包含前 10 个斐波那契数字。代理将编写 Python 代码来计算序列并返回代码和结果。
如果遇到错误,请验证:
-
您的 IAM 角色具有正确的权限和信任策略
-
您已在 Amazon Bedrock 控制台中启用模型访问权限
-
您的 AWS 凭证配置正确