]> git.giacomolli.uk - onechat/blob - model.go
Stop a subagent with /stop NAME
[onechat] / model.go
1 package main
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "encoding/json"
8         "errors"
9         "fmt"
10         "io"
11         "net/http"
12         "os"
13         "path/filepath"
14         "strings"
15         "sync"
16         "sync/atomic"
17         "time"
18 )
19
20 const (
21         // modelChatGPTURL is the Responses endpoint of the ChatGPT backend.
22         modelChatGPTURL = "https://chatgpt.com/backend-api/codex/responses"
23
24         // modelAPIURL is the Responses endpoint of the OpenAI API.
25         modelAPIURL = "https://api.openai.com/v1/responses"
26
27         // modelQuotaPrefix starts the names of the quota headers of the ChatGPT
28         // backend, in canonical form.
29         modelQuotaPrefix = "X-Codex-"
30
31         // modelTurnStateHeader is an x-codex-* header that holds an opaque
32         // state of the backend, not quota.
33         modelTurnStateHeader = "X-Codex-Turn-State"
34
35         // modelErrorBytes is the most bytes of an error response that go into
36         // the error.
37         modelErrorBytes = 4096
38 )
39
40 // errModelCallLimit tells that a client sent its limit of calls.
41 var errModelCallLimit = errors.New("call limit reached")
42
43 // modelEndpoint returns the URL and the authorizer of the endpoint in config.
44 // The ChatGPT backend uses the token file in dir. The OpenAI API uses the key in
45 // OPENAI_API_KEY, and there is no fallback from one to the other. All clients
46 // share the authorizer, so one refresh runs at a time.
47 func modelEndpoint(config Config, dir string) (string, ModelAuthorizer, error) {
48         if config.Endpoint == configEndpointAPI {
49                 key := os.Getenv("OPENAI_API_KEY")
50                 if key == "" {
51                         return "", nil, errors.New("endpoint api needs OPENAI_API_KEY")
52                 }
53
54                 return modelAPIURL, ModelAPIKey(key), nil
55         }
56
57         return modelChatGPTURL, newChatGPTAuth(filepath.Join(dir, chatgptTokenFileName), chatgptIssuer), nil
58 }
59
60 // newModelClient returns a client for the Responses endpoint at url. It records
61 // each call in the usage file at usagePath.
62 func newModelClient(url string, auth ModelAuthorizer, cacheKey, usagePath string) *ModelClient {
63         return &ModelClient{
64                 url:      url,
65                 auth:     auth,
66                 cacheKey: cacheKey,
67                 usage: &ModelUsageLog{
68                         path: usagePath,
69                 },
70                 http: &http.Client{},
71         }
72 }
73
74 // modelUserMessage returns a user input item with one text part for each text.
75 func modelUserMessage(texts ...string) any {
76         type part struct {
77                 Type string `json:"type"`
78                 Text string `json:"text"`
79         }
80
81         content := make([]part, len(texts))
82         for n, text := range texts {
83                 content[n] = part{
84                         Type: "input_text",
85                         Text: text,
86                 }
87         }
88
89         return struct {
90                 Role    string `json:"role"`
91                 Content []part `json:"content"`
92         }{
93                 Role:    "user",
94                 Content: content,
95         }
96 }
97
98 // modelOutputText returns the text of the message items of output.
99 func modelOutputText(output []json.RawMessage) (string, error) {
100         var text strings.Builder
101         for _, raw := range output {
102                 var item ModelOutputItem
103                 err := json.Unmarshal(raw, &item)
104                 if err != nil {
105                         return "", fmt.Errorf("decode output item: %w", err)
106                 }
107
108                 if item.Type != "message" {
109                         continue
110                 }
111
112                 for _, part := range item.Content {
113                         if part.Type == "output_text" {
114                                 text.WriteString(part.Text)
115                         }
116                 }
117         }
118
119         return text.String(), nil
120 }
121
122 // ModelAuthorizer adds the credentials of a model call to the headers of its
123 // request.
124 type ModelAuthorizer interface {
125         Authorize(ctx context.Context, header http.Header) error
126 }
127
128 // ModelAPIKey authorizes calls to the OpenAI API with a key.
129 type ModelAPIKey string
130
131 // Authorize sets the key as the bearer token.
132 func (k ModelAPIKey) Authorize(ctx context.Context, header http.Header) error {
133         header.Set("Authorization", "Bearer "+string(k))
134         return ctx.Err()
135 }
136
137 // ModelClient sends model calls to a Responses endpoint for one agent. The
138 // ChatGPT backend and the OpenAI API take the same request body and differ only
139 // in the URL and the credentials. Every call sends the fixed cache key of the
140 // agent, so the turns and the compactions of the agent share one prompt cache.
141 // The ChatGPT backend caches only with the key in the session_id header, so a
142 // call to it sends the key there and in the body. Every call is recorded in the
143 // usage file.
144 //
145 // The request never holds max_output_tokens or metadata, because the ChatGPT
146 // backend refuses them. It sets store to false, so the client sends the whole
147 // input on each call, and it asks for the encrypted reasoning, so a later call
148 // can send the reasoning items back.
149 type ModelClient struct {
150         url      string
151         auth     ModelAuthorizer
152         cacheKey string
153         usage    *ModelUsageLog
154         http     *http.Client
155         limit    int64
156         calls    atomic.Int64
157 }
158
159 // LimitCalls makes the client refuse each call after the first limit calls.
160 func (c *ModelClient) LimitCalls(limit int64) {
161         c.limit = limit
162 }
163
164 // LimitReached tells if the client refuses further calls.
165 func (c *ModelClient) LimitReached() bool {
166         return c.limit > 0 && c.calls.Load() >= c.limit
167 }
168
169 // Create sends the call and reads its event stream to the end. Over the call
170 // limit it sends nothing and returns errModelCallLimit.
171 func (c *ModelClient) Create(ctx context.Context, request ModelRequest) (ModelResponse, error) {
172         if c.calls.Add(1) > c.limit && c.limit > 0 {
173                 return ModelResponse{}, errModelCallLimit
174         }
175
176         body, err := json.Marshal(ModelRequestBody{
177                 Model:        request.Model,
178                 Instructions: request.Instructions,
179                 Input:        request.Input,
180                 Tools:        request.Tools,
181                 Reasoning: ModelReasoning{
182                         Effort: request.Effort,
183                 },
184                 Store:          false,
185                 Stream:         true,
186                 Include:        []string{"reasoning.encrypted_content"},
187                 PromptCacheKey: c.cacheKey,
188         })
189         if err != nil {
190                 return ModelResponse{}, fmt.Errorf("encode request: %w", err)
191         }
192
193         httpRequest, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
194         if err != nil {
195                 return ModelResponse{}, fmt.Errorf("create request: %w", err)
196         }
197
198         httpRequest.Header.Set("Content-Type", "application/json")
199         httpRequest.Header.Set("Accept", "text/event-stream")
200         err = c.auth.Authorize(ctx, httpRequest.Header)
201         if err != nil {
202                 return ModelResponse{}, fmt.Errorf("authorize model call: %w", err)
203         }
204
205         _, chatgpt := c.auth.(*ChatGPTAuth)
206         if chatgpt {
207                 httpRequest.Header.Set("session_id", c.cacheKey)
208         }
209
210         start := time.Now()
211         record := ModelUsageRecord{
212                 Date:  start.Format(time.RFC3339Nano),
213                 Model: request.Model,
214         }
215
216         if request.Node != nil {
217                 record.Node = &[2]int{request.Node.level, request.Node.index}
218         }
219
220         record.Turn = request.Turn
221         record.Agent = request.Agent
222         response, err := c.send(httpRequest, &record)
223         if err != nil {
224                 record.Error = err.Error()
225         }
226
227         record.Seconds = time.Since(start).Seconds()
228         record.InputTokens = response.Usage.Input
229         record.CachedTokens = response.Usage.Cached
230         record.OutputTokens = response.Usage.Output
231         record.TextBytes = len(response.Text)
232
233         return response, errors.Join(err, c.usage.Write(record))
234 }
235
236 // send makes the HTTP call and reads its stream. It puts the status and the
237 // quota headers into record.
238 func (c *ModelClient) send(httpRequest *http.Request, record *ModelUsageRecord) (response ModelResponse, err error) {
239         httpResponse, err := c.http.Do(httpRequest)
240         if err != nil {
241                 return ModelResponse{}, fmt.Errorf("send model call: %w", err)
242         }
243
244         defer func() {
245                 err = errors.Join(err, httpResponse.Body.Close())
246         }()
247
248         record.Status = httpResponse.StatusCode
249         record.Quota = modelQuotaHeaders(httpResponse.Header)
250         if httpResponse.StatusCode != http.StatusOK {
251                 text, readErr := io.ReadAll(io.LimitReader(httpResponse.Body, modelErrorBytes))
252                 err = fmt.Errorf("model call: HTTP %d: %s", httpResponse.StatusCode, strings.TrimSpace(string(text)))
253
254                 return ModelResponse{}, errors.Join(err, readErr)
255         }
256
257         return modelReadStream(httpResponse.Body)
258 }
259
260 // ModelUsageLog appends one JSON line for each model call to usage.jsonl. Calls
261 // can run at once, so a mutex serializes the writes.
262 type ModelUsageLog struct {
263         mutex sync.Mutex
264         path  string
265 }
266
267 // Write appends record to the file with one write.
268 func (u *ModelUsageLog) Write(record ModelUsageRecord) (err error) {
269         line, err := json.Marshal(record)
270         if err != nil {
271                 return fmt.Errorf("encode usage: %w", err)
272         }
273
274         u.mutex.Lock()
275         defer u.mutex.Unlock()
276
277         file, err := os.OpenFile(u.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
278         if err != nil {
279                 return fmt.Errorf("open usage file: %w", err)
280         }
281
282         defer func() {
283                 err = errors.Join(err, file.Close())
284         }()
285
286         _, err = file.Write(append(line, '\n'))
287         if err != nil {
288                 return fmt.Errorf("write usage: %w", err)
289         }
290
291         return nil
292 }
293
294 // ModelOutputItem holds the fields of an output item that give its text.
295 type ModelOutputItem struct {
296         Type    string `json:"type"`
297         Content []struct {
298                 Type string `json:"type"`
299                 Text string `json:"text"`
300         } `json:"content"`
301 }
302
303 // ModelRequest is one model call. Input holds the input items in order, such as
304 // modelUserMessage values or output items of an earlier response. Node names
305 // the node that a compaction builds, or is nil. Turn names the request of a
306 // turn: first or next. Agent names the subagent that makes the call, or is
307 // empty for a call of the agent itself. Node, Turn, and Agent go only to the
308 // usage file, never to the endpoint.
309 type ModelRequest struct {
310         Model        string
311         Effort       string
312         Instructions string
313         Tools        []ModelTool
314         Input        []any
315         Node         *NodeKey
316         Turn         string
317         Agent        string
318 }
319
320 // ModelResponse is the result of a model call. Output holds the output items as
321 // the endpoint sent them. Text is the text of the message items.
322 type ModelResponse struct {
323         Output []json.RawMessage
324         Text   string
325         Usage  ModelUsage
326 }
327
328 // ModelRequestBody is the JSON body of a call.
329 type ModelRequestBody struct {
330         Model          string         `json:"model"`
331         Instructions   string         `json:"instructions"`
332         Input          []any          `json:"input"`
333         Tools          []ModelTool    `json:"tools"`
334         Reasoning      ModelReasoning `json:"reasoning"`
335         Store          bool           `json:"store"`
336         Stream         bool           `json:"stream"`
337         Include        []string       `json:"include"`
338         PromptCacheKey string         `json:"prompt_cache_key"`
339 }
340
341 type ModelReasoning struct {
342         Effort string `json:"effort"`
343 }
344
345 // ModelUsageRecord is one line of usage.jsonl. Date is the start of the call,
346 // and Seconds its length. Node is the node [l, i] of a compaction. Status is
347 // the HTTP status, or 0 when no response came. TextBytes is the size of the
348 // text of the reply. Turn names the request of a turn. Agent names the subagent
349 // of the call. Quota holds the x-codex-* headers of the response, without the
350 // turn state.
351 type ModelUsageRecord struct {
352         Date         string            `json:"date"`
353         Seconds      float64           `json:"seconds"`
354         Model        string            `json:"model"`
355         Node         *[2]int           `json:"node,omitempty"`
356         Turn         string            `json:"turn,omitempty"`
357         Agent        string            `json:"agent,omitempty"`
358         Status       int               `json:"status"`
359         InputTokens  int               `json:"input_tokens"`
360         CachedTokens int               `json:"cached_tokens"`
361         OutputTokens int               `json:"output_tokens"`
362         TextBytes    int               `json:"text_bytes"`
363         Quota        map[string]string `json:"quota,omitempty"`
364         Error        string            `json:"error,omitempty"`
365 }
366
367 // ModelTool is the definition of a function tool.
368 type ModelTool struct {
369         Type        string `json:"type"`
370         Name        string `json:"name"`
371         Description string `json:"description"`
372         Parameters  any    `json:"parameters"`
373         Strict      bool   `json:"strict"`
374 }
375
376 // ModelUsage gives the token counts of a call. Cached is the part of the input
377 // tokens that came from the prompt cache.
378 type ModelUsage struct {
379         Input  int
380         Cached int
381         Output int
382 }
383
384 // ModelStreamEvent holds the fields of the stream events that the client reads.
385 type ModelStreamEvent struct {
386         Type     string              `json:"type"`
387         Item     json.RawMessage     `json:"item"`
388         Response *ModelEventResponse `json:"response"`
389         Code     string              `json:"code"`
390         Message  string              `json:"message"`
391 }
392
393 type ModelEventResponse struct {
394         Output            []json.RawMessage `json:"output"`
395         Usage             *ModelWireUsage   `json:"usage"`
396         Error             *ModelWireError   `json:"error"`
397         IncompleteDetails *struct {
398                 Reason string `json:"reason"`
399         } `json:"incomplete_details"`
400 }
401
402 type ModelWireUsage struct {
403         InputTokens        int `json:"input_tokens"`
404         OutputTokens       int `json:"output_tokens"`
405         InputTokensDetails struct {
406                 CachedTokens int `json:"cached_tokens"`
407         } `json:"input_tokens_details"`
408 }
409
410 type ModelWireError struct {
411         Code    string `json:"code"`
412         Message string `json:"message"`
413 }
414
415 // modelQuotaHeaders returns the x-codex-* headers, with lowercase names,
416 // without the turn state.
417 func modelQuotaHeaders(header http.Header) map[string]string {
418         var quota map[string]string
419         for name, values := range header {
420                 if !strings.HasPrefix(name, modelQuotaPrefix) || name == modelTurnStateHeader || len(values) == 0 {
421                         continue
422                 }
423
424                 if quota == nil {
425                         quota = make(map[string]string)
426                 }
427
428                 quota[strings.ToLower(name)] = values[0]
429         }
430
431         return quota
432 }
433
434 // modelReadStream reads the server-sent events of a call until the response
435 // completes. The output items come from the output_item.done events, or from
436 // the completed response when the stream sent none.
437 func modelReadStream(stream io.Reader) (ModelResponse, error) {
438         var response ModelResponse
439         reader := bufio.NewReader(stream)
440         var data bytes.Buffer
441         for {
442                 line, err := reader.ReadBytes('\n')
443                 if err != nil && !errors.Is(err, io.EOF) {
444                         return response, fmt.Errorf("read event stream: %w", err)
445                 }
446
447                 line = bytes.TrimRight(line, "\r\n")
448                 if len(line) > 0 {
449                         value, found := bytes.CutPrefix(line, []byte("data:"))
450                         if found {
451                                 data.Write(bytes.TrimPrefix(value, []byte(" ")))
452                                 data.WriteByte('\n')
453                         }
454                 } else if data.Len() > 0 {
455                         done, eventErr := modelReadEvent(&response, data.Bytes())
456                         data.Reset()
457                         if eventErr != nil || done {
458                                 return response, eventErr
459                         }
460                 }
461
462                 if errors.Is(err, io.EOF) {
463                         return response, errors.New("event stream ended before the response completed")
464                 }
465         }
466 }
467
468 // modelReadEvent adds one stream event to response, and tells if it ends the
469 // stream.
470 func modelReadEvent(response *ModelResponse, data []byte) (bool, error) {
471         var event ModelStreamEvent
472         err := json.Unmarshal(data, &event)
473         if err != nil {
474                 return true, fmt.Errorf("decode stream event: %w", err)
475         }
476
477         switch event.Type {
478         case "response.output_item.done":
479                 response.Output = append(response.Output, event.Item)
480         case "response.completed":
481                 if event.Response == nil {
482                         return true, errors.New("completed event without a response")
483                 }
484
485                 if len(response.Output) == 0 {
486                         response.Output = event.Response.Output
487                 }
488
489                 if event.Response.Usage != nil {
490                         response.Usage = ModelUsage{
491                                 Input:  event.Response.Usage.InputTokens,
492                                 Cached: event.Response.Usage.InputTokensDetails.CachedTokens,
493                                 Output: event.Response.Usage.OutputTokens,
494                         }
495                 }
496
497                 response.Text, err = modelOutputText(response.Output)
498
499                 return true, err
500         case "response.incomplete":
501                 reason := "unknown"
502                 if event.Response != nil && event.Response.IncompleteDetails != nil {
503                         reason = event.Response.IncompleteDetails.Reason
504                 }
505
506                 return true, fmt.Errorf("response incomplete: %s", reason)
507         case "response.failed":
508                 message := "no details"
509                 if event.Response != nil && event.Response.Error != nil {
510                         message = event.Response.Error.Code + ": " + event.Response.Error.Message
511                 }
512
513                 return true, fmt.Errorf("response failed: %s", message)
514         case "error":
515                 return true, fmt.Errorf("stream error: %s: %s", event.Code, event.Message)
516         }
517
518         return false, nil
519 }