openai/openai-go
Publicmirrored from https://github.com/openai/openai-goAvailable
option/requestoption.go
259lines · modecode
| 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. |
| 2 | |
| 3 | package option |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "log" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/openai/openai-go/internal/requestconfig" |
| 16 | "github.com/tidwall/sjson" |
| 17 | ) |
| 18 | |
| 19 | // RequestOption is an option for the requests made by the openai API Client |
| 20 | // which can be supplied to clients, services, and methods. You can read more about this functional |
| 21 | // options pattern in our [README]. |
| 22 | // |
| 23 | // [README]: https://pkg.go.dev/github.com/openai/openai-go#readme-requestoptions |
| 24 | type RequestOption = requestconfig.RequestOption |
| 25 | |
| 26 | // WithBaseURL returns a RequestOption that sets the BaseURL for the client. |
| 27 | // |
| 28 | // For security reasons, ensure that the base URL is trusted. |
| 29 | func WithBaseURL(base string) RequestOption { |
| 30 | u, err := url.Parse(base) |
| 31 | if err != nil { |
| 32 | log.Fatalf("failed to parse BaseURL: %s\n", err) |
| 33 | } |
| 34 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 35 | if u.Path != "" && !strings.HasSuffix(u.Path, "/") { |
| 36 | u.Path += "/" |
| 37 | } |
| 38 | r.BaseURL = u |
| 39 | return nil |
| 40 | }) |
| 41 | } |
| 42 | |
| 43 | // WithHTTPClient returns a RequestOption that changes the underlying [http.Client] used to make this |
| 44 | // request, which by default is [http.DefaultClient]. |
| 45 | func WithHTTPClient(client *http.Client) RequestOption { |
| 46 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 47 | r.HTTPClient = client |
| 48 | return nil |
| 49 | }) |
| 50 | } |
| 51 | |
| 52 | // MiddlewareNext is a function which is called by a middleware to pass an HTTP request |
| 53 | // to the next stage in the middleware chain. |
| 54 | type MiddlewareNext = func(*http.Request) (*http.Response, error) |
| 55 | |
| 56 | // Middleware is a function which intercepts HTTP requests, processing or modifying |
| 57 | // them, and then passing the request to the next middleware or handler |
| 58 | // in the chain by calling the provided MiddlewareNext function. |
| 59 | type Middleware = func(*http.Request, MiddlewareNext) (*http.Response, error) |
| 60 | |
| 61 | // WithMiddleware returns a RequestOption that applies the given middleware |
| 62 | // to the requests made. Each middleware will execute in the order they were given. |
| 63 | func WithMiddleware(middlewares ...Middleware) RequestOption { |
| 64 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 65 | r.Middlewares = append(r.Middlewares, middlewares...) |
| 66 | return nil |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | // WithMaxRetries returns a RequestOption that sets the maximum number of retries that the client |
| 71 | // attempts to make. When given 0, the client only makes one request. By |
| 72 | // default, the client retries two times. |
| 73 | // |
| 74 | // WithMaxRetries panics when retries is negative. |
| 75 | func WithMaxRetries(retries int) RequestOption { |
| 76 | if retries < 0 { |
| 77 | panic("option: cannot have fewer than 0 retries") |
| 78 | } |
| 79 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 80 | r.MaxRetries = retries |
| 81 | return nil |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | // WithHeader returns a RequestOption that sets the header value to the associated key. It overwrites |
| 86 | // any value if there was one already present. |
| 87 | func WithHeader(key, value string) RequestOption { |
| 88 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 89 | r.Request.Header.Set(key, value) |
| 90 | return nil |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | // WithHeaderAdd returns a RequestOption that adds the header value to the associated key. It appends |
| 95 | // onto any existing values. |
| 96 | func WithHeaderAdd(key, value string) RequestOption { |
| 97 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 98 | r.Request.Header.Add(key, value) |
| 99 | return nil |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | // WithHeaderDel returns a RequestOption that deletes the header value(s) associated with the given key. |
| 104 | func WithHeaderDel(key string) RequestOption { |
| 105 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 106 | r.Request.Header.Del(key) |
| 107 | return nil |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | // WithQuery returns a RequestOption that sets the query value to the associated key. It overwrites |
| 112 | // any value if there was one already present. |
| 113 | func WithQuery(key, value string) RequestOption { |
| 114 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 115 | query := r.Request.URL.Query() |
| 116 | query.Set(key, value) |
| 117 | r.Request.URL.RawQuery = query.Encode() |
| 118 | return nil |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | // WithQueryAdd returns a RequestOption that adds the query value to the associated key. It appends |
| 123 | // onto any existing values. |
| 124 | func WithQueryAdd(key, value string) RequestOption { |
| 125 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 126 | query := r.Request.URL.Query() |
| 127 | query.Add(key, value) |
| 128 | r.Request.URL.RawQuery = query.Encode() |
| 129 | return nil |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | // WithQueryDel returns a RequestOption that deletes the query value(s) associated with the key. |
| 134 | func WithQueryDel(key string) RequestOption { |
| 135 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 136 | query := r.Request.URL.Query() |
| 137 | query.Del(key) |
| 138 | r.Request.URL.RawQuery = query.Encode() |
| 139 | return nil |
| 140 | }) |
| 141 | } |
| 142 | |
| 143 | // WithJSONSet returns a RequestOption that sets the body's JSON value associated with the key. |
| 144 | // The key accepts a string as defined by the [sjson format]. |
| 145 | // |
| 146 | // [sjson format]: https://github.com/tidwall/sjson |
| 147 | func WithJSONSet(key string, value interface{}) RequestOption { |
| 148 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) (err error) { |
| 149 | if buffer, ok := r.Body.(*bytes.Buffer); ok { |
| 150 | b := buffer.Bytes() |
| 151 | b, err = sjson.SetBytes(b, key, value) |
| 152 | if err != nil { |
| 153 | return err |
| 154 | } |
| 155 | r.Body = bytes.NewBuffer(b) |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | return fmt.Errorf("cannot use WithJSONSet on a body that is not serialized as *bytes.Buffer") |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | // WithJSONDel returns a RequestOption that deletes the body's JSON value associated with the key. |
| 164 | // The key accepts a string as defined by the [sjson format]. |
| 165 | // |
| 166 | // [sjson format]: https://github.com/tidwall/sjson |
| 167 | func WithJSONDel(key string) RequestOption { |
| 168 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) (err error) { |
| 169 | if buffer, ok := r.Body.(*bytes.Buffer); ok { |
| 170 | b := buffer.Bytes() |
| 171 | b, err = sjson.DeleteBytes(b, key) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | r.Body = bytes.NewBuffer(b) |
| 176 | return nil |
| 177 | } |
| 178 | |
| 179 | return fmt.Errorf("cannot use WithJSONDel on a body that is not serialized as *bytes.Buffer") |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | // WithResponseBodyInto returns a RequestOption that overwrites the deserialization target with |
| 184 | // the given destination. If provided, we don't deserialize into the default struct. |
| 185 | func WithResponseBodyInto(dst any) RequestOption { |
| 186 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 187 | r.ResponseBodyInto = dst |
| 188 | return nil |
| 189 | }) |
| 190 | } |
| 191 | |
| 192 | // WithResponseInto returns a RequestOption that copies the [*http.Response] into the given address. |
| 193 | func WithResponseInto(dst **http.Response) RequestOption { |
| 194 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 195 | r.ResponseInto = dst |
| 196 | return nil |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | // WithRequestBody returns a RequestOption that provides a custom serialized body with the given |
| 201 | // content type. |
| 202 | // |
| 203 | // body accepts an io.Reader or raw []bytes. |
| 204 | func WithRequestBody(contentType string, body any) RequestOption { |
| 205 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 206 | if reader, ok := body.(io.Reader); ok { |
| 207 | r.Body = reader |
| 208 | return r.Apply(WithHeader("Content-Type", contentType)) |
| 209 | } |
| 210 | |
| 211 | if b, ok := body.([]byte); ok { |
| 212 | r.Body = bytes.NewBuffer(b) |
| 213 | return r.Apply(WithHeader("Content-Type", contentType)) |
| 214 | } |
| 215 | |
| 216 | return fmt.Errorf("body must be a byte slice or implement io.Reader") |
| 217 | }) |
| 218 | } |
| 219 | |
| 220 | // WithRequestTimeout returns a RequestOption that sets the timeout for |
| 221 | // each request attempt. This should be smaller than the timeout defined in |
| 222 | // the context, which spans all retries. |
| 223 | func WithRequestTimeout(dur time.Duration) RequestOption { |
| 224 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 225 | r.RequestTimeout = dur |
| 226 | return nil |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | // WithEnvironmentProduction returns a RequestOption that sets the current |
| 231 | // environment to be the "production" environment. An environment specifies which base URL |
| 232 | // to use by default. |
| 233 | func WithEnvironmentProduction() RequestOption { |
| 234 | return WithBaseURL("https://api.openai.com/v1/") |
| 235 | } |
| 236 | |
| 237 | // WithAPIKey returns a RequestOption that sets the client setting "api_key". |
| 238 | func WithAPIKey(value string) RequestOption { |
| 239 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 240 | r.APIKey = value |
| 241 | return r.Apply(WithHeader("authorization", fmt.Sprintf("Bearer %s", r.APIKey))) |
| 242 | }) |
| 243 | } |
| 244 | |
| 245 | // WithOrganization returns a RequestOption that sets the client setting "organization". |
| 246 | func WithOrganization(value string) RequestOption { |
| 247 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 248 | r.Organization = value |
| 249 | return r.Apply(WithHeader("OpenAI-Organization", value)) |
| 250 | }) |
| 251 | } |
| 252 | |
| 253 | // WithProject returns a RequestOption that sets the client setting "project". |
| 254 | func WithProject(value string) RequestOption { |
| 255 | return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error { |
| 256 | r.Project = value |
| 257 | return r.Apply(WithHeader("OpenAI-Project", value)) |
| 258 | }) |
| 259 | } |
| 260 | |