openai-node
openai-node copied to clipboard
fix(chat): support custom tool calls in parser and ChatCompletionStream
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
assertToolCallsAreChatCompletionFunctionToolCallsinsrc/lib/parser.tsstrictly rejected any non-functiontool calls, causingmaybeParseChatCompletionandparseChatCompletionto throw an error when processing completions with custom tool calls.shouldParseToolCalldid not guard against non-functiontool calls before accessingtoolCall.function.name.ChatCompletionStreamassumed all streamed tool call snapshots and deltas have afunctionproperty, throwing errors in#addChunk,#emitToolCallDoneEvent, andfinalizeChatCompletion.
Solution
- Updated
maybeParseChatCompletion,parseChatCompletion, andparseToolCallinsrc/lib/parser.tsto pass through non-function tool calls (such ascustomtool calls) without throwing. - Added a
toolCall.type === 'function'guard toshouldParseToolCall. - Updated
ChatCompletionStreamto safely accumulate deltas forcustomtool calls, map them during finalization, and skiptool_calls.function.arguments.*event emission for non-function tool calls. - Expanded
ChatCompletionSnapshot.Choice.Message.ToolCalltype definitions to supportCustomToolCall.
Regression Coverage
Added unit tests in:
tests/lib/parser.test.ts: verifyingmaybeParseChatCompletionpreservescustomtool 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/.