Skip to content

Commit 62dc817

Browse files
authored
feat: make finish reason nullable in json marshal (#449)
1 parent 1153eb2 commit 62dc817

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

chat.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@ const (
114114
FinishReasonNull FinishReason = "null"
115115
)
116116

117+
func (r FinishReason) MarshalJSON() ([]byte, error) {
118+
if r == FinishReasonNull || r == "" {
119+
return []byte("null"), nil
120+
}
121+
return []byte(`"` + string(r) + `"`), nil // best effort to not break future API changes
122+
}
123+
117124
type ChatCompletionChoice struct {
118125
Index int `json:"index"`
119126
Message ChatCompletionMessage `json:"message"`

chat_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,3 +298,34 @@ func getChatCompletionBody(r *http.Request) (ChatCompletionRequest, error) {
298298
}
299299
return completion, nil
300300
}
301+
302+
func TestFinishReason(t *testing.T) {
303+
c := &ChatCompletionChoice{
304+
FinishReason: FinishReasonNull,
305+
}
306+
resBytes, _ := json.Marshal(c)
307+
if !strings.Contains(string(resBytes), `"finish_reason":null`) {
308+
t.Error("null should not be quoted")
309+
}
310+
311+
c.FinishReason = ""
312+
313+
resBytes, _ = json.Marshal(c)
314+
if !strings.Contains(string(resBytes), `"finish_reason":null`) {
315+
t.Error("null should not be quoted")
316+
}
317+
318+
otherReasons := []FinishReason{
319+
FinishReasonStop,
320+
FinishReasonLength,
321+
FinishReasonFunctionCall,
322+
FinishReasonContentFilter,
323+
}
324+
for _, r := range otherReasons {
325+
c.FinishReason = r
326+
resBytes, _ = json.Marshal(c)
327+
if !strings.Contains(string(resBytes), fmt.Sprintf(`"finish_reason":"%s"`, r)) {
328+
t.Errorf("%s should be quoted", r)
329+
}
330+
}
331+
}

0 commit comments

Comments
 (0)