20 // chatgptURL is the Responses endpoint of the ChatGPT backend.
21 chatgptURL = "https://chatgpt.com/backend-api/codex/responses"
23 // apiURL is the Responses endpoint of the OpenAI API.
24 apiURL = "https://api.openai.com/v1/responses"
26 // quotaPrefix starts the names of the quota headers of the ChatGPT
27 // backend, in canonical form.
28 quotaPrefix = "X-Codex-"
30 // turnStateHeader is an x-codex-* header that holds an opaque state of
31 // the backend, not quota.
32 turnStateHeader = "X-Codex-Turn-State"
34 // errorBytes is the most bytes of an error response that go into the
39 // authorizer adds the credentials of a model call to the headers of its
41 type authorizer interface {
42 Authorize(ctx context.Context, header http.Header) error
45 // apiKey authorizes calls to the OpenAI API with a key.
48 // Client sends model calls to a Responses endpoint for one agent. The ChatGPT
49 // backend and the OpenAI API take the same request body and differ only in the
50 // URL and the credentials. Every call sends the fixed cache key of the agent,
51 // so the turns and the compactions of the agent share one prompt cache. Every
52 // call is recorded in the usage file.
54 // The request never holds max_output_tokens or metadata, because the ChatGPT
55 // backend refuses them. It sets store to false, so the client sends the whole
56 // input on each call, and it asks for the encrypted reasoning, so a later call
57 // can send the reasoning items back.
66 // Request is one model call. Input holds the input items in order, such as
67 // userMessage values or output items of an earlier response.
76 // Tool is the definition of a function tool.
78 Type string `json:"type"`
79 Name string `json:"name"`
80 Description string `json:"description"`
81 Parameters any `json:"parameters"`
82 Strict bool `json:"strict"`
85 // Response is the result of a model call. Output holds the output items as the
86 // endpoint sent them. Text is the text of the message items.
87 type Response struct {
88 Output []json.RawMessage
93 // Usage gives the token counts of a call. Cached is the part of the input
94 // tokens that came from the prompt cache.
101 // requestBody is the JSON body of a call.
102 type requestBody struct {
103 Model string `json:"model"`
104 Instructions string `json:"instructions"`
105 Input []any `json:"input"`
106 Tools []Tool `json:"tools"`
107 Reasoning reasoning `json:"reasoning"`
108 Store bool `json:"store"`
109 Stream bool `json:"stream"`
110 Include []string `json:"include"`
111 PromptCacheKey string `json:"prompt_cache_key"`
114 type reasoning struct {
115 Effort string `json:"effort"`
118 // streamEvent holds the fields of the stream events that the client reads.
119 type streamEvent struct {
120 Type string `json:"type"`
121 Item json.RawMessage `json:"item"`
122 Response *eventResponse `json:"response"`
123 Code string `json:"code"`
124 Message string `json:"message"`
127 type eventResponse struct {
128 Output []json.RawMessage `json:"output"`
129 Usage *wireUsage `json:"usage"`
130 Error *wireError `json:"error"`
131 IncompleteDetails *struct {
132 Reason string `json:"reason"`
133 } `json:"incomplete_details"`
136 type wireUsage struct {
137 InputTokens int `json:"input_tokens"`
138 OutputTokens int `json:"output_tokens"`
139 InputTokensDetails struct {
140 CachedTokens int `json:"cached_tokens"`
141 } `json:"input_tokens_details"`
144 type wireError struct {
145 Code string `json:"code"`
146 Message string `json:"message"`
149 // outputItem holds the fields of an output item that give its text.
150 type outputItem struct {
151 Type string `json:"type"`
153 Type string `json:"type"`
154 Text string `json:"text"`
158 // modelEndpoint returns the URL and the authorizer of the endpoint in config.
159 // The ChatGPT backend uses the token file in dir. The OpenAI API uses the key in
160 // OPENAI_API_KEY, and there is no fallback from one to the other. All clients
161 // share the authorizer, so one refresh runs at a time.
162 func modelEndpoint(config Config, dir string) (string, authorizer, error) {
163 if config.Endpoint == endpointAPI {
164 key := os.Getenv("OPENAI_API_KEY")
166 return "", nil, errors.New("endpoint api needs OPENAI_API_KEY")
169 return apiURL, apiKey(key), nil
172 return chatgptURL, newChatGPTAuth(filepath.Join(dir, tokenFileName), authIssuer), nil
175 // newClient returns a client for the Responses endpoint at url. It records
176 // each call in the usage file at usagePath.
177 func newClient(url string, auth authorizer, cacheKey, usagePath string) *Client {
185 http: &http.Client{},
189 // Create sends the call and reads its event stream to the end.
190 func (c *Client) Create(ctx context.Context, request Request) (Response, error) {
191 body, err := json.Marshal(requestBody{
192 Model: request.Model,
193 Instructions: request.Instructions,
194 Input: request.Input,
195 Tools: request.Tools,
196 Reasoning: reasoning{
197 Effort: request.Effort,
201 Include: []string{"reasoning.encrypted_content"},
202 PromptCacheKey: c.cacheKey,
205 return Response{}, fmt.Errorf("encode request: %w", err)
208 httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
210 return Response{}, fmt.Errorf("create request: %w", err)
213 httpRequest.Header.Set("Content-Type", "application/json")
214 httpRequest.Header.Set("Accept", "text/event-stream")
215 err = c.auth.Authorize(ctx, httpRequest.Header)
217 return Response{}, fmt.Errorf("authorize model call: %w", err)
220 record := usageRecord{
221 Date: time.Now().Format(time.RFC3339Nano),
222 Model: request.Model,
225 response, err := c.send(httpRequest, &record)
227 record.Error = err.Error()
230 record.InputTokens = response.Usage.Input
231 record.CachedTokens = response.Usage.Cached
232 record.OutputTokens = response.Usage.Output
234 return response, errors.Join(err, c.usage.Write(record))
237 // send makes the HTTP call and reads its stream. It puts the status and the
238 // quota headers into record.
239 func (c *Client) send(httpRequest *http.Request, record *usageRecord) (response Response, err error) {
240 httpResponse, err := c.http.Do(httpRequest)
242 return Response{}, fmt.Errorf("send model call: %w", err)
246 err = errors.Join(err, httpResponse.Body.Close())
249 record.Status = httpResponse.StatusCode
250 record.Quota = quotaHeaders(httpResponse.Header)
251 if httpResponse.StatusCode != http.StatusOK {
252 text, readErr := io.ReadAll(io.LimitReader(httpResponse.Body, errorBytes))
253 err = fmt.Errorf("model call: HTTP %d: %s", httpResponse.StatusCode, strings.TrimSpace(string(text)))
255 return Response{}, errors.Join(err, readErr)
258 return readStream(httpResponse.Body)
261 // usageLog appends one JSON line for each model call to usage.jsonl. Calls can
262 // run at once, so a mutex serializes the writes.
263 type usageLog struct {
268 // usageRecord is one line of usage.jsonl. Status is the HTTP status, or 0 when
269 // no response came. Quota holds the x-codex-* headers of the response, without
271 type usageRecord struct {
272 Date string `json:"date"`
273 Model string `json:"model"`
274 Status int `json:"status"`
275 InputTokens int `json:"input_tokens"`
276 CachedTokens int `json:"cached_tokens"`
277 OutputTokens int `json:"output_tokens"`
278 Quota map[string]string `json:"quota,omitempty"`
279 Error string `json:"error,omitempty"`
282 // Write appends record to the file with one write.
283 func (u *usageLog) Write(record usageRecord) (err error) {
284 line, err := json.Marshal(record)
286 return fmt.Errorf("encode usage: %w", err)
290 defer u.mutex.Unlock()
292 file, err := os.OpenFile(u.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
294 return fmt.Errorf("open usage file: %w", err)
298 err = errors.Join(err, file.Close())
301 _, err = file.Write(append(line, '\n'))
303 return fmt.Errorf("write usage: %w", err)
309 // Authorize sets the key as the bearer token.
310 func (k apiKey) Authorize(ctx context.Context, header http.Header) error {
311 header.Set("Authorization", "Bearer "+string(k))
315 // userMessage returns a user input item with one text part for each text.
316 func userMessage(texts ...string) any {
318 Type string `json:"type"`
319 Text string `json:"text"`
322 content := make([]part, len(texts))
323 for n, text := range texts {
331 Role string `json:"role"`
332 Content []part `json:"content"`
339 // quotaHeaders returns the x-codex-* headers, with lowercase names, without the
341 func quotaHeaders(header http.Header) map[string]string {
342 var quota map[string]string
343 for name, values := range header {
344 if !strings.HasPrefix(name, quotaPrefix) || name == turnStateHeader || len(values) == 0 {
349 quota = make(map[string]string)
352 quota[strings.ToLower(name)] = values[0]
358 // readStream reads the server-sent events of a call until the response
359 // completes. The output items come from the output_item.done events, or from
360 // the completed response when the stream sent none.
361 func readStream(stream io.Reader) (Response, error) {
362 var response Response
363 reader := bufio.NewReader(stream)
364 var data bytes.Buffer
366 line, err := reader.ReadBytes('\n')
367 if err != nil && !errors.Is(err, io.EOF) {
368 return response, fmt.Errorf("read event stream: %w", err)
371 line = bytes.TrimRight(line, "\r\n")
373 value, found := bytes.CutPrefix(line, []byte("data:"))
375 data.Write(bytes.TrimPrefix(value, []byte(" ")))
378 } else if data.Len() > 0 {
379 done, eventErr := readEvent(&response, data.Bytes())
381 if eventErr != nil || done {
382 return response, eventErr
386 if errors.Is(err, io.EOF) {
387 return response, errors.New("event stream ended before the response completed")
392 // readEvent adds one stream event to response, and tells if it ends the
394 func readEvent(response *Response, data []byte) (bool, error) {
395 var event streamEvent
396 err := json.Unmarshal(data, &event)
398 return true, fmt.Errorf("decode stream event: %w", err)
402 case "response.output_item.done":
403 response.Output = append(response.Output, event.Item)
404 case "response.completed":
405 if event.Response == nil {
406 return true, errors.New("completed event without a response")
409 if len(response.Output) == 0 {
410 response.Output = event.Response.Output
413 if event.Response.Usage != nil {
414 response.Usage = Usage{
415 Input: event.Response.Usage.InputTokens,
416 Cached: event.Response.Usage.InputTokensDetails.CachedTokens,
417 Output: event.Response.Usage.OutputTokens,
421 response.Text, err = outputText(response.Output)
424 case "response.incomplete":
426 if event.Response != nil && event.Response.IncompleteDetails != nil {
427 reason = event.Response.IncompleteDetails.Reason
430 return true, fmt.Errorf("response incomplete: %s", reason)
431 case "response.failed":
432 message := "no details"
433 if event.Response != nil && event.Response.Error != nil {
434 message = event.Response.Error.Code + ": " + event.Response.Error.Message
437 return true, fmt.Errorf("response failed: %s", message)
439 return true, fmt.Errorf("stream error: %s: %s", event.Code, event.Message)
445 // outputText returns the text of the message items of output.
446 func outputText(output []json.RawMessage) (string, error) {
447 var text strings.Builder
448 for _, raw := range output {
450 err := json.Unmarshal(raw, &item)
452 return "", fmt.Errorf("decode output item: %w", err)
455 if item.Type != "message" {
459 for _, part := range item.Content {
460 if part.Type == "output_text" {
461 text.WriteString(part.Text)
466 return text.String(), nil