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

# Modal

> 使用 Modal 沙箱后端与 deepagents 进行隔离代码执行，支持 GPU

[Modal](https://modal.com) 提供支持 GPU 的无服务器容器基础设施。最适合 ML/AI 工作负载和 Python 开发。

## 设置

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install @langchain/modal
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/modal
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add @langchain/modal
  ```
</CodeGroup>

### 认证

从 [modal.com/settings/tokens](https://modal.com/settings/tokens) 获取您的令牌。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export MODAL_TOKEN_ID=your_token_id
export MODAL_TOKEN_SECRET=your_token_secret
```

或者直接传递凭证：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const sandbox = await ModalSandbox.create({
  auth: {
    tokenId: "your-token-id",
    tokenSecret: "your-token-secret",
  },
});
```

## 与 deepagents 一起使用

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createDeepAgent } from "deepagents";
import { ChatAnthropic } from "@langchain/anthropic";
import { ModalSandbox } from "@langchain/modal";

const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  timeoutMs: 600_000, // 10 分钟
});

try {
  const agent = createDeepAgent({
    model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
    systemPrompt: "You are a coding assistant with sandbox access.",
    backend: sandbox,
  });

  const result = await agent.invoke({
    messages: [{ role: "user", content: "Install numpy and calculate pi" }],
  });
} finally {
  await sandbox.close();
}
```

## 独立使用

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ModalSandbox } from "@langchain/modal";

const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  timeoutMs: 600_000,
});

const result = await sandbox.execute("python --version");
console.log(result.output);

await sandbox.close();
```

## 配置

| 选项             | 类型                                     | 默认值             | 描述                                 |
| -------------- | -------------------------------------- | --------------- | ---------------------------------- |
| `imageName`    | `string`                               | `"alpine:3.21"` | 要使用的 Docker 镜像                     |
| `timeoutMs`    | `number`                               | `300000`        | 最大生命周期（毫秒）                         |
| `workdir`      | `string`                               | -               | 工作目录                               |
| `gpu`          | `string`                               | -               | GPU 类型（`"T4"`、`"A100"`、`"H100"` 等） |
| `cpu`          | `number`                               | -               | CPU 核心数（允许小数）                      |
| `memoryMiB`    | `number`                               | -               | 内存分配（MiB）                          |
| `volumes`      | `Record<string, string>`               | -               | 卷名称映射（挂载路径到卷名称）                    |
| `secrets`      | `string[]`                             | -               | 要注入的 Modal Secret 名称               |
| `initialFiles` | `Record<string, string \| Uint8Array>` | -               | 启动时要创建的文件                          |
| `env`          | `Record<string, string>`               | -               | 环境变量                               |
| `blockNetwork` | `boolean`                              | -               | 阻止网络访问                             |
| `name`         | `string`                               | -               | 沙箱名称（在应用内唯一）                       |

## GPU 支持

Modal 支持用于 ML 工作负载的 NVIDIA GPU：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  gpu: "T4",  // 或 "L4"、"A10G"、"A100"、"H100"
});
```

## 卷和密钥

挂载 Modal 卷以实现持久化存储，并将密钥作为环境变量注入：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// 卷和密钥必须首先在 Modal 中创建
const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  volumes: {
    "/data": "my-data-volume",
    "/models": "my-models-volume",
  },
  secrets: ["my-api-keys", "database-credentials"],
});

// /data 和 /models 中的文件在沙箱重启后仍然存在
await sandbox.execute("echo 'Hello' > /data/test.txt");

// 密钥可作为环境变量使用
await sandbox.execute("echo $API_KEY");
```

## 初始文件

在创建时预填充沙箱文件：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  initialFiles: {
    "/app/main.py": 'print("Hello from Python!")',
    "/app/config.json": JSON.stringify({ name: "my-app" }, null, 2),
  },
});

const result = await sandbox.execute("python /app/main.py");
```

## 访问 Modal SDK

对于 `BaseSandbox` 未暴露的高级功能，访问底层的 Modal SDK：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const modalSandbox = await ModalSandbox.create();

const client = modalSandbox.client;     // ModalClient
const instance = modalSandbox.instance;  // Sandbox

// 直接 SDK 操作
const process = await instance.exec(["python", "-c", "print('Hello')"], {
  stdout: "pipe",
  stderr: "pipe",
});
```

## 重新连接到现有沙箱

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// 通过 ID 重新连接
const reconnected = await ModalSandbox.fromId(sandboxId);

// 通过名称重新连接
const reconnected2 = await ModalSandbox.fromName("my-app", "my-sandbox");
```

## 工厂函数

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createModalSandboxFactory, createModalSandboxFactoryFromSandbox } from "@langchain/modal";

// 每次调用创建新沙箱
const factory = createModalSandboxFactory({ imageName: "python:3.12-slim" });

// 或者跨调用重用现有沙箱
const sandbox = await ModalSandbox.create();
const reuseFactory = createModalSandboxFactoryFromSandbox(sandbox);
```

## 错误处理

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ModalSandboxError } from "@langchain/modal";

try {
  await sandbox.execute("some command");
} catch (error) {
  if (error instanceof ModalSandboxError) {
    switch (error.code) {
      case "NOT_INITIALIZED":
        await sandbox.initialize();
        break;
      case "COMMAND_TIMEOUT":
        console.error("Command took too long");
        break;
      case "AUTHENTICATION_FAILED":
        console.error("Check your Modal token credentials");
        break;
    }
  }
}
```

### 错误代码

| 代码                        | 描述                         |
| ------------------------- | -------------------------- |
| `NOT_INITIALIZED`         | 沙箱未初始化 - 调用 `initialize()` |
| `ALREADY_INITIALIZED`     | 不能初始化两次                    |
| `AUTHENTICATION_FAILED`   | Modal 令牌无效或缺失              |
| `SANDBOX_CREATION_FAILED` | 创建沙箱失败                     |
| `SANDBOX_NOT_FOUND`       | 沙箱 ID/名称未找到或已过期            |
| `COMMAND_TIMEOUT`         | 命令执行超时                     |
| `COMMAND_FAILED`          | 命令执行失败                     |
| `FILE_OPERATION_FAILED`   | 文件读写失败                     |
| `RESOURCE_LIMIT_EXCEEDED` | 超出 CPU、内存或存储限制             |
| `VOLUME_ERROR`            | 卷操作失败                      |

## 环境变量

| 变量                   | 描述              |
| -------------------- | --------------- |
| `MODAL_TOKEN_ID`     | Modal API 令牌 ID |
| `MODAL_TOKEN_SECRET` | Modal API 令牌密钥  |

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs) 到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/providers/modal.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
