Skip to content

parse_chat_completion drops custom tool calls #4235

Open

Description

@PranavMishra28

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • This is an issue with the Python library

Describe the bug

parse_chat_completion(), which backs client.chat.completions.parse(), drops custom tool calls. when the model calls only a custom tool, the parsed message has tool_calls=None even though the raw completion contains the call. on a turn with both kinds, the function calls are kept and the custom ones are dropped.

root cause, on main @ f6e8480: the custom branch in src/openai/lib/_parsing/_completions.py only logs a warning and never appends the call (L136-L143), and the list it would append to is typed list[ParsedFunctionToolCall] (L117), so no parsed type can hold one.

To Reproduce

  1. build a chat completion whose message has one custom tool call (no network needed, snippet below)
  2. pass it through parse_chat_completion
  3. the raw completion has the call; the parsed message has tool_calls=None

Code snippets

from openai.types.chat import ChatCompletion
from openai.lib._parsing._completions import parse_chat_completion

completion = ChatCompletion.model_validate({
    "id": "chatcmpl-1", "object": "chat.completion", "created": 0, "model": "gpt-5",
    "choices": [{
        "index": 0, "finish_reason": "tool_calls", "logprobs": None,
        "message": {
            "role": "assistant", "content": None,
            "tool_calls": [{
                "id": "call_1", "type": "custom",
                "custom": {"name": "code_exec", "input": "print('hi')"},
            }],
        },
    }],
})

print("raw:   ", [c.type for c in completion.choices[0].message.tool_calls])
parsed = parse_chat_completion(
    response_format=None, input_tools=[{"type": "custom", "custom": {"name": "code_exec"}}],
    chat_completion=completion,
)
print("parsed:", parsed.choices[0].message.tool_calls)

output on 3.42.1:

Custom tool calls are not callable. Ignoring tool call: call_1 - code_exec
raw:    ['custom']
parsed: None

suggested fix

the diff in #3505 appends the call in that branch. review on that pr found that appending alone is not enough: ParsedChatCompletionMessage.tool_calls is declared as list[ParsedFunctionToolCall], so an appended custom call is dumped as {id, type} and custom.name / custom.input are lost from model_dump(). the complete fix is to widen the parsed tool-call type to a discriminated union of ParsedFunctionToolCall and ChatCompletionMessageCustomToolCall in the generated source of truth, append in this branch, and add a regression test that dumps the whole parsed completion.

streaming is a separate gap: ChoiceDeltaToolCall.type is Optional[Literal["function"]] in 3.42.1, so a streamed custom call fails validation before it reaches this parser.

pr diff: https://github.com/openai/openai-python/pull/3505/files

OS

macOS 26.6.2 (arm64)

Python version

3.13.13

Library version

3.42.1

Activity

  1. Sainath-Reddy7 commented on Nov 5, 2026

    @Sainath-Reddy7

    Reproduced the snippet against 3.42.1 — parsed tool_calls is None while the raw completion carries the custom call, matching the analysis of the custom branch in _completions.py.

    If it would help, I'd be happy to work on the suggested fix (append in the custom branch + widen ParsedChatCompletionMessage.tool_calls to the discriminated union in the generated source, plus a whole-completion dump regression test) — or the streaming gap, if that's the preferred first step. Wanted to check the intended shape with maintainers first, since this touches the generated types.

  2. siddardh-core commented on Nov 8, 2026

    @siddardh-core

    Hi @PranavMishra28, thanks for the detailed analysis and reproduction. I understand that custom tool calls are present in the raw completion but are lost during parsing, including their name and input fields. I would be interested in helping with the regression tests or a separate part of this issue if the maintainers need additional help. Is there any specific area that would be useful for another contributor to investigate?

  3. PranavMishra28 commented on Nov 9, 2026

    @PranavMishra28
    Author

    @siddardh-core @Sainath-Reddy7 thanks for digging into this.

    @siddardh-core, a useful test would cover both a custom-only completion and one with function + custom calls. The important check is the full completion’s model_dump(): keeping the call in memory isn’t enough if custom.name and custom.input disappear during serialization. That came up in my earlier PR: #3505.

    @Sainath-Reddy7 I’d keep the first fix non-streaming. The current streaming delta type only allows function calls, so that needs separate direction rather than getting bundled into this fix.

    One wrinkle: the repo now only accepts PRs from collaborators. We can share test cases here, but I don’t want either of you spending time preparing a PR you can’t submit. We still need maintainer guidance on the type change.

  4. Sainath-Reddy7 commented on Nov 9, 2026

    @Sainath-Reddy7

    Thanks @PranavMishra28 — here are those tests, ready for whoever implements the fix. I checked CONTRIBUTING and saw PRs are limited to collaborators, so posting them here instead.

    Both are strict-xfail on the current release (2 xfailed against openai 3.42.1): they turn green only when a custom call survives parsing and model_dump(); if the call is appended but custom.name/custom.input vanish from the dump (the #3505 review finding), they go XPASS and fail, which pins exactly the serialization check you called out.

    import pytest
    from openai.types.chat import ChatCompletion, ParsedChatCompletion
    from openai.lib._parsing._completions import parse_chat_completion
    
    CUSTOM_ONLY = { ... "tool_calls": [{"id": "call_custom_1", "type": "custom", "custom": {"name": "code_exec", "input": "print('hi')"}}] ... }
    MIXED = { ... "tool_calls": [
        {"id": "call_fn_1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"SF\"}"}},
        {"id": "call_custom_2", "type": "custom", "custom": {"name": "render_chart", "input": "series: 1,2,3"}},
    ] ... }
    
    
    def _parse(payload):
        return parse_chat_completion(
            response_format=None,
            input_tools=[
                {"type": "custom", "custom": {"name": "code_exec"}},
                {"type": "custom", "custom": {"name": "render_chart"}},
                {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {}}}},
            ],
            chat_completion=ChatCompletion.model_validate(payload),
        )
    
    
    @pytest.mark.xfail(reason="parse_chat_completion drops custom tool calls (#4235)", strict=True)
    def test_custom_only_completion_keeps_the_call_and_dumps_it():
        parsed = _parse(CUSTOM_ONLY)
        tool_calls = parsed.choices[0].message.tool_calls
        assert tool_calls is not None and len(tool_calls) == 1
        dumped = parsed.model_dump()["choices"][0]["message"]["tool_calls"][0]
        assert dumped["type"] == "custom"
        assert dumped["custom"]["name"] == "code_exec"
        assert dumped["custom"]["input"] == "print('hi')"
    
    
    @pytest.mark.xfail(reason="parse_chat_completion drops custom tool calls (#4235)", strict=True)
    def test_mixed_completion_keeps_function_and_custom_calls():
        parsed = _parse(MIXED)
        tool_calls = parsed.choices[0].message.tool_calls
        assert tool_calls is not None and len(tool_calls) == 2
        dumped = {c["id"]: c for c in parsed.model_dump()["choices"][0]["message"]["tool_calls"]}
        assert dumped["call_fn_1"]["function"]["name"] == "get_weather"
        assert dumped["call_custom_2"]["custom"]["name"] == "render_chart"
        assert dumped["call_custom_2"]["custom"]["input"] == "series: 1,2,3"

    (Full payloads for CUSTOM_ONLY/MIXED are the minimal valid ChatCompletion dicts from the issue's reproduction; happy to attach the complete runnable file or a gist if preferred.)

  5. TejasLamba2006 commented on Nov 9, 2026

    @TejasLamba2006

    I pushed a candidate fix to https://github.com/TejasLamba2006/openai-python/tree/fix/parse-custom-tool-calls. It preserves custom calls in parse_chat_completion() and widens the parsed call type so model_dump() retains custom.name and custom.input. The regression test checks both parsed fields and serialized output.

    I could not open a pull request because repository policy restricts PRs to collaborators. The code is ready for a collaborator to review or submit.

  6. siddardh-core commented on Nov 10, 2026

    @siddardh-core

    Thank you, @PranavMishra28, @Sainath-Reddy7 and @TejasLamba2006 for investigating this issue and sharing the regression tests and candidate fix.

    I understand the repository's collaborator-only PR restriction. I'll review the supplied test cases and focus on independently reproducing the serialization behaviour rather than preparing a duplicate implementation.

    Thank you for clarifying the expected checks and the current limitations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions