feat: make finish reason nullable in json marshal (#449)

This commit is contained in:
Yu
2023-07-28 12:06:48 +08:00
committed by GitHub
parent 1153eb2595
commit 62dc817b39
2 changed files with 38 additions and 0 deletions

View File

@@ -114,6 +114,13 @@ const (
FinishReasonNull FinishReason = "null" FinishReasonNull FinishReason = "null"
) )
func (r FinishReason) MarshalJSON() ([]byte, error) {
if r == FinishReasonNull || r == "" {
return []byte("null"), nil
}
return []byte(`"` + string(r) + `"`), nil // best effort to not break future API changes
}
type ChatCompletionChoice struct { type ChatCompletionChoice struct {
Index int `json:"index"` Index int `json:"index"`
Message ChatCompletionMessage `json:"message"` Message ChatCompletionMessage `json:"message"`

View File

@@ -298,3 +298,34 @@ func getChatCompletionBody(r *http.Request) (ChatCompletionRequest, error) {
} }
return completion, nil return completion, nil
} }
func TestFinishReason(t *testing.T) {
c := &ChatCompletionChoice{
FinishReason: FinishReasonNull,
}
resBytes, _ := json.Marshal(c)
if !strings.Contains(string(resBytes), `"finish_reason":null`) {
t.Error("null should not be quoted")
}
c.FinishReason = ""
resBytes, _ = json.Marshal(c)
if !strings.Contains(string(resBytes), `"finish_reason":null`) {
t.Error("null should not be quoted")
}
otherReasons := []FinishReason{
FinishReasonStop,
FinishReasonLength,
FinishReasonFunctionCall,
FinishReasonContentFilter,
}
for _, r := range otherReasons {
c.FinishReason = r
resBytes, _ = json.Marshal(c)
if !strings.Contains(string(resBytes), fmt.Sprintf(`"finish_reason":"%s"`, r)) {
t.Errorf("%s should be quoted", r)
}
}
}