View a markdown version of this page

通过以下方式使用 AgentCore 代码解释器 AWS Strands - 亚马逊基岩 AgentCore

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

通过以下方式使用 AgentCore 代码解释器 AWS Strands

以下部分向您展示如何在 Strands SDK 中使用亚马逊 Bedrock AgentCore 代码解释器。在阅读本节中的示例之前,请参阅先决条件。

第 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: 适用于亚马逊 Bedrock 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 角色具有正确的权限和信任政策

  • 您在亚马逊 Bedrock 控制台中启用了模型访问权限

  • 您的 AWS 证书配置正确