v0.2.14 63e33d9

openai.go RawHistoryFolder

1package provider
2
3import (
4	"bytes"
5	"context"
6	"encoding/base64"
7	"encoding/json"
8	"fmt"
9	"io"
10	"net/http"
11	"strings"
12	"time"
13)
14
15const openaiDefaultBaseURL = "https://api.openai.com"
16
17type openaiClient struct {
18	apiKey  string
19	baseURL string
20	name    string
21	oauth   bool // when true, apiKey actually holds an OAuth access token
22	headers map[string]string
23	http    *http.Client
24}
25
26// NewOpenAI creates an OpenAI client using an API key. baseURL may be empty.
27func NewOpenAI(apiKey, baseURL string) Client {
28	if baseURL == "" {
29		baseURL = openaiDefaultBaseURL
30	}
31	return &openaiClient{
32		apiKey:  apiKey,
33		baseURL: strings.TrimRight(baseURL, "/"),
34		name:    "openai",
35		http:    &http.Client{Timeout: 0},
36	}
37}
38
39// NewOpenAIOAuth creates an OpenAI client using a subscription OAuth access token.
40// The token is sent as an HTTP Bearer credential on the standard chat/completions endpoint.
41func NewOpenAIOAuth(accessToken, baseURL string) Client {
42	if baseURL == "" {
43		baseURL = openaiDefaultBaseURL
44	}
45	return &openaiClient{
46		apiKey:  accessToken,
47		baseURL: strings.TrimRight(baseURL, "/"),
48		name:    "openai",
49		oauth:   true,
50		http:    &http.Client{Timeout: 0},
51	}
52}
53
54// NewKimi creates a Kimi/Moonshot client. Kimi's chat API is OpenAI-compatible.
55func NewKimi(apiKey, baseURL string) Client {
56	return NewKimiWithHeaders(apiKey, baseURL, nil)
57}
58
59// NewDeepSeek creates a DeepSeek client. DeepSeek's chat API is
60// OpenAI-compatible at https://api.deepseek.com/v1.
61func NewDeepSeek(apiKey, baseURL string) Client {
62	if baseURL == "" {
63		baseURL = "https://api.deepseek.com/v1"
64	}
65	return &openaiClient{
66		apiKey:  apiKey,
67		baseURL: strings.TrimRight(baseURL, "/"),
68		name:    "deepseek",
69		http:    &http.Client{Timeout: 0},
70	}
71}
72
73// NewKimiWithHeaders creates a Kimi/Moonshot client with extra headers.
74// Subscription tokens from Kimi Code need the official CLI's X-Msh-* headers.
75func NewKimiWithHeaders(apiKey, baseURL string, headers map[string]string) Client {
76	if baseURL == "" {
77		baseURL = "https://api.kimi.com/coding/v1"
78	}
79	return &openaiClient{
80		apiKey:  apiKey,
81		baseURL: strings.TrimRight(baseURL, "/"),
82		name:    "kimi",
83		headers: headers,
84		http:    &http.Client{Timeout: 0},
85	}
86}
87
88func (c *openaiClient) Name() string {
89	if c.name != "" {
90		return c.name
91	}
92	return "openai"
93}
94
95// ---- wire types ----
96
97type oaiContentText struct {
98	Type string `json:"type"` // "text"
99	Text string `json:"text"`
100}
101
102type oaiContentImage struct {
103	Type     string `json:"type"` // "image_url"
104	ImageURL struct {
105		URL string `json:"url"`
106	} `json:"image_url"`
107}
108
109type oaiToolCallFn struct {
110	Name      string `json:"name"`
111	Arguments string `json:"arguments"` // JSON string
112}
113
114type oaiToolCall struct {
115	ID       string        `json:"id"`
116	Type     string        `json:"type"` // "function"
117	Function oaiToolCallFn `json:"function"`
118}
119
120type oaiMessage struct {
121	Role       string        `json:"role"`
122	Content    interface{}   `json:"content,omitempty"` // string or []block
123	Name       string        `json:"name,omitempty"`
124	ToolCalls  []oaiToolCall `json:"tool_calls,omitempty"`
125	ToolCallID string        `json:"tool_call_id,omitempty"`
126	// ReasoningContent carries the model's chain-of-thought summary
127	// alongside an assistant tool-call message. Required by Kimi's
128	// chat completions endpoint when thinking is enabled and the
129	// assistant message contains a tool call; OpenAI ignores it.
130	ReasoningContent string `json:"reasoning_content,omitempty"`
131}
132
133type oaiTool struct {
134	Type     string `json:"type"` // "function"
135	Function struct {
136		Name        string          `json:"name"`
137		Description string          `json:"description,omitempty"`
138		Parameters  json.RawMessage `json:"parameters"`
139	} `json:"function"`
140}
141
142type oaiStreamOptions struct {
143	IncludeUsage bool `json:"include_usage"`
144}
145
146type oaiRequest struct {
147	Model            string            `json:"model"`
148	Messages         []oaiMessage      `json:"messages"`
149	Tools            []oaiTool         `json:"tools,omitempty"`
150	ToolChoice       string            `json:"tool_choice,omitempty"`
151	Stream           bool              `json:"stream"`
152	StreamOptions    *oaiStreamOptions `json:"stream_options,omitempty"`
153	Temperature      *float32          `json:"temperature,omitempty"`
154	MaxTokens        *int              `json:"max_tokens,omitempty"`
155	MaxCompletionTok *int              `json:"max_completion_tokens,omitempty"`
156	ReasoningEffort  string            `json:"reasoning_effort,omitempty"`
157}
158
159// ---- request building ----
160
161func (c *openaiClient) buildRequest(req Request) (*oaiRequest, error) {
162	// Look up the model by id across all providers (not just openai)
163	// because the OpenAI client is also used for ollama and other
164	// OpenAI-compatible backends.
165	m, err := FindModel("", req.Model)
166	if err != nil {
167		// Unknown model: use sensible defaults so local/custom
168		// models still work without a catalog entry.
169		m = Model{
170			ID:            req.Model,
171			ContextWindow: 32768,
172			MaxOutput:     8192,
173		}
174	}
175	out := &oaiRequest{
176		Model:         req.Model,
177		Stream:        true,
178		StreamOptions: &oaiStreamOptions{IncludeUsage: true},
179		Temperature:   req.Temperature,
180	}
181
182	maxTok := req.MaxTokens
183	if maxTok <= 0 {
184		maxTok = m.MaxOutput
185	}
186	if m.Reasoning {
187		out.MaxCompletionTok = &maxTok
188		effort := OpenAIReasoningEffort(req.Reasoning)
189		if usesAdaptiveThinking(m) {
190			// Some gateways expose adaptive-thinking Anthropic models through
191			// the OpenAI-compatible chat-completions wire. They accept the
192			// same reasoning_effort knob, including the top "xhigh" tier;
193			// don't clamp zot's "maximum" to "high" for those models.
194			effort = OpenAICompatAnthropicEffort(req.Reasoning)
195		}
196		if effort != "" {
197			out.ReasoningEffort = effort
198		}
199	} else {
200		out.MaxTokens = &maxTok
201	}
202
203	if req.System != "" {
204		out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
205	}
206
207	// DeepSeek's chat-completions API rejects the multimodal content
208	// schema (parts arrays containing image_url). Force every user/tool
209	// message to a plain string and silently drop image blocks for
210	// this provider so historical sessions with screenshots still replay.
211	textOnly := c.name == "deepseek"
212
213	req.Messages = RepairOrphanedToolResults(req.Messages)
214	for _, msg := range req.Messages {
215		switch msg.Role {
216		case RoleUser:
217			content := buildOAIUserContent(msg.Content, textOnly)
218			out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
219		case RoleAssistant:
220			am := oaiMessage{Role: "assistant"}
221			var text strings.Builder
222			var reasoning strings.Builder
223			for _, b := range msg.Content {
224				switch v := b.(type) {
225				case TextBlock:
226					if strings.TrimSpace(v.Text) == "" {
227						continue
228					}
229					if text.Len() > 0 {
230						text.WriteString("\n")
231					}
232					text.WriteString(v.Text)
233				case ToolCallBlock:
234					args := v.Arguments
235					if len(args) == 0 || !json.Valid(args) {
236						args = json.RawMessage("{}")
237					}
238					am.ToolCalls = append(am.ToolCalls, oaiToolCall{
239						ID:   v.ID,
240						Type: "function",
241						Function: oaiToolCallFn{
242							Name:      v.Name,
243							Arguments: string(args),
244						},
245					})
246				case ReasoningBlock:
247					if v.Summary != "" {
248						if reasoning.Len() > 0 {
249							reasoning.WriteString("\n")
250						}
251						reasoning.WriteString(v.Summary)
252					}
253				}
254			}
255			if text.Len() > 0 {
256				am.Content = text.String()
257			}
258			if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
259				am.ReasoningContent = reasoning.String()
260			}
261			// Kimi rejects assistant messages with neither visible text nor
262			// tool calls ("assistant must not be empty"). This can happen when
263			// a previous stream produced only reasoning_content, which zot keeps
264			// internally for provider replay but cannot send back as standalone
265			// assistant content on OpenAI-compatible chat-completions APIs.
266			if am.Content == nil && len(am.ToolCalls) == 0 {
267				continue
268			}
269			out.Messages = append(out.Messages, am)
270		case RoleTool:
271			// Each ToolResultBlock becomes its own tool message. Preserve
272			// image blocks for vision-capable OpenAI models instead of
273			// flattening the tool output to plain text.
274			for _, b := range msg.Content {
275				if tr, ok := b.(ToolResultBlock); ok {
276					content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
277					out.Messages = append(out.Messages, oaiMessage{
278						Role:       "tool",
279						ToolCallID: tr.CallID,
280						Content:    content,
281					})
282				}
283			}
284		}
285	}
286
287	for _, t := range req.Tools {
288		var tool oaiTool
289		tool.Type = "function"
290		tool.Function.Name = t.Name
291		tool.Function.Description = t.Description
292		tool.Function.Parameters = t.Schema
293		out.Tools = append(out.Tools, tool)
294	}
295	if len(out.Tools) > 0 {
296		out.ToolChoice = "auto"
297	}
298
299	return out, nil
300}
301
302func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
303	hasImage := false
304	for _, b := range blocks {
305		if _, ok := b.(ImageBlock); ok {
306			hasImage = true
307			break
308		}
309	}
310	if textOnly || !hasImage {
311		var sb strings.Builder
312		for _, b := range blocks {
313			if tb, ok := b.(TextBlock); ok {
314				if sb.Len() > 0 {
315					sb.WriteString("\n")
316				}
317				sb.WriteString(tb.Text)
318			}
319		}
320		return sb.String()
321	}
322	return buildOAIContentBlocks(blocks, false)
323}
324
325func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
326	hasImage := false
327	for _, b := range blocks {
328		if _, ok := b.(ImageBlock); ok {
329			hasImage = true
330			break
331		}
332	}
333	if textOnly || !hasImage {
334		var sb strings.Builder
335		for _, b := range blocks {
336			if tb, ok := b.(TextBlock); ok {
337				if sb.Len() > 0 {
338					sb.WriteString("\n")
339				}
340				sb.WriteString(tb.Text)
341			}
342		}
343		if isError && sb.Len() > 0 {
344			sb.WriteString(" [error]")
345		}
346		return sb.String()
347	}
348	return buildOAIContentBlocks(blocks, isError)
349}
350
351func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
352	var arr []interface{}
353	for _, b := range blocks {
354		switch v := b.(type) {
355		case TextBlock:
356			arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
357		case ImageBlock:
358			var img oaiContentImage
359			img.Type = "image_url"
360			img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
361			arr = append(arr, img)
362		}
363	}
364	if isError {
365		arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
366	}
367	return arr
368}
369
370// ---- streaming ----
371
372func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
373	apiPath := "/v1/chat/completions"
374	if strings.HasSuffix(c.baseURL, "/v1") {
375		apiPath = "/chat/completions"
376	}
377	wire, err := c.buildRequest(req)
378	if err != nil {
379		return nil, err
380	}
381	body, err := json.Marshal(wire)
382	if err != nil {
383		return nil, err
384	}
385	newReq := func() (*http.Request, error) {
386		httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+apiPath, bytes.NewReader(body))
387		if err != nil {
388			return nil, err
389		}
390		httpReq.Header.Set("content-type", "application/json")
391		httpReq.Header.Set("accept", "text/event-stream")
392		httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
393		for k, v := range c.headers {
394			httpReq.Header.Set(k, v)
395		}
396		return httpReq, nil
397	}
398
399	resp, err := doStreamWithRetry(ctx, c.http, newReq)
400	if err != nil {
401		return nil, fmt.Errorf("%s: %w", c.Name(), err)
402	}
403	if resp.StatusCode != http.StatusOK {
404		b, _ := io.ReadAll(resp.Body)
405		resp.Body.Close()
406		return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
407	}
408
409	out := make(chan Event, 16)
410	go c.runStream(ctx, resp, req, out)
411	return out, nil
412}
413
414func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
415	defer close(out)
416	defer resp.Body.Close()
417
418	model, _ := FindModel("", req.Model)
419	out <- EventStart{Model: req.Model, Provider: c.Name()}
420
421	raw := make(chan sseEvent, 16)
422	go readSSE(resp.Body, raw)
423
424	// Interleaved block tracking: text and tool_calls preserve their
425	// emission order so the assistant message renders in the same order
426	// the model produced it. The builder fires one kind of block at a
427	// time — incoming text deltas after a tool_call split into a fresh
428	// text block; subsequent tool_calls each get their own slot.
429	type blockEntry struct {
430		kind      string // "text" | "tool_use"
431		textBuf   strings.Builder
432		toolID    string
433		toolName  string
434		toolArgs  strings.Builder
435		announced bool
436	}
437	var (
438		blocks       []*blockEntry
439		currentText  *blockEntry             // most-recent text block, nil if none
440		toolByIdx    = map[int]*blockEntry{} // openai tool_call index -> block
441		reasoningBuf strings.Builder
442		usage        Usage
443		stop         StopReason = StopEnd
444		finalErr     error
445	)
446
447	appendText := func(delta string) {
448		if currentText == nil {
449			currentText = &blockEntry{kind: "text"}
450			blocks = append(blocks, currentText)
451		}
452		currentText.textBuf.WriteString(delta)
453	}
454
455	getOrCreateTool := func(idx int) *blockEntry {
456		if t, ok := toolByIdx[idx]; ok {
457			return t
458		}
459		t := &blockEntry{kind: "tool_use"}
460		toolByIdx[idx] = t
461		blocks = append(blocks, t)
462		// A new tool block breaks the current text block. Subsequent text
463		// deltas will start a fresh text block after this tool.
464		currentText = nil
465		return t
466	}
467
468	assembleMsg := func() Message {
469		content := []Content{}
470		for _, b := range blocks {
471			switch b.kind {
472			case "text":
473				if b.textBuf.Len() > 0 {
474					content = append(content, TextBlock{Text: b.textBuf.String()})
475				}
476			case "tool_use":
477				args := b.toolArgs.String()
478				if args == "" || !json.Valid([]byte(args)) {
479					args = "{}"
480				}
481				content = append(content, ToolCallBlock{
482					ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
483				})
484			}
485		}
486		if reasoningBuf.Len() > 0 {
487			content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
488		}
489		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
490	}
491
492	sendDone := func() {
493		usage.CostUSD = ComputeCost(model, usage)
494		out <- EventUsage{Usage: usage}
495		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
496	}
497
498	for {
499		select {
500		case <-ctx.Done():
501			stop = StopAborted
502			finalErr = ctx.Err()
503			sendDone()
504			return
505		case ev, ok := <-raw:
506			if !ok {
507				sendDone()
508				return
509			}
510			if ev.Data == "[DONE]" {
511				sendDone()
512				return
513			}
514			var chunk struct {
515				Choices []struct {
516					Index int `json:"index"`
517					Delta struct {
518						Content          string `json:"content"`
519						ReasoningContent string `json:"reasoning_content"`
520						ToolCalls        []struct {
521							Index    int    `json:"index"`
522							ID       string `json:"id"`
523							Type     string `json:"type"`
524							Function struct {
525								Name      string `json:"name"`
526								Arguments string `json:"arguments"`
527							} `json:"function"`
528						} `json:"tool_calls"`
529					} `json:"delta"`
530					FinishReason string `json:"finish_reason"`
531				} `json:"choices"`
532				Usage *struct {
533					PromptTokens        int `json:"prompt_tokens"`
534					CompletionTokens    int `json:"completion_tokens"`
535					PromptTokensDetails struct {
536						CachedTokens int `json:"cached_tokens"`
537					} `json:"prompt_tokens_details"`
538				} `json:"usage"`
539				Error *struct {
540					Message string `json:"message"`
541					Type    string `json:"type"`
542				} `json:"error"`
543			}
544			if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
545				continue
546			}
547			if chunk.Error != nil {
548				stop = StopError
549				finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
550				sendDone()
551				return
552			}
553			if chunk.Usage != nil {
554				usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
555				if usage.InputTokens < 0 {
556					usage.InputTokens = chunk.Usage.PromptTokens
557				}
558				usage.OutputTokens = chunk.Usage.CompletionTokens
559				usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
560			}
561			for _, ch := range chunk.Choices {
562				if ch.Delta.ReasoningContent != "" {
563					reasoningBuf.WriteString(ch.Delta.ReasoningContent)
564				}
565				if ch.Delta.Content != "" {
566					appendText(ch.Delta.Content)
567					out <- EventTextDelta{Delta: ch.Delta.Content}
568				}
569				for _, tc := range ch.Delta.ToolCalls {
570					t := getOrCreateTool(tc.Index)
571					if tc.ID != "" {
572						t.toolID = tc.ID
573					}
574					if tc.Function.Name != "" {
575						t.toolName = tc.Function.Name
576					}
577					if !t.announced && t.toolID != "" && t.toolName != "" {
578						t.announced = true
579						out <- EventToolStart{ID: t.toolID, Name: t.toolName}
580					}
581					if tc.Function.Arguments != "" {
582						t.toolArgs.WriteString(tc.Function.Arguments)
583						if t.announced {
584							out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
585						}
586					}
587				}
588				switch ch.FinishReason {
589				case "stop":
590					stop = StopEnd
591				case "length":
592					stop = StopLength
593				case "tool_calls", "function_call":
594					stop = StopToolUse
595					for _, b := range blocks {
596						if b.kind == "tool_use" && b.announced {
597							out <- EventToolEnd{ID: b.toolID}
598						}
599					}
600				}
601			}
602		}
603	}
604}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close