codeinterpreter

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package codeinterpreter provides a CodeInterpreter implementation for E2B.

Index

Constants

View Source
const DefaultDomain = "e2b.app"

DefaultDomain is the default e2b.dev API domain.

View Source
const DefaultRequestTimeout = 30

DefaultRequestTimeout is the default HTTP request timeout in seconds.

View Source
const DefaultSandboxTimeout = 300

DefaultSandboxTimeout is the default lifetime of a freshly created sandbox in seconds (matches e2b defaults).

View Source
const DefaultTemplate = "code-interpreter-v1"

DefaultTemplate is the default sandbox template used for the code interpreter.

View Source
const DefaultTimeout = 300

DefaultTimeout is the default timeout for code execution in seconds.

View Source
const JupyterPort = 49999

JupyterPort is the internal port on which the Jupyter/Code-Interpreter server listens inside the sandbox.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthenticationError

type AuthenticationError struct {
	Message string
}

AuthenticationError is returned when the supplied API key is invalid or missing.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type BarChart

type BarChart struct {
	Chart2D
	Bars []BarData `json:"-"`
}

BarChart represents a bar chart.

type BarData

type BarData struct {
	Label string `json:"label"`
	Value string `json:"value"`
	Group string `json:"group"`
}

BarData represents a single bar in a bar chart.

type BaseChart

type BaseChart struct {
	Type     ChartType `json:"type"`
	Title    string    `json:"title"`
	Elements []any     `json:"elements"`
	// contains filtered or unexported fields
}

BaseChart contains the fields shared by every chart type.

func (*BaseChart) ChartTitle

func (c *BaseChart) ChartTitle() string

ChartTitle returns the title of the chart.

func (*BaseChart) ChartType

func (c *BaseChart) ChartType() ChartType

ChartType returns the type of the chart.

func (*BaseChart) ToJSON

func (c *BaseChart) ToJSON() map[string]any

ToJSON returns the raw JSON representation of the chart.

type BoxAndWhiskerChart

type BoxAndWhiskerChart struct {
	Chart2D
	Boxes []BoxAndWhiskerData `json:"-"`
}

BoxAndWhiskerChart represents a box-and-whisker chart.

type BoxAndWhiskerData

type BoxAndWhiskerData struct {
	Label         string    `json:"label"`
	Min           float64   `json:"min"`
	FirstQuartile float64   `json:"first_quartile"`
	Median        float64   `json:"median"`
	ThirdQuartile float64   `json:"third_quartile"`
	Max           float64   `json:"max"`
	Outliers      []float64 `json:"outliers"`
}

BoxAndWhiskerData represents one box-and-whisker series.

type Chart

type Chart interface {
	ChartType() ChartType
	ChartTitle() string
	// ToDict returns the raw JSON representation of the chart.
	ToJSON() map[string]any
}

Chart is the common interface implemented by all concrete chart types. Use a type switch on the concrete types to inspect specialized fields, e.g.

switch c := result.Chart.(type) {
case *LineChart: ...
case *BarChart: ...
}

type Chart2D

type Chart2D struct {
	BaseChart
	XLabel string `json:"x_label,omitempty"`
	YLabel string `json:"y_label,omitempty"`
	XUnit  string `json:"x_unit,omitempty"`
	YUnit  string `json:"y_unit,omitempty"`
}

Chart2D is the base for charts that live on a 2D plane.

type ChartType

type ChartType string

ChartType represents the kind of chart returned by the server.

const (
	// ChartTypeLine represents a line chart.
	ChartTypeLine ChartType = "line"
	// ChartTypeScatter represents a scatter plot.
	ChartTypeScatter ChartType = "scatter"
	// ChartTypeBar represents a bar chart.
	ChartTypeBar ChartType = "bar"
	// ChartTypePie represents a pie chart.
	ChartTypePie ChartType = "pie"
	// ChartTypeBoxAndWhisker represents a box and whisker plot.
	ChartTypeBoxAndWhisker ChartType = "box_and_whisker"
	// ChartTypeSuperChart represents a super chart.
	ChartTypeSuperChart ChartType = "superchart"
	// ChartTypeUnknown represents an unknown chart type.
	ChartTypeUnknown ChartType = "unknown"
)

type ConnectionConfig

type ConnectionConfig struct {
	// APIKey is the E2B API key. If empty the E2B_API_KEY environment variable
	// is used.
	APIKey string
	// AccessToken is an optional envd access token used to authenticate direct
	// requests to the sandbox.
	AccessToken string
	// TrafficAccessToken is an optional token used to bypass traffic controls.
	TrafficAccessToken string
	// Domain is the e2b domain (default: e2b.app). The E2B_DOMAIN env var is
	// used when empty.
	Domain string
	// Debug turns on debug-mode. When true, the SDK talks over http:// and
	// uses the sandbox host unchanged (useful for local development).
	Debug bool
	// RequestTimeout is the default HTTP request timeout.
	RequestTimeout time.Duration
	// HTTPClient is the underlying client used for all HTTP traffic. If nil a
	// sensible default is created.
	HTTPClient *http.Client
	// Headers lets callers inject additional headers on every request.
	Headers map[string]string
}

ConnectionConfig holds the configuration needed to talk to the E2B API and to an individual sandbox.

func (*ConnectionConfig) APIBase

func (c *ConnectionConfig) APIBase() string

APIBase returns the base URL for the E2B management API.

type Context

type Context struct {
	// ID of the context.
	ID string `json:"id"`
	// Language of the context.
	Language string `json:"language"`
	// Cwd is the working directory inside the sandbox.
	Cwd string `json:"cwd"`
}

Context represents a code execution context (a persistent kernel).

type CreateCodeContextOpts

type CreateCodeContextOpts struct {
	// Cwd is the working directory for the context (default /home/user).
	Cwd string
	// Language of the new context (default python).
	Language RunCodeLanguage
	// RequestTimeout overrides the default HTTP request timeout.
	RequestTimeout time.Duration
}

CreateCodeContextOpts holds options for Sandbox.CreateCodeContext.

type Execution

type Execution struct {
	// Results collects the cell's main result and any intermediate display
	// calls (e.g. matplotlib plots).
	Results []*Result `json:"results"`
	// Logs holds stdout/stderr lines printed during execution.
	Logs Logs `json:"logs"`
	// Error is set if the execution failed; nil otherwise.
	Error *ExecutionError `json:"error,omitempty"`
	// ExecutionCount is the execution count (cell index) reported by the kernel.
	ExecutionCount int `json:"execution_count,omitempty"`
}

Execution represents the result of a cell execution.

func NewExecution

func NewExecution() *Execution

NewExecution creates an empty Execution.

func (*Execution) Text

func (e *Execution) Text() string

Text returns the text representation of the main result, if any.

func (*Execution) ToJSON

func (e *Execution) ToJSON() (string, error)

ToJSON serializes the execution to JSON.

type ExecutionError

type ExecutionError struct {
	// Name of the error (e.g. "NameError").
	Name string `json:"name"`
	// Value/message of the error.
	Value string `json:"value"`
	// Traceback is the raw traceback text.
	Traceback string `json:"traceback"`
}

ExecutionError represents an error that occurred during the execution of a cell.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

func (*ExecutionError) ToJSON

func (e *ExecutionError) ToJSON() string

ToJSON returns the JSON representation of this error.

type InvalidArgumentError

type InvalidArgumentError struct {
	Message string
}

InvalidArgumentError is returned when input parameters are invalid (e.g. providing both `context` and `language`).

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

type LineChart

type LineChart struct {
	PointChart
}

LineChart represents a line chart.

type Logs

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

Logs holds data printed to stdout and stderr during execution.

type MIMEType

type MIMEType = string

MIMEType is a string alias for convenience.

type NotFoundError

type NotFoundError struct {
	Message string
}

NotFoundError is returned when a resource (context, sandbox, file) is missing.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type OnErrorFunc

type OnErrorFunc func(err *ExecutionError)

