forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ratelimit.go
43 lines (37 loc) · 1.35 KB
/
ratelimit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package openai
import (
"net/http"
"strconv"
"time"
)
// RateLimitHeaders struct represents Openai rate limits headers.
type RateLimitHeaders struct {
LimitRequests int `json:"x-ratelimit-limit-requests"`
LimitTokens int `json:"x-ratelimit-limit-tokens"`
RemainingRequests int `json:"x-ratelimit-remaining-requests"`
RemainingTokens int `json:"x-ratelimit-remaining-tokens"`
ResetRequests ResetTime `json:"x-ratelimit-reset-requests"`
ResetTokens ResetTime `json:"x-ratelimit-reset-tokens"`
}
type ResetTime string
func (r ResetTime) String() string {
return string(r)
}
func (r ResetTime) Time() time.Time {
d, _ := time.ParseDuration(string(r))
return time.Now().Add(d)
}
func newRateLimitHeaders(h http.Header) RateLimitHeaders {
limitReq, _ := strconv.Atoi(h.Get("x-ratelimit-limit-requests"))
limitTokens, _ := strconv.Atoi(h.Get("x-ratelimit-limit-tokens"))
remainingReq, _ := strconv.Atoi(h.Get("x-ratelimit-remaining-requests"))
remainingTokens, _ := strconv.Atoi(h.Get("x-ratelimit-remaining-tokens"))
return RateLimitHeaders{
LimitRequests: limitReq,
LimitTokens: limitTokens,
RemainingRequests: remainingReq,
RemainingTokens: remainingTokens,
ResetRequests: ResetTime(h.Get("x-ratelimit-reset-requests")),
ResetTokens: ResetTime(h.Get("x-ratelimit-reset-tokens")),
}
}