client.go

  1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2
  3package openai
  4
  5import (
  6	"context"
  7	"net/http"
  8	"os"
  9
 10	"github.com/openai/openai-go/internal/requestconfig"
 11	"github.com/openai/openai-go/option"
 12	"github.com/openai/openai-go/responses"
 13	"github.com/openai/openai-go/webhooks"
 14)
 15
 16// Client creates a struct with services and top level methods that help with
 17// interacting with the openai API. You should not instantiate this client
 18// directly, and instead use the [NewClient] method instead.
 19type Client struct {
 20	Options      []option.RequestOption
 21	Completions  CompletionService
 22	Chat         ChatService
 23	Embeddings   EmbeddingService
 24	Files        FileService
 25	Images       ImageService
 26	Audio        AudioService
 27	Moderations  ModerationService
 28	Models       ModelService
 29	FineTuning   FineTuningService
 30	Graders      GraderService
 31	VectorStores VectorStoreService
 32	Webhooks     webhooks.WebhookService
 33	Beta         BetaService
 34	Batches      BatchService
 35	Uploads      UploadService
 36	Responses    responses.ResponseService
 37	Containers   ContainerService
 38}
 39
 40// DefaultClientOptions read from the environment (OPENAI_API_KEY, OPENAI_ORG_ID,
 41// OPENAI_PROJECT_ID, OPENAI_WEBHOOK_SECRET, OPENAI_BASE_URL). This should be used
 42// to initialize new clients.
 43func DefaultClientOptions() []option.RequestOption {
 44	defaults := []option.RequestOption{option.WithEnvironmentProduction()}
 45	if o, ok := os.LookupEnv("OPENAI_BASE_URL"); ok {
 46		defaults = append(defaults, option.WithBaseURL(o))
 47	}
 48	if o, ok := os.LookupEnv("OPENAI_API_KEY"); ok {
 49		defaults = append(defaults, option.WithAPIKey(o))
 50	}
 51	if o, ok := os.LookupEnv("OPENAI_ORG_ID"); ok {
 52		defaults = append(defaults, option.WithOrganization(o))
 53	}
 54	if o, ok := os.LookupEnv("OPENAI_PROJECT_ID"); ok {
 55		defaults = append(defaults, option.WithProject(o))
 56	}
 57	if o, ok := os.LookupEnv("OPENAI_WEBHOOK_SECRET"); ok {
 58		defaults = append(defaults, option.WithWebhookSecret(o))
 59	}
 60	return defaults
 61}
 62
 63// NewClient generates a new client with the default option read from the
 64// environment (OPENAI_API_KEY, OPENAI_ORG_ID, OPENAI_PROJECT_ID,
 65// OPENAI_WEBHOOK_SECRET, OPENAI_BASE_URL). The option passed in as arguments are
 66// applied after these default arguments, and all option will be passed down to the
 67// services and requests that this client makes.
 68func NewClient(opts ...option.RequestOption) (r Client) {
 69	opts = append(DefaultClientOptions(), opts...)
 70
 71	r = Client{Options: opts}
 72
 73	r.Completions = NewCompletionService(opts...)
 74	r.Chat = NewChatService(opts...)
 75	r.Embeddings = NewEmbeddingService(opts...)
 76	r.Files = NewFileService(opts...)
 77	r.Images = NewImageService(opts...)
 78	r.Audio = NewAudioService(opts...)
 79	r.Moderations = NewModerationService(opts...)
 80	r.Models = NewModelService(opts...)
 81	r.FineTuning = NewFineTuningService(opts...)
 82	r.Graders = NewGraderService(opts...)
 83	r.VectorStores = NewVectorStoreService(opts...)
 84	r.Webhooks = webhooks.NewWebhookService(opts...)
 85	r.Beta = NewBetaService(opts...)
 86	r.Batches = NewBatchService(opts...)
 87	r.Uploads = NewUploadService(opts...)
 88	r.Responses = responses.NewResponseService(opts...)
 89	r.Containers = NewContainerService(opts...)
 90
 91	return
 92}
 93
 94// Execute makes a request with the given context, method, URL, request params,
 95// response, and request options. This is useful for hitting undocumented endpoints
 96// while retaining the base URL, auth, retries, and other options from the client.
 97//
 98// If a byte slice or an [io.Reader] is supplied to params, it will be used as-is
 99// for the request body.
100//
101// The params is by default serialized into the body using [encoding/json]. If your
102// type implements a MarshalJSON function, it will be used instead to serialize the
103// request. If a URLQuery method is implemented, the returned [url.Values] will be
104// used as query strings to the url.
105//
106// If your params struct uses [param.Field], you must provide either [MarshalJSON],
107// [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a
108// struct uses [param.Field] without specifying how it is serialized.
109//
110// Any "…Params" object defined in this library can be used as the request
111// argument. Note that 'path' arguments will not be forwarded into the url.
112//
113// The response body will be deserialized into the res variable, depending on its
114// type:
115//
116//   - A pointer to a [*http.Response] is populated by the raw response.
117//   - A pointer to a byte array will be populated with the contents of the request
118//     body.
119//   - A pointer to any other type uses this library's default JSON decoding, which
120//     respects UnmarshalJSON if it is defined on the type.
121//   - A nil value will not read the response body.
122//
123// For even greater flexibility, see [option.WithResponseInto] and
124// [option.WithResponseBodyInto].
125func (r *Client) Execute(ctx context.Context, method string, path string, params any, res any, opts ...option.RequestOption) error {
126	opts = append(r.Options, opts...)
127	return requestconfig.ExecuteNewRequest(ctx, method, path, params, res, opts...)
128}
129
130// Get makes a GET request with the given URL, params, and optionally deserializes
131// to a response. See [Execute] documentation on the params and response.
132func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error {
133	return r.Execute(ctx, http.MethodGet, path, params, res, opts...)
134}
135
136// Post makes a POST request with the given URL, params, and optionally
137// deserializes to a response. See [Execute] documentation on the params and
138// response.
139func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error {
140	return r.Execute(ctx, http.MethodPost, path, params, res, opts...)
141}
142
143// Put makes a PUT request with the given URL, params, and optionally deserializes
144// to a response. See [Execute] documentation on the params and response.
145func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error {
146	return r.Execute(ctx, http.MethodPut, path, params, res, opts...)
147}
148
149// Patch makes a PATCH request with the given URL, params, and optionally
150// deserializes to a response. See [Execute] documentation on the params and
151// response.
152func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error {
153	return r.Execute(ctx, http.MethodPatch, path, params, res, opts...)
154}
155
156// Delete makes a DELETE request with the given URL, params, and optionally
157// deserializes to a response. See [Execute] documentation on the params and
158// response.
159func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error {
160	return r.Execute(ctx, http.MethodDelete, path, params, res, opts...)
161}