OnErrorFunc is a callback invoked when the running code raises an error.

type OnResultFunc

type OnResultFunc func(result *Result)

OnResultFunc is a callback invoked for every Result emitted by the running code (display calls as well as the final main result).

type OnStderrFunc

type OnStderrFunc func(msg OutputMessage)

OnStderrFunc is a callback invoked for every stderr chunk produced by the running code.

type OnStdoutFunc

type OnStdoutFunc func(msg OutputMessage)

OnStdoutFunc is a callback invoked for every stdout chunk produced by the running code.

type OutputMessage

type OutputMessage struct {
	// Line is the raw output line.
	Line string
	// Timestamp is the unix epoch in nanoseconds.
	Timestamp int64
	// Error indicates whether this output originates from stderr.
	Error bool
}

OutputMessage represents an output message from the sandbox code execution.

func (OutputMessage) String

func (o OutputMessage) String() string

type PieChart

type PieChart struct {
	BaseChart
	Slices []PieData `json:"-"`
}

PieChart represents a pie chart.

type PieData

type PieData struct {
	Label  string  `json:"label"`
	Angle  float64 `json:"angle"`
	Radius float64 `json:"radius"`
}

PieData represents a slice of a pie chart.

type PointChart

type PointChart struct {
	Chart2D
	XTicks      []any       `json:"x_ticks"`
	XTickLabels []string    `json:"x_tick_labels"`
	XScale      ScaleType   `json:"x_scale"`
	YTicks      []any       `json:"y_ticks"`
	YTickLabels []string    `json:"y_tick_labels"`
	YScale      ScaleType   `json:"y_scale"`
	Points      []PointData `json:"-"`
}

PointChart is the base for line/scatter.

type PointData

type PointData struct {
	Label  string   `json:"label"`
	Points [][2]any `json:"points"`
}

PointData is one series in a point based chart (line/scatter).

type RateLimitError

type RateLimitError struct {
	Message string
}

RateLimitError is returned when the caller has exceeded the API's rate limit.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type Result

type Result struct {
	Text       string         `json:"text,omitempty"`
	HTML       string         `json:"html,omitempty"`
	Markdown   string         `json:"markdown,omitempty"`
	SVG        string         `json:"svg,omitempty"`
	PNG        string         `json:"png,omitempty"`
	JPEG       string         `json:"jpeg,omitempty"`
	PDF        string         `json:"pdf,omitempty"`
	LaTeX      string         `json:"latex,omitempty"`
	JSON       map[string]any `json:"json,omitempty"`
	JavaScript string         `json:"javascript,omitempty"`
	Data       map[string]any `json:"data,omitempty"`
	// Chart is the structured chart data extracted by the server, if any.
	Chart Chart `json:"-"`
	// IsMainResult indicates whether this is the primary result of the cell
	// (as opposed to an intermediate display call).
	IsMainResult bool `json:"is_main_result,omitempty"`
	// Extra holds any additional representations not covered by the
	// standard fields above.
	Extra map[string]any `json:"extra,omitempty"`
	// Raw holds the full raw JSON payload as returned by the server.
	Raw map[string]any `json:"-"`
}

Result represents the data to be displayed as a result of executing a cell in a Jupyter notebook. A Result may carry several representations of the same underlying data (text, HTML, PNG, SVG, …).

func (*Result) Formats

func (r *Result) Formats() []string

Formats returns the list of MIME-like format names available on this result.

func (*Result) String

func (r *Result) String() string

String returns a short description of the result. If a textual representation exists it is returned as-is, otherwise the list of available formats is returned.

type RunCodeLanguage

type RunCodeLanguage string

RunCodeLanguage is a supported language identifier for code execution.

Known values: "python", "javascript", "typescript", "r", "java", "bash". Custom strings are allowed for user-installed kernels.

