Skip to content

Commit

Permalink
fix: calculate usage if not given in non-stream mode (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
glzjin authored Aug 6, 2023
1 parent 1dfa190 commit 446337c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
14 changes: 13 additions & 1 deletion controller/relay-openai.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func openaiStreamHandler(c *gin.Context, resp *http.Response, relayMode int) (*O
return nil, responseText
}

func openaiHandler(c *gin.Context, resp *http.Response, consumeQuota bool) (*OpenAIErrorWithStatusCode, *Usage) {
func openaiHandler(c *gin.Context, resp *http.Response, consumeQuota bool, promptTokens int, model string) (*OpenAIErrorWithStatusCode, *Usage) {
var textResponse TextResponse
if consumeQuota {
responseBody, err := io.ReadAll(resp.Body)
Expand Down Expand Up @@ -132,5 +132,17 @@ func openaiHandler(c *gin.Context, resp *http.Response, consumeQuota bool) (*Ope
if err != nil {
return errorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
}

if textResponse.Usage.TotalTokens == 0 {
completionTokens := 0
for _, choice := range textResponse.Choices {
completionTokens += countTokenText(choice.Message.Content, model)
}
textResponse.Usage = Usage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
}
}
return nil, &textResponse.Usage
}
2 changes: 1 addition & 1 deletion controller/relay-text.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ func relayTextHelper(c *gin.Context, relayMode int) *OpenAIErrorWithStatusCode {
textResponse.Usage.CompletionTokens = countTokenText(responseText, textRequest.Model)
return nil
} else {
err, usage := openaiHandler(c, resp, consumeQuota)
err, usage := openaiHandler(c, resp, consumeQuota, promptTokens, textRequest.Model)
if err != nil {
return err
}
Expand Down
5 changes: 3 additions & 2 deletions controller/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,9 @@ type OpenAIErrorWithStatusCode struct {
}

type TextResponse struct {
Usage `json:"usage"`
Error OpenAIError `json:"error"`
Choices []OpenAITextResponseChoice `json:"choices"`
Usage `json:"usage"`
Error OpenAIError `json:"error"`
}

type OpenAITextResponseChoice struct {
Expand Down

0 comments on commit 446337c

Please sign in to comment.