diff --git a/chat.go b/chat.go index 0bb2e98ee..ccde5d568 100644 --- a/chat.go +++ b/chat.go @@ -322,6 +322,9 @@ type ChatCompletionRequest struct { ServiceTier ServiceTier `json:"service_tier,omitempty"` // Embedded struct for non-OpenAI extensions ChatCompletionRequestExtensions + // The ExtraBody field allows for the inclusion of arbitrary key-value pairs + // in the request body that may not be explicitly defined in this struct. + ExtraBody map[string]any `json:"extra_body,omitempty"` } type StreamOptions struct { @@ -472,11 +475,28 @@ func (c *Client) CreateChatCompletion( return } + // The body map is used to dynamically construct the request payload for the embedding API. + // Instead of relying on a fixed struct, the body map allows for flexible inclusion of fields + // based on their presence, avoiding unnecessary or empty fields in the request. + extraBody := request.ExtraBody + request.ExtraBody = nil + + // Serialize baseReq to JSON + jsonData, err := json.Marshal(request) + if err != nil { + return + } + + // Deserialize JSON to map[string]any + var body map[string]any + _ = json.Unmarshal(jsonData, &body) + req, err := c.newRequest( ctx, http.MethodPost, c.fullURL(urlSuffix, withModel(request.Model)), - withBody(request), + withBody(body), // Main request body. + withExtraBody(extraBody), // Merge ExtraBody fields. ) if err != nil { return diff --git a/chat_stream.go b/chat_stream.go index 80d16cc63..e95c91e7e 100644 --- a/chat_stream.go +++ b/chat_stream.go @@ -2,6 +2,7 @@ package openai import ( "context" + "encoding/json" "net/http" ) @@ -91,11 +92,28 @@ func (c *Client) CreateChatCompletionStream( return } + // The body map is used to dynamically construct the request payload for the embedding API. + // Instead of relying on a fixed struct, the body map allows for flexible inclusion of fields + // based on their presence, avoiding unnecessary or empty fields in the request. + extraBody := request.ExtraBody + request.ExtraBody = nil + + // Serialize baseReq to JSON + jsonData, err := json.Marshal(request) + if err != nil { + return + } + + // Deserialize JSON to map[string]any + var body map[string]any + _ = json.Unmarshal(jsonData, &body) + req, err := c.newRequest( ctx, http.MethodPost, c.fullURL(urlSuffix, withModel(request.Model)), - withBody(request), + withBody(body), // Main request body. + withExtraBody(extraBody), // Merge ExtraBody fields. ) if err != nil { return nil, err