e2b

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 12, 2026 License: MIT Imports: 12 Imported by: 0

README

e2b-go

Unofficial Go SDK for E2B - Cloud runtime for AI agents. Inspired by the official E2B Code Interpreter SDKs.

E2B is an open-source infrastructure that allows you to run AI-generated code in secure isolated sandboxes in the cloud.

Installation

go get github.com/ClayWarren/e2b-go

Quick Start

1. Get your E2B API key
  1. Sign up to E2B here.
  2. Get your API key here.
2. Execute code with Code Interpreter

The CodeInterpreter provides a stateful Jupyter-like environment.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ClayWarren/e2b-go"
)

func main() {
	ctx := context.Background()

	// Create a new code interpreter sandbox
	// By default it uses the "code-interpreter-v1" template
	sbx, err := e2b.NewCodeInterpreter(ctx, "your-api-key")
	if err != nil {
		log.Fatal(err)
	}
	defer sbx.Close(ctx)

	// Execute code
	_, err = sbx.RunCode(ctx, "x = 1")
	if err != nil {
		log.Fatal(err)
	}

	// State is preserved between calls
	execution, err := sbx.RunCode(ctx, "x += 1; x")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(execution.Text()) // Outputs: 2
}

Features

  • Code Interpreter: Stateful execution of Python/JS code with rich output support (charts, images).
  • Sandbox Lifecycle: Create, keep alive, reconnect, and stop sandboxes.
  • Filesystem Operations: Read, write, list, mkdir, and watch for changes.
  • Process Execution: Start processes with environment variables and working directory.
  • Event Streaming: Subscribe to stdout, stderr, and exit events.

Parity with JS/Python SDK

This SDK is designed to be a 1:1 Go implementation of the E2B V2 specialized SDKs. It supports the same JSON-RPC methods and abstractions found in @e2b/code-interpreter.

Documentation

E2B Cookbook

Visit the E2B Cookbook to get inspired by examples with different LLMs and AI frameworks.

License

MIT

Documentation

Overview

Package e2b provides a Go SDK for E2B (https://e2b.dev/), a cloud runtime for AI agents that provides secure sandboxed environments for code execution.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    int    `json:"code,omitempty"` // Code is the code of the error.
	Message string `json:"message"`        // Message is the message of the error.
}

APIError is the error of the API.

type CodeInterpreter

type CodeInterpreter struct {
	*Sandbox
}

CodeInterpreter is a specialized sandbox for executing AI-generated code. It uses a Jupyter-like notebook environment.

func NewCodeInterpreter

func NewCodeInterpreter(ctx context.Context, apiKey string, opts ...Option) (*CodeInterpreter, error)

NewCodeInterpreter creates a new CodeInterpreter sandbox. By default, it uses the "code-interpreter-v1" template.

func (*CodeInterpreter) ExecCell

func (ci *CodeInterpreter) ExecCell(ctx context.Context, code string) (*Execution, error)

ExecCell executes a code cell in the notebook environment.

func (*CodeInterpreter) RunCode

func (ci *CodeInterpreter) RunCode(ctx context.Context, code string) (*Execution, error)

RunCode is an alias for ExecCell, matching the TS SDK naming.

type ErrMissingRequiredArgument

type ErrMissingRequiredArgument struct {
	ToolName string
	ArgName  string
}

ErrMissingRequiredArgument is returned when a required argument is missing.

func (ErrMissingRequiredArgument) Error

Error implements the error interface for ErrMissingRequiredArgument.

type ErrToolArgument

type ErrToolArgument struct {
	ToolName string
	ArgName  string
}

ErrToolArgument is returned when an argument is invalid.

func (ErrToolArgument) Error

func (e ErrToolArgument) Error() string

Error implements the error interface for ErrToolArgument.

type ErrToolNotFound

type ErrToolNotFound struct {
	ToolName string
}

ErrToolNotFound is returned when a tool is not found.

func (ErrToolNotFound) Error

func (e ErrToolNotFound) Error() string

Error implements the error interface for ErrToolNotFound.

type Event

type Event struct {
	Path      string      `json:"path"`      // Path is the path of the event.
	Name      string      `json:"name"`      // Name is the name of file or directory.
	Timestamp int64       `json:"timestamp"` // Timestamp is the timestamp of the event.
	Error     string      `json:"error"`     // Error is the possible error of the event.
	Params    EventParams `json:"params"`    // Params is the parameters of the event.
}

Event is a file system event.

type EventParams

type EventParams struct {
	Subscription string      `json:"subscription"` // Subscription is the subscription id of the event.
	Result       EventResult `json:"result"`       // Result is the result of the event.
}

EventParams is the params for subscribing to a process event.

type EventResult

type EventResult struct {
	Type        string `json:"type"`
	Line        string `json:"line"`
	Timestamp   int64  `json:"timestamp"`
	IsDirectory bool   `json:"isDirectory"`
	Error       string `json:"error"`
}

EventResult is a file system event response.

type Execution

type Execution struct {
	Results []Result        `json:"results"`
	Logs    ExecutionLogs   `json:"logs"`
	Error   *ExecutionError `json:"error"`
}

Execution represents the full result of a cell execution.

func (*Execution) Text

func (e *Execution) Text() string

Text returns the text representation of the main result.

type ExecutionError

type ExecutionError struct {
	Name      string `json:"name"`
	Value     string `json:"value"`
	Traceback string `json:"traceback"`
}

ExecutionError contains the error information from a cell execution.

type ExecutionLogs

type ExecutionLogs struct {
	Stdout []string `json:"stdout"`
	Stderr []string `json:"stderr"`
}

ExecutionLogs contains the stdout and stderr from a cell execution.

type LsResult

type LsResult struct {
	Name  string `json:"name"`  // Name is the name of the file or directory.
	IsDir bool   `json:"isDir"` // isDir is true if the entry is a directory.
}

LsResult is a result of the list request.

type Method

type Method string

Method is a JSON-RPC method.

type Option

type Option func(*Sandbox)

Option is an option for the sandbox.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the base URL for the e2b sandbox.

func WithClient

func WithClient(client *http.Client) Option

WithClient sets the client for the e2b sandbox.

func WithCwd

func WithCwd(cwd string) Option

WithCwd sets the current working directory.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for the e2b sandbox.

func WithMetaData

func WithMetaData(metaData map[string]string) Option

WithMetaData sets the meta data for the e2b sandbox.

func WithTemplate

func WithTemplate(template SandboxTemplate) Option

WithTemplate sets the template for the e2b sandbox.

func WithWsURL

func WithWsURL(wsURL func(s *Sandbox) string) Option

WithWsURL sets the websocket url resolving function for the e2b sandbox.

This is useful for testing.

type Process

type Process struct {
	Cwd string // cwd is process's current working directory.

	Env map[string]string // env is process's environment variables.
	// contains filtered or unexported fields
}

Process is a process in the sandbox.

func (*Process) Done

func (p *Process) Done() <-chan struct{}

Done returns a channel that is closed when the process is done.

func (*Process) Start

func (p *Process) Start(ctx context.Context) (err error)

Start starts a process in the sandbox.

func (*Process) SubscribeExit

func (p *Process) SubscribeExit(ctx context.Context) (chan Event, chan error)

SubscribeExit subscribes to the process's exit.

func (*Process) SubscribeStderr

func (p *Process) SubscribeStderr(ctx context.Context) (chan Event, chan error)

SubscribeStderr subscribes to the process's stderr.

func (*Process) SubscribeStdout

func (p *Process) SubscribeStdout(ctx context.Context) (chan Event, chan error)

SubscribeStdout subscribes to the process's stdout.

type ProcessEvents

type ProcessEvents string

ProcessEvents is a process event type.

const (
	// OnStdout is the event for the stdout.
	OnStdout ProcessEvents = "onStdout"
	// OnStderr is the event for the stderr.
	OnStderr ProcessEvents = "onStderr"
	// OnExit is the event for the exit.
	OnExit ProcessEvents = "onExit"
)

type ProcessOption

type ProcessOption func(*Process)

ProcessOption is an option for the process.

func ProcessWithCwd

func ProcessWithCwd(cwd string) ProcessOption

ProcessWithCwd sets the current working directory for the process.

func ProcessWithEnv

func ProcessWithEnv(env map[string]string) ProcessOption

ProcessWithEnv sets the environment variables for the process.

type Request

type Request struct {
	JSONRPC string `json:"jsonrpc"` // JSONRPC is the JSON-RPC version of the request.
	Method  Method `json:"method"`  // Method is the request method.
	ID      int    `json:"id"`      // ID of the request.
	Params  []any  `json:"params"`  // Params of the request.
}

