详情

首页手游攻略 tensorlake:AI Agent 工具实践指南

tensorlake:AI Agent 工具实践指南

佚名 2026-09-12 17:20:01

在项目中评估tensorlake,可以先看清用途边界:Tensorlake 是一个用于沙箱和部署后台代理应用程序的无服务器运行时。这类部署与运行环境工具真正难在权限、依赖和环境差异会放大维护成本,仓库说明只能作为第一层证据。试跑可以从在非生产环境复现一次安装与运行开始,并把依赖锁定、权限边界、日志、回滚和资源消耗写进验收记录。对愿意维护环境并重视故障恢复的工程团队来说,这个仓库值得继续验证;只求即装即用的人则要先看维护成本。

Build 具有沙箱和无服务器编排的代理 runtime

Tensorlake 是一个计算基础设施平台,用于使用沙箱构建代理应用程序。

沙箱 API 创建 MicroVM 沙箱,您可以使用它们来运行代理,或将它们用作运行工具或 LLM 生成的代码的隔离环境。

除了有状态 VMs 之外,您还可以使用具有扇出功能的无服务器函数运行时向代理添加长时间运行的编排功能。

沙箱

Tensorlake 沙箱是有状态的 Firecracker MicroVMs,专为 AI 代理的即时、有状态执行环境而构建 - 以接近 SSD 文件系统性能启动数百万个 VMs。

关键能力

  • 最快的文件系统 I/O — 基于块的存储在虚拟机内实现接近 SSD 的速度。在 SQLite 基准测试中(2 vCPUs、4 GB RAM),Tensorlake 在 2.45s 内完成,而 Vercel 3.00s (1.2×)、E2B 3.92s (1.6×)、Modal 4.66s (1.9×) 和 Daytona 5.51s (2.2×)。
  • 快速启动 — 通过动态集群调度程序 Lattice 在不到一秒的时间内创建沙箱。
  • 快照和克隆 — 任意点的快照以创建持久内存和文件系统检查点;跨机器即时克隆运行沙箱。
  • 自动 suspend/resume — 沙箱在空闲时暂停,并在一秒内恢复,而不会丢失任何内存或文件系统状态。
  • 实时迁移 — 沙盒在更新期间自动在计算机之间移动,只需短暂的几秒钟的暂停。
  • 规模 — 在单个项目中支持多达 500 万个沙箱。

Python SDK 安装

pip install tensorlake

CLI 安装

tl CLI 作为独立二进制文件分发,而不是通过 PyPI 或 npm 分发。 使用安装脚本安装它:

curl -fsSL https://tensorlake.ai/install | sh

设置

在 cloud.tensorlake.ai 注册并获取您的 API 密钥。

export TENSORLAKE_API_KEY="your-api-key"
tl login

创建您的第一个沙箱(CLI)

创建沙箱,运行命令并清理:

# Create a sandbox
tl sbx create --image tensorlake/tensorlake/ubuntu-minimal

# Run a command inside it
tl sbx exec <sandbox-id> -- sh -lc "printf 'Hello from the sandbox!n'"

# Copy a file into the sandbox
tl sbx cp ./my_script.py <sandbox-id>:/tmp/my_script.py

# Open an interactive terminal
tl sbx ssh <sandbox-id>

# Block all outbound internet access on a running sandbox
tl sbx update <sandbox-id> --no-internet

# Allow outbound traffic only to selected destinations
tl sbx update <sandbox-id> --network-allow api.example.com

# Remove the network policy and restore unrestricted outbound access
tl sbx update <sandbox-id> --clear-network

# Terminate when done
tl sbx terminate <sandbox-id>

--image 需要一个沙箱映像名称,例如 tensorlake/ubuntu-minimal 或注册的沙箱映像名称,而不是任意 Docker 映像引用。

以编程方式创建沙箱

from tensorlake.sandbox import SandboxClient

client = SandboxClient.for_cloud(api_key="your-api-key")

# Create a sandbox and connect to it
with client.create_and_connect(image="tensorlake/ubuntu-minimal") as sandbox:
    # Run a command
    result = sandbox.run("sh", ["-lc", "printf 'Hello from the sandbox!\n'"])
    print(result.stdout)  # "Hello from the sandbox!"

    # Write and read files
    sandbox.write_file("/tmp/data.txt", b"some data")
    content = sandbox.read_file("/tmp/data.txt")

    # Start a long-running process
    proc = sandbox.start_process("sleep", ["300"])
    print(proc.pid)

# Sandbox is automatically terminated when the context manager exits

快照

保存沙箱的状态并稍后恢复:

# Snapshot a running sandbox
snapshot = client.snapshot_and_wait(sandbox_id)

# Later, create a new sandbox from the snapshot
with client.create_and_connect(snapshot_id=snapshot.snapshot_id) as sandbox:
    # Picks up right where you left off
    result = sandbox.run("ls", ["/tmp"])
    print(result.stdout)

沙盒池

预热容器以实现快速启动:

from tensorlake.sandbox import FileSystemMount, NetworkConfig

