Skip to content

Commit

Permalink
feat: make finish reason nullable in json marshal (sashabaranov#449)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuikns authored Jul 28, 2023
1 parent 1153eb2 commit 62dc817
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,13 @@ const (
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 {
Index int `json:"index"`
Message ChatCompletionMessage `json:"message"`
Expand Down
31 changes: 31 additions & 0 deletions chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,34 @@ func getChatCompletionBody(r *http.Request) (ChatCompletionRequest, error) {
}
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)
}
}
}

0 comments on commit 62dc817

Please sign in to comment.