const (
	// LanguagePython is the language identifier for Python.
	LanguagePython RunCodeLanguage = "python"
	// LanguageJavaScript is the language identifier for JavaScript.
	LanguageJavaScript RunCodeLanguage = "javascript"
	// LanguageTypeScript is the language identifier for TypeScript.
	LanguageTypeScript RunCodeLanguage = "typescript"
	// LanguageR is the language identifier for R.
	LanguageR RunCodeLanguage = "r"
	// LanguageJava is the language identifier for Java.
	LanguageJava RunCodeLanguage = "java"
	// LanguageBash is the language identifier for Bash.
	LanguageBash RunCodeLanguage = "bash"
)

type RunCodeOpts

type RunCodeOpts struct {
	// Language to use. Must not be combined with Context.
	Language RunCodeLanguage
	// Context (pre-created kernel) to run the code in.
	Context *Context
	// OnStdout is called for every stdout chunk.
	OnStdout OnStdoutFunc
	// OnStderr is called for every stderr chunk.
	OnStderr OnStderrFunc
	// OnResult is called for every Result (display call or final result).
	OnResult OnResultFunc
	// OnError is called when the kernel reports an error for this cell.
	OnError OnErrorFunc
	// Envs are extra environment variables exposed to the running code.
	Envs map[string]string
	// Timeout is the maximum execution time for this cell (default: 300s).
	// Pass -1 to disable.
	Timeout time.Duration
	// RequestTimeout is the HTTP-level request timeout.
	RequestTimeout time.Duration
}

RunCodeOpts holds options for Sandbox.RunCode.

Either Language or Context may be supplied — not both. When both are empty the default Python context is used.

type Sandbox

type Sandbox struct {
	// contains filtered or unexported fields
}

Sandbox is a running E2B sandbox with code-interpreter capabilities.

func Connect

func Connect(ctx context.Context, sandboxID string, opts *SandboxOpts) (*Sandbox, error)

Connect attaches to an already running sandbox by its ID. The caller must supply at least the API key (via opts or the env var).

func Create

func Create(ctx context.Context, opts *SandboxOpts) (*Sandbox, error)

Create starts a new sandbox. `opts` may be nil, in which case sensible defaults are used (template = code-interpreter-v1).

func (*Sandbox) ClientID

func (s *Sandbox) ClientID() string

ClientID returns the client id (envd worker) running this sandbox.

func (*Sandbox) CreateCodeContext

func (s *Sandbox) CreateCodeContext(ctx context.Context, opts *CreateCodeContextOpts) (*Context, error)

CreateCodeContext creates a fresh kernel in which subsequent code can be run.

func (*Sandbox) GetHost

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

GetHost returns a routable hostname for a port exposed by the sandbox. This lets callers build URLs to user-exposed services.

func (*Sandbox) GetInfo

func (s *Sandbox) GetInfo(ctx context.Context) (*SandboxInfo, error)

GetInfo returns information about this sandbox, including metadata and start/end times.

func (*Sandbox) IsRunning

func (s *Sandbox) IsRunning(ctx context.Context) (bool, error)

IsRunning checks whether the sandbox is still reachable.

func (*Sandbox) Kill

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

Kill terminates the sandbox.

func (*Sandbox) ListCodeContexts

func (s *Sandbox) ListCodeContexts(ctx context.Context) ([]*Context, error)

ListCodeContexts lists the contexts currently available in the sandbox.

func (*Sandbox) RemoveCodeContext

func (s *Sandbox) RemoveCodeContext(ctx context.Context, c any) error

RemoveCodeContext removes the context. The parameter can either be a *Context or a context-id string.

func (*Sandbox) RestartCodeContext

func (s *Sandbox) RestartCodeContext(ctx context.Context, c any) error

RestartCodeContext restarts the given context. The parameter can either be a *Context or a context-id string.

func (*Sandbox) RunCode

func (s *Sandbox) RunCode(ctx context.Context, code string, opts *RunCodeOpts) (*Execution, error)

RunCode executes the supplied code in the sandbox and returns the full Execution result.

Streaming output is forwarded to the callbacks on opts in real time.

func (*Sandbox) SandboxID

func (s *Sandbox) SandboxID() string

SandboxID returns the ID of this sandbox.

