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