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 // The OpenAI wire client is shared by many providers, so prefer its own
185 // provider namespace before falling back to a provider-agnostic lookup.
186 m, err := FindModel(c.Name(), req.Model)
187 if err != nil {
188 m, err = FindModel("", req.Model)
189 }
190 if err != nil {
191 // Unknown model: use sensible defaults so local/custom
192 // models still work without a catalog entry.
193 m = Model{
194 ID: req.Model,
195 ContextWindow: 32768,
196 MaxOutput: 8192,
197 }
198 }
199 reasoning := ClampReasoningForModel(m, req.Reasoning)
200 out := &oaiRequest{
201 Model: req.Model,
202 Stream: true,
203 StreamOptions: &oaiStreamOptions{IncludeUsage: true},
204 Temperature: req.Temperature,
205 }
206
207 maxTok := req.MaxTokens
208 if maxTok <= 0 {
209 maxTok = m.MaxOutput
210 }
211 // Clamp max_tokens so output plus a minimum input reservation fits
212 // within the context window. Some providers (OpenRouter) enforce
213 // input + max_output <= context_length and reject requests where the
214 // total exceeds it. Reserving headroom guarantees the system prompt,
215 // first message, and tool definitions have room.
216 //
217 // The cap is derived from the context window, never from MaxOutput:
218 // MaxOutput is already the output ceiling, so subtracting from it
219 // would shrink every model's budget even when its output comfortably
220 // fits the window. We only lower maxTok when ContextWindow - reserve
221 // is actually tighter than the requested budget, which is exactly the
222 // pathological case (e.g. a model whose MaxOutput equals its window).
223 //
224 // The reserve is proportional (window/8, capped at 4096) rather than a
225 // flat 4096 so small-window models aren't over-penalized: a flat 4096
226 // would halve gpt-4's 8192 budget, while window/8 reserves a sensible
227 // 1024 there and still tops out at 4096 for large contexts.
228 //
229 // Some providers (OpenRouter) report inflated model-level context
230 // windows (e.g. 1000000) while the serving provider enforces a much
231 // tighter limit (e.g. 262144). Discovery already prefers the serving
232 // provider's smaller context_length, so m.ContextWindow is the real
233 // limit by the time we get here.
234 if m.ContextWindow > 0 {
235 reserve := m.ContextWindow / 8
236 const maxReserve = 4096
237 if reserve > maxReserve {
238 reserve = maxReserve
239 }
240 clamped := m.ContextWindow - reserve
241 if clamped < 1 {
242 clamped = 1
243 }
244 if maxTok > clamped {
245 maxTok = clamped
246 }
247 }
248 if m.Reasoning {
249 if maxTok > 0 {
250 out.MaxCompletionTok = &maxTok
251 }
252 effort := OpenAIReasoningEffort(reasoning)
253 if usesAdaptiveThinking(m) {
254 // Some gateways expose adaptive-thinking Anthropic models through
255 // the OpenAI-compatible chat-completions wire. They accept the
256 // same reasoning_effort knob, including the top "xhigh" tier;
257 // don't clamp zot's "maximum" to "high" for those models.
258 effort = OpenAICompatAnthropicEffort(reasoning)
259 }
260 if effort != "" {
261 out.ReasoningEffort = effort
262 }
263 } else if maxTok > 0 {
264 // Omit max_tokens when unknown (some discovered models don't
265 // advertise an output cap) so the server applies its own default
266 // instead of receiving an invalid max_tokens: 0.
267 out.MaxTokens = &maxTok
268 }
269
270 if req.System != "" {
271 out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
272 }
273
274 deferredMode := isKimiDeferredModel(req.Model)
275 toolByName := make(map[string]Tool, len(req.Tools))
276 for _, t := range req.Tools {
277 toolByName[t.Name] = t
278 }
279 activatedTools := activatedToolNames(req.Messages)
280
281 // DeepSeek's chat-completions API rejects the multimodal content
282 // schema (parts arrays containing image_url). Force every user/tool
283 // message to a plain string and silently drop image blocks for
284 // this provider so historical sessions with screenshots still replay.
285 textOnly := c.name == "deepseek"
286
287 req.Messages = RepairOrphanedToolResults(req.Messages)
288 for _, msg := range req.Messages {
289 switch msg.Role {
290 case RoleUser:
291 content := buildOAIUserContent(msg.Content, textOnly)
292 out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
293 case RoleAssistant:
294 am := oaiMessage{Role: "assistant"}
295 var text strings.Builder
296 var reasoning strings.Builder
297 for _, b := range msg.Content {
298 switch v := b.(type) {
299 case TextBlock:
300 if strings.TrimSpace(v.Text) == "" {
301 continue
302 }
303 if text.Len() > 0 {
304 text.WriteString("\n")
305 }
306 text.WriteString(v.Text)
307 case ToolCallBlock:
308 args := v.Arguments
309 if len(args) == 0 || !json.Valid(args) {
310 args = json.RawMessage("{}")
311 }
312 am.ToolCalls = append(am.ToolCalls, oaiToolCall{
313 ID: v.ID,
314 Type: "function",
315 Function: oaiToolCallFn{
316 Name: v.Name,
317 Arguments: string(args),
318 },
319 })
320 case ReasoningBlock:
321 if v.Summary != "" {
322 if reasoning.Len() > 0 {
323 reasoning.WriteString("\n")
324 }
325 reasoning.WriteString(v.Summary)
326 }
327 }
328 }
329 if text.Len() > 0 {
330 am.Content = text.String()
331 }
332 if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
333 am.ReasoningContent = reasoning.String()
334 }
335 // Kimi rejects assistant messages with neither visible text nor
336 // tool calls ("assistant must not be empty"). This can happen when
337 // a previous stream produced only reasoning_content, which zot keeps
338 // internally for provider replay but cannot send back as standalone
339 // assistant content on OpenAI-compatible chat-completions APIs.
340 if am.Content == nil && len(am.ToolCalls) == 0 {
341 continue
342 }
343 out.Messages = append(out.Messages, am)
344 case RoleTool:
345 // Each ToolResultBlock becomes its own tool message. Preserve
346 // image blocks for vision-capable OpenAI models instead of
347 // flattening the tool output to plain text.
348 for _, b := range msg.Content {
349 if tr, ok := b.(ToolResultBlock); ok {
350 content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
351 out.Messages = append(out.Messages, oaiMessage{
352 Role: "tool",
353 ToolCallID: tr.CallID,
354 Content: content,
355 })
356 }
357 }
358 }
359 if deferredMode {
360 var loaded []oaiTool
361 for _, name := range msg.AddedToolNames {
362 if t, ok := toolByName[name]; ok && t.Deferred {
363 loaded = append(loaded, makeOAITool(t))
364 }
365 }
366 if len(loaded) > 0 {
367 out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
368 }
369 }
370 }
371
372 for _, t := range req.Tools {
373 if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
374 continue
375 }
376 out.Tools = append(out.Tools, makeOAITool(t))
377 }
378 if len(out.Tools) > 0 {
379 out.ToolChoice = "auto"
380 }
381
382 return out, nil
383}
384
385func isKimiDeferredModel(model string) bool {
386 model = strings.ToLower(model)
387 return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
388}
389
390func makeOAITool(t Tool) oaiTool {
391 var tool oaiTool
392 tool.Type = "function"
393 tool.Function.Name = t.Name
394 tool.Function.Description = t.Description
395 tool.Function.Parameters = t.Schema
396 return tool
397}
398
399func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
400 hasImage := false
401 for _, b := range blocks {
402 if _, ok := b.(ImageBlock); ok {
403 hasImage = true
404 break
405 }
406 }
407 if textOnly || !hasImage {
408 var sb strings.Builder
409 for _, b := range blocks {
410 if tb, ok := b.(TextBlock); ok {
411 if sb.Len() > 0 {
412 sb.WriteString("\n")
413 }
414 sb.WriteString(tb.Text)
415 }
416 }
417 return sb.String()
418 }
419 return buildOAIContentBlocks(blocks, false)
420}
421
422func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
423 hasImage := false
424 for _, b := range blocks {
425 if _, ok := b.(ImageBlock); ok {
426 hasImage = true
427 break
428 }
429 }
430 if textOnly || !hasImage {
431 var sb strings.Builder
432 for _, b := range blocks {
433 if tb, ok := b.(TextBlock); ok {
434 if sb.Len() > 0 {
435 sb.WriteString("\n")
436 }
437 sb.WriteString(tb.Text)
438 }
439 }
440 if isError && sb.Len() > 0 {
441 sb.WriteString(" [error]")
442 }
443 return sb.String()
444 }
445 return buildOAIContentBlocks(blocks, isError)
446}
447
448func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
449 var arr []interface{}
450 for _, b := range blocks {
451 switch v := b.(type) {
452 case TextBlock:
453 arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
454 case ImageBlock:
455 var img oaiContentImage
456 img.Type = "image_url"
457 img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
458 arr = append(arr, img)
459 }
460 }
461 if isError {
462 arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
463 }
464 return arr
465}
466
467// ---- streaming ----
468
469func (c *openaiClient) chatCompletionsURL() string {
470 if c.chatCompletionsPath != "" {
471 return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
472 }
473 return chatCompletionsURL(c.baseURL)
474}
475
476func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
477 endpoint := c.chatCompletionsURL()
478 wire, err := c.buildRequest(req)
479 if err != nil {
480 return nil, err
481 }
482 body, err := json.Marshal(wire)
483 if err != nil {
484 return nil, err
485 }
486 newReq := func() (*http.Request, error) {
487 httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
488 if err != nil {
489 return nil, err
490 }
491 httpReq.Header.Set("content-type", "application/json")
492 httpReq.Header.Set("accept", "text/event-stream")
493 httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
494 for k, v := range c.headers {
495 httpReq.Header.Set(k, v)
496 }
497 return httpReq, nil
498 }
499
500 resp, err := doStreamWithRetry(ctx, c.http, newReq)
501 if err != nil {
502 return nil, fmt.Errorf("%s: %w", c.Name(), err)
503 }
504 if resp.StatusCode != http.StatusOK {
505 b, _ := io.ReadAll(resp.Body)
506 resp.Body.Close()
507 return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
508 }
509
510 out := make(chan Event, 16)
511 go c.runStream(ctx, resp, req, out)
512 return out, nil
513}
514
515func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
516 defer close(out)
517 defer resp.Body.Close()
518
519 model, _ := FindModel("", req.Model)
520 out <- EventStart{Model: req.Model, Provider: c.Name()}
521
522 raw := make(chan sseEvent, 16)
523 go readSSE(resp.Body, raw)
524
525 // Interleaved block tracking: text and tool_calls preserve their
526 // emission order so the assistant message renders in the same order
527 // the model produced it. The builder fires one kind of block at a
528 // time — incoming text deltas after a tool_call split into a fresh
529 // text block; subsequent tool_calls each get their own slot.
530 type blockEntry struct {
531 kind string // "text" | "tool_use"
532 textBuf strings.Builder
533 toolID string
534 toolName string
535 toolArgs strings.Builder
536 announced bool
537 }
538 var (
539 blocks []*blockEntry
540 currentText *blockEntry // most-recent text block, nil if none
541 toolByIdx = map[int]*blockEntry{} // openai tool_call index -> block
542 reasoningBuf strings.Builder
543 usage Usage
544 stop StopReason = StopEnd
545 finalErr error
546 )
547
548 appendText := func(delta string) {
549 if currentText == nil {
550 currentText = &blockEntry{kind: "text"}
551 blocks = append(blocks, currentText)
552 }
553 currentText.textBuf.WriteString(delta)
554 }
555
556 getOrCreateTool := func(idx int) *blockEntry {
557 if t, ok := toolByIdx[idx]; ok {
558 return t
559 }
560 t := &blockEntry{kind: "tool_use"}
561 toolByIdx[idx] = t
562 blocks = append(blocks, t)
563 // A new tool block breaks the current text block. Subsequent text
564 // deltas will start a fresh text block after this tool.
565 currentText = nil
566 return t
567 }
568
569 assembleMsg := func() Message {
570 content := []Content{}
571 for _, b := range blocks {
572 switch b.kind {
573 case "text":
574 if b.textBuf.Len() > 0 {
575 content = append(content, TextBlock{Text: b.textBuf.String()})
576 }
577 case "tool_use":
578 args := b.toolArgs.String()
579 if args == "" || !json.Valid([]byte(args)) {
580 args = "{}"
581 }
582 content = append(content, ToolCallBlock{
583 ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
584 })
585 }
586 }
587 if reasoningBuf.Len() > 0 {
588 content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
589 }
590 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
591 }
592
593 sendDone := func() {
594 usage.CostUSD = ComputeCost(model, usage)
595 out <- EventUsage{Usage: usage}
596 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
597 }
598
599 for {
600 select {
601 case <-ctx.Done():
602 stop = StopAborted
603 finalErr = ctx.Err()
604 sendDone()
605 return
606 case ev, ok := <-raw:
607 if !ok {
608 sendDone()
609 return
610 }
611 if ev.Data == "[DONE]" {
612 sendDone()
613 return
614 }
615 var chunk struct {
616 Choices []struct {
617 Index int `json:"index"`
618 Delta struct {
619 Content string `json:"content"`
620 ReasoningContent string `json:"reasoning_content"`
621 ToolCalls []struct {
622 Index int `json:"index"`
623 ID string `json:"id"`
624 Type string `json:"type"`
625 Function struct {
626 Name string `json:"name"`
627 Arguments string `json:"arguments"`
628 } `json:"function"`
629 } `json:"tool_calls"`
630 } `json:"delta"`
631 FinishReason string `json:"finish_reason"`
632 } `json:"choices"`
633 Usage *struct {
634 PromptTokens int `json:"prompt_tokens"`
635 CompletionTokens int `json:"completion_tokens"`
636 PromptTokensDetails struct {
637 CachedTokens int `json:"cached_tokens"`
638 } `json:"prompt_tokens_details"`
639 CompletionTokensDetails *struct {
640 ReasoningTokens int `json:"reasoning_tokens"`
641 } `json:"completion_tokens_details"`
642 } `json:"usage"`
643 Error *struct {
644 Message string `json:"message"`
645 Type string `json:"type"`
646 } `json:"error"`
647 }
648 if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
649 continue
650 }
651 if chunk.Error != nil {
652 stop = StopError
653 finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
654 sendDone()
655 return
656 }
657 if chunk.Usage != nil {
658 usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
659 if usage.InputTokens < 0 {
660 usage.InputTokens = chunk.Usage.PromptTokens
661 }
662 usage.OutputTokens = chunk.Usage.CompletionTokens
663 usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
664 if details := chunk.Usage.CompletionTokensDetails; details != nil {
665 usage.ReasoningTokens = details.ReasoningTokens
666 usage.ReasoningTokensKnown = true
667 }
668 }
669 for _, ch := range chunk.Choices {
670 if ch.Delta.ReasoningContent != "" {
671 reasoningBuf.WriteString(ch.Delta.ReasoningContent)
672 }
673 if ch.Delta.Content != "" {
674 appendText(ch.Delta.Content)
675 out <- EventTextDelta{Delta: ch.Delta.Content}
676 }
677 for _, tc := range ch.Delta.ToolCalls {
678 t := getOrCreateTool(tc.Index)
679 if tc.ID != "" {
680 t.toolID = tc.ID
681 }
682 if tc.Function.Name != "" {
683 t.toolName = tc.Function.Name
684 }
685 if !t.announced && t.toolID != "" && t.toolName != "" {
686 t.announced = true
687 out <- EventToolStart{ID: t.toolID, Name: t.toolName}
688 }
689 if tc.Function.Arguments != "" {
690 t.toolArgs.WriteString(tc.Function.Arguments)
691 if t.announced {
692 out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
693 }
694 }
695 }
696 switch ch.FinishReason {
697 case "stop":
698 stop = StopEnd
699 case "length":
700 stop = StopLength
701 case "tool_calls", "function_call":
702 stop = StopToolUse
703 for _, b := range blocks {
704 if b.kind == "tool_use" && b.announced {
705 out <- EventToolEnd{ID: b.toolID}
706 }
707 }
708 }
709 }
710 }
711 }
712}