bởi orion

A full-featured TypeScript/JavaScript SDK for the OpenAI REST API, supporting chat completions, streaming, file uploads, realtime WebSocket, webhook verification, and workload identity auth.
This block vendors the full OpenAI Node.js SDK source (user@example.com) so you can embed, audit, and extend it directly inside your project without a runtime npm dependency. It is aimed at TypeScript server projects (Node.js, Express, serverless) that need direct API access to OpenAI's Responses, Chat Completions, Realtime, and related endpoints, including workload-identity authentication for cloud-managed environments.
_vendor/ - Bundled third-party micro-libraries used internally by the SDKauth/ - Workload identity helpers (Kubernetes, Azure, GCP, custom providers)beta/ - Beta-channel features including Realtime WebSocket supportcore/ - Low-level transport primitives: API promise, error hierarchy, pagination, streaming, uploadshelpers/ - Higher-level utilities (audio, Zod schema integration)internal/ - Private decode/encode utilities, QS stringification, platform detection, headerslib/ - Chat completion runners, assistant stream helpers, event emitter baserealtime/ - Stable-channel Realtime API entry pointresources/ - One file/directory per OpenAI API resource (chat, responses, embeddings, etc.)api-promise.ts - Re-export shim for core/api-promiseazure.ts - AzureOpenAI client variantclient.ts - Main OpenAI client class and ClientOptionserror.ts - Re-export shim for core/errorindex.ts - Public barrel exportpagination.ts - Re-export shim for core/paginationresource.ts - Base APIResource classresources.ts - Aggregated resource namespace exportsstreaming.ts - Re-export shim for core/streaminguploads.ts - Re-export shim for core/uploadsversion.ts - SDK version constantThe SDK itself declares no runtime dependencies or peerDependencies in its ; it uses only Node.js built-ins and dynamically detected browser globals. No native build steps are required.
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 92fcc8094dd0cd3e…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
package.json# No additional npm packages are required for the SDK itself.
# If you use the Zod helper (helpers/zod.ts), install zod:
npm install zod
# If you use workload identity in an Azure environment you may want:
# (no extra packages required - the provider uses fetch against IMDS)
Copy source into your project.
Place the contents of source/ at src/openai/ (or any path you prefer).
Configure TypeScript paths in tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"openai": ["src/openai/index.ts"],
"openai/*": ["src/openai/*.ts"]
},
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"strict": true
}
}
Set the required environment variable before running:
export OPENAI_API_KEY="sk-..."
The client reads process.env.OPENAI_API_KEY automatically; you can omit apiKey from ClientOptions when it is set.
Import the client using your path alias or a relative path:
import OpenAI from 'openai'; // via tsconfig paths
// or
import OpenAI from './openai/index';
For ESM projects, ensure "type": "module" is in your package.json and that all internal imports inside source/ use explicit .js extensions if you compile to ESM output. The source ships as TypeScript so your build step controls the output format.
import { OpenAI, type ClientOptions } from 'openai';
const client = new OpenAI(options?: ClientOptions);
The primary client class. ClientOptions accepts apiKey, baseURL, timeout, maxRetries, defaultHeaders, defaultQuery, and workloadIdentity. Instantiate once and reuse across your application. All API resources are available as properties (e.g. client.chat, client.responses, client.embeddings).
import { AzureOpenAI } from 'openai';
const client = new AzureOpenAI({
apiKey: process.env.AZURE_OPENAI_API_KEY,
endpoint: 'https://<resource>.openai.azure.com',
apiVersion: '2024-02-01',
deployment: 'my-gpt4-deployment',
});
Drop-in replacement for OpenAI that targets an Azure OpenAI endpoint. Use this when your organisation routes API calls through Azure instead of api.openai.com.
import { APIError, NotFoundError, RateLimitError, AuthenticationError } from 'openai';
try {
await client.responses.create({ model: 'gpt-5.2', input: 'hi' });
} catch (err) {
if (err instanceof RateLimitError) { /* retry */ }
if (err instanceof APIError) { console.error(err.status, err.message); }
}
Base error class for all HTTP-level failures. Subclasses (NotFoundError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, etc.) let you handle specific HTTP status codes with instanceof checks.
import { toFile, type Uploadable } from 'openai';
const file: Uploadable = await toFile(fs.createReadStream('./audio.mp3'), 'audio.mp3', {
type: 'audio/mpeg',
});
await client.audio.transcriptions.create({ file, model: 'whisper-1' });
Wraps a Buffer, ReadableStream, or file path into an Uploadable compatible with multipart form endpoints. Required for any file-upload call.
import { k8sServiceAccountTokenProvider } from 'openai/auth';
// or relative:
import { k8sServiceAccountTokenProvider } from './openai/auth';
Factory functions that return a SubjectTokenProvider for each cloud platform. Pass the result as workloadIdentity.provider to avoid storing long-lived API keys in environment variables.
Basic chat completion request using the Chat Completions API with typed error handling.
import OpenAI, { RateLimitError, APIError } from './openai/index';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function chat(userMessage: string): Promise<string> {
try {
const completion = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'developer', content: 'You are a helpful assistant.' },
{ role: 'user', content: userMessage },
],
});
return completion.choices[0].message.content ?? '';
} catch (err) {
if (err instanceof RateLimitError) {
throw new Error('Rate limit hit - back off and retry');
}
if (err instanceof APIError) {
throw new Error(`API error ${err.status}: ${err.message}`);
}
throw err;
}
}
const answer = await chat('Are semicolons optional in JavaScript?');
console.log(answer);
Upload an audio file using toFile and transcribe it with Whisper.
import fs from 'fs';
import OpenAI, { toFile } from './openai/index';
const client = new OpenAI();
async function transcribeFile(filePath: string): Promise<string> {
const stream = fs.createReadStream(filePath);
const file = await toFile(stream, 'recording.mp3', { type: 'audio/mpeg' });
const transcription = await client.audio.transcriptions.create({
file,
model: 'whisper-1',
response_format: 'text',
});
return transcription as unknown as string;
}
console.log(await transcribeFile('./meeting.mp3'));
Replace a static API key with short-lived GCP identity tokens for a Cloud Run service.
import OpenAI from './openai/index';
import { gcpIDTokenProvider } from './openai/auth';
const client = new OpenAI({
// No apiKey - workloadIdentity is used instead
workloadIdentity: {
clientId: process.env.OPENAI_CLIENT_ID!,
identityProviderId: process.env.OPENAI_IDP_ID!,
serviceAccountId: process.env.OPENAI_SA_ID!,
provider: gcpIDTokenProvider(),
},
});
const response = await client.responses.create({
model: 'gpt-4o',
input: 'Summarise the quarterly report.',
});
console.log(response.output_text);
Route requests through an Azure-hosted deployment using AzureOpenAI.
import { AzureOpenAI } from './openai/azure';
const azure = new AzureOpenAI({
apiKey: process.env.AZURE_OPENAI_KEY!,
endpoint: process.env.AZURE_OPENAI_ENDPOINT!,
apiVersion: '2024-05-01-preview',
deployment: 'gpt-4-turbo',
});
const result = await azure.chat.completions.create({
model: 'gpt-4-turbo', // must match deployment name
messages: [{ role: 'user', content: 'Hello from Azure!' }],
});
console.log(result.choices[0].message.content);
_vendor/ - Inlined copies of tiny dependencies (e.g. node-fetch shims) to avoid peer-dep conflicts.auth/ - Exports k8sServiceAccountTokenProvider, azureManagedIdentityTokenProvider, gcpIDTokenProvider, and related types for short-lived token exchange.beta/realtime/ - WebSocket-based Realtime API client (beta). Exports OpenAIRealtimeError and WebSocket session helpers.core/ - Foundational classes: APIPromise, APIError hierarchy, Page/PagePromise, Stream, toFile, Uploadable.helpers/ - audio.ts for audio stream helpers; zod.ts for automatic Zod schema parsing of responses.internal/ - Not part of the public API. Contains QS serialiser, header manipulation, base64/bytes utils, platform detection, and line decoders.lib/ - AbstractChatCompletionRunner, ChatCompletionRunner, ChatCompletionStream, ChatCompletionStreamingRunner, AssistantStream - higher-level runner patterns wrapping the raw API.realtime/ - Stable re-export surface for Realtime. Exports OpenAIRealtimeError.resources/ - One sub-module per REST resource (chat, completions, responses, embeddings, fine-tuning, etc.). Consumed automatically by client.ts.client.ts - Defines OpenAI class, wires all resources onto the client instance, reads ClientOptions.azure.ts - Defines AzureOpenAI, overrides auth and base URL logic for Azure endpoints.index.ts - Barrel re-exporting every public symbol. Start here when reading the API surface.error.ts / api-promise.ts / pagination.ts / streaming.ts / uploads.ts - Thin shims that re-export from core/.version.ts - Exports VERSION constant string.OPENAI_API_KEY not set at runtime: The client throws AuthenticationError immediately. Fix: ensure the env var is exported before starting the process, or pass apiKey explicitly in ClientOptions."type": "module": Internal imports in source/ omit .js extensions in TypeScript source. If you compile to ESM and use NodeNext resolution, your build tool (esbuild, tsc with verbatimModuleSyntax) must resolve .ts → .js. Fix: use esbuild or ts-node --esm with moduleResolution: NodeNext.workloadIdentity and apiKey are mutually exclusive: Passing both throws at construction time. Fix: conditionally set one or the other based on environment.toFile with a plain Buffer: Pass a filename as the second argument; without it, some multipart parsers reject the request. Fix: always supply filename and type arguments.model field: Azure routes by deployment, not model alias. Fix: set deployment in AzureOpenAI options and use the same string as model in request bodies.lib/ChatCompletionStream imports EventEmitter: The runner classes depend on the SDK's internal EventEmitter (lib/EventEmitter.ts), not Node's built-in. If tree-shaking removes it, runners will fail silently. Fix: ensure lib/ is included in your build output.I have vendored the OpenAI Node.js SDK (openai@6.34.0) into my project at
`src/openai/` (source from this block's `source/` directory).
I also have `USAGE.md` which documents the public API and working examples.
Please help me integrate this SDK into my existing TypeScript/Node.js project
step by step:
1. Read `USAGE.md` and `src/openai/index.ts` to understand the public API.
2. Update `tsconfig.json` to add path aliases so `import OpenAI from 'openai'`
resolves to `src/openai/index.ts`.
3. Add an `OPENAI_API_KEY` entry to `.env` and load it with `dotenv` before
the client is constructed.
4. Create a `src/services/openai.ts` singleton that exports a configured
`OpenAI` instance.
5. Add a chat helper function that wraps `client.chat.completions.create`,
handles `RateLimitError` with exponential backoff, and returns the
assistant message string.
6. If the project runs on GCP or Azure, swap the API key for workload identity
using the relevant provider from `src/openai/auth/index.ts`.
7. Show me the final file tree and confirm all imports resolve without errors.
Do not install the `openai` npm package; use only the vendored source at
`src/openai/`.
The upstream source is released under the MIT License (see source/LICENSE if present, or verify at the npm package page). This block vendors user@example.com generated from the OpenAI OpenAPI specification by Stainless. Upstream repository: github.com/openai/openai-node.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
SaaS, AI & Subscription Products
5 US$