> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Amazon Bedrock AgentCore 代码解释器集成

> 使用 LangChain Python 集成 Amazon Bedrock AgentCore 代码解释器工具。

[Amazon Bedrock AgentCore Code Interpreter](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/code-interpreter-tool.html)使智能体能安全、受管理地在一个沙盒环境中执行代码。智能体可以运行Python、JavaScript和TypeScript代码以进行计算、数据分析、文件操作和可视化。

## 概述

### 集成细节

| 类别 | 包 | 可序列化 | [JS支持](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/tools.md) | 版本 |
| :- | :- | :-: | :-: | :-: |
| [`CodeInterpreterToolkit`](https://github.com/langchain-ai/langchain-aws/tree/main/libs/aws/langchain_aws/tools) | [`langchain-aws`](https://pypi.org/project/langchain-aws/) | ❌ | ❌ | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-aws?style=flat-square\&label=%20) |

### 工具功能

| [返回 artifact](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | 原生异步 | 返回数据 | 定价 |
| :-: | :-: | :-: | :-: |
| ✅ | ✅ | 文本、文件、图像 | 按需付费（AWS） |

### 可用工具

该工具包提供多种用于代码执行和文件管理的工具：

| 工具 | 描述 |
| :- | :- |
| `execute_code` | 运行 Python/JavaScript/TypeScript 代码（支持持久化状态） |
| `execute_command` | 在环境中执行 shell 命令 |
| `read_files` | 读取环境中文件内容 |
| `write_files` | 创建或更新文件 |
| `list_files` | 列出目录中的文件 |
| `delete_files` | 从环境中删除文件 |
| `upload_file` | 上传带语义描述的文件 |
| `install_packages` | 安装 Python 包 |
| `start_command_execution` | 异步启动长时间运行命令 |
| `get_task` | 通过 task\_id 查询异步任务状态 |
| `stop_task` | 通过 task\_id 终止运行中的异步任务 |

## 配置

该集成位于 `langchain-aws` 包中，封装了 `bedrock-agentcore` SDK。

```bash pip theme={null}
pip install -U langchain-aws bedrock-agentcore
```

```bash uv theme={null}
uv add langchain-aws bedrock-agentcore
```

### 凭证

需要配置 AWS 凭证（权限需支持 Bedrock AgentCore 代码解释器）。请参考 [Amazon Bedrock AgentCore 文档](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html) 中要求的 IAM 权限。

若需最佳实践的可观测性，建议（非必需）配置 LangSmith：

```python theme={null}
import os

os.environ["LANGSMITH_API_KEY"] = "your-api-key"
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

工具通过 **异步** 工厂函数创建：

```python theme={null}
from langchain_aws.tools import create_code_interpreter_toolkit

# Create toolkit and get tools (async)
toolkit, code_tools = await create_code_interpreter_toolkit(region="us-west-2")
```

## 调用

### 直接调用工具

获取特定工具并调用它们：

```python theme={null}
# Get tools by name
tools_by_name = toolkit.get_tools_by_name()

# Execute Python code
result = tools_by_name["execute_code"].invoke({
    "code": """
import numpy as np
data = [1, 2, 3, 4, 5]
print(f"Mean: {np.mean(data)}")
print(f"Sum: {np.sum(data)}")
""",
    "language": "python"
})
print(result)
```

### 在智能体中调用

```python theme={null}
import asyncio
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_aws.tools import create_code_interpreter_toolkit

async def main():
    # Create toolkit
    toolkit, code_tools = await create_code_interpreter_toolkit(region="us-west-2")

    # Initialize chat model
    llm = init_chat_model(
        "us.anthropic.claude-sonnet-4-20250514-v1:0",
        model_provider="bedrock_converse",
    )

    # Create agent with code interpreter tools
    agent = create_agent(
        model=llm,
        tools=code_tools,
    )

    # Create config with thread_id for session isolation
    config = {"configurable": {"thread_id": "session-123"}}

    # Run the agent
    result = await agent.ainvoke(
        {"messages": [{"role": "user", "content": "Calculate the factorial of 10"}]},
        config=config
    )
    print(result["messages"][-1].content)

    # Clean up when done
    await toolkit.cleanup()

asyncio.run(main())
```

## 线程级会话隔离

工具支持通过 `thread_id` 实现多并发会话。每个线程维护独立的代码解释器会话及隔离状态：

```python theme={null}
# Different threads have isolated sessions
config_user1 = {"configurable": {"thread_id": "user-1"}}
config_user2 = {"configurable": {"thread_id": "user-2"}}

# Variables defined in user-1's session won't exist in user-2's session
await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Set x = 100"}]},
    config=config_user1
)

await agent.ainvoke(
    {"messages": [{"role": "user", "content": "What is x?"}]},  # x is undefined here
    config=config_user2
)
```

## 文件操作

### 写入和读取文件

```python theme={null}
tools_by_name = toolkit.get_tools_by_name()

# Write a file
tools_by_name["write_files"].invoke({
    "files": [{"path": "data.csv", "text": "name,value\nAlice,100\nBob,200"}]
})

# Read it back
content = tools_by_name["read_files"].invoke({"paths": ["data.csv"]})
print(content)

# List files in current directory
files = tools_by_name["list_files"].invoke({"directory_path": "."})
print(files)
```

### 上传带描述的文件

```python theme={null}
tools_by_name["upload_file"].invoke({
    "path": "sales.csv",
    "content": "date,revenue,product\n2024-01-01,1000,Widget\n2024-01-02,1500,Gadget",
    "description": "Sales data with columns: date, revenue, product_id"
})
```

## 安装包管理

```python theme={null}
tools_by_name["install_packages"].invoke({
    "packages": ["pandas>=2.0", "matplotlib", "scikit-learn"],
    "upgrade": False
})
```

## 异步任务管理

对于长时间运行的命令，可异步启动并检查状态：

```python theme={null}
tools_by_name = toolkit.get_tools_by_name()
config = {"configurable": {"thread_id": "session-123"}}

# Start a long-running command asynchronously
result = tools_by_name["start_command_execution"].invoke(
    {"command": "python long_running_script.py"},
    config=config
)
# Returns a task_id

# Check task status
status = tools_by_name["get_task"].invoke(
    {"task_id": "task-abc123"},
    config=config
)
print(status)

# Stop a running task if needed
tools_by_name["stop_task"].invoke(
    {"task_id": "task-abc123"},
    config=config
)
```

## 会话清理

使用后务必清理会话以释放资源：

```python theme={null}
# Clean up all sessions
await toolkit.cleanup()

# Or clean up a specific thread's session
await toolkit.cleanup(thread_id="session-123")
```

***

## API 参考文档

所有功能及配置的详细文档请参考：

* [langchain-aws API reference](https://reference.langchain.com/python/langchain-aws)
* [Amazon Bedrock AgentCore 文档](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html)

***

> 官方原文：[src/oss/python/integrations/tools/bedrock\_agentcore\_code\_interpreter.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/tools/bedrock_agentcore_code_interpreter.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.