Tensorlake SDK

repository·main·Indexed 21 days ago

https://github.com/tensorlakeai/tensorlake

A compute infrastructure platform for building agentic applications using high-performance, stateful Firecracker MicroVM sandboxes and serverless orchestration runtimes. It provides tools for running untrusted or LLM-generated code with features like memory and filesystem snapshots, sandbox pools for fast startup, and a versioned immutable filesystem via FilesystemClient. The SDK and tl CLI support deploying distributed orchestration APIs using @application and @function decorators.

Tokens
80.2K
Snippets
249
Records
343
Agent score
76%

What's inside tensorlake

  1. What is Tensorlake?

    main
    Tensorlake is a sandbox-native cloud designed for AI agents. It provides a compute platform for securely running untrusted or LLM-generated code in isolated Firecracker MicroVM sandboxes. It is optimized for heavy filesystem I/O, fast startup, and large-scale fan-out, supporting up to 5 million sandboxes per project.
  2. What is the Function Executor?

    main

    The Function Executor is a low-level process providing an API to load and run customer Functions. Each function execution is treated as a discrete task.

    Key characteristics:

    • Concurrency: Multiple tasks can be executed concurrently, with concurrency levels controlled by the API client.
    • Resource Management: Because the Tensorlake SDK does not currently provide callbacks for customer code to manually free resources, the primary way to ensure all resources used by a function are released is to kill the Function Executor process.
    • Lifecycle: Function Executors are managed by the Executor component (part of Indexify). They are created and destroyed automatically and are not intended to be deployed or managed manually by users.
  3. How sandboxes work in Tensorlake

    main

    Tensorlake sandboxes are isolated Firecracker MicroVMs that provide hardware-virtualized environments. Key features include:

    • Snapshots: Capture both memory and filesystem state at any point to checkpoint an agent and resume from that exact state later.
    • Auto Suspend/Resume: Sandboxes automatically suspend when idle and can resume in under a second without losing state.
    • Fast Startup: Sandboxes are created in under a second via Lattice (a dynamic cluster scheduler). For even faster execution, use sandbox pools to maintain warm containers.
    • Isolation: Provides a secure environment for running LLM-generated code or agent tools separate from your main infrastructure.
  4. Compare `tl git mount` and `tl fs`

    main

    It is important to distinguish between the Git-based workflow and the Filesystem-based workflow:

    Featuretl git mounttl fs
    Primary PurposePrivate commit workflow for repositoriesContinuously published shared drive
    VersioningNamed commits (snapshots) on a private linePath-addressed generations/snapshots
    Persistencesnapshot creates an immutable commitsnapshot records a permanent, billed generation
    Workflowsnapshot $\rightarrow$ promote to branchpush or snapshot to save state

    tl fs Specifics

    • Snapshots: Use tl fs snapshot [PATH] -m "message" to record a permanent generation. Without -m, it is an ephemeral autosave.
    • History: Use tl fs history [FILESYSTEM|PATH] to view permanent snapshots and the ephemeral WAL. The output separates these into snapshots and autosaves arrays.
    • Status: tl fs status [PATH] reports local changes, last autosave time, and permanent snapshot count.
  5. Use Sandbox Pools for fast startup

    main

    Sandbox Pools allow you to pre-warm containers to achieve near-instant startup. You can define network policies (like allow_internet_access) at the pool level. When a pool's network policy is updated, unclaimed warm containers are recycled, but containers already claimed by sandboxes keep their original policy.

    from tensorlake.sandbox import 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
    resp = client.claim(pool.pool_id)
    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")
  6. Perform structured data extraction from documents

    main

    You can extract specific data from a document into a structured format by defining a Pydantic model and passing it to the DocumentAI.parse method via StructuredExtractionOptions.

    1. Define a BaseModel representing your desired schema.
    2. Initialize DocumentAI.
    3. Create StructuredExtractionOptions using your schema.
    4. Call doc_ai.parse() with the file path and options.
    5. Use doc_ai.wait_for_completion(parse_id) to retrieve the results.
    from tensorlake.documentai import DocumentAI
    from tensorlake.documentai.models import ParsingOptions, StructuredExtractionOptions, ChunkingStrategy
    from pydantic import BaseModel, Field
    from typing import List, Optional
    
    # 1. Define Schema
    class ResearchPaperSchema(BaseModel):
        title: str = Field(description="Title of the research paper")
        authors: List[str] = Field(description="List of author names")
        abstract: str = Field(description="Abstract of the paper")
    
    # 2. Initialize Client
    doc_ai = DocumentAI()
    file_path = "https://example.com/paper.pdf"
    
    # 3. Configure Options
    parsing_options = ParsingOptions(chunking_strategy=ChunkingStrategy.PAGE)
    structured_extraction_options = StructuredExtractionOptions(
        schema_name="Research Paper Analysis", 
        json_schema=ResearchPaperSchema
    )
    
    # 4. Parse
    parse_id = doc_ai.parse(
        file_path,
        parsing_options=parsing_options,
        structured_extraction_options=[structured_extraction_options],
    )
    
    # 5. Wait for results
    result = doc_ai.wait_for_completion(parse_id)
  7. Manage Git repository mounts with the Git workflow

    main

    When using tl git mount, edits are first stored in a crash-safe local journal and continuously uploaded as ordered, idempotent checkpoints in a workspace WAL. These are not repository commits. To manage these changes, use the following workflow:

    Core Commands

    • tl git status [/code]: Check the status of the mount.
    • tl git snapshot [/code] --message "<msg>": Flushes the current WAL state and materializes it as an immutable commit on the workspace's private line.
    • tl git sync [/code] [BRANCH|TAG|FULL_COMMIT]: Refreshes the current source. If a target is provided, it switches the view or workspace. If the workspace has snapshots, use rebase instead to change the base.
    • tl git rebase [/code] BRANCH|TAG|FULL_COMMIT: Runs server-side to replay materialized snapshots and the unsnapshotted WAL tail onto a new base. Conflicts are shown as diff3 markers.
    • tl git promote [/code] BRANCH [--merge]: The command to land changes. It autosaves edits, creates a snapshot, and lands it onto a real branch. By default, it performs a squash landing. Use --merge for a true merge.
    • tl git log [/code|REPOSITORY] and tl git smartlog [/code|REPOSITORY] [--project]: View history and retained recovery chains.

    The --publish Workspace

    A --publish workspace continuously serves a fixed target branch.

    • Snapshots: Explicit snapshots are reconciled directly onto the target branch.
    • Restrictions: sync can refresh the target but cannot retarget it. rebase is rejected for --publish workspaces.
    • Usage: Use a normal workspace if you need explicit rebase or retarget control.
    tl git status [/code]
    tl git snapshot [/code] --message "checkpoint"
    tl git sync [/code] [BRANCH|TAG|FULL_COMMIT]
    tl git rebase [/code] BRANCH|TAG|FULL_COMMIT
    tl git promote [/code] BRANCH [--merge]
    tl git log [/code|REPOSITORY]
    tl git smartlog [/code|REPOSITORY] [--project]
  8. Install Tensorlake and OpenAI Agents SDK

    main

    To build smart document understanding agents, install the required Python packages using pip:

    pip install tensorlake openai-agents

    Ensure you have set the following environment variables:

    • TENSORLAKE_API_KEY: Your Tensorlake authentication key.
    • OPENAI_API_KEY: Your OpenAI API key.
    !pip install tensorlake openai-agents
  9. Deploy and call Orchestration APIs

    main

    After defining your application, deploy it using the tl deploy command. Once deployed, you can invoke the application via HTTP requests. You can retrieve results using the request_id or stream results using Server-Sent Events (SSE).

    # 1. Set secrets
    export TENSORLAKE_API_KEY="your-api-key"
    tl secrets set OPENAI_API_KEY "your-openai-key"
    
    # 2. Deploy
    tl deploy examples/readme_example/city_guide.py
    
    # 3. Invoke via HTTP
    curl https://api.tensorlake.ai/applications/city_guide_app \
      -H "Authorization: Bearer $TENSORLAKE_API_KEY" \
      --json '"San Francisco"'
    
    # 4. Get result using request_id
    curl https://api.tensorlake.ai/applications/city_guide_app/requests/{request_id}/output \
      -H "Authorization: Bearer $TENSORLAKE_API_KEY"
    
    # 5. 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"'