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// NewKimiWithHeaders creates a Kimi/Moonshot client with extra headers.
60// Subscription tokens from Kimi Code need the official CLI's X-Msh-* headers.
61func NewKimiWithHeaders(apiKey, baseURL string, headers map[string]string) Client {
62 if baseURL == "" {
63 baseURL = "https://api.kimi.com/coding/v1"
64 }
65 return &openaiClient{
66 apiKey: apiKey,
67 baseURL: strings.TrimRight(baseURL, "/"),
68 name: "kimi",
69 headers: headers,
70 http: &http.Client{Timeout: 0},
71 }
72}
73
74func (c *openaiClient) Name() string {
75 if c.name != "" {
76 return c.name
77 }
78 return "openai"
79}
80
81// ---- wire types ----
82
83type oaiContentText struct {
84 Type string `json:"type"` // "text"
85 Text string `json:"text"`
86}
87
88type oaiContentImage struct {
89 Type string `json:"type"` // "image_url"
90 ImageURL struct {
91 URL string `json:"url"`
92 } `json:"image_url"`
93}
94
95type oaiToolCallFn struct {
96 Name string `json:"name"`
97 Arguments string `json:"arguments"` // JSON string
98}
99
100type oaiToolCall struct {
101 ID string `json:"id"`
102 Type string `json:"type"` // "function"
103 Function oaiToolCallFn `json:"function"`
104}
105
106type oaiMessage struct {
107 Role string `json:"role"`
108 Content interface{} `json:"content,omitempty"` // string or []block
109 Name string `json:"name,omitempty"`
110 ToolCalls []oaiToolCall `json:"tool_calls,omitempty"`
111 ToolCallID string `json:"tool_call_id,omitempty"`
112 // ReasoningContent carries the model's chain-of-thought summary
113 // alongside an assistant tool-call message. Required by Kimi's
114 // chat completions endpoint when thinking is enabled and the
115 // assistant message contains a tool call; OpenAI ignores it.
116 ReasoningContent string `json:"reasoning_content,omitempty"`
117}
118
119type oaiTool struct {
120 Type string `json:"type"` // "function"
121 Function struct {
122 Name string `json:"name"`
123 Description string `json:"description,omitempty"`
124 Parameters json.RawMessage `json:"parameters"`
125 } `json:"function"`
126}
127
128type oaiStreamOptions struct {
129 IncludeUsage bool `json:"include_usage"`
130}
131
132type oaiRequest struct {
133 Model string `json:"model"`
134 Messages []oaiMessage `json:"messages"`
135 Tools []oaiTool `json:"tools,omitempty"`
136 ToolChoice string `json:"tool_choice,omitempty"`
137 Stream bool `json:"stream"`
138 StreamOptions *oaiStreamOptions `json:"stream_options,omitempty"`
139 Temperature *float32 `json:"temperature,omitempty"`
140 MaxTokens *int `json:"max_tokens,omitempty"`
141 MaxCompletionTok *int `json:"max_completion_tokens,omitempty"`
142 ReasoningEffort string `json:"reasoning_effort,omitempty"`
143}
144
145// ---- request building ----
146
147func (c *openaiClient) buildRequest(req Request) (*oaiRequest, error) {
148 // Look up the model by id across all providers (not just openai)
149 // because the OpenAI client is also used for ollama and other
150 // OpenAI-compatible backends.
151 m, err := FindModel("", req.Model)
152 if err != nil {
153 // Unknown model: use sensible defaults so local/custom
154 // models still work without a catalog entry.
155 m = Model{
156 ID: req.Model,
157 ContextWindow: 32768,
158 MaxOutput: 8192,
159 }
160 }
161 out := &oaiRequest{
162 Model: req.Model,
163 Stream: true,
164 StreamOptions: &oaiStreamOptions{IncludeUsage: true},
165 Temperature: req.Temperature,
166 }
167
168 maxTok := req.MaxTokens
169 if maxTok <= 0 {
170 maxTok = m.MaxOutput
171 }
172 if m.Reasoning {
173 out.MaxCompletionTok = &maxTok
174 if req.Reasoning != "" {
175 out.ReasoningEffort = strings.ToLower(req.Reasoning)
176 }
177 } else {
178 out.MaxTokens = &maxTok
179 }
180
181 if req.System != "" {
182 out.Messages = append(out.Messages, oaiMessage{Role: "system", Content: req.System})
183 }
184
185 req.Messages = RepairOrphanedToolResults(req.Messages)
186 for _, msg := range req.Messages {
187 switch msg.Role {
188 case RoleUser:
189 content := buildOAIUserContent(msg.Content)
190 out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
191 case RoleAssistant:
192 am := oaiMessage{Role: "assistant"}
193 var text strings.Builder
194 var reasoning strings.Builder
195 for _, b := range msg.Content {
196 switch v := b.(type) {
197 case TextBlock:
198 if text.Len() > 0 {
199 text.WriteString("\n")
200 }
201 text.WriteString(v.Text)
202 case ToolCallBlock:
203 args := v.Arguments
204 if len(args) == 0 || !json.Valid(args) {
205 args = json.RawMessage("{}")
206 }
207 am.ToolCalls = append(am.ToolCalls, oaiToolCall{
208 ID: v.ID,
209 Type: "function",
210 Function: oaiToolCallFn{
211 Name: v.Name,
212 Arguments: string(args),
213 },
214 })
215 case ReasoningBlock:
216 if v.Summary != "" {
217 if reasoning.Len() > 0 {
218 reasoning.WriteString("\n")
219 }
220 reasoning.WriteString(v.Summary)
221 }
222 }
223 }
224 if text.Len() > 0 {
225 am.Content = text.String()
226 }
227 if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
228 am.ReasoningContent = reasoning.String()
229 }
230 out.Messages = append(out.Messages, am)
231 case RoleTool:
232 // Each ToolResultBlock becomes its own tool message. Preserve
233 // image blocks for vision-capable OpenAI models instead of
234 // flattening the tool output to plain text.
235 for _, b := range msg.Content {
236 if tr, ok := b.(ToolResultBlock); ok {
237 content := buildOAIToolContent(tr.Content, tr.IsError)
238 out.Messages = append(out.Messages, oaiMessage{
239 Role: "tool",
240 ToolCallID: tr.CallID,
241 Content: content,
242 })
243 }
244 }
245 }
246 }
247
248 for _, t := range req.Tools {
249 var tool oaiTool
250 tool.Type = "function"
251 tool.Function.Name = t.Name
252 tool.Function.Description = t.Description
253 tool.Function.Parameters = t.Schema
254 out.Tools = append(out.Tools, tool)
255 }
256 if len(out.Tools) > 0 {
257 out.ToolChoice = "auto"
258 }
259
260 return out, nil
261}
262
263func buildOAIUserContent(blocks []Content) interface{} {
264 hasImage := false
265 for _, b := range blocks {
266 if _, ok := b.(ImageBlock); ok {
267 hasImage = true
268 break
269 }
270 }
271 if !hasImage {
272 var sb strings.Builder
273 for _, b := range blocks {
274 if tb, ok := b.(TextBlock); ok {
275 if sb.Len() > 0 {
276 sb.WriteString("\n")
277 }
278 sb.WriteString(tb.Text)
279 }
280 }
281 return sb.String()
282 }
283 return buildOAIContentBlocks(blocks, false)
284}
285
286func buildOAIToolContent(blocks []Content, isError bool) interface{} {
287 hasImage := false
288 for _, b := range blocks {
289 if _, ok := b.(ImageBlock); ok {
290 hasImage = true
291 break
292 }
293 }
294 if !hasImage {
295 var sb strings.Builder
296 for _, b := range blocks {
297 if tb, ok := b.(TextBlock); ok {
298 if sb.Len() > 0 {
299 sb.WriteString("\n")
300 }
301 sb.WriteString(tb.Text)
302 }
303 }
304 if isError && sb.Len() > 0 {
305 sb.WriteString(" [error]")
306 }
307 return sb.String()
308 }
309 return buildOAIContentBlocks(blocks, isError)
310}
311
312func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
313 var arr []interface{}
314 for _, b := range blocks {
315 switch v := b.(type) {
316 case TextBlock:
317 arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
318 case ImageBlock:
319 var img oaiContentImage
320 img.Type = "image_url"
321 img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
322 arr = append(arr, img)
323 }
324 }
325 if isError {
326 arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
327 }
328 return arr
329}
330
331// ---- streaming ----
332
333func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
334 apiPath := "/v1/chat/completions"
335 if strings.HasSuffix(c.baseURL, "/v1") {
336 apiPath = "/chat/completions"
337 }
338 wire, err := c.buildRequest(req)
339 if err != nil {
340 return nil, err
341 }
342 body, err := json.Marshal(wire)
343 if err != nil {
344 return nil, err
345 }
346 httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+apiPath, bytes.NewReader(body))
347 if err != nil {
348 return nil, err
349 }
350 httpReq.Header.Set("content-type", "application/json")
351 httpReq.Header.Set("accept", "text/event-stream")
352 httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
353 for k, v := range c.headers {
354 httpReq.Header.Set(k, v)
355 }
356
357 resp, err := c.http.Do(httpReq)
358 if err != nil {
359 return nil, fmt.Errorf("openai: %w", err)
360 }
361 if resp.StatusCode != http.StatusOK {
362 b, _ := io.ReadAll(resp.Body)
363 resp.Body.Close()
364 return nil, fmt.Errorf("openai: http %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
365 }
366
367 out := make(chan Event, 16)
368 go c.runStream(ctx, resp, req, out)
369 return out, nil
370}
371
372func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
373 defer close(out)
374 defer resp.Body.Close()
375
376 model, _ := FindModel("", req.Model)
377 out <- EventStart{Model: req.Model, Provider: c.Name()}
378
379 raw := make(chan sseEvent, 16)
380 go readSSE(resp.Body, raw)
381
382 // Interleaved block tracking: text and tool_calls preserve their
383 // emission order so the assistant message renders in the same order
384 // the model produced it. The builder fires one kind of block at a
385 // time — incoming text deltas after a tool_call split into a fresh
386 // text block; subsequent tool_calls each get their own slot.
387 type blockEntry struct {
388 kind string // "text" | "tool_use"
389 textBuf strings.Builder
390 toolID string
391 toolName string
392 toolArgs strings.Builder
393 announced bool
394 }
395 var (
396 blocks []*blockEntry
397 currentText *blockEntry // most-recent text block, nil if none
398 toolByIdx = map[int]*blockEntry{} // openai tool_call index -> block
399 reasoningBuf strings.Builder
400 usage Usage
401 stop StopReason = StopEnd
402 finalErr error
403 )
404
405 appendText := func(delta string) {
406 if currentText == nil {
407 currentText = &blockEntry{kind: "text"}
408 blocks = append(blocks, currentText)
409 }
410 currentText.textBuf.WriteString(delta)
411 }
412
413 getOrCreateTool := func(idx int) *blockEntry {
414 if t, ok := toolByIdx[idx]; ok {
415 return t
416 }
417 t := &blockEntry{kind: "tool_use"}
418 toolByIdx[idx] = t
419 blocks = append(blocks, t)
420 // A new tool block breaks the current text block. Subsequent text
421 // deltas will start a fresh text block after this tool.
422 currentText = nil
423 return t
424 }
425
426 assembleMsg := func() Message {
427 content := []Content{}
428 for _, b := range blocks {
429 switch b.kind {
430 case "text":
431 if b.textBuf.Len() > 0 {
432 content = append(content, TextBlock{Text: b.textBuf.String()})
433 }
434 case "tool_use":
435 args := b.toolArgs.String()
436 if args == "" || !json.Valid([]byte(args)) {
437 args = "{}"
438 }
439 content = append(content, ToolCallBlock{
440 ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
441 })
442 }
443 }
444 if reasoningBuf.Len() > 0 {
445 content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
446 }
447 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
448 }
449
450 sendDone := func() {
451 usage.CostUSD = ComputeCost(model, usage)
452 out <- EventUsage{Usage: usage}
453 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
454 }
455
456 for {
457 select {
458 case <-ctx.Done():
459 stop = StopAborted
460 finalErr = ctx.Err()
461 sendDone()
462 return
463 case ev, ok := <-raw:
464 if !ok {
465 sendDone()
466 return
467 }
468 if ev.Data == "[DONE]" {
469 sendDone()
470 return
471 }
472 var chunk struct {
473 Choices []struct {
474 Index int `json:"index"`
475 Delta struct {
476 Content string `json:"content"`
477 ReasoningContent string `json:"reasoning_content"`
478 ToolCalls []struct {
479 Index int `json:"index"`
480 ID string `json:"id"`
481 Type string `json:"type"`
482 Function struct {
483 Name string `json:"name"`
484 Arguments string `json:"arguments"`
485 } `json:"function"`
486 } `json:"tool_calls"`
487 } `json:"delta"`
488 FinishReason string `json:"finish_reason"`
489 } `json:"choices"`
490 Usage *struct {
491 PromptTokens int `json:"prompt_tokens"`
492 CompletionTokens int `json:"completion_tokens"`
493 PromptTokensDetails struct {
494 CachedTokens int `json:"cached_tokens"`
495 } `json:"prompt_tokens_details"`
496 } `json:"usage"`
497 Error *struct {
498 Message string `json:"message"`
499 Type string `json:"type"`
500 } `json:"error"`
501 }
502 if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
503 continue
504 }
505 if chunk.Error != nil {
506 stop = StopError
507 finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
508 sendDone()
509 return
510 }
511 if chunk.Usage != nil {
512 usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
513 if usage.InputTokens < 0 {
514 usage.InputTokens = chunk.Usage.PromptTokens
515 }
516 usage.OutputTokens = chunk.Usage.CompletionTokens
517 usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
518 }
519 for _, ch := range chunk.Choices {
520 if ch.Delta.ReasoningContent != "" {
521 reasoningBuf.WriteString(ch.Delta.ReasoningContent)
522 }
523 if ch.Delta.Content != "" {
524 appendText(ch.Delta.Content)
525 out <- EventTextDelta{Delta: ch.Delta.Content}
526 }
527 for _, tc := range ch.Delta.ToolCalls {
528 t := getOrCreateTool(tc.Index)
529 if tc.ID != "" {
530 t.toolID = tc.ID
531 }
532 if tc.Function.Name != "" {
533 t.toolName = tc.Function.Name
534 }
535 if !t.announced && t.toolID != "" && t.toolName != "" {
536 t.announced = true
537 out <- EventToolStart{ID: t.toolID, Name: t.toolName}
538 }
539 if tc.Function.Arguments != "" {
540 t.toolArgs.WriteString(tc.Function.Arguments)
541 if t.announced {
542 out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
543 }
544 }
545 }
546 switch ch.FinishReason {
547 case "stop":
548 stop = StopEnd
549 case "length":
550 stop = StopLength
551 case "tool_calls", "function_call":
552 stop = StopToolUse
553 for _, b := range blocks {
554 if b.kind == "tool_use" && b.announced {
555 out <- EventToolEnd{ID: b.toolID}
556 }
557 }
558 }
559 }
560 }
561 }
562}