Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
20 changes: 19 additions & 1 deletion chat_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package openai

import (
"context"
"encoding/json"
"net/http"
)

Expand Down Expand Up @@ -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
Expand Down
Loading