直接使用 AgentCore 代码解释器
以下各节介绍如何在没有代理框架的情况下直接使用 Amazon Bedrock AgentCore 代码解释器。当你想以编程方式执行特定的代码片段时,这特别有用。在阅读本节中的示例之前,请参阅先决条件。
第 1 步:选择您的方法并安装依赖项
Amazon Bedrock AgentCore 提供了两种与 AgentCore 代码解释器交互的方式:使用高级软件开发工具包客户端或直接使用 boto3。
创建一个项目文件夹(如果你之前没有创建过)并安装所需的软件包:
mkdir agentcore-tools-quickstart
cd agentcore-tools-quickstart
python3 -m venv .venv
source .venv/bin/activate
在 Windows 上,使用:.venv\Scripts\activate
安装所需的软件包:
pip install bedrock-agentcore boto3
这些软件包提供:
步骤 2:执行代码
选择以下方法之一使用代码解释器执行 AgentCore 代码:
<Region>替换为您的实际 AWS 区域(例如,us-east-1或us-west-2)。
例
- SDK Client
-
-
创建一个名为的文件direct_code_execution_sdk.py并添加以下代码:
from bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
import json
# Initialize the Code Interpreter client for your region
code_client = CodeInterpreter('<Region>')
# Start a Code Interpreter session
code_client.start()
try:
# Execute Python code
response = code_client.invoke("executeCode", {
"language": "python",
"code": 'print("Hello World!!!")'
})
# Process and print the response
for event in response["stream"]:
print(json.dumps(event["result"], indent=2))
finally:
# Always clean up the session
code_client.stop()
这段代码:
-
为您所在的地区创建 AgentCore 代码解释器客户端
-
启动会话(在执行代码之前是必需的)
-
执行 Python 代码并流式传输包含完整事件详细信息的结果
-
停止会话以清理资源
运行脚本
执行下面的 命令:
python direct_code_execution_sdk.py
预期产出
您应该会在输出内容Hello World!!!中看到包含执行结果的 JSON 响应。
- Boto3
-
-
创建一个名为的文件direct_code_execution_boto3.py并添加以下代码:
import boto3
import json
# Code to execute
code_to_execute = """
print("Hello World!!!")
"""
# Initialize the bedrock-agentcore client
client = boto3.client(
"bedrock-agentcore",
region_name="<Region>"
)
# Start a Code Interpreter session
session_response = client.start_code_interpreter_session(
codeInterpreterIdentifier="aws.codeinterpreter.v1",
name="my-code-session",
sessionTimeoutSeconds=900
)
session_id = session_response["sessionId"]
print(f"Started session: {session_id}\n\n")
try:
# Execute code in the session
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'])
finally:
# Stop the session when done
client.stop_code_interpreter_session(
codeInterpreterIdentifier="aws.codeinterpreter.v1",
sessionId=session_id
)
print(f"\n\nStopped session: {session_id}")
这段代码:
-
为 bedrock-agentcore 服务创建一个 boto3 客户端
-
以 900 AgentCore 秒的超时时间启动代码解释器会话
-
使用会话 ID 执行 Python 代码
-
解析流媒体响应以提取文本输出
-
正确停止会话以释放资源
boto3 方法需要明确的会话管理。你必须在执行代码start_code_interpreter_session之前和stop_code_interpreter_session完成后调用。
运行脚本
执行下面的 命令:
python direct_code_execution_boto3.py
预期产出
您应该看到代码执行的结果以及会话 ID 信息Hello World!!!打印出来。