v0.1.79 7970412

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		if req.Reasoning != "" {
189			out.ReasoningEffort = strings.ToLower(req.Reasoning)
190		}
191	} else {
192		out.MaxTokens = &maxTok
193	}
194
195	if req.System != "" {
196		out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
197	}
198
199	// DeepSeek's chat-completions API rejects the multimodal content
200	// schema (parts arrays containing image_url). Force every user/tool
201	// message to a plain string and silently drop image blocks for
202	// this provider so historical sessions with screenshots still replay.
203	textOnly := c.name == "deepseek"
204
205	req.Messages = RepairOrphanedToolResults(req.Messages)
206	for _, msg := range req.Messages {
207		switch msg.Role {
208		case RoleUser:
209			content := buildOAIUserContent(msg.Content, textOnly)
210			out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
211		case RoleAssistant:
212			am := oaiMessage{Role: "assistant"}
213			var text strings.Builder
214			var reasoning strings.Builder
215			for _, b := range msg.Content {
216				switch v := b.(type) {
217				case TextBlock:
218					if strings.TrimSpace(v.Text) == "" {
219						continue
220					}
221					if text.Len() > 0 {
222						text.WriteString("\n")
223					}
224					text.WriteString(v.Text)
225				case ToolCallBlock:
226					args := v.Arguments
227					if len(args) == 0 || !json.Valid(args) {
228						args = json.RawMessage("{}")
229					}
230					am.ToolCalls = append(am.ToolCalls, oaiToolCall{
231						ID:   v.ID,
232						Type: "function",
233						Function: oaiToolCallFn{
234							Name:      v.Name,
235							Arguments: string(args),
236						},
237					})
238				case ReasoningBlock:
239					if v.Summary != "" {
240						if reasoning.Len() > 0 {
241							reasoning.WriteString("\n")
242						}
243						reasoning.WriteString(v.Summary)
244					}
245				}
246			}
247			if text.Len() > 0 {
248				am.Content = text.String()
249			}
250			if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
251				am.ReasoningContent = reasoning.String()
252			}
253			// Kimi rejects assistant messages with neither visible text nor
254			// tool calls ("assistant must not be empty"). This can happen when
255			// a previous stream produced only reasoning_content, which zot keeps
256			// internally for provider replay but cannot send back as standalone
257			// assistant content on OpenAI-compatible chat-completions APIs.
258			if am.Content == nil && len(am.ToolCalls) == 0 {
259				continue
260			}
261			out.Messages = append(out.Messages, am)
262		case RoleTool:
263			// Each ToolResultBlock becomes its own tool message. Preserve
264			// image blocks for vision-capable OpenAI models instead of
265			// flattening the tool output to plain text.
266			for _, b := range msg.Content {
267				if tr, ok := b.(ToolResultBlock); ok {
268					content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
269					out.Messages = append(out.Messages, oaiMessage{
270						Role:       "tool",
271						ToolCallID: tr.CallID,
272						Content:    content,
273					})
274				}
275			}
276		}
277	}
278
279	for _, t := range req.Tools {
280		var tool oaiTool
281		tool.Type = "function"
282		tool.Function.Name = t.Name
283		tool.Function.Description = t.Description
284		tool.Function.Parameters = t.Schema
285		out.Tools = append(out.Tools, tool)
286	}
287	if len(out.Tools) > 0 {
288		out.ToolChoice = "auto"
289	}
290
291	return out, nil
292}
293
294func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
295	hasImage := false
296	for _, b := range blocks {
297		if _, ok := b.(ImageBlock); ok {
298			hasImage = true
299			break
300		}
301	}
302	if textOnly || !hasImage {
303		var sb strings.Builder
304		for _, b := range blocks {
305			if tb, ok := b.(TextBlock); ok {
306				if sb.Len() > 0 {
307					sb.WriteString("\n")
308				}
309				sb.WriteString(tb.Text)
310			}
311		}
312		return sb.String()
313	}
314	return buildOAIContentBlocks(blocks, false)
315}
316
317func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
318	hasImage := false
319	for _, b := range blocks {
320		if _, ok := b.(ImageBlock); ok {
321			hasImage = true
322			break
323		}
324	}
325	if textOnly || !hasImage {
326		var sb strings.Builder
327		for _, b := range blocks {
328			if tb, ok := b.(TextBlock); ok {
329				if sb.Len() > 0 {
330					sb.WriteString("\n")
331				}
332				sb.WriteString(tb.Text)
333			}
334		}
335		if isError && sb.Len() > 0 {
336			sb.WriteString(" [error]")
337		}
338		return sb.String()
339	}
340	return buildOAIContentBlocks(blocks, isError)
341}
342
343func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
344	var arr []interface{}
345	for _, b := range blocks {
346		switch v := b.(type) {
347		case TextBlock:
348			arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
349		case ImageBlock:
350			var img oaiContentImage
351			img.Type = "image_url"
352			img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
353			arr = append(arr, img)
354		}
355	}
356	if isError {
357		arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
358	}
359	return arr
360}
361
362// ---- streaming ----
363
364func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
365	apiPath := "/v1/chat/completions"
366	if strings.HasSuffix(c.baseURL, "/v1") {
367		apiPath = "/chat/completions"
368	}
369	wire, err := c.buildRequest(req)
370	if err != nil {
371		return nil, err
372	}
373	body, err := json.Marshal(wire)
374	if err != nil {
375		return nil, err
376	}
377	newReq := func() (*http.Request, error) {
378		httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+apiPath, bytes.NewReader(body))
379		if err != nil {
380			return nil, err
381		}
382		httpReq.Header.Set("content-type", "application/json")
383		httpReq.Header.Set("accept", "text/event-stream")
384		httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
385		for k, v := range c.headers {
386			httpReq.Header.Set(k, v)
387		}
388		return httpReq, nil
389	}
390
391	resp, err := doStreamWithRetry(ctx, c.http, newReq)
392	if err != nil {
393		return nil, fmt.Errorf("%s: %w", c.Name(), err)
394	}
395	if resp.StatusCode != http.StatusOK {
396		b, _ := io.ReadAll(resp.Body)
397		resp.Body.Close()
398		return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
399	}
400
401	out := make(chan Event, 16)
402	go c.runStream(ctx, resp, req, out)
403	return out, nil
404}
405
406func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
407	defer close(out)
408	defer resp.Body.Close()
409
410	model, _ := FindModel("", req.Model)
411	out <- EventStart{Model: req.Model, Provider: c.Name()}
412
413	raw := make(chan sseEvent, 16)
414	go readSSE(resp.Body, raw)
415
416	// Interleaved block tracking: text and tool_calls preserve their
417	// emission order so the assistant message renders in the same order
418	// the model produced it. The builder fires one kind of block at a
419	// time — incoming text deltas after a tool_call split into a fresh
420	// text block; subsequent tool_calls each get their own slot.
421	type blockEntry struct {
422		kind      string // "text" | "tool_use"
423		textBuf   strings.Builder
424		toolID    string
425		toolName  string
426		toolArgs  strings.Builder
427		announced bool
428	}
429	var (
430		blocks       []*blockEntry
431		currentText  *blockEntry             // most-recent text block, nil if none
432		toolByIdx    = map[int]*blockEntry{} // openai tool_call index -> block
433		reasoningBuf strings.Builder
434		usage        Usage
435		stop         StopReason = StopEnd
436		finalErr     error
437	)
438
439	appendText := func(delta string) {
440		if currentText == nil {
441			currentText = &blockEntry{kind: "text"}
442			blocks = append(blocks, currentText)
443		}
444		currentText.textBuf.WriteString(delta)
445	}
446
447	getOrCreateTool := func(idx int) *blockEntry {
448		if t, ok := toolByIdx[idx]; ok {
449			return t
450		}
451		t := &blockEntry{kind: "tool_use"}
452		toolByIdx[idx] = t
453		blocks = append(blocks, t)
454		// A new tool block breaks the current text block. Subsequent text
455		// deltas will start a fresh text block after this tool.
456		currentText = nil
457		return t
458	}
459
460	assembleMsg := func() Message {
461		content := []Content{}
462		for _, b := range blocks {
463			switch b.kind {
464			case "text":
465				if b.textBuf.Len() > 0 {
466					content = append(content, TextBlock{Text: b.textBuf.String()})
467				}
468			case "tool_use":
469				args := b.toolArgs.String()
470				if args == "" || !json.Valid([]byte(args)) {
471					args = "{}"
472				}
473				content = append(content, ToolCallBlock{
474					ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
475				})
476			}
477		}
478		if reasoningBuf.Len() > 0 {
479			content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
480		}
481		return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
482	}
483
484	sendDone := func() {
485		usage.CostUSD = ComputeCost(model, usage)
486		out <- EventUsage{Usage: usage}
487		out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
488	}
489
490	for {
491		select {
492		case <-ctx.Done():
493			stop = StopAborted
494			finalErr = ctx.Err()
495			sendDone()
496			return
497		case ev, ok := <-raw:
498			if !ok {
499				sendDone()
500				return
501			}
502			if ev.Data == "[DONE]" {
503				sendDone()
504				return
505			}
506			var chunk struct {
507				Choices []struct {
508					Index int `json:"index"`
509					Delta struct {
510						Content          string `json:"content"`
511						ReasoningContent string `json:"reasoning_content"`
512						ToolCalls        []struct {
513							Index    int    `json:"index"`
514							ID       string `json:"id"`
515							Type     string `json:"type"`
516							Function struct {
517								Name      string `json:"name"`
518								Arguments string `json:"arguments"`
519							} `json:"function"`
520						} `json:"tool_calls"`
521					} `json:"delta"`
522					FinishReason string `json:"finish_reason"`
523				} `json:"choices"`
524				Usage *struct {
525					PromptTokens        int `json:"prompt_tokens"`
526					CompletionTokens    int `json:"completion_tokens"`
527					PromptTokensDetails struct {
528						CachedTokens int `json:"cached_tokens"`
529					} `json:"prompt_tokens_details"`
530				} `json:"usage"`
531				Error *struct {
532					Message string `json:"message"`
533					Type    string `json:"type"`
534				} `json:"error"`
535			}
536			if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
537				continue
538			}
539			if chunk.Error != nil {
540				stop = StopError
541				finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
542				sendDone()
543				return
544			}
545			if chunk.Usage != nil {
546				usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
547				if usage.InputTokens < 0 {
548					usage.InputTokens = chunk.Usage.PromptTokens
549				}
550				usage.OutputTokens = chunk.Usage.CompletionTokens
551				usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
552			}
553			for _, ch := range chunk.Choices {
554				if ch.Delta.ReasoningContent != "" {
555					reasoningBuf.WriteString(ch.Delta.ReasoningContent)
556				}
557				if ch.Delta.Content != "" {
558					appendText(ch.Delta.Content)
559					out <- EventTextDelta{Delta: ch.Delta.Content}
560				}
561				for _, tc := range ch.Delta.ToolCalls {
562					t := getOrCreateTool(tc.Index)
563					if tc.ID != "" {
564						t.toolID = tc.ID
565					}
566					if tc.Function.Name != "" {
567						t.toolName = tc.Function.Name
568					}
569					if !t.announced && t.toolID != "" && t.toolName != "" {
570						t.announced = true
571						out <- EventToolStart{ID: t.toolID, Name: t.toolName}
572					}
573					if tc.Function.Arguments != "" {
574						t.toolArgs.WriteString(tc.Function.Arguments)
575						if t.announced {
576							out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
577						}
578					}
579				}
580				switch ch.FinishReason {
581				case "stop":
582					stop = StopEnd
583				case "length":
584					stop = StopLength
585				case "tool_calls", "function_call":
586					stop = StopToolUse
587					for _, b := range blocks {
588						if b.kind == "tool_use" && b.announced {
589							out <- EventToolEnd{ID: b.toolID}
590						}
591					}
592				}
593			}
594		}
595	}
596}

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