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

# Daytona

> 使用 Daytona 沙盒后端与 deepagents 配合，实现隔离代码执行（支持快速冷启动）

[Daytona](https://daytona.io) 提供支持多语言的快速启动沙箱环境。最适合 TypeScript 和 Python 开发。

## 安装

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

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

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

### 认证

从 [app.daytona.io](https://app.daytona.io) 获取您的 API 密钥。

```bash theme={null}
export DAYTONA_API_KEY=your_api_key
```

或者直接传递凭证：

```typescript theme={null}
const sandbox = await DaytonaSandbox.create({
  auth: { apiKey: "your-api-key-here" },
});
```

## 与 deepagents 一起使用

:::js

```typescript theme={null}
import { createDeepAgent } from "deepagents";
import { ChatAnthropic } from "@langchain/anthropic";
import { DaytonaSandbox } from "@langchain/daytona";

const sandbox = await DaytonaSandbox.create({
  language: "typescript",
  timeout: 300,
});

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: "Create a hello world TypeScript app and run it" }],
  });
} finally {
  await sandbox.close();
}
```

:::

## 独立使用

:::js

```typescript theme={null}
import { DaytonaSandbox } from "@langchain/daytona";

const sandbox = await DaytonaSandbox.create({
  language: "typescript",
  timeout: 300,
});

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

await sandbox.close();
```

:::

## 配置

| 选项 | 类型 | 默认值 | 描述 |
| - | - | - | - |
| `language` | `string` | `"typescript"` | 主要语言运行时。选项: `"typescript" \| "python" \| "javascript"` |
| `timeout` | `number` | `300` | 命令超时时间（秒） |
| `target` | `string` | `"us"` | 区域。选项: `"us" \| "eu"` |
| `image` | `string` | - | 自定义 Docker 镜像（例如，`"node:20"`, `"python:3.12"`） |
| `snapshot` | `string` | - | 快照名称（不能与 `image` 一起使用） |
| `resources` | `object` | - | CPU、内存、磁盘分配（需要 `image`） |
| `autoStopInterval` | `number` | `15` | 空闲 N 分钟后自动停止（0 禁用） |
| `labels` | `Record<string, string>` | - | 用于组织沙箱的自定义标签 |
| `initialFiles` | `Record<string, string>` | - | 启动时创建的文件 |

## 自定义资源

要自定义 CPU、内存或磁盘，您必须指定一个 Docker 镜像：

:::js

```typescript theme={null}
const sandbox = await DaytonaSandbox.create({
  image: "node:20",
  language: "typescript",
  resources: {
    cpu: 4,       // Number of CPUs
    memory: 8,    // GiB
    disk: 50,     // GiB
  },
});
```

:::

## 可用区域

| 区域 | 位置 |
| - | - |
| `us` | 美国 |
| `eu` | 欧洲 |

## 访问 Daytona SDK

要使用高级功能，访问底层的 Daytona SDK：

:::js

```typescript theme={null}
const daytonaSandbox = await DaytonaSandbox.create();
const sdk = daytonaSandbox.sandbox;

// Use any Daytona SDK feature directly
const workDir = await sdk.getWorkDir();
const homeDir = await sdk.getUserHomeDir();
await sdk.fs.createFolder("src", "755");
```

:::

## 重新连接到现有沙箱

:::js

```typescript theme={null}
// Create sandbox with auto-stop interval
const sandbox = await DaytonaSandbox.create({
  language: "typescript",
  autoStopInterval: 60,
});
const sandboxId = sandbox.id;

// Stop the sandbox (keeps it available)
await sandbox.stop();

// Later: reconnect
const reconnected = await DaytonaSandbox.connect(sandboxId);
await reconnected.start();
const result = await reconnected.execute("ls -la");
```

:::

## 沙箱生命周期

:::js

```typescript theme={null}
const sandbox = await DaytonaSandbox.create();

await sandbox.stop();   // Stop (can be restarted)
await sandbox.start();  // Start a stopped sandbox
await sandbox.close();  // Delete permanently
```

:::

## 工厂函数

:::js

```typescript theme={null}
import { createDaytonaSandboxFactory, createDaytonaSandboxFactoryFromSandbox } from "@langchain/daytona";

// Create new sandbox per invocation
const factory = createDaytonaSandboxFactory({ language: "typescript" });

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

:::

## 错误处理

```typescript theme={null}
import { DaytonaSandboxError } from "@langchain/daytona";

try {
  await sandbox.execute("some command");
} catch (error) {
  if (error instanceof DaytonaSandboxError) {
    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 Daytona API key");
        break;
    }
  }
}
```

### 错误代码

| 代码 | 描述 |
| - | - |
| `NOT_INITIALIZED` | 沙箱未初始化 - 调用 `initialize()` |
| `ALREADY_INITIALIZED` | 无法重复初始化 |
| `AUTHENTICATION_FAILED` | 无效或缺少 Daytona API 密钥 |
| `SANDBOX_CREATION_FAILED` | 创建沙箱失败 |
| `SANDBOX_NOT_FOUND` | 未找到沙箱 ID 或已删除 |
| `SANDBOX_NOT_STARTED` | 沙箱未处于启动状态 |
| `COMMAND_TIMEOUT` | 命令执行超时 |
| `COMMAND_FAILED` | 命令执行失败 |
| `FILE_OPERATION_FAILED` | 文件读写失败 |
| `RESOURCE_LIMIT_EXCEEDED` | 超出 CPU、内存或存储限制 |

## 环境变量

| 变量 | 描述 |
| - | - |
| `DAYTONA_API_KEY` | Daytona API 密钥（必需） |
| `DAYTONA_API_URL` | 自定义 Daytona API URL |
| `DAYTONA_TARGET` | 默认目标区域（us/eu） |

***

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


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