以编程方式使用文档

Modal provides serverless container infrastructure with GPU support. Best for ML/AI workloads and Python development.

设置

    npm install @langchain/modal
    
    yarn add @langchain/modal
    
    pnpm add @langchain/modal
    

身份验证

从以下位置获取您的令牌 modal.com/settings/tokens.

或直接传递凭据:

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

与 deepagents 结合使用

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-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();
}

独立使用

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();

配置

选项类型默认值描述
imageNamestring"alpine:3.21"要使用的 Docker 镜像
timeoutMsnumber300000最大生命周期(毫秒)
workdirstring-工作目录
gpustring-GPU 类型 ("T4", "A100", "H100" 等)
cpunumber-CPU 核心数(允许小数)
memoryMiBnumber-内存分配(MiB)
volumesRecord<string, string>-卷名称映射(挂载路径到卷名称)
secretsstring[]-要注入的 Modal Secret 名称
initialFiles`Record<string, string \Uint8Array>`-
envRecord<string, string>-环境变量
blockNetworkboolean-阻止网络访问
namestring-沙盒名称(应用内唯一)

GPU 支持

Modal 支持 NVIDIA GPU 用于机器学习工作负载:

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

卷和密钥

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

// 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");

初始文件

在创建期间预填充沙盒文件:

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:

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",
});

重新连接到现有沙盒

// Reconnect by ID
const reconnected = await ModalSandbox.fromId(sandboxId);

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

工厂函数

// 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);

错误处理

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_FOUNDSandbox ID/name not found or expired
COMMAND_TIMEOUT命令执行超时
COMMAND_FAILED命令执行失败
FILE_OPERATION_FAILEDFile read/write failed
RESOURCE_LIMIT_EXCEEDED超出 CPU、内存或存储限制
VOLUME_ERROR卷操作失败

环境变量

变量描述
MODAL_TOKEN_IDModal API 令牌 ID
MODAL_TOKEN_SECRETModal API 令牌密钥