Request is a JSON-RPC request.

type Response

type Response[T any, Q any] struct {
	ID     int `json:"id"`     // ID of the response.
	Result T   `json:"result"` // Result of the response.
	Error  Q   `json:"error"`  // Error of the message.
}

Response is a JSON-RPC response.

type Result

type Result struct {
	IsMainResult bool              `json:"isMainResult"`
	Data         map[string]string `json:"data"`
	Formats      []string          `json:"formats"`
}

Result represents an output from a cell execution.

func (*Result) Text

func (r *Result) Text() string

Text returns the plain text representation of the result if available.

type Sandbox

type Sandbox struct {
	ID       string `json:"sandboxID"` // ID of the sandbox.
	ClientID string `json:"clientID"`  // ClientID of the sandbox.
	Cwd      string `json:"cwd"`       // Cwd is the sandbox's current working directory.

	Template SandboxTemplate `json:"templateID"` // Template of the sandbox.

	Metadata map[string]string `json:"metadata"` // Metadata of the sandbox.

	Map *sync.Map `json:"-"` // Map is the map of the sandbox.
	// contains filtered or unexported fields
}

Sandbox is a code sandbox.

The sandbox is like an isolated, but interactive system.

func ConnectSandbox

func ConnectSandbox(
	ctx context.Context,
	sandboxID string,
	apiKey string,
	opts ...Option,
) (*Sandbox, error)

ConnectSandbox connects to an existing sandbox.

func NewSandbox

func NewSandbox(
	ctx context.Context,
	apiKey string,
	opts ...Option,
) (*Sandbox, error)

NewSandbox creates a new sandbox.

func (*Sandbox) Close

func (s *Sandbox) Close(ctx context.Context) error

Close is an alias for Stop.

func (*Sandbox) GetHost

func (s *Sandbox) GetHost(port int) string

GetHost returns the host address for the specified port.

func (*Sandbox) KeepAlive

func (s *Sandbox) KeepAlive(ctx context.Context, timeout time.Duration) error

KeepAlive keeps the sandbox alive.

func (*Sandbox) Ls

func (s *Sandbox) Ls(ctx context.Context, path string) ([]LsResult, error)

Ls lists the files and/or directories in the sandbox file system at the given path.

func (*Sandbox) Mkdir

func (s *Sandbox) Mkdir(ctx context.Context, path string) error

Mkdir makes a directory in the sandbox file system.

func (*Sandbox) NewProcess

func (s *Sandbox) NewProcess(
	cmd string,
	opts ...ProcessOption,
) (*Process, error)

NewProcess creates a new process startable in the sandbox.

func (*Sandbox) Read

func (s *Sandbox) Read(
	ctx context.Context,
	path string,
) (string, error)

Read reads a file from the sandbox file system.

func (*Sandbox) ReadBytes

func (s *Sandbox) ReadBytes(ctx context.Context, path string) ([]byte, error)

ReadBytes reads a file from the sandbox file system.

func (*Sandbox) Reconnect

func (s *Sandbox) Reconnect(ctx context.Context) (err error)

Reconnect reconnects to the sandbox.

func (*Sandbox) Stop

func (s *Sandbox) Stop(ctx context.Context) error

Stop stops the sandbox.

func (*Sandbox) Watch

func (s *Sandbox) Watch(
	ctx context.Context,
	path string,
	eCh chan<- Event,
) error

Watch watches a directory in the sandbox file system.

This is intended to be run in a goroutine as it will block until the connection is closed, an error occurs, or the context is canceled.

While blocking, filesystem events will be written to the provided channel.

func (*Sandbox) Write

func (s *Sandbox) Write(ctx context.Context, path string, data []byte) error

Write writes to a file to the sandbox file system.

func (*Sandbox) WriteBytes

func (s *Sandbox) WriteBytes(ctx context.Context, path string, data []byte) error

WriteBytes writes bytes to a file in the sandbox file system.

type SandboxTemplate

type SandboxTemplate string

SandboxTemplate is a sandbox template.

const (
	// DefaultCodeInterpreterTemplate is the default template for CodeInterpreter.
	DefaultCodeInterpreterTemplate SandboxTemplate = "code-interpreter-v1"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL