> ## 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.

# Modal

> 使用 Modal 沙盒后端与 deepagents 配合，实现 GPU 支持的隔离代码执行

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

## 安装

```bash npm theme={null}
npm install @langchain/modal
```

```bash yarn theme={null}
yarn add @langchain/modal
```

```bash pnpm theme={null}
pnpm add @langchain/modal
```

### 身份验证

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

```bash theme={null}
export MODAL_TOKEN_ID=your_token_id
export MODAL_TOKEN_SECRET=your_token_secret
```

或者直接传递凭证：

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

## 与 deepagents 一起使用

:::js

```typescript theme={null}
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 minutes
});

try {
  const agent = createDeepAgent({
    model: new ChatAnthropic({ model: "claude-sonnet-4-6" }),
    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();
}
```

:::

## 独立使用

:::js

```typescript theme={null}
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 支持 NVIDIA GPU 用于 ML 工作负载：

:::js

```typescript theme={null}
const sandbox = await ModalSandbox.create({
  imageName: "python:3.12-slim",
  gpu: "T4",  // or "L4", "A10G", "A100", "H100"
});
```

:::

## 卷和 Secret

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

:::js

```typescript theme={null}
// Volumes and secrets must be created in Modal first
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"],
});

// Files in /data and /models persist across sandbox restarts
await sandbox.execute("echo 'Hello' > /data/test.txt");

// Secrets are available as environment variables
await sandbox.execute("echo $API_KEY");
```

:::

## 初始文件

在创建时预填充沙盒中的文件：

:::js

```typescript theme={null}
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：

:::js

```typescript theme={null}
const modalSandbox = await ModalSandbox.create();

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

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

:::

## 重新连接到现有沙盒

:::js

```typescript theme={null}
// Reconnect by ID
const reconnected = await ModalSandbox.fromId(sandboxId);

// Reconnect by name
const reconnected2 = await ModalSandbox.fromName("my-app", "my-sandbox");
```

:::

## 工厂函数

:::js

```typescript theme={null}
import { createModalSandboxFactory, createModalSandboxFactoryFromSandbox } from "@langchain/modal";

// Create new sandbox per invocation
const factory = createModalSandboxFactory({ imageName: "python:3.12-slim" });

// Or reuse an existing sandbox across invocations
const sandbox = await ModalSandbox.create();
const reuseFactory = createModalSandboxFactoryFromSandbox(sandbox);
```

:::

## 错误处理

```typescript theme={null}
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 Token |
| `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 token ID |
| `MODAL_TOKEN_SECRET` | Modal API token secret |

***

> 官方原文：[src/oss/javascript/integrations/providers/modal.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/providers/modal.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


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