openai-node icon indicating copy to clipboard operation
openai-node copied to clipboard

fix(chat): support custom tool calls in parser and ChatCompletionStream

Open hsusul opened this issue 4 months ago • 0 comments

Problem

When a Chat Completion response contains a custom tool call (tool_call.type === 'custom'), helper functions in src/lib/parser.ts and src/lib/ChatCompletionStream.ts fail with errors such as Currently only 'function' tool calls are supported; Received 'custom' or TypeError: Cannot read properties of undefined (reading 'name') or missing choices[0].tool_calls[0].function.name.

Affected Scenario

Using client.chat.completions.parse(), maybeParseChatCompletion(), or ChatCompletionStream / .stream() with completions containing custom tool calls.

Root Cause

  1. assertToolCallsAreChatCompletionFunctionToolCalls in src/lib/parser.ts strictly rejected any non-function tool calls, causing maybeParseChatCompletion and parseChatCompletion to throw an error when processing completions with custom tool calls.
  2. shouldParseToolCall did not guard against non-function tool calls before accessing toolCall.function.name.
  3. ChatCompletionStream assumed all streamed tool call snapshots and deltas have a function property, throwing errors in #addChunk, #emitToolCallDoneEvent, and finalizeChatCompletion.

Solution

  1. Updated maybeParseChatCompletion, parseChatCompletion, and parseToolCall in src/lib/parser.ts to pass through non-function tool calls (such as custom tool calls) without throwing.
  2. Added a toolCall.type === 'function' guard to shouldParseToolCall.
  3. Updated ChatCompletionStream to safely accumulate deltas for custom tool calls, map them during finalization, and skip tool_calls.function.arguments.* event emission for non-function tool calls.
  4. Expanded ChatCompletionSnapshot.Choice.Message.ToolCall type definitions to support CustomToolCall.

Regression Coverage

Added unit tests in:

  • tests/lib/parser.test.ts: verifying maybeParseChatCompletion preserves custom tool calls without throwing.
  • tests/lib/ChatCompletionStream.test.ts: verifying stream accumulation and finalization of custom tool calls.

Validation Commands

  • pnpm jest tests/lib/parser.test.ts tests/lib/ChatCompletionStream.test.ts (PASS)
  • pnpm build (PASS)
  • pnpm lint (PASS)
  • pnpm format (PASS)
  • pnpm test (PASS)

Generated Code Impact

None. Changes are strictly confined to manually maintained files in src/lib/ and tests/lib/.

hsusul avatar Jul 27 '26 13:07 hsusul