Skip to content

Conversation

@carlos-code-max
Copy link

Problem:
In the current OpenAI Go SDK, the inline union ChatCompletionNewParamsResponseFormatUnion has a deserialization bug:

The union contains three inline structs: OfText, OfJSONSchema, and OfJSONObject, each of which has a type field.

During JSON deserialization, Go’s encoding/json maps the JSON data to the first matching inline struct (OfText), causing OfJSONSchema and OfJSONObject to be ignored.

As a result, when a user sends response_format of type "json_schema" or "json_object", the SDK fails to parse it correctly.

Solution:

Register a union discriminator so that apijson knows how to dispatch JSON to the correct inline struct based on the type field.

Add the following code in the init() function:

func init() {
	apijson.RegisterUnion[ChatCompletionNewParamsResponseFormatUnion](
		"type",
		apijson.Discriminator[shared.ResponseFormatTextParam]("text"),
		apijson.Discriminator[shared.ResponseFormatJSONSchemaParam]("json_schema"),
		apijson.Discriminator[shared.ResponseFormatJSONObjectParam]("json_object"),
	)
}

Effect:

JSON is automatically deserialized to the correct union struct based on type.

Fixes the issue where response_format of "json_schema" or "json_object" could not be parsed.

Eliminates the need for users to manually patch response_format handling.

Compatibility:

Backward compatible: text type behavior remains unchanged.

Does not affect other union types.

@carlos-code-max carlos-code-max requested a review from a team as a code owner October 21, 2025 03:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant