CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-openai

The official TypeScript library for the OpenAI API

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

containers.mddocs/

Containers

Manage isolated execution containers for code interpreter and other tools. Containers provide sandboxed environments with file system access, allowing you to create, manage, and execute code in isolated contexts with full file management capabilities.

Capabilities

Container Management

Create and manage isolated execution containers.

/**
 * Create a new container
 * @param params - Container creation parameters
 * @returns Container object with unique identifier
 */
function create(params: ContainerCreateParams): Promise<ContainerCreateResponse>;

/**
 * Retrieve container information
 * @param containerID - Unique identifier for the container
 * @returns Container object with current status
 */
function retrieve(containerID: string): Promise<ContainerRetrieveResponse>;

/**
 * List all containers
 * @param params - List parameters for pagination and sorting
 * @returns Paginated list of containers
 */
function list(params?: ContainerListParams): Promise<ContainerListResponsesPage>;

/**
 * Delete a container
 * @param containerID - Unique identifier for the container
 * @returns Void on successful deletion
 */
function delete(containerID: string): Promise<void>;

interface ContainerCreateParams {
  /** Name of the container to create */
  name: string;
  /** IDs of files to copy to the container */
  file_ids?: Array<string>;
  /** Container expiration time relative to the 'anchor' time */
  expires_after?: ExpiresAfterCreate;
}

/**
 * Expiration configuration for container creation.
 * When creating a container, the anchor field is required.
 * Note: This is accessed as ContainerCreateParams.ExpiresAfter in TypeScript.
 */
interface ExpiresAfterCreate {
  /** Time anchor for the expiration time. Currently only 'last_active_at' is supported */
  anchor: "last_active_at";
  /** Number of minutes after the anchor before the container expires */
  minutes: number;
}

/**
 * Expiration configuration in container responses.
 * In response objects, the anchor field is optional.
 * Note: This is accessed as nested interface (e.g., ContainerRetrieveResponse.ExpiresAfter) in TypeScript.
 */
interface ExpiresAfter {
  /** Time anchor for the expiration time. Currently only 'last_active_at' is supported */
  anchor?: "last_active_at";
  /** Number of minutes after the anchor before the container expires */
  minutes: number;
}

interface ContainerListParams {
  /** Sort order by the created_at timestamp */
  order?: "asc" | "desc";
  /** Maximum number of items to return */
  limit?: number;
  /** Cursor for fetching the next page of results */
  after?: string;
  /** Cursor for fetching the previous page of results */
  before?: string;
}

Usage Examples:

import OpenAI from "openai";

const client = new OpenAI();

// Create a new container
const container = await client.containers.create({
  name: "python-executor",
  expires_after: {
    anchor: "last_active_at",
    minutes: 60, // Expires 60 minutes after last activity
  },
});

console.log(`Container created: ${container.id}`);

// Retrieve container details
const retrieved = await client.containers.retrieve(container.id);
console.log(`Container status: ${retrieved.status}`);

// List all containers
for await (const container of client.containers.list({ order: "desc" })) {
  console.log(`${container.id}: ${container.name} (${container.status})`);
}

// Delete a container
await client.containers.delete(container.id);
console.log("Container deleted");

File Management

Manage files within containers for code execution and data processing.

/**
 * Create a file in a container
 * You can send either a multipart/form-data request with raw file content,
 * or a JSON request with a file ID
 * @param containerID - Unique identifier for the container
 * @param params - File creation parameters
 * @returns File object with path and metadata
 */
function containers.files.create(
  containerID: string,
  params: FileCreateParams
): Promise<FileCreateResponse>;

/**
 * Retrieve file information
 * @param fileID - Unique identifier for the file
 * @param params - Parameters including container_id
 * @returns File object with metadata
 */
function containers.files.retrieve(
  fileID: string,
  params: FileRetrieveParams
): Promise<FileRetrieveResponse>;

/**
 * List files in a container
 * @param containerID - Unique identifier for the container
 * @param params - List parameters for pagination and sorting
 * @returns Paginated list of files
 */
function containers.files.list(
  containerID: string,
  params?: FileListParams
): Promise<FileListResponsesPage>;

/**
 * Delete a file from a container
 * @param fileID - Unique identifier for the file
 * @param params - Parameters including container_id
 * @returns Void on successful deletion
 */
function containers.files.delete(
  fileID: string,
  params: FileDeleteParams
): Promise<void>;

interface FileCreateParams {
  /** The File object (not file name) to be uploaded */
  file?: Uploadable;
  /** ID of an existing file to copy into the container */
  file_id?: string;
}

interface FileRetrieveParams {
  container_id: string;
}

interface FileListParams {
  /** Sort order by the created_at timestamp */
  order?: "asc" | "desc";
  /** Maximum number of items to return */
  limit?: number;
  /** Cursor for fetching the next page of results */
  after?: string;
  /** Cursor for fetching the previous page of results */
  before?: string;
}

interface FileDeleteParams {
  container_id: string;
}

Usage Examples:

import OpenAI, { toFile } from "openai";
import fs from "fs";

const client = new OpenAI();

// Create a container
const container = await client.containers.create({
  name: "data-processor",
});

// Upload a file to the container
const fileContent = fs.readFileSync("./data.csv");
const containerFile = await client.containers.files.create(container.id, {
  file: await toFile(fileContent, "data.csv"),
});

console.log(`File uploaded: ${containerFile.path}`);
console.log(`File size: ${containerFile.bytes} bytes`);

// Copy an existing file into the container
const existingFile = await client.files.create({
  file: await toFile(fs.readFileSync("./script.py"), "script.py"),
  purpose: "assistants",
});

await client.containers.files.create(container.id, {
  file_id: existingFile.id,
});

// List files in the container
for await (const file of client.containers.files.list(container.id)) {
  console.log(`${file.path}: ${file.bytes} bytes (${file.source})`);
}

// Retrieve file info
const fileInfo = await client.containers.files.retrieve(containerFile.id, {
  container_id: container.id,
});
console.log(`File created at: ${new Date(fileInfo.created_at * 1000)}`);

// Delete a file
await client.containers.files.delete(containerFile.id, {
  container_id: container.id,
});

File Content Access

Download file content from containers.

/**
 * Retrieve the raw content of a file in a container
 * @param fileID - Unique identifier for the file
 * @param params - Parameters including container_id
 * @returns Response object containing the binary file content
 */
function containers.files.content.retrieve(
  fileID: string,
  params: ContentRetrieveParams
): Promise<Response>;

interface ContentRetrieveParams {
  container_id: string;
}

Usage Example:

// Download file content
const response = await client.containers.files.content.retrieve(fileId, {
  container_id: container.id,
});

// Read as text
const text = await response.text();
console.log(text);

// Or save to disk
const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync("downloaded-file.txt", buffer);

Types

Container Response Types

interface ContainerCreateResponse {
  /** Unique identifier for the container */
  id: string;
  /** Unix timestamp (in seconds) when the container was created */
  created_at: number;
  /** Name of the container */
  name: string;
  /** Status of the container (e.g., active, deleted) */
  status: string;
  /** The type of this object */
  object: string;
  /** Container expiration configuration */
  expires_after?: ExpiresAfter;
}

interface ContainerRetrieveResponse {
  /** Unique identifier for the container */
  id: string;
  /** Unix timestamp (in seconds) when the container was created */
  created_at: number;
  /** Name of the container */
  name: string;
  /** Status of the container (e.g., active, deleted) */
  status: string;
  /** The type of this object */
  object: string;
  /** Container expiration configuration */
  expires_after?: ExpiresAfter;
}

interface ContainerListResponse {
  /** Unique identifier for the container */
  id: string;
  /** Unix timestamp (in seconds) when the container was created */
  created_at: number;
  /** Name of the container */
  name: string;
  /** Status of the container (e.g., active, deleted) */
  status: string;
  /** The type of this object */
  object: string;
  /** Container expiration configuration */
  expires_after?: ExpiresAfter;
}

File Response Types

interface FileCreateResponse {
  /** Unique identifier for the file */
  id: string;
  /** Size of the file in bytes */
  bytes: number;
  /** The container this file belongs to */
  container_id: string;
  /** Unix timestamp (in seconds) when the file was created */
  created_at: number;
  /** Path of the file in the container */
  path: string;
  /** Source of the file (e.g., 'user', 'assistant') */
  source: string;
  /** The type of this object ('container.file') */
  object: "container.file";
}

interface FileRetrieveResponse {
  /** Unique identifier for the file */
  id: string;
  /** Size of the file in bytes */
  bytes: number;
  /** The container this file belongs to */
  container_id: string;
  /** Unix timestamp (in seconds) when the file was created */
  created_at: number;
  /** Path of the file in the container */
  path: string;
  /** Source of the file (e.g., 'user', 'assistant') */
  source: string;
  /** The type of this object ('container.file') */
  object: "container.file";
}

interface FileListResponse {
  /** Unique identifier for the file */
  id: string;
  /** Size of the file in bytes */
  bytes: number;
  /** The container this file belongs to */
  container_id: string;
  /** Unix timestamp (in seconds) when the file was created */
  created_at: number;
  /** Path of the file in the container */
  path: string;
  /** Source of the file (e.g., 'user', 'assistant') */
  source: string;
  /** The type of this object ('container.file') */
  object: "container.file";
}

Complete Workflow Example

import OpenAI, { toFile } from "openai";
import fs from "fs";

const client = new OpenAI();

async function processDataInContainer() {
  // 1. Create a container with 2-hour expiration
  const container = await client.containers.create({
    name: "data-analysis-env",
    expires_after: {
      anchor: "last_active_at",
      minutes: 120,
    },
  });

  console.log(`Container created: ${container.id}`);

  // 2. Upload data files
  const dataFile = await client.containers.files.create(container.id, {
    file: await toFile(
      fs.readFileSync("./data.csv"),
      "data.csv",
      { type: "text/csv" }
    ),
  });

  console.log(`Data file uploaded: ${dataFile.path}`);

  // 3. Upload processing script
  const scriptFile = await client.containers.files.create(container.id, {
    file: await toFile(
      fs.readFileSync("./process.py"),
      "process.py",
      { type: "text/x-python" }
    ),
  });

  console.log(`Script uploaded: ${scriptFile.path}`);

  // 4. List all files in container
  console.log("\nFiles in container:");
  for await (const file of client.containers.files.list(container.id)) {
    console.log(`- ${file.path} (${file.bytes} bytes)`);
  }

  // 5. Execute code in container (via Assistants API or other tools)
  // ... execution logic here ...

  // 6. Download results
  const resultFiles = [];
  for await (const file of client.containers.files.list(container.id)) {
    if (file.path.startsWith("output_")) {
      const content = await client.containers.files.content.retrieve(file.id, {
        container_id: container.id,
      });
      resultFiles.push({
        path: file.path,
        content: await content.text(),
      });
    }
  }

  console.log(`\nDownloaded ${resultFiles.length} result files`);

  // 7. Clean up - delete container when done
  await client.containers.delete(container.id);
  console.log("Container deleted");

  return resultFiles;
}

processDataInContainer();

Notes

  • Containers provide isolated file systems for code execution
  • Files can be uploaded directly or copied from existing OpenAI file objects
  • Containers automatically expire based on the expires_after configuration
  • The last_active_at anchor tracks the last time the container was accessed
  • File sources indicate whether files were uploaded by users or generated by assistants
  • Container files are separate from the main Files API and only accessible within their container
  • Deleting a container does not delete files in the main Files API that were copied to it

Install with Tessl CLI

npx tessl i tessl/npm-openai

docs

assistants.md

audio.md

batches-evals.md

chat-completions.md

client-configuration.md

containers.md

conversations.md

embeddings.md

files-uploads.md

fine-tuning.md

helpers-audio.md

helpers-zod.md

images.md

index.md

realtime.md

responses-api.md

vector-stores.md

videos.md

tile.json