X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/1c1771140063b1b4aa5d508ced1b285e773fce04..6755f2645bf6bcf8c7cd5b1f3a682a11bf2392f5:/responses.go diff --git a/responses.go b/responses.go index f887e6d..ebffaa3 100644 --- a/responses.go +++ b/responses.go @@ -10,12 +10,19 @@ import ( "io" "net/http" "os" + "path/filepath" "strings" "sync" "time" ) const ( + // chatgptURL is the Responses endpoint of the ChatGPT backend. + chatgptURL = "https://chatgpt.com/backend-api/codex/responses" + + // apiURL is the Responses endpoint of the OpenAI API. + apiURL = "https://api.openai.com/v1/responses" + // quotaPrefix starts the names of the quota headers of the ChatGPT // backend, in canonical form. quotaPrefix = "X-Codex-" @@ -50,7 +57,6 @@ type Client struct { cacheKey string usage *usageLog http *http.Client - clock func() time.Time } // Request is one model call. Input holds the input items in order, such as @@ -145,6 +151,23 @@ type outputItem struct { } `json:"content"` } +// modelEndpoint returns the URL and the authorizer of the endpoint in config. +// The ChatGPT backend uses the token file in dir. The OpenAI API uses the key in +// OPENAI_API_KEY, and there is no fallback from one to the other. All clients +// share the authorizer, so one refresh runs at a time. +func modelEndpoint(config Config, dir string) (string, authorizer, error) { + if config.Endpoint == endpointAPI { + key := os.Getenv("OPENAI_API_KEY") + if key == "" { + return "", nil, errors.New("endpoint api needs OPENAI_API_KEY") + } + + return apiURL, apiKey(key), nil + } + + return chatgptURL, newChatGPTAuth(filepath.Join(dir, tokenFileName), authIssuer), nil +} + // newClient returns a client for the Responses endpoint at url. It records // each call in the usage file at usagePath. func newClient(url string, auth authorizer, cacheKey, usagePath string) *Client { @@ -155,8 +178,7 @@ func newClient(url string, auth authorizer, cacheKey, usagePath string) *Client usage: &usageLog{ path: usagePath, }, - http: &http.Client{}, - clock: time.Now, + http: &http.Client{}, } } @@ -192,7 +214,7 @@ func (c *Client) Create(ctx context.Context, request Request) (Response, error) } record := usageRecord{ - Date: c.clock().Format(time.RFC3339Nano), + Date: time.Now().Format(time.RFC3339Nano), Model: request.Model, }