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