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 activatedTools := make(map[string]bool)
274 for _, t := range req.Tools {
275 toolByName[t.Name] = t
276 }
277 for _, msg := range req.Messages {
278 for _, name := range msg.AddedToolNames {
279 activatedTools[name] = true
280 }
281 }
282
283 // DeepSeek's chat-completions API rejects the multimodal content
284 // schema (parts arrays containing image_url). Force every user/tool
285 // message to a plain string and silently drop image blocks for
286 // this provider so historical sessions with screenshots still replay.
287 textOnly := c.name == "deepseek"
288
289 req.Messages = RepairOrphanedToolResults(req.Messages)
290 for _, msg := range req.Messages {
291 switch msg.Role {
292 case RoleUser:
293 content := buildOAIUserContent(msg.Content, textOnly)
294 out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
295 case RoleAssistant:
296 am := oaiMessage{Role: "assistant"}
297 var text strings.Builder
298 var reasoning strings.Builder
299 for _, b := range msg.Content {
300 switch v := b.(type) {
301 case TextBlock:
302 if strings.TrimSpace(v.Text) == "" {
303 continue
304 }
305 if text.Len() > 0 {
306 text.WriteString("\n")
307 }
308 text.WriteString(v.Text)
309 case ToolCallBlock:
310 args := v.Arguments
311 if len(args) == 0 || !json.Valid(args) {
312 args = json.RawMessage("{}")
313 }
314 am.ToolCalls = append(am.ToolCalls, oaiToolCall{
315 ID: v.ID,
316 Type: "function",
317 Function: oaiToolCallFn{
318 Name: v.Name,
319 Arguments: string(args),
320 },
321 })
322 case ReasoningBlock:
323 if v.Summary != "" {
324 if reasoning.Len() > 0 {
325 reasoning.WriteString("\n")
326 }
327 reasoning.WriteString(v.Summary)
328 }
329 }
330 }
331 if text.Len() > 0 {
332 am.Content = text.String()
333 }
334 if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
335 am.ReasoningContent = reasoning.String()
336 }
337 // Kimi rejects assistant messages with neither visible text nor
338 // tool calls ("assistant must not be empty"). This can happen when
339 // a previous stream produced only reasoning_content, which zot keeps
340 // internally for provider replay but cannot send back as standalone
341 // assistant content on OpenAI-compatible chat-completions APIs.
342 if am.Content == nil && len(am.ToolCalls) == 0 {
343 continue
344 }
345 out.Messages = append(out.Messages, am)
346 case RoleTool:
347 // Each ToolResultBlock becomes its own tool message. Preserve
348 // image blocks for vision-capable OpenAI models instead of
349 // flattening the tool output to plain text.
350 for _, b := range msg.Content {
351 if tr, ok := b.(ToolResultBlock); ok {
352 content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
353 out.Messages = append(out.Messages, oaiMessage{
354 Role: "tool",
355 ToolCallID: tr.CallID,
356 Content: content,
357 })
358 }
359 }
360 }
361 if deferredMode {
362 var loaded []oaiTool
363 for _, name := range msg.AddedToolNames {
364 if t, ok := toolByName[name]; ok && t.Deferred {
365 loaded = append(loaded, makeOAITool(t))
366 }
367 }
368 if len(loaded) > 0 {
369 out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
370 }
371 }
372 }
373
374 for _, t := range req.Tools {
375 if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
376 continue
377 }
378 out.Tools = append(out.Tools, makeOAITool(t))
379 }
380 if len(out.Tools) > 0 {
381 out.ToolChoice = "auto"
382 }
383
384 return out, nil
385}
386
387func isKimiDeferredModel(model string) bool {
388 model = strings.ToLower(model)
389 return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
390}
391
392func makeOAITool(t Tool) oaiTool {
393 var tool oaiTool
394 tool.Type = "function"
395 tool.Function.Name = t.Name
396 tool.Function.Description = t.Description
397 tool.Function.Parameters = t.Schema
398 return tool
399}
400
401func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
402 hasImage := false
403 for _, b := range blocks {
404 if _, ok := b.(ImageBlock); ok {
405 hasImage = true
406 break
407 }
408 }
409 if textOnly || !hasImage {
410 var sb strings.Builder
411 for _, b := range blocks {
412 if tb, ok := b.(TextBlock); ok {
413 if sb.Len() > 0 {
414 sb.WriteString("\n")
415 }
416 sb.WriteString(tb.Text)
417 }
418 }
419 return sb.String()
420 }
421 return buildOAIContentBlocks(blocks, false)
422}
423
424func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
425 hasImage := false
426 for _, b := range blocks {
427 if _, ok := b.(ImageBlock); ok {
428 hasImage = true
429 break
430 }
431 }
432 if textOnly || !hasImage {
433 var sb strings.Builder
434 for _, b := range blocks {
435 if tb, ok := b.(TextBlock); ok {
436 if sb.Len() > 0 {
437 sb.WriteString("\n")
438 }
439 sb.WriteString(tb.Text)
440 }
441 }
442 if isError && sb.Len() > 0 {
443 sb.WriteString(" [error]")
444 }
445 return sb.String()
446 }
447 return buildOAIContentBlocks(blocks, isError)
448}
449
450func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
451 var arr []interface{}
452 for _, b := range blocks {
453 switch v := b.(type) {
454 case TextBlock:
455 arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
456 case ImageBlock:
457 var img oaiContentImage
458 img.Type = "image_url"
459 img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
460 arr = append(arr, img)
461 }
462 }
463 if isError {
464 arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
465 }
466 return arr
467}
468
469// ---- streaming ----
470
471func (c *openaiClient) chatCompletionsURL() string {
472 if c.chatCompletionsPath != "" {
473 return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
474 }
475 return chatCompletionsURL(c.baseURL)
476}
477
478func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
479 endpoint := c.chatCompletionsURL()
480 wire, err := c.buildRequest(req)
481 if err != nil {
482 return nil, err
483 }
484 body, err := json.Marshal(wire)
485 if err != nil {
486 return nil, err
487 }
488 newReq := func() (*http.Request, error) {
489 httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
490 if err != nil {
491 return nil, err
492 }
493 httpReq.Header.Set("content-type", "application/json")
494 httpReq.Header.Set("accept", "text/event-stream")
495 httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
496 for k, v := range c.headers {
497 httpReq.Header.Set(k, v)
498 }
499 return httpReq, nil
500 }
501
502 resp, err := doStreamWithRetry(ctx, c.http, newReq)
503 if err != nil {
504 return nil, fmt.Errorf("%s: %w", c.Name(), err)
505 }
506 if resp.StatusCode != http.StatusOK {
507 b, _ := io.ReadAll(resp.Body)
508 resp.Body.Close()
509 return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
510 }
511
512 out := make(chan Event, 16)
513 go c.runStream(ctx, resp, req, out)
514 return out, nil
515}
516
517func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
518 defer close(out)
519 defer resp.Body.Close()
520
521 model, _ := FindModel("", req.Model)
522 out <- EventStart{Model: req.Model, Provider: c.Name()}
523
524 raw := make(chan sseEvent, 16)
525 go readSSE(resp.Body, raw)
526
527 // Interleaved block tracking: text and tool_calls preserve their
528 // emission order so the assistant message renders in the same order
529 // the model produced it. The builder fires one kind of block at a
530 // time — incoming text deltas after a tool_call split into a fresh
531 // text block; subsequent tool_calls each get their own slot.
532 type blockEntry struct {
533 kind string // "text" | "tool_use"
534 textBuf strings.Builder
535 toolID string
536 toolName string
537 toolArgs strings.Builder
538 announced bool
539 }
540 var (
541 blocks []*blockEntry
542 currentText *blockEntry // most-recent text block, nil if none
543 toolByIdx = map[int]*blockEntry{} // openai tool_call index -> block
544 reasoningBuf strings.Builder
545 usage Usage
546 stop StopReason = StopEnd
547 finalErr error
548 )
549
550 appendText := func(delta string) {
551 if currentText == nil {
552 currentText = &blockEntry{kind: "text"}
553 blocks = append(blocks, currentText)
554 }
555 currentText.textBuf.WriteString(delta)
556 }
557
558 getOrCreateTool := func(idx int) *blockEntry {
559 if t, ok := toolByIdx[idx]; ok {
560 return t
561 }
562 t := &blockEntry{kind: "tool_use"}
563 toolByIdx[idx] = t
564 blocks = append(blocks, t)
565 // A new tool block breaks the current text block. Subsequent text
566 // deltas will start a fresh text block after this tool.
567 currentText = nil
568 return t
569 }
570
571 assembleMsg := func() Message {
572 content := []Content{}
573 for _, b := range blocks {
574 switch b.kind {
575 case "text":
576 if b.textBuf.Len() > 0 {
577 content = append(content, TextBlock{Text: b.textBuf.String()})
578 }
579 case "tool_use":
580 args := b.toolArgs.String()
581 if args == "" || !json.Valid([]byte(args)) {
582 args = "{}"
583 }
584 content = append(content, ToolCallBlock{
585 ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
586 })
587 }
588 }
589 if reasoningBuf.Len() > 0 {
590 content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
591 }
592 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
593 }
594
595 sendDone := func() {
596 usage.CostUSD = ComputeCost(model, usage)
597 out <- EventUsage{Usage: usage}
598 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
599 }
600
601 for {
602 select {
603 case <-ctx.Done():
604 stop = StopAborted
605 finalErr = ctx.Err()
606 sendDone()
607 return
608 case ev, ok := <-raw:
609 if !ok {
610 sendDone()
611 return
612 }
613 if ev.Data == "[DONE]" {
614 sendDone()
615 return
616 }
617 var chunk struct {
618 Choices []struct {
619 Index int `json:"index"`
620 Delta struct {
621 Content string `json:"content"`
622 ReasoningContent string `json:"reasoning_content"`
623 ToolCalls []struct {
624 Index int `json:"index"`
625 ID string `json:"id"`
626 Type string `json:"type"`
627 Function struct {
628 Name string `json:"name"`
629 Arguments string `json:"arguments"`
630 } `json:"function"`
631 } `json:"tool_calls"`
632 } `json:"delta"`
633 FinishReason string `json:"finish_reason"`
634 } `json:"choices"`
635 Usage *struct {
636 PromptTokens int `json:"prompt_tokens"`
637 CompletionTokens int `json:"completion_tokens"`
638 PromptTokensDetails struct {
639 CachedTokens int `json:"cached_tokens"`
640 } `json:"prompt_tokens_details"`
641 } `json:"usage"`
642 Error *struct {
643 Message string `json:"message"`
644 Type string `json:"type"`
645 } `json:"error"`
646 }
647 if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
648 continue
649 }
650 if chunk.Error != nil {
651 stop = StopError
652 finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
653 sendDone()
654 return
655 }
656 if chunk.Usage != nil {
657 usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
658 if usage.InputTokens < 0 {
659 usage.InputTokens = chunk.Usage.PromptTokens
660 }
661 usage.OutputTokens = chunk.Usage.CompletionTokens
662 usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
663 }
664 for _, ch := range chunk.Choices {
665 if ch.Delta.ReasoningContent != "" {
666 reasoningBuf.WriteString(ch.Delta.ReasoningContent)
667 }
668 if ch.Delta.Content != "" {
669 appendText(ch.Delta.Content)
670 out <- EventTextDelta{Delta: ch.Delta.Content}
671 }
672 for _, tc := range ch.Delta.ToolCalls {
673 t := getOrCreateTool(tc.Index)
674 if tc.ID != "" {
675 t.toolID = tc.ID
676 }
677 if tc.Function.Name != "" {
678 t.toolName = tc.Function.Name
679 }
680 if !t.announced && t.toolID != "" && t.toolName != "" {
681 t.announced = true
682 out <- EventToolStart{ID: t.toolID, Name: t.toolName}
683 }
684 if tc.Function.Arguments != "" {
685 t.toolArgs.WriteString(tc.Function.Arguments)
686 if t.announced {
687 out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
688 }
689 }
690 }
691 switch ch.FinishReason {
692 case "stop":
693 stop = StopEnd
694 case "length":
695 stop = StopLength
696 case "tool_calls", "function_call":
697 stop = StopToolUse
698 for _, b := range blocks {
699 if b.kind == "tool_use" && b.announced {
700 out <- EventToolEnd{ID: b.toolID}
701 }
702 }
703 }
704 }
705 }
706 }
707}