Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai node APIPromise

From Leeroopedia
Revision as of 13:34, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Openai_Openai_node_APIPromise.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains SDK, Core
Last Updated 2026-02-15 12:00 GMT

Overview

APIPromise is a Promise subclass that wraps every API response in the SDK, providing lazy parsing and direct access to both parsed data and raw HTTP response metadata.

Description

APIPromise<T> extends the native Promise<WithRequestID<T>> to add SDK-specific response handling capabilities. The key design feature is lazy evaluation: the response body is not parsed until the promise is actually awaited (via then, catch, or finally). This is achieved by overriding these three Promise methods to delegate to an internal parse() method that memoizes the parsed result.

The class provides two additional accessor methods beyond standard promise resolution. asResponse() returns the raw Response object without parsing the body, useful for streaming or custom processing scenarios. withResponse() returns an object containing the parsed data, the raw Response, and the x-request-id header value for debugging and issue reporting purposes.

Internally, APIPromise also exposes a _thenUnwrap() method used by the SDK to transform parsed responses (e.g., unwrapping nested response envelopes) while preserving request ID metadata. The constructor accepts a custom parseResponse function that defaults to the SDK's standard JSON parsing logic.

Usage

APIPromise is returned by every API method in the SDK. Developers interact with it implicitly by awaiting API calls. Use asResponse() when you need the raw HTTP response (e.g., for streaming), and withResponse() when you need both the parsed data and request metadata for debugging.

Code Reference

Source Location

Signature

export class APIPromise<T> extends Promise<WithRequestID<T>> {
  constructor(
    client: OpenAI,
    responsePromise: Promise<APIResponseProps>,
    parseResponse?: (client: OpenAI, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>,
  );

  asResponse(): Promise<Response>;
  withResponse(): Promise<{ data: T; response: Response; request_id: string | null }>;

  // Overrides
  then<TResult1, TResult2>(
    onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | null,
    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,
  ): Promise<TResult1 | TResult2>;
  catch<TResult>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<WithRequestID<T> | TResult>;
  finally(onfinally?: (() => void) | null): Promise<WithRequestID<T>>;
}

Import

import { APIPromise } from 'openai/core/api-promise';

I/O Contract

Inputs

Name Type Required Description
client OpenAI Yes The OpenAI client instance used for parsing context.
responsePromise Promise<APIResponseProps> Yes The underlying HTTP response promise from the request layer.
parseResponse (client: OpenAI, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>> No Custom response parser. Defaults to defaultParseResponse which handles JSON deserialization.

Outputs

Name Type Description
(awaited) WithRequestID<T> The parsed response data, augmented with a _request_id property.
asResponse() Promise<Response> The raw HTTP Response object without body parsing.
withResponse() null }> An object containing parsed data, raw response, and the request ID.

Usage Examples

import OpenAI from 'openai';

const client = new OpenAI();

// Standard usage -- APIPromise is returned and awaited
const completion = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello' }],
});

// Access the raw Response object
const response = await client.chat.completions
  .create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }] })
  .asResponse();
console.log(response.status); // 200

// Access both parsed data and response metadata
const { data, response: res, request_id } = await client.chat.completions
  .create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello' }] })
  .withResponse();
console.log('Request ID:', request_id);
console.log('Data:', data.choices[0].message.content);

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment