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