LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
  • Client
  • AsyncClient
  • Run Helpers
  • Run Trees
  • Evaluation
  • Schemas
  • Utilities
  • Wrappers
  • Anonymizer
  • Testing
  • Expect API
  • Middleware
  • Pytest Plugin
  • Deployment SDK
⌘I

Chat LangChain

What can I help with?

Enter to send·Shift+Enter new line

Menu

OverviewClientAsyncClientRun HelpersRun TreesEvaluationSchemasUtilitiesWrappersAnonymizerTestingExpect APIMiddlewarePytest PluginDeployment SDK
Language
Theme
Pythonlangsmithsandbox
Module●Since v0.6

sandbox

LangSmith Sandbox Module.

This module provides sandboxed code execution capabilities through the LangSmith Sandbox API.

Example:

from langsmith.sandbox import SandboxClient

Uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY from environment

client = SandboxClient()

snapshot = client.create_snapshot( docker_image="python:3.12-slim", name="python-snapshot" ) with client.sandbox(snapshot_id=snapshot.id) as sb: result = sb.run("python --version") print(result.stdout)

Or async:

from langsmith.sandbox import AsyncSandboxClient

async with AsyncSandboxClient() as client: snapshot = await client.create_snapshot( docker_image="python:3.12-slim", name="python-snapshot" ) async with await client.sandbox(snapshot_id=snapshot.id) as sb: result = await sb.run("python --version") print(result.stdout)

Attributes

attribute
AccessDelegationMode: Literal['INHERIT', 'EXPLICIT']
attribute
DownloadContentDisposition: Literal['attachment', 'inline']

How a download link asks the browser to handle the file.

attribute
ServiceAccess: Literal['restricted', 'workspace']
attribute
SandboxMountAuth: SandboxProxyRule
attribute
SandboxProxyConfig: dict[str, Any]
attribute
SandboxProxyRule: dict[str, Any]
attribute
CALLBACK_SIGNATURE_HEADER: str
attribute
USER_TOKEN_HEADER: str

Functions

function
context_hub_mount

Build a read-only Context Hub-backed sandbox mount specification.

The repo's latest commit tree is mirrored into mount_path and kept in sync for the sandbox's lifetime unless initial_pull_only is set. The sync is one-way: files written under mount_path inside the sandbox are never pushed back to the repo, and the next sync overwrites them.

function
gcs_mount

Build a GCS-backed sandbox mount specification.

function
git_mount

Build a public Git-backed sandbox mount specification.

function
mount_config

Build a high-level mount config from provider auth and mount specs.

The returned value is sent as the public mount_config field. The backend expands provider auth into runtime proxy rules.

For S3 mounts, pass the same proxy_config here and to sandbox creation to use its enabled AWS rule. That rule remains general proxy auth; it is not copied into mount-scoped auth or restricted to mount paths. GCS mounts still require explicit GCP authentication in auth.

function
s3_mount

Build an S3-backed sandbox mount specification.

function
aws_auth

Build a sandbox proxy rule that signs AWS HTTPS requests.

The sandbox proxy keeps the real AWS credentials outside the sandbox and signs supported AWS requests with SigV4 on the sandbox's behalf. Provide either role_arn or both static credentials, supplied as workspace_secret or opaque values. IAM-role support must be enabled on the backend. LangSmith supplies the workspace External ID and renews credentials; clients must not provide temporary credentials or External IDs.

In proxy_config, a role uses its effective IAM permissions. In mount_config(auth=[...]), it is restricted to the configured S3 mounts. Role authentication is configured at sandbox creation, not through updates.

function
gcp_auth

Build a sandbox proxy rule that injects GCP OAuth bearer auth.

The sandbox proxy keeps the service account JSON outside the sandbox and injects OAuth bearer tokens for built-in Google API host matching. service_account_json must be supplied as a workspace_secret or opaque value; plaintext service account JSON is intentionally not supported.

function
opaque_secret

Provide a write-only secret value for a proxy configuration.

The value is sent when creating or updating the sandbox proxy config, but LangSmith stores it as an opaque secret and does not return it from the API.

function
proxy_config

Build a sandbox proxy config from one or more proxy rules.

Use provider-specific rule helpers such as aws_auth and gcp_auth when a sandbox needs multiple auth flows.

function
workspace_secret

Create a LangSmith workspace secret reference for a proxy configuration.

Classes

class
AccessDelegation

Grant letting code inside a sandbox call the LangSmith API as the creator.

mode is "INHERIT" for everything the creator can do, or "EXPLICIT" for the subset named in permissions. Permissions are a ceiling re-checked on every request rather than a snapshot, so access the creator loses is lost here too.

class
AsyncSandboxClient

Async client for interacting with the Sandbox Server API.

This client provides an async interface for managing sandboxes and snapshots.

class
AsyncSandbox

Represents an active sandbox for running commands and file operations async.

This class is typically obtained from AsyncSandboxClient.sandbox() and supports the async context manager protocol for automatic cleanup.

class
SandboxClient

Client for interacting with the Sandbox Server API.

This client provides a simple interface for managing sandboxes and snapshots.

class
CommandTimeoutError

Raised when a command exceeds its timeout.

class
DataplaneNotConfiguredError

Raised when dataplane_url is not available for the sandbox.

This occurs when the sandbox-router URL is not configured for the cluster.

class
QuotaExceededError

Raised when organization quota limits are exceeded.

Users should contact technical support via our Support Portal (https://support.langchain.com) to increase quotas.

class
ResourceAlreadyExistsError

Raised when creating a resource that already exists.

class
ResourceCreationError

Raised when resource provisioning fails.

class
ResourceInUseError

Raised when deleting a resource that is still in use.

class
ResourceNameConflictError

Raised when updating a resource name to one that already exists.

class
ResourceNotFoundError

Raised when a resource is not found.

class
ResourceTimeoutError

Raised when an operation times out.

class
SandboxAPIError

Raised when the API endpoint returns an unexpected error.

For example, this is raised for wrong URL or path.

class
SandboxAuthenticationError

Raised when authentication fails (invalid or missing API key).

class
SandboxClientError

Base exception for sandbox client errors.

class
SandboxConnectionError

Raised when connection to the sandbox server fails.

class
SandboxConnectTimeoutError

Raised when the socket fails or times out before the WebSocket handshake.

The execute frame was never sent, so re-issuing the same command ID cannot double-run a command.

class
SandboxNotReadyError

Raised when attempting to interact with a sandbox that is not ready.

class
SandboxOperationError

Raised when a sandbox operation fails (run, read, write).

class
SandboxRetryableConnectionError

Raised when a transient failure occurs before a command can start.

run() retries this error with the same command ID, so the server can deduplicate an attempt whose outcome is unknown.

class
SandboxServerReloadError

Raised when the server sends a 1001 Going Away close frame.

This indicates a server hot-reload, not a true connection failure. The command is still running on the server.

This is a subclass of SandboxConnectionError, so the auto-reconnect logic in CommandHandle catches it along with all other connection errors. The distinction matters for retry strategy: SandboxServerReloadError triggers immediate reconnect (no backoff), while other SandboxConnectionError triggers exponential backoff.

Users typically never see this exception — it's handled internally.

class
TunnelConnectionRefusedError

Nothing is listening on the target port inside the sandbox.

class
TunnelError

Base exception for TCP tunnel errors.

class
TunnelPortNotAllowedError

The daemon rejected the port as not allowed.

class
TunnelUnsupportedVersionError

Protocol version mismatch between the tunnel client and the daemon.

class
ValidationError

Raised when request validation fails.

This includes:

  • Resource values exceeding server-defined limits (CPU, memory, storage)
  • Invalid resource units
  • Invalid name formats
class
AsyncCommandHandle

Async handle to a running command with streaming output and auto-reconnect.

Async iterable, yielding OutputChunk objects (stdout and stderr interleaved in arrival order). Access .result after iteration to get the full ExecutionResult.

Auto-reconnect behavior:

  • Server hot-reload (1001 Going Away): reconnect immediately
  • Network error / unexpected close: reconnect with exponential backoff
  • User called kill(): do NOT reconnect (propagate error)

Construction modes (controlled by command_id):

  • New execution (command_id="", the default): call await handle._ensure_started() after construction to read the server's "started" message and populate command_id / pid.
  • Reconnection (command_id set): skips the started-message read. A reconnect stream's "started" message is the server's acknowledgement that the reattachment landed, consumed while iterating to clear the reconnect budget — the only such signal for a command that emits no output.
class
AsyncServiceURL

Async variant of :class:ServiceURL with auto-refreshing token.

Properties and HTTP helpers are async. Use with :meth:AsyncSandboxClient.service or :meth:AsyncSandbox.service.

Example::

svc = await sb.service(port=3000)

resp = await svc.get("/api/data")
print(await svc.get_browser_url())
class
CommandHandle

Handle to a running command with streaming output and auto-reconnect.

Iterable, yielding OutputChunk objects (stdout and stderr interleaved in arrival order). Access .result after iteration to get the full ExecutionResult.

Auto-reconnect behavior:

  • Server hot-reload (1001 Going Away): reconnect immediately
  • Network error / unexpected close: reconnect with exponential backoff
  • User called kill(): do NOT reconnect (propagate error)

The auto-reconnect is transparent -- the iterator reconnects and continues yielding chunks without any user intervention. If all reconnect attempts are exhausted, SandboxConnectionError is raised.

Construction modes (controlled by command_id):

  • New execution (command_id="", the default): the constructor eagerly reads the server's "started" message to populate command_id and pid before returning.
  • Reconnection (command_id set): skips the started-message read. A reconnect stream's "started" message is the server's acknowledgement that the reattachment landed, consumed while iterating to clear the reconnect budget — the only such signal for a command that emits no output.
class
DownloadURL

A link that downloads one sandbox file with no LangSmith credential.

The link is pinned to the sandbox, the file path, and the response headers, so it cannot be repointed at another file. It is pinned to the path rather than to a snapshot of the contents, so the file must not be modified while the link is in use.

class
ExecutionResult

Result of executing a command in a sandbox.

class
FileChunk

Bytes returned by a ranged read, and where they sit in the file.

class
FileInfo

One filesystem entry returned by :meth:Sandbox.glob.

class
FileStat

What a HEAD on a sandbox file reports, without transferring it.

class
GlobResult

Entries matching a glob pattern.

class
GrepMatch

One matching line found by :meth:Sandbox.grep.

class
GrepResult

Lines matching a literal search.

class
OutputChunk

A single chunk of streaming output from command execution.

class
ResourceStatus

Lightweight provisioning status for any async-created resource.

class
RunConfig

The user, working directory and environment commands run with.

Mirrors docker run -u / -w / -e: user and work_dir replace the layer below, env_vars merge into it key by key. It applies at three points, each layered over the one before -- the snapshot, the sandbox, and a single command.

class
ServiceLoginURL

Service URL gated by LangSmith login rather than a token.

The grant is durable: there is no token to carry and no expiry, so the URL is only usable from a browser signed in to LangSmith. That is also why this carries none of :class:ServiceURL's auth-injecting HTTP helpers — a programmatic request cannot satisfy the login.

class
ServiceURL

Authenticated URL for accessing an HTTP service running in a sandbox.

Properties auto-refresh the token transparently when it nears expiry. HTTP helper methods (.get, .post, etc.) inject the auth header automatically.

When constructed by :meth:SandboxClient.service or :meth:Sandbox.service, the object holds an internal refresher that re-calls the API to obtain a fresh token before the current one expires.

Example::

svc = sb.service(port=3000)

resp = svc.get("/api/data")  # token injected + auto-refreshed
print(svc.browser_url)  # always-fresh URL
class
Snapshot

Represents a sandbox snapshot.

Snapshots are built from Docker images or captured from running sandboxes. They are used to create new sandboxes.

class
SnapshotTag

One tag published under a snapshot name, and the snapshot it resolves to.

class
AWSMountAuthConfig

AWS credentials used by the backend to authenticate S3 mounts.

class
AWSMountRoleAuthConfig

IAM role restricted by the backend to this sandbox's S3 mount scopes.

class
ContextHubMountConfig

Context Hub configuration for a sandbox mount.

class
ContextHubMountSpec

Read-only Context Hub-backed sandbox mount specification.

class
GCPMountAuthConfig

GCP credentials used by the backend to authenticate GCS mounts.

class
GCSMountConfig

GCS configuration for a sandbox mount.

class
GCSMountSpec

GCS-backed sandbox mount specification.

class
GitMountConfig

Git configuration for a sandbox mount.

class
GitMountRefSpec

Git ref selected for a sandbox mount.

class
GitMountSpec

Git-backed sandbox mount specification.

class
MountCacheConfig

Optional per-mount cache configuration supported by bucket mounts.

class
MountEncryptionConfig

Customer-managed key that uploads through a mount are encrypted with.

For S3 mounts, kms_key is a KMS key ARN in the mount's region and uploads use SSE-KMS with it.

class
S3MountConfig

S3 configuration for a sandbox mount.

class
S3MountSpec

S3-backed sandbox mount specification.

class
SandboxMountAuthConfig

Provider auth blocks for sandbox mounts.

class
SandboxMountConfig

Public mount config sent to the sandbox API.

class
SandboxProxySecret

A secret value that can be used by sandbox proxy rules.

class
Sandbox

Represents an active sandbox for running commands and file operations.

This class is typically obtained from SandboxClient.sandbox() and supports the context manager protocol for automatic cleanup.

class
AsyncTunnel

Async wrapper around :class:Tunnel.

The underlying tunnel runs in background threads (TCP listener + bridges); async context-manager methods delegate to the sync tunnel via the event loop's executor.

Usage::

async with await sandbox.tunnel(remote_port=5432) as t:
    conn = await asyncpg.connect(host="127.0.0.1", port=t.local_port)
class
Tunnel

TCP tunnel to a port inside a sandbox.

Opens a local TCP listener and forwards each accepted connection through a yamux-multiplexed WebSocket to the daemon, which dials the target port inside the sandbox.

Typically used as a context manager::

with sandbox.tunnel(remote_port=5432) as t:
    conn = psycopg2.connect(host="127.0.0.1", port=t.local_port)

Or with explicit lifecycle::

t = sandbox.tunnel(remote_port=5432)
# ... use tunnel ...
t.close()
class
SandboxCallback

A verified proxy callback payload.

class
SandboxCallbackIdentity

The sandbox whose outbound request triggered a proxy callback.

class
SandboxCallbackRequest

Snapshot of the outbound request, sent for full_request callbacks.

class
SandboxTokenVerificationError

Raised when a sandbox user token or callback signature fails verification.

class
SandboxTokenVerifier

Verifies tokens LangSmith signs for code running in or behind a sandbox.

Keys are fetched from LangSmith's JWKS endpoint and cached.

class
SandboxUser

The LangSmith user a service URL request was made by.

Type Aliases

typeAlias
SandboxMount: Union[S3MountSpec, GCSMountSpec, GitMountSpec, ContextHubMountSpec]
typeAlias
AudienceMatcher: Union[str, Callable[[str], bool]]
View source on GitHub