Implementation:Openai Openai node Completions Resource
| Knowledge Sources | |
|---|---|
| Domains | SDK, Chat Completions |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
The Completions class is the Chat Completions resource in the openai-node SDK, providing methods to create, retrieve, update, list, delete, parse, stream, and run tools against the /chat/completions API endpoint.
Description
The Completions class extends APIResource and is the primary resource for interacting with OpenAI's Chat Completions API. It is accessed via client.chat.completions. The class provides a comprehensive set of methods: create for generating chat completions (with streaming and non-streaming overloads), retrieve for fetching stored completions, update for modifying metadata on stored completions, list for paginating stored completions, and delete for removing stored completions.
Beyond the basic CRUD operations, the resource provides three powerful helper methods. The parse method wraps create and automatically parses structured output using Zod schemas, returning a ParsedChatCompletion with typed parsed fields on each choice message. The stream method returns a ChatCompletionStream object for convenient streaming with event handling. The runTools method provides an automated function-calling loop that calls your JavaScript functions, sends results back to the model, and loops until the model stops requesting tool calls.
Key types exported from this module include ChatCompletion, ChatCompletionChunk, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionCreateParams, and the various content part types for text, images, audio, and files. The resource also has a messages sub-resource for accessing stored completion messages.
Usage
Use this resource for all chat-based text generation tasks, including basic completions, streaming responses, structured output parsing with Zod schemas, and automated tool/function calling workflows.
Code Reference
Source Location
- Repository: openai-node
- File: src/resources/chat/completions/completions.ts
Signature
export class Completions extends APIResource {
messages: MessagesAPI.Messages;
create(body: ChatCompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise<ChatCompletion>;
create(body: ChatCompletionCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<ChatCompletionChunk>>;
retrieve(completionID: string, options?: RequestOptions): APIPromise<ChatCompletion>;
update(completionID: string, body: ChatCompletionUpdateParams, options?: RequestOptions): APIPromise<ChatCompletion>;
list(query?: ChatCompletionListParams | null, options?: RequestOptions): PagePromise<ChatCompletionsPage, ChatCompletion>;
delete(completionID: string, options?: RequestOptions): APIPromise<ChatCompletionDeleted>;
parse<Params extends ChatCompletionParseParams, ParsedT>(
body: Params,
options?: RequestOptions,
): APIPromise<ParsedChatCompletion<ParsedT>>;
runTools<Params extends ChatCompletionToolRunnerParams<any>, ParsedT>(
body: Params,
options?: RunnerOptions,
): ChatCompletionRunner<ParsedT>;
runTools<Params extends ChatCompletionStreamingToolRunnerParams<any>, ParsedT>(
body: Params,
options?: RunnerOptions,
): ChatCompletionStreamingRunner<ParsedT>;
stream<Params extends ChatCompletionStreamParams, ParsedT>(
body: Params,
options?: RequestOptions,
): ChatCompletionStream<ParsedT>;
}
Import
import OpenAI from 'openai';
// Access via client.chat.completions
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| messages | Array<ChatCompletionMessageParam> |
Yes | The conversation messages (developer, system, user, assistant, tool, function roles) |
| model | ChatModel | Yes | Model ID such as 'gpt-4o', 'o3', etc. |
| stream | boolean |
No | If true, returns a streaming response |
| tools | Array<ChatCompletionTool> |
No | Tools the model may call (function or custom) |
| response_format | ResponseFormatJSONSchema | ResponseFormatJSONObject | No | Controls the output format; enables Structured Outputs with json_schema |
| temperature | number |
No | Sampling temperature between 0 and 2 |
| max_completion_tokens | number |
No | Upper bound for generated tokens including reasoning tokens |
| reasoning_effort | ReasoningEffort |
No | Constrains reasoning effort for reasoning models (low, medium, high, etc.) |
| store | boolean |
No | Whether to store the completion for later retrieval/distillation |
Outputs
| Name | Type | Description |
|---|---|---|
| ChatCompletion | ChatCompletion |
Non-streaming response with id, choices (finish_reason, message), model, usage |
| Stream<ChatCompletionChunk> | Stream<ChatCompletionChunk> |
Streaming response yielding delta chunks |
| ParsedChatCompletion<T> | ParsedChatCompletion<T> |
Extended ChatCompletion with typed parsed fields on messages and tool calls |
| ChatCompletionStream<T> | ChatCompletionStream<T> |
Event-emitting stream wrapper for streaming completions |
| ChatCompletionRunner<T> | ChatCompletionRunner<T> |
Automated tool-calling runner (non-streaming) |
| ChatCompletionStreamingRunner<T> | ChatCompletionStreamingRunner<T> |
Automated tool-calling runner (streaming) |
Usage Examples
import OpenAI from 'openai';
const client = new OpenAI();
// Basic non-streaming completion
const completion = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(completion.choices[0].message.content);
// Streaming completion
const stream = client.chat.completions.stream({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Write a haiku.' }],
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
// Structured output with parse
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const parsed = await client.chat.completions.parse({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Plan a meeting for Friday with Alice and Bob.' }],
response_format: zodResponseFormat(CalendarEvent, 'event'),
});
console.log(parsed.choices[0].message.parsed);
// Retrieve a stored completion
const stored = await client.chat.completions.retrieve('chatcmpl_abc123');
// List stored completions
for await (const item of client.chat.completions.list()) {
console.log(item.id);
}