OpenAI
The official Node.js/TypeScript client for the OpenAI API, auto-generated from OpenAI's own OpenAPI spec.
Repository Health
Technical Analysis
openai is the official Node.js and TypeScript library for the OpenAI REST API, generated directly from OpenAI’s OpenAPI specification via Stainless. It exposes typed methods for essentially every documented endpoint — the Responses API, Chat Completions, Assistants, Realtime, fine-tuning, batches, embeddings, images, and moderations — with first-class support for streaming, flexible file uploads, and webhook signature verification.
The package ships with zero required runtime dependencies: integrations for AWS Bedrock, Azure managed identity, WebSocket-based Realtime, and Zod-based structured outputs are all optional peer dependencies, so teams only pay for what they actually use. Workload identity authentication (Kubernetes, Azure, GCP) sits alongside standard API-key auth for teams that need short-lived, cloud-native credentials instead of long-lived secrets.
What You Get
- Full typed coverage of the OpenAI REST API surface (Responses, Chat Completions, Assistants, Realtime, Batches, Fine-tuning, Embeddings, Images, Moderations, Evals, Graders)
- Streaming response iterators for text and Realtime events over Server-Sent Events and WebSockets
- A structured
APIErrorhierarchy with per-status-code subclasses, request-ID propagation, and typedcode/param/typefields - Workload identity auth providers for Kubernetes service accounts, Azure managed identity, and GCP metadata servers, alongside standard API-key auth
- Webhook signature verification (
client.webhooks.unwrap()/verifySignature()) for handling async OpenAI events safely - Zero hard runtime dependencies — AWS Bedrock, Azure, WebSocket, and Zod integrations are all optional peer dependencies
Common Use Cases
- Generating text, images, or structured JSON output from GPT models inside a Node.js or TypeScript backend
- Building multi-turn conversational or agentic products that manage Responses API state across requests
- Verifying and handling OpenAI webhook events (batch or fine-tuning completion) in a server route or serverless function
- Streaming chat completions or Realtime audio/text events to a frontend client
- Authenticating server-to-server calls with short-lived workload-identity tokens instead of static, long-lived API keys
Under The Hood
Architecture — client.ts (1,668 lines) is the central OpenAI class composing dozens of resource classes (Batches, Completions, Embeddings, Files, Images, Models, Moderations, Responses, Chat, Realtime, Beta, Admin, Containers, Conversations, Evals, Fine-tuning, Graders), each defined under src/resources/ and extending a thin APIResource base in src/core/resource.ts. Requests flow through a shared internal transport layer (src/internal/ — request-options.ts, parse.ts, detect-platform.ts, shims.ts) that normalizes fetch behavior across Node, Deno, Bun, and browsers, wrapped in APIPromise (src/core/api-promise.ts), which is both thenable and iterable so a single call can be awaited or streamed. Streaming itself runs through src/streaming.ts and src/core/decoders/, an SSE decoder shared by the plain HTTP client and the Realtime WebSocket client (src/realtime/). Auth is factored into src/auth/ (workload-identity-auth.ts plus per-provider token providers for Kubernetes/Azure/GCP), and provider-specific clients (AzureOpenAI in azure.ts, bedrock.ts) subclass the base client to override request signing and base URLs. Nearly every file under resources/ and error.ts carries a “generated from our OpenAPI spec by Stainless” banner, making clear the whole endpoint surface is codegen-produced on top of a hand-written, stable core/internal/auth substrate.
Tech Stack — Pure TypeScript (98.8% of the codebase by language stats), built via a custom scripts/build pipeline (tsc-multi.json plus separate build/deno/dist-src tsconfig variants) that emits dual CJS/ESM output (dist/index.js and dist/index.mjs) plus a JSR-published Deno-compatible bundle (jsr.json). package.json declares zero required “dependencies” — AWS Bedrock support (@aws-sdk/credential-provider-node, @smithy/*), WebSocket support (ws), and Zod-based structured outputs are all optional peerDependencies gated by peerDependenciesMeta, keeping the base install minimal. The repo is a pnpm workspace (ecosystem-tests/ lives as its own workspace package), linted with ESLint 9’s flat config and typescript-eslint 8, formatted with Prettier, and tested with Jest 29 (ts-jest/@swc/jest) plus fast-check for property-based testing of internal utilities.
Code Quality — tests/ contains 119 .test.ts files spanning unit-level internals (tests/internal/, tests/lib/), auto-generated per-resource API surface tests (tests/api-resources/), and a separate tests/live/ suite gated behind its own jest.live.config.ts for exercising real endpoints. Error handling is centralized in src/core/error.ts’s APIError hierarchy, with status-code-specific subclasses (BadRequestError, AuthenticationError, RateLimitError, etc.) produced via APIError.generate(), each carrying a typed code/param/type/requestID instead of an opaque throw. Naming is consistent and codegen-enforced — resource classes and param/response types mirror the OpenAPI spec 1:1 — and the generated-file banner comments make the hand-maintained vs. regenerated boundary explicit for contributors.
API Design — The public surface is a single new OpenAI({ apiKey }) client whose methods (client.chat.completions.create(), client.responses.create()) mirror the REST endpoints almost 1:1, so anyone who knows OpenAI’s HTTP docs transfers that knowledge directly. Ergonomics go past basic CRUD: streaming is opt-in via a stream: true param that returns an async iterable rather than requiring a different method, file uploads accept five different input shapes (File, fetch Response, fs.ReadStream, toFile(), toStreamingFile()) so the API meets whatever the caller already has, and toResponseInputItems() directly solves a real correctness footgun — dropping reasoning/tool-call items when replaying multi-turn conversation state. Getting started requires only npm install openai and an OPENAI_API_KEY env var. The tradeoff is surface area: dozens of resource namespaces and four distinct auth mechanisms (API key, workload identity, Azure, Bedrock) add real conceptual overhead once you go past the basic chat/responses path.
Used by 86 apps in this directory
Latitude
AI Agents · Monitoring
Open-source AI agent monitoring that catches what will break next before your users do.
LibreChat
AI Assistants · Developer Tools
Unite every major AI model in one self-hosted chat platform with agents, code execution, MCP tools, and enterprise authentication.
LiteLLM
AI Development · Developer Tools
Open source AI gateway and Python SDK that gives you one OpenAI-compatible interface to call 100+ LLM providers, with built-in routing, cost tracking, guardrails, and virtual keys.
Litlyx
Analytics
Cookie-free, AI-powered web analytics you can self-host in 30 seconds with Docker.
LLM Gateway
AI Development · Devops
One API endpoint for 25+ LLM providers — route, track costs, enforce compliance, and switch models without changing your code.
LobeHub
AI Assistants · Automation · Productivity
Your Chief Agent Operator — build, schedule, and collaborate with an entire AI team in one self-hostable workspace.
localforge
AI Agents · AI Code Assistants · Developer Tools
A local, multi-provider AI coding agent with a real desktop and web UI — bring your own Anthropic, OpenAI, Gemini, Bedrock, or local Ollama keys and let it read, edit, and run code in your own project folder.
Mastra Code
AI Code Assistants
"A coding agent that never compacts" — a terminal-based AI coding agent built on the Mastra framework, with Observational Memory instead of context compaction, multi-model support, and OAuth login for Claude Max or ChatGPT Plus.
medusa
Ecommerce
The most flexible open-source commerce platform — build B2C, B2B, and marketplace applications with modular, composable commerce primitives.