func (*Sandbox) SetTimeout

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

SetTimeout updates the remaining lifetime of the sandbox. Pass the desired wall-clock time-until-expiration.

type SandboxError

type SandboxError struct {
	Message    string
	StatusCode int
}

SandboxError is the generic error returned by the SDK for unexpected server responses.

func (*SandboxError) Error

func (e *SandboxError) Error() string

type SandboxInfo

type SandboxInfo struct {
	SandboxID  string            `json:"sandboxID"`
	ClientID   string            `json:"clientID"`
	TemplateID string            `json:"templateID"`
	Alias      string            `json:"alias,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	StartedAt  string            `json:"startedAt,omitempty"`
	EndAt      string            `json:"endAt,omitempty"`
	State      string            `json:"state,omitempty"`
}

SandboxInfo is the JSON shape returned by the API when listing sandboxes.

func List

func List(ctx context.Context, opts *SandboxOpts) ([]SandboxInfo, error)

List returns all sandboxes currently running under the configured API key.

type SandboxOpts

type SandboxOpts struct {
	// APIKey to use. Falls back to the E2B_API_KEY env variable.
	APIKey string
	// AccessToken to use.
	AccessToken string
	// Domain to use (defaults to e2b.app).
	Domain string
	// Debug, if true, uses plain http:// against the sandbox.
	Debug bool
	// RequestTimeout default HTTP request timeout.
	RequestTimeout time.Duration
	// Timeout is the sandbox lifetime in seconds (not the request timeout).
	Timeout time.Duration
	// Template id/alias to use when creating a sandbox. Defaults to the
	// code-interpreter template.
	Template string
	// Metadata attached to the sandbox.
	Metadata map[string]string
	// EnvVars passed to the sandbox at startup.
	EnvVars map[string]string
	// HTTPClient allows overriding the underlying http.Client.
	HTTPClient *http.Client
	// Headers are additional headers to send on every request.
	Headers map[string]string
}

SandboxOpts are options for creating or connecting to a Sandbox.

type ScaleType

type ScaleType string

ScaleType represents an axis scale type (linear, log, etc.)

const (
	// ScaleTypeLinear represents a linear scale.
	ScaleTypeLinear ScaleType = "linear"
	// ScaleTypeDatetime represents a datetime scale.
	ScaleTypeDatetime ScaleType = "datetime"
	// ScaleTypeCategorical represents a categorical scale.
	ScaleTypeCategorical ScaleType = "categorical"
	// ScaleTypeLog represents a log scale.
	ScaleTypeLog ScaleType = "log"
	// ScaleTypeSymlog represents a symlog scale.
	ScaleTypeSymlog ScaleType = "symlog"
	// ScaleTypeLogit represents a logit scale.
	ScaleTypeLogit ScaleType = "logit"
	// ScaleTypeFunction represents a function scale.
	ScaleTypeFunction ScaleType = "function"
	// ScaleTypeFunctionLog represents a function log scale.
	ScaleTypeFunctionLog ScaleType = "functionlog"
	// ScaleTypeAsinh represents an asinh scale.
	ScaleTypeAsinh ScaleType = "asinh"
	// ScaleTypeUnknown represents an unknown scale.
	ScaleTypeUnknown ScaleType = "unknown"
)

type ScatterChart

type ScatterChart struct {
	PointChart
}

ScatterChart represents a scatter chart.

type SuperChart

type SuperChart struct {
	BaseChart
	Charts []Chart `json:"-"`
}

SuperChart is a composite chart containing multiple sub-charts.

type TimeoutError

type TimeoutError struct {
	Message string
}

TimeoutError is returned when a request or execution times out.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type UnknownChart

type UnknownChart struct {
	BaseChart
}

UnknownChart is used when the server returns a chart type that the SDK does not yet understand; all data is still accessible through ToDict().

Directories

Path Synopsis
Example command demonstrating typical use of the Go Code Interpreter SDK.
Example command demonstrating typical use of the Go Code Interpreter SDK.

Jump to

Keyboard shortcuts

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