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 ChatCompletionParser

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

Overview

The parser module provides the auto-parsing infrastructure for Chat Completions responses, converting raw JSON content and tool call arguments into typed, validated objects using registered parsers.

Description

This module defines the type system and runtime logic for the SDK's "auto-parseable" response formats and tools. At its core are two branded types: AutoParseableResponseFormat<ParsedT> for structured response formats, and AutoParseableTool<OptionsT> for function tools with typed arguments. Both carry a hidden $parseRaw method and a $brand identifier that the SDK uses to detect whether automatic parsing should be applied.

The makeParseableResponseFormat and makeParseableTool factory functions attach these hidden properties to standard response format and tool objects using Object.defineProperties with enumerable: false, ensuring they do not appear in JSON serialization when sent to the API.

The main parsing pipeline consists of maybeParseChatCompletion (which checks whether any auto-parseable inputs exist and falls through to a null-parsed result if not) and parseChatCompletion (which maps over choices, parses response content via parseResponseFormat, and parses tool call arguments via parseToolCall). The module also handles error conditions: if a completion finishes with length or content_filter finish reasons when auto-parseable inputs are present, it throws LengthFinishReasonError or ContentFilterFinishReasonError.

Helper functions hasAutoParseableInput, shouldParseToolCall, isAutoParsableResponseFormat, and isAutoParsableTool provide brand-checking utilities used by ChatCompletionStream and other consumers to determine parsing behavior at runtime.

Usage

This module is used internally by client.chat.completions.parse(), ChatCompletionStream, and ChatCompletionRunner to automatically parse structured outputs. Consumers create auto-parseable formats and tools via zodResponseFormat() and zodFunction() helper functions, which call the factories in this module.

Code Reference

Source Location

Signature

// Core parsing functions
export function maybeParseChatCompletion<Params, ParsedT>(
  completion: ChatCompletion,
  params: Params,
): ParsedChatCompletion<ParsedT>;

export function parseChatCompletion<Params, ParsedT>(
  completion: ChatCompletion,
  params: Params,
): ParsedChatCompletion<ParsedT>;

// Factory functions
export function makeParseableResponseFormat<ParsedT>(
  response_format: ResponseFormatJSONSchema,
  parser: (content: string) => ParsedT,
): AutoParseableResponseFormat<ParsedT>;

export function makeParseableTool<OptionsT extends ToolOptions>(
  tool: ChatCompletionFunctionTool,
  opts: { parser: (content: string) => OptionsT['arguments']; callback: ((args: any) => any) | undefined },
): AutoParseableTool<OptionsT['arguments']>;

// Type guards
export function isAutoParsableResponseFormat<ParsedT>(response_format: any): response_format is AutoParseableResponseFormat<ParsedT>;
export function isAutoParsableTool(tool: any): tool is AutoParseableTool<any>;
export function hasAutoParseableInput(params: AnyChatCompletionCreateParams): boolean;
export function shouldParseToolCall(params: ChatCompletionCreateParams | null | undefined, toolCall: ChatCompletionMessageFunctionToolCall): boolean;

Import

import {
  maybeParseChatCompletion,
  parseChatCompletion,
  makeParseableResponseFormat,
  makeParseableTool,
} from 'openai/lib/parser';

I/O Contract

Inputs (maybeParseChatCompletion)

Name Type Required Description
completion ChatCompletion Yes The raw chat completion response from the API
params null Yes The original request params (used to find auto-parseable formats/tools)

Outputs (maybeParseChatCompletion)

Name Type Description
result ParsedChatCompletion<ParsedT> The completion with parsed fields populated on messages and tool calls

Key Types

export type AutoParseableResponseFormat<ParsedT> = ResponseFormatJSONSchema & {
  __output: ParsedT;
  $brand: 'auto-parseable-response-format';
  $parseRaw(content: string): ParsedT;
};

export type AutoParseableTool<OptionsT extends ToolOptions> = ChatCompletionFunctionTool & {
  __arguments: OptionsT['arguments'];
  __name: OptionsT['name'];
  $brand: 'auto-parseable-tool';
  $callback: ((args: OptionsT['arguments']) => any) | undefined;
  $parseRaw(args: string): OptionsT['arguments'];
};

Usage Examples

Basic Usage

import OpenAI from 'openai';
import { zodResponseFormat } from 'openai/helpers/zod';
import { z } from 'zod';

const Step = z.object({
  explanation: z.string(),
  output: z.string(),
});

const MathResponse = z.object({
  steps: z.array(Step),
  final_answer: z.string(),
});

const client = new OpenAI();

// The parser module powers the `.parse()` method
const completion = await client.beta.chat.completions.parse({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Solve: 8x + 31 = 2' }],
  response_format: zodResponseFormat(MathResponse, 'math_response'),
});

// completion.choices[0].message.parsed is typed as MathResponse
const result = completion.choices[0].message.parsed;
console.log(result?.final_answer);

Related Pages

Page Connections

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