# Create a pool with warm containers and no internet access
pool = client.create_pool(
    image="tensorlake/ubuntu-minimal",
    warm_containers=3,
    network=NetworkConfig(allow_internet_access=False),
)

# Claim a sandbox instantly from the pool. Claim-specific file systems are
# mounted before the sandbox is reported as running.
resp = client.claim(
    pool.pool_id,
    file_systems=[
        FileSystemMount(
            file_system_id="file_system_abc",
            mount_path="/mnt/skills",
        )
    ],
)
sandbox = client.connect(resp.sandbox_id)

# Named sandboxes can be reconnected later by name
named = client.create(image="tensorlake/ubuntu-minimal", name="stable-name")
sandbox = client.connect("stable-name")

创建池时设置池网络策略,稍后将其替换为 池更新,或将 CLEAR_NETWORK_POLICY (Python) / null (TypeScript) 传递给 删除它。更改后,该服务会回收泳池中无人认领的温水 将容器纳入新策略,而容器已被沙箱认领 保留他们启动时使用的策略。

云卷

FilesystemClient 管理持久的、版本化的文件树,而无需安装它们。 SDK 写入哈希 本地文件,将缺少的 64 个 MiB 部分直接上传到校验和绑定对象存储 URLs,然后 以原子方式发布元数据。读取解析经过身份验证的不可变计划并获取选定的 直接来自签名对象存储 URLs 的记录。文件负载通常不会通过 Tensorlake API 服务。

import { FilesystemClient } from "tensorlake";

const client = new FilesystemClient({
  apiKey: "your-api-key",
  organizationId: "org_...",
  projectId: "proj_...",
});
const fs = await client.create("agent-artifacts");

// In-memory data; all changes become visible atomically.
await fs.writeFiles({
  "run/config.json": JSON.stringify({ model: "gpt-5" }),
  "run/input.txt": "hello",
});

// Multi-GiB files use bounded memory and stream directly to object storage.
await fs.writeFileFromPath("models/weights.bin", "./weights.bin");

// These reuse immutable content references and transfer no payload bytes.
await fs.copyFile("run/input.txt", "run/input-copy.txt");
await fs.moveFile("run/config.json", "archive/config.json");

// One request returns only the selected bytes plus full-file identity/size.
const read = await fs.readFileWithMetadata("models/weights.bin", {
  range: { offset: 0, length: 1024 * 1024 },
});

// Snapshot retention and forks are metadata-only operations.
const snapshot = await fs.snapshot("ready for evaluation");
const fork = await client.fork("agent-artifacts-eval", fs.name, snapshot.id);
await fork.writeFile("results/score.txt", "0.98");

await fs.deleteSnapshot(snapshot.id);

writeFile()writeFiles() 接受内存中已有的字节。首选 writeFileFromPath()writeFilesFromPaths() 用于大型本地文件,因此 JavaScript 和 Rust 都不会保留完整的 有效负载。成功的写入在返回之前是持久的,但仅保留活动头 自动; snapshot() 在一次 client/server 往返中永久固定当前磁头。 readFileWithMetadata() 返回不可变的内容标识和总大小以及字节;它的 可选范围仅下载重叠的不可变记录。 SDK 限制每个响应, 验证存储的逻辑内容校验和,并仅回退到经过身份验证的服务 当对象存储无法遵守签名范围时。 删除快照会释放该保留根,同时仍然可以从活动头访问字节, 另一个快照、分叉或安装保持持久。

编排

在具有自动扩展、扇出功能和内置跟踪的分布式运行时上创建编排 APIs。可以使用 HTTP 请求或使用 Python SDK 来调用编排 APIs。

快速入门

@application() 装饰您的入口点,用 @function() 装饰您的函数。每个函数都在自己的隔离沙箱中运行。

示例:使用 OpenAI 代理进行网络搜索和代码执行的城市指南:

from agents import Agent, Runner
from agents.tool import WebSearchTool, function_tool
from tensorlake.applications import application, function, Image

# Define the image with necessary dependencies
FUNCTION_CONTAINER_IMAGE = Image(base_image="python:3.11-slim", name="city_guide_image").run(
    "pip install openai openai-agents"
)

@function_tool
@function(
    description="Gets the weather for a city using an OpenAI Agent with web search",
    secrets=["OPENAI_API_KEY"],
    image=FUNCTION_CONTAINER_IMAGE,
)
def get_weather_tool(city: str) -> str:
    """Uses an OpenAI Agent with WebSearchTool to find current weather."""
    agent = Agent(
        name="Weather Reporter",
        instructions="Use web search to find current weather in Fahrenheit for the city.",
        tools=[WebSearchTool()],  # Agent can search the web
    )
    result = Runner.run_sync(agent, f"City: {city}")
    return result.final_output.strip()

@application(tags={"type": "example", "use_case": "city_guide"})
@function(
    description="Creates a guide with temperature conversion using function_tool",
    secrets=["OPENAI_API_KEY"],
    image=FUNCTION_CONTAINER_IMAGE,
)
def city_guide_app(city: str) -> str:
    """Uses an OpenAI Agent with function_tool to run Python code for conversion."""

    @function_tool
    def convert_to_celsius_tool(python_code: str) -> float:
        """Converts Fahrenheit to Celsius - runs as Python code via Agent."""
        return float(eval(python_code))

    agent = Agent(
        name="Guide Creator",
        instructions="Using the appropriate tools, get the weather for the purposes of the guide. If the city uses Celsius, call convert_to_celsius_tool to convert the temperature, passing in the code needed to convert the temperature to Celsius. Create a friendly guide that references the temperature of the city in Celsius if the city typically uses Celsius, otherwise reference the temperature in Fahrenheit. Only reference Celsius or Fahrenheit, not both.",
        tools=[get_weather_tool, convert_to_celsius_tool],  # Agent can execute this Python function
    )
    result = Runner.run_sync(agent, f"City: {city}")
    return result.final_output.strip()

部署到 Tensorlake

  1. 设置您的 API 密钥:
export TENSORLAKE_API_KEY="your-api-key"
tl secrets set OPENAI_API_KEY "your-openai-key"
  1. 部署:
tl deploy examples/readme_example/city_guide.py

tl deploy 通过以下方式为每个函数发布版本范围的运行时映像 图像服务并存储返回的不可变 cas-v1:<image_id> 引用 在应用程序清单中。目录名称只是一个构建句柄,可以 移动而不更改已部署的功能。该图像包含 由 Image、语言运行程序和本机声明的依赖项 功能代理核心。应用程序源仍然是上传的单独的ZIP 与舱单;它不会复制到运行时映像中。重复使用 具有不同代码或配置的应用程序版本被拒绝;一个 相同的重新部署是幂等的。 部署通常通过以下方式路由图像和应用程序请求 TENSORLAKE_API_URL。分割本地安装可以设置 TENSORLAKE_IMAGE_SERVICE_URLTENSORLAKE_FUNCTION_SERVICE_URL 独立。

通过 HTTP 拨打

# Invoke the application
curl https://api.tensorlake.ai/applications/city_guide_app 
  -H "Authorization: Bearer $TENSORLAKE_API_KEY" 
  --json '"San Francisco"'
# Returns: {"request_id": "beae8736ece31ef9"}

# Get the result
curl https://api.tensorlake.ai/applications/city_guide_app/requests/{request_id}/output 
  -H "Authorization: Bearer $TENSORLAKE_API_KEY"

# Stream results with SSE
curl https://api.tensorlake.ai/applications/city_guide_app 
  -H "Authorization: Bearer $TENSORLAKE_API_KEY" 
  -H "Accept: text/event-stream" 
  --json '"San Francisco"'

FAQ

什么是 Tensorlake? Tensorlake 是 AI 代理的沙箱原生云,这是一个计算平台,用于在隔离沙箱中安全运行不受信任的、LLM- 生成的代码,并大规模编排代理应用程序。

如何安全运行不受信任或 LLM- 生成的代码? 每个 Tensorlake 沙箱都是一个独立的 Firecracker MicroVM,因此不受信任或 LLM- 生成的代码在与基础设施和其他沙箱分开的硬件虚拟化环境中运行。使用 Python 或 TypeScript SDK 或 CLI 只需几行即可创建一个。

Tensorlake 与 E2B、Modal 或 Daytona 有何不同? Tensorlake 专为重型文件系统 I/O、快速启动和大规模扇出而构建。在 SQLite 基准测试(2 vCPUs、4 GB RAM)中,它在 2.45 秒内完成,而 E2B (3.92 秒)、Modal (4.66 秒) 和 Daytona (5.51 秒) 则支持快照、自动suspend/resume,实时迁移,每个项目最多 500 万个沙箱。

我可以检查点并恢复 AI 代理吗? 是的。随时对正在运行的沙箱进行快照,以捕获内存和文件系统状态,然后从该快照创建一个新的沙箱,以准确地从您停止的位置继续。沙箱还会在空闲时自动暂停,并在一秒钟内恢复,而不会丢失状态。

沙箱启动速度有多快? 沙箱是通过动态集群调度程序 Lattice 在不到一秒的时间内创建的。为了更快地启动,请使用沙箱池来保持温暖的容器,以便立即领取。

如何为 LLM 代理运行代码解释器/工具执行? 将沙箱启动为代理工具或生成代码的隔离执行环境,在其中运行命令或进程,读取和写入文件,并在完成后终止它 - 所有这些都来自 Python 或 TypeScript SDK 或 CLI。

支持哪些语言和界面? Tensorlake 提供了 Python SDK、TypeScript SDK 和独立的 CLI (tl),以及用于调用编排应用程序的 HTTP API。

我该如何开始? 注册 cloud.tensorlake.ai,为 Python SDK 运行 pip install tensorlake,使用 curl -fsSL 安装 CLI https://tensorlake.ai/install | sh, set your TENSORLAKE_API_KEY,并创建您的第一个沙箱。有关完整指南,请参阅 文档。

了解更多

  • 沙箱文档
  • 编排文档
  • tl git mount 存储库和子树工作流程
相关资讯
点击查看更多
游戏推荐
推荐专题
热门阅读
推荐下载