返回 DeepSeek-Reasonix
openai.go
根目录 / internal / provider / openai / openai.go
1 // Package openai implements the OpenAI-compatible /chat/completions provider.
2 // It self-registers under the "openai" kind, so DeepSeek, MiMo, MiniMax-M3, and
3 // any other OpenAI-compatible endpoint are just config instances rather than
4 // code. Each instance picks the wire shape from its base URL:
5 // - api.deepseek.com → emits thinking.type=enabled (DeepSeek-flavor CoT) plus
6 // reasoning_effort as a depth hint.
7 // - api.minimaxi.com → emits thinking.type=adaptive|disabled (M3's binary
8 // knob) instead of reasoning_effort, since M3 has no level scale.
9 // - open.bigmodel.cn / api.z.ai (Zhipu GLM) → emits thinking.type=enabled|
10 // disabled instead of reasoning_effort, which Zhipu silently ignores.
11 // - api.longcat.chat → emits thinking.type=enabled|disabled and omits
12 // reasoning_effort, matching LongCat's OpenAI-compatible API.
13 // - ollama.com → accepts hosted Ollama Cloud's reasoning_effort scale,
14 // including max, and omits the field for none/disabled.
15 // - Kimi K3 preserves complete messages and uses max_completion_tokens.
16 // - everything else (MiMo and other OpenAI-compatible gateways) uses the
17 // vanilla reasoning_effort scale (low/medium/high), unless its config
18 // declares a custom supported_efforts validation contract.
19 //
20 // See docs/REASONING_PROVIDERS.md for the per-backend protocol reference.
21 package openai
22
23 import (
24 "bytes"
25 "context"
26 "encoding/json"
27 "errors"
28 "fmt"
29 "io"
30 "maps"
31 "net/http"
32 "sort"
33 "strings"
34 "sync"
35 "sync/atomic"
36 "time"
37
38 "reasonix/internal/netclient"
39 "reasonix/internal/provider"
40 )
41
42 // defaultStreamIdleTimeout caps how long a started SSE stream may go without any
43 // bytes before it's treated as a dropped connection. A half-open TCP connection
44 // (e.g. a proxy switched mid-stream) sends no RST, so scanner.Scan() would block
45 // forever; this turns that hang into a recoverable error. Generous on purpose —
46 // live streams emit tokens/keepalives far more often. Stored per-client
47 // (client.idleTimeout) so a test can shorten it without a shared global that
48 // would race other streams' watchdogs.
49 const defaultStreamIdleTimeout = 300 * time.Second
50
51 // maxPrefixContinuations keeps automatic recovery bounded. A second length
52 // finish is surfaced through the existing truncation notice instead of opening
53 // an unbounded (and billable) continuation loop against the Beta endpoint.
54 const maxPrefixContinuations = 1
55
56 func init() {
57 provider.RegisterReasoning("openai", ReasoningForConfig)
58 provider.Register("openai", New)
59 }
60
61 // New builds an OpenAI-compatible provider from a resolved config.
62 func New(cfg provider.Config) (provider.Provider, error) {
63 cfg = provider.ApplyOpenCodeGoContract("openai", cfg)
64 if cfg.BaseURL == "" {
65 return nil, fmt.Errorf("openai: base_url is required for provider %q", cfg.Name)
66 }
67 if cfg.Model == "" {
68 return nil, fmt.Errorf("openai: model is required for provider %q", cfg.Name)
69 }
70 name := cfg.Name
71 if name == "" {
72 name = "openai"
73 }
74 keyEnv, _ := cfg.Extra["api_key_env"].(string) // for actionable auth errors
75 keySource, _ := cfg.Extra["api_key_source"].(string)
76 effort, err := configuredEffort(cfg)
77 if err != nil {
78 return nil, err
79 }
80 if effort == "auto" {
81 effort = ""
82 }
83 protocol, _ := cfg.Extra["reasoning_protocol"].(string)
84 protocol = normalizeReasoningProtocol(protocol)
85 kimiK3 := usesKimiK3Contract(protocol, cfg.BaseURL, cfg.Model)
86 supportedEfforts, _ := cfg.Extra["supported_efforts"].([]string)
87 // A meaningful explicit list is the endpoint's declared effort vocabulary;
88 // auto remains implicit and is therefore ignored here.
89 supportedEfforts, hasExplicitEfforts := reasoningEffortVocabulary(kimiK3, supportedEfforts)
90 chatURL := resolveOpenAIChatURL(cfg.BaseURL, cfg.Extra)
91 prefixChatURL := deepSeekPrefixChatURL(chatURL)
92 headers, _ := cfg.Extra["headers"].(map[string]string)
93 extraBody, _ := cfg.Extra["extra_body"].(map[string]any)
94 vision, _ := cfg.Extra["vision"].(bool)
95 officialDeepSeek := IsDeepSeek(cfg.BaseURL)
96 modelInfo := provider.ModelInfo{ID: cfg.Model, InputModalities: []provider.ModelModality{provider.ModalityText}}
97 if cfg.ModelInfo != nil {
98 modelInfo = *cfg.ModelInfo
99 modelInfo.ID = cfg.Model
100 }
101 if cfg.ModelInfo != nil {
102 vision = modelInfo.SupportsInput(provider.ModalityImage)
103 }
104 // Keep known text-only models blocked; unknown models use declared capability.
105 vision = DeepSeekImageInputAllowed(officialDeepSeek, chatURL, cfg.Model, cfg.ModelInfo != nil, vision)
106 if vision {
107 modelInfo.InputModalities = []provider.ModelModality{provider.ModalityText, provider.ModalityImage}
108 } else if modelInfo.SupportsInput(provider.ModalityImage) {
109 modelInfo.InputModalities = []provider.ModelModality{provider.ModalityText}
110 }
111 visionDetail, _ := cfg.Extra["vision_detail"].(string)
112 visionDetail = strings.ToLower(strings.TrimSpace(visionDetail))
113 if visionDetail != "low" && visionDetail != "high" {
114 visionDetail = "" // auto — omit the field
115 }
116 deepseek := protocol == "deepseek" || (protocol == "" && officialDeepSeek)
117 maxOutputTokens, _ := cfg.Extra["max_output_tokens"].(int)
118 deepseekV4Model := strings.EqualFold(strings.TrimSpace(cfg.Model), "deepseek-v4-flash") ||
119 strings.EqualFold(strings.TrimSpace(cfg.Model), "deepseek-v4-pro") ||
120 IsOfficialDeepSeekVisionModel(cfg.Model)
121 minimax := protocol == "" && IsMiniMax(cfg.BaseURL)
122 zhipu := protocol == "glm" || (protocol == "" && IsZhipu(cfg.BaseURL))
123 longcat := protocol == "" && IsLongCat(cfg.BaseURL)
124 ollamaCloud := protocol == "" && IsOllamaCloud(cfg.BaseURL)
125 thinkingType := configuredThinkingType(cfg)
126 switch {
127 case protocol == "none":
128 effort = ""
129 case deepseek:
130 if thinkingType == "disabled" {
131 effort = ""
132 break
133 }
134 if deepseekV4Model && !hasExplicitEfforts && (effort == "medium" || effort == "xhigh") {
135 effort = "high"
136 }
137 switch effort {
138 case "", "off": // "off" is a retired level (disabled thinking); fall back to the default depth
139 effort = "high"
140 case "disabled":
141 if hasExplicitEfforts && !supportsEffort(supportedEfforts, effort) {
142 return nil, fmt.Errorf("openai: provider %q: effort %q is not listed in supported_efforts: %v", name, effort, supportedEfforts)
143 }
144 // DeepSeek can turn thinking off too; route through thinking.type and
145 // drop the depth hint so the wire carries thinking.type=disabled only.
146 effort = ""
147 thinkingType = "disabled"
148 default:
149 if hasExplicitEfforts {
150 // A provider that declares supported_efforts defines the endpoint's
151 // complete effort vocabulary. Honor that list for compatible DeepSeek
152 // request shapes instead of applying the built-in official scale.
153 if !supportsEffort(supportedEfforts, effort) {
154 return nil, fmt.Errorf("openai: provider %q: effort %q is not listed in supported_efforts: %v", name, effort, supportedEfforts)
155 }
156 break
157 }
158 switch effort {
159 case "low":
160 if !deepseekV4Model {
161 return nil, fmt.Errorf("openai: provider %q uses DeepSeek thinking; effort low requires deepseek-v4-flash, deepseek-v4-pro, deepseek-v4-flash-vision-exp, or explicit supported_efforts", name)
162 }
163 case "high", "max":
164 default:
165 return nil, fmt.Errorf("openai: provider %q uses DeepSeek thinking; effort must be low, high, max, or disabled", name)
166 }
167 }
168 case minimax:
169 // The adapter capability admits only the binary M3 vocabulary.
170 effort = strings.ToLower(strings.TrimSpace(effort))
171 switch effort {
172 case "": // auto — leave empty so the wire emits thinking.type=adaptive
173 case "adaptive", "disabled":
174 default:
175 return nil, fmt.Errorf("openai: provider %q uses MiniMax thinking; effort must be adaptive or disabled", name)
176 }
177 case zhipu:
178 // Zhipu GLM gates chain-of-thought through `thinking.type`
179 // (enabled|disabled) and silently ignores reasoning_effort, so /effort
180 // mirrors that binary knob; "" preserves the default (thinking on).
181 switch effort {
182 case "", "enabled", "disabled":
183 default:
184 return nil, fmt.Errorf("openai: provider %q uses Zhipu thinking; effort must be enabled or disabled", name)
185 }
186 case longcat:
187 // LongCat exposes a binary thinking knob on its OpenAI-compatible endpoint:
188 // thinking.type=enabled|disabled. It documents reasoning text via
189 // reasoning_content, but not the generic reasoning_effort scale.
190 switch effort {
191 case "", "enabled", "disabled":
192 default:
193 return nil, fmt.Errorf("openai: provider %q uses LongCat thinking; effort must be enabled or disabled", name)
194 }
195 case ollamaCloud:
196 // Hosted Ollama Cloud uses top-level reasoning_effort. "none" and the
197 // legacy/off aliases intentionally omit the field, which lets the model
198 // run without thinking. Local Ollama is not auto-detected because its
199 // model/version support varies.
200 switch effort {
201 case "", "none", "disabled", "off":
202 effort = ""
203 case "xhigh", "max":
204 effort = "max"
205 case "low", "medium", "high":
206 default:
207 return nil, fmt.Errorf("openai: provider %q uses Ollama Cloud thinking; effort must be none, low, medium, high, or max", name)
208 }
209 case effort != "":
210 if hasExplicitEfforts {
211 // Explicit endpoint metadata overrides the generic OpenAI enum and its
212 // legacy max-to-high compatibility clamp.
213 if !supportsEffort(supportedEfforts, effort) {
214 return nil, fmt.Errorf("openai: provider %q: effort %q is not listed in supported_efforts: %v", name, effort, supportedEfforts)
215 }
216 break
217 }
218 // Non-DeepSeek backends use OpenAI's reasoning_effort scale (low/medium/
219 // high) by default. Without an explicit provider vocabulary, max remains
220 // clamped to the OpenAI ceiling because MiMo and similar backends reject it.
221 switch effort {
222 case "max":
223 effort = "high"
224 case "low", "medium", "high":
225 default:
226 return nil, fmt.Errorf("openai: provider %q: effort must be low, medium, or high", name)
227 }
228 }
229
230 // max_output_tokens=0 on official DeepSeek omits the wire field so the
231 // server uses its 384K ceiling. Effort only selects thinking depth.
232 // Non-DeepSeek endpoints leave 0 as "unset / omit". Never compact_ratio.
233 httpClient, err := newHTTPClient(cfg)
234 if err != nil {
235 return nil, fmt.Errorf("openai: network: %w", err)
236 }
237 return &client{
238 identityHeaders: provider.NewClientIdentityHeaders(),
239 reasoningState: reasoningState{ollamaCloud: ollamaCloud, thinkingLocked: configuredThinkingType(cfg) == "disabled", reasoning: ReasoningForConfig(cfg)},
240 name: name,
241 identity: provider.RequestIdentity{Provider: name, DisplayName: cfg.DisplayName, Protocol: cfg.Protocol},
242 apiKey: cfg.APIKey,
243 keyEnv: keyEnv,
244 keySource: keySource,
245 baseURL: strings.TrimRight(cfg.BaseURL, "/"),
246 chatURL: chatURL,
247 prefixChatURL: prefixChatURL,
248 headers: cleanCustomHeaders(headers),
249 extraBody: cleanExtraBody(extraBody),
250 model: deepSeekChatWireModel(chatURL, normalizeModelID(cfg.BaseURL, cfg.Model)),
251 deepseek: deepseek,
252 minimax: minimax,
253 zhipu: zhipu,
254 longcat: longcat,
255 kimiK3: kimiK3,
256 mimo: IsMiMo(cfg.BaseURL),
257 thinkingType: thinkingType,
258 vision: vision,
259 modelInfo: modelInfo,
260 visionDetail: visionDetail,
261 maxOutputTokens: maxOutputTokens,
262 effort: effort,
263 http: httpClient,
264 idleTimeout: defaultStreamIdleTimeout,
265 }, nil
266 }
267
268 func newHTTPClient(cfg provider.Config) (*http.Client, error) {
269 if cfg.HTTPClient != nil {
270 return cfg.HTTPClient, nil
271 }
272 spec, _ := cfg.Extra["proxy_spec"].(netclient.ProxySpec)
273 client, err := netclient.NewHTTPClient(spec, netclient.TransportOptions{
274 DialTimeout: 30 * time.Second,
275 KeepAlive: 30 * time.Second,
276 TLSHandshakeTimeout: 15 * time.Second,
277 ResponseHeaderTimeout: 300 * time.Second, // unified provider response-header idle guard
278 })
279 if err != nil {
280 return nil, err
281 }
282 return provider.WithProtocolCompatibility(client, provider.RequestIdentity{Provider: cfg.Name, Protocol: "openai"}), nil
283 }
284
285 type client struct {
286 identityHeaders http.Header
287 reasoningState
288 name string
289 identity provider.RequestIdentity
290 apiKey string
291 keyEnv string // api_key_env name, surfaced in auth errors
292 keySource string // source of keyEnv, surfaced in auth errors
293 baseURL string
294 chatURL string
295 prefixChatURL string // official DeepSeek Beta endpoint; empty for custom gateways
296 headers map[string]string
297 extraBody map[string]any
298 model string
299 http *http.Client
300 deepseek bool
301 minimax bool // true for api.minimaxi.com — emits MiniMax-M3's thinking knob instead of reasoning_effort
302 zhipu bool // true for Zhipu GLM (bigmodel.cn / z.ai) — gates thinking via thinking.type, ignores reasoning_effort
303 longcat bool // true for LongCat — gates thinking via thinking.type, ignores reasoning_effort
304 kimiK3 bool // true for the explicit K3 protocol or kimi-k3 on Moonshot's direct API hosts
305 mimo bool // true for MiMo — upgrades legacy tuple schemas to Draft 2020-12
306 thinkingType string // explicit `thinking` config override (enabled|disabled); "" = no override
307 vision bool // model accepts image input — embed attached images as image_url parts
308 modelInfo provider.ModelInfo
309 visionDetail string // image_url detail hint (low|high); "" = auto/omit
310 maxOutputTokens int // resolved total output budget; <=0 omits the optional field
311 effort string // reasoning_effort for OpenAI; thinking.type for MiniMax; "" = auto/provider default
312 idleTimeout time.Duration // SSE stall watchdog window; defaultStreamIdleTimeout unless a test overrides
313 authed atomic.Bool // a request has succeeded — gate transient-401 retry
314 }
315
316 func (c *client) Name() string { return c.name }
317
318 func (c *client) ModelInfo() provider.ModelInfo {
319 if c == nil {
320 return provider.ModelInfo{}
321 }
322 info := c.modelInfo
323 info.InputModalities = append([]provider.ModelModality(nil), info.InputModalities...)
324 return info
325 }
326
327 func (c *client) RequiresToolCallReasoning() bool {
328 if c == nil || c.thinkingType == "disabled" {
329 return false
330 }
331 if c.deepseek {
332 return true
333 }
334 // Generic OpenAI-compatible gateways can explicitly opt into the
335 // DeepSeek-style replay contract with thinking=enabled (#7763/#7748).
336 // GLM and Kimi K3 keep their broader round-trip policies.
337 return !c.zhipu && !c.kimiK3 && c.thinkingType == "enabled"
338 }
339
340 func (c *client) AllowsEmptyReasoningFallback() bool {
341 return c != nil && (c.RequiresToolCallReasoning() || c.glmThinkingEnabled())
342 }
343
344 func (c *client) RequiresReasoningRoundTrip() bool {
345 return c != nil && (c.kimiK3 || c.glmThinkingEnabled())
346 }
347
348 func (c *client) WarnOnMissingToolCallReasoning() bool {
349 return c.RequiresToolCallReasoning() && expectsDeepSeekToolCallReasoning(c.model, c.thinkingType)
350 }
351
352 func (c *client) glmThinkingEnabled() bool {
353 if c == nil || !c.zhipu {
354 return false
355 }
356 t := c.effort
357 if c.thinkingType != "" {
358 t = c.thinkingType
359 }
360 return t != "disabled"
361 }
362
363 func expectsDeepSeekToolCallReasoning(model, thinkingType string) bool {
364 if strings.EqualFold(strings.TrimSpace(thinkingType), "enabled") {
365 return true
366 }
367 model = strings.ToLower(strings.TrimSpace(model))
368 return strings.Contains(model, "deepseek-v4-flash") ||
369 strings.Contains(model, "deepseek-v4-pro") ||
370 strings.Contains(model, "deepseek-v3.2") ||
371 strings.Contains(model, "deepseek-reasoner") ||
372 strings.Contains(model, "deepseek-r1")
373 }
374
375 func (c *client) MissingToolCallReasoningWarningIdentity() string {
376 if c == nil {
377 return ""
378 }
379 protocol := "openai"
380 if c.deepseek {
381 protocol = "deepseek"
382 }
383 return strings.Join([]string{
384 "openai", strings.TrimSpace(c.name), strings.TrimSpace(c.baseURL),
385 strings.TrimSpace(c.model), protocol, strings.TrimSpace(c.thinkingType), strings.TrimSpace(c.effort),
386 }, "\x00")
387 }
388
389 func (c *client) sendOpts() provider.SendOptions {
390 return provider.SendOptions{
391 Provider: c.name,
392 ProviderDisplayName: c.identity.DisplayName,
393 Protocol: c.identity.Protocol,
394 KeyEnv: c.keyEnv,
395 KeySource: c.keySource,
396 KeyPresent: c.apiKey != "",
397 RetryAuth: c.authed.Load(),
398 }
399 }
400
401 func normalizeReasoningProtocol(raw string) string {
402 switch strings.ToLower(strings.TrimSpace(raw)) {
403 case "deepseek", "glm", "kimi-k3", "openai", "none":
404 return strings.ToLower(strings.TrimSpace(raw))
405 default:
406 return ""
407 }
408 }
409
410 func cleanCustomHeaders(in map[string]string) map[string]string {
411 if len(in) == 0 {
412 return nil
413 }
414 out := make(map[string]string, len(in))
415 for rawName, rawValue := range in {
416 name := strings.TrimSpace(rawName)
417 value := strings.TrimSpace(rawValue)
418 if name == "" || value == "" || reservedCustomHeader(name) {
419 continue
420 }
421 out[name] = value
422 }
423 if len(out) == 0 {
424 return nil
425 }
426 return out
427 }
428
429 func applyCustomHeaders(h http.Header, headers map[string]string) {
430 for name, value := range cleanCustomHeaders(headers) {
431 h.Set(name, value)
432 }
433 }
434
435 func applyAPIKeyHeader(h http.Header, baseURL, apiKey string) {
436 apiKey = strings.TrimSpace(apiKey)
437 if apiKey == "" {
438 return
439 }
440 if IsMiMo(baseURL) {
441 h.Set("api-key", apiKey)
442 return
443 }
444 h.Set("Authorization", "Bearer "+apiKey)
445 }
446
447 func cleanExtraBody(in map[string]any) map[string]any {
448 if len(in) == 0 {
449 return nil
450 }
451 out := make(map[string]any, len(in))
452 for rawName, value := range in {
453 name := strings.TrimSpace(rawName)
454 if name == "" || reservedExtraBodyField(name) {
455 continue
456 }
457 out[name] = value
458 }
459 if len(out) == 0 {
460 return nil
461 }
462 return out
463 }
464
465 func reservedExtraBodyField(name string) bool {
466 switch strings.ToLower(strings.TrimSpace(name)) {
467 case "model", "messages", "tools", "stream", "stream_options", "temperature", "max_tokens", "max_completion_tokens", "max_output_tokens", "reasoning_effort", "thinking":
468 return true
469 default:
470 return false
471 }
472 }
473
474 func reservedCustomHeader(name string) bool {
475 switch strings.ToLower(strings.TrimSpace(name)) {
476 case "authorization", "content-type", "accept", "host":
477 return true
478 default:
479 return false
480 }
481 }
482
483 // bufPool reuses byte buffers for JSON-marshalled request bodies. Each turn
484 // allocates a buffer, marshals the request, and sends it — pooling avoids the
485 // GC churn from repeated alloc/free of ~10-100KB buffers. The pool is
486 // provider-level (not global) so OpenAI and Anthropic don't compete.
487 var bufPool = sync.Pool{
488 New: func() any { return new(bytes.Buffer) },
489 }
490
491 func (c *client) Stream(ctx context.Context, req provider.Request) (<-chan provider.Chunk, error) {
492 if err := c.reasoning.Validate(c.model, req.EffortOverride); err != nil {
493 return nil, err
494 }
495 stream, err := c.openStream(ctx, c.chatURL, c.buildRequest(req), req.Tools)
496 if err != nil {
497 return nil, err
498 }
499 if c.prefixChatURL == "" {
500 return stream, nil
501 }
502
503 out := make(chan provider.Chunk)
504 go c.streamWithPrefixContinuation(ctx, req, stream, out)
505 return out, nil
506 }
507
508 func (c *client) openStream(ctx context.Context, targetURL string, wireReq chatRequest, tools []provider.ToolSchema) (<-chan provider.Chunk, error) {
509 requestCtx := provider.WithRequestAttemptCounter(ctx)
510 buf := bufPool.Get().(*bytes.Buffer)
511 buf.Reset()
512 if err := json.NewEncoder(buf).Encode(wireReq); err != nil {
513 bufPool.Put(buf)
514 return nil, fmt.Errorf("%s: marshal request: %w", c.name, err)
515 }
516 body := make([]byte, buf.Len())
517 copy(body, buf.Bytes())
518 bufPool.Put(buf)
519
520 newReq := func(ctx context.Context) (*http.Request, error) {
521 httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body))
522 if err != nil {
523 return nil, err
524 }
525 httpReq.Header.Set("Content-Type", "application/json")
526 applyAPIKeyHeader(httpReq.Header, c.baseURL, c.apiKey)
527 httpReq.Header.Set("Accept", "text/event-stream")
528 applyCustomHeaders(httpReq.Header, c.headers)
529 provider.ApplyOpenCodeGoHeaders(httpReq, c.baseURL, c.identityHeaders)
530 return httpReq, nil
531 }
532 resp, err := provider.SendWithRetry(requestCtx, c.http, c.sendOpts(), newReq)
533 if err != nil {
534 return nil, provider.AnnotateToolSchemaError(err, tools)
535 }
536 c.authed.Store(true)
537
538 out := make(chan provider.Chunk)
539 // Body-phase stream cuts surface as StreamInterruptedError so the Agent
540 // can preserve partial output and let the user decide whether to retry.
541 go c.streamOnce(requestCtx, resp, out)
542 return out, nil
543 }
544
545 // streamWithPrefixContinuation makes a DeepSeek Beta continuation look like one
546 // ordinary provider stream. Text/reasoning stays live, while usage is folded
547 // across both requests so cost and cache accounting remain truthful. If the
548 // Beta request fails before emitting anything, the original truncated response
549 // is kept and its finish_reason=length reaches the agent's existing warning.
550 func (c *client) streamWithPrefixContinuation(ctx context.Context, req provider.Request, current <-chan provider.Chunk, out chan<- provider.Chunk) {
551 defer close(out)
552
553 var fullText, fullReasoning strings.Builder
554 var totalUsage *provider.Usage
555 continuations := 0
556
557 for {
558 var currentUsage *provider.Usage
559 currentHadTool := false
560 currentEmitted := false
561
562 for chunk := range current {
563 switch chunk.Type {
564 case provider.ChunkText:
565 fullText.WriteString(chunk.Text)
566 currentEmitted = currentEmitted || chunk.Text != ""
567 if !sendChunk(ctx, out, chunk) {
568 return
569 }
570 case provider.ChunkReasoning:
571 fullReasoning.WriteString(chunk.Text)
572 currentEmitted = currentEmitted || chunk.Text != ""
573 if !sendChunk(ctx, out, chunk) {
574 return
575 }
576 case provider.ChunkToolCallStart, provider.ChunkToolCallArgsDelta, provider.ChunkToolCall:
577 currentHadTool = true
578 currentEmitted = true
579 if !sendChunk(ctx, out, chunk) {
580 return
581 }
582 case provider.ChunkUsage:
583 currentUsage = mergeUsage(currentUsage, chunk.Usage, false)
584 case provider.ChunkDone:
585 // The wrapper emits one final Done after any continuation.
586 case provider.ChunkError:
587 // A Beta failure before any continuation bytes is a safe fallback:
588 // the already-streamed first response remains visible and its
589 // length finish reason triggers the normal truncation warning.
590 if continuations > 0 && !currentEmitted && ctx.Err() == nil {
591 emitUsageAndDone(ctx, out, totalUsage)
592 return
593 }
594 _ = sendChunk(ctx, out, chunk)
595 return
596 default:
597 if !sendChunk(ctx, out, chunk) {
598 return
599 }
600 }
601 }
602
603 totalUsage = mergeUsage(totalUsage, currentUsage, true)
604 if continuations >= maxPrefixContinuations ||
605 currentUsage == nil || currentUsage.FinishReason != "length" ||
606 currentHadTool ||
607 (fullText.Len() == 0 && (c.thinkingType == "disabled" || fullReasoning.Len() == 0)) {
608 emitUsageAndDone(ctx, out, totalUsage)
609 return
610 }
611
612 prefixReq := c.buildPrefixRequest(req, fullText.String(), fullReasoning.String())
613 next, err := c.openStream(ctx, c.prefixChatURL, prefixReq, req.Tools)
614 if err != nil {
615 emitUsageAndDone(ctx, out, totalUsage)
616 return
617 }
618 continuations++
619 current = next
620 }
621 }
622
623 func emitUsageAndDone(ctx context.Context, out chan<- provider.Chunk, usage *provider.Usage) {
624 if usage != nil && !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkUsage, Usage: usage}) {
625 return
626 }
627 _ = sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkDone})
628 }
629
630 // mergeUsage folds token counters. countRequests is false for multiple usage
631 // chunks from one HTTP stream (keep its request count), and true when combining
632 // distinct prefix-continuation requests (sum their request counts).
633 func mergeUsage(total, next *provider.Usage, countRequests bool) *provider.Usage {
634 if next == nil {
635 return total
636 }
637 if total == nil {
638 clone := *next
639 return &clone
640 }
641 totalRequests := usageRequestCount(total)
642 nextRequests := usageRequestCount(next)
643 total.PromptTokens += next.PromptTokens
644 total.CompletionTokens += next.CompletionTokens
645 total.TotalTokens += next.TotalTokens
646 total.CacheHitTokens += next.CacheHitTokens
647 total.CacheMissTokens += next.CacheMissTokens
648 total.CacheWriteTokens += next.CacheWriteTokens
649 total.CacheWriteBilledTokens += next.CacheWriteBilledTokens
650 total.ReasoningTokens += next.ReasoningTokens
651 if countRequests {
652 total.RequestCount = totalRequests + nextRequests
653 } else if nextRequests > totalRequests {
654 total.RequestCount = nextRequests
655 } else {
656 total.RequestCount = totalRequests
657 }
658 total.FinishReason = next.FinishReason
659 return total
660 }
661
662 func usageRequestCount(usage *provider.Usage) int {
663 if usage != nil && usage.RequestCount > 0 {
664 return usage.RequestCount
665 }
666 return 1
667 }
668
669 // streamOnce drives a single body read. Mid-stream transport cuts become
670 // StreamInterruptedError so the Agent can commit-or-replay; providers no longer
671 // replay the body themselves (that would stack retry budgets with the Agent).
672 func (c *client) streamOnce(ctx context.Context, resp *http.Response, out chan<- provider.Chunk) {
673 defer close(out)
674 _, err := c.readStream(ctx, resp, out)
675 if err == nil {
676 return
677 }
678 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
679 sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkError, Err: err})
680 return
681 }
682 if provider.IsConnReset(err) {
683 sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkError, Err: provider.StreamInterrupt(err, provider.ClassifyStreamInterrupt(err))})
684 return
685 }
686 sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkError, Err: err})
687 }
688
689 func sendChunk(ctx context.Context, out chan<- provider.Chunk, chunk provider.Chunk) bool {
690 select {
691 case out <- chunk:
692 return true
693 default:
694 }
695 select {
696 case <-ctx.Done():
697 return false
698 case out <- chunk:
699 return true
700 }
701 }
702
703 func (c *client) buildRequest(req provider.Request) chatRequest {
704 openCodeGoRoute, officialOpenCodeGo := provider.OpenCodeGoRequestRoute("openai", c.baseURL, c.chatURL, "")
705 openCodeGoChat := officialOpenCodeGo && openCodeGoRoute == provider.OpenCodeGoRouteChat
706 // Repair tool-call pairing before sending: an interrupted/resumed history can
707 // carry an assistant tool_calls turn whose results never landed, which DeepSeek
708 // rejects with a 400 ("must be followed by tool messages …").
709 src := provider.SanitizeToolPairing(req.Messages)
710 msgs := make([]chatMessage, 0, len(src))
711 // Images returned by tool calls can't ride in the tool message itself — the
712 // OpenAI API accepts only text content parts under role "tool" — so they are
713 // carried by a synthetic user message injected after the turn's full run of
714 // tool results, before the next non-tool message (splitting a tool-result
715 // run would break the API's tool-call pairing validation).
716 var pendingToolImages []string
717 flushToolImages := func() {
718 if len(pendingToolImages) == 0 {
719 return
720 }
721 msgs = append(msgs, chatMessage{
722 Role: "user",
723 Content: imageContentParts("Images returned by the preceding tool call(s):", pendingToolImages, c.visionDetail),
724 })
725 pendingToolImages = nil
726 }
727 for _, m := range src {
728 if m.Role != provider.RoleTool {
729 flushToolImages()
730 }
731 cm := chatMessage{
732 Role: string(m.Role),
733 ToolCallID: m.ToolCallID,
734 }
735 if m.Role == provider.RoleTool && !openCodeGoChat {
736 // Strict backends (MiMo) 400 a tool result without name (#4711).
737 name := m.Name
738 cm.Name = &name
739 }
740 // DeepSeek thinking mode requires the reasoning_content KEY on every
741 // assistant history turn, plain turns included: the API accepts an empty
742 // string, while omitting the key produces a 400. Preserve non-empty
743 // reasoning even when the current round has since disabled thinking.
744 if m.Role == provider.RoleAssistant {
745 switch {
746 case c.kimiK3 && (m.ReasoningContent != "" || len(m.ToolCalls) > 0):
747 // Kimi K3 requires the complete assistant message on multi-turn
748 // and tool-call requests, including provider-issued reasoning.
749 cm.ReasoningContent = &m.ReasoningContent
750 case c.RequiresToolCallReasoning() && (c.deepseek || hasReasoningOrToolCall(m)):
751 cm.ReasoningContent = &m.ReasoningContent
752 case c.deepseek && m.ReasoningContent != "":
753 cm.ReasoningContent = &m.ReasoningContent
754 case c.zhipu && (m.ReasoningContent != "" || (c.glmThinkingEnabled() && len(m.ToolCalls) > 0)):
755 // GLM interleaved and preserved thinking require provider-issued
756 // reasoning unchanged. Coding Plan includes the field on tool turns
757 // even when empty; preserve non-empty history after disabling too.
758 cm.ReasoningContent = &m.ReasoningContent
759 }
760 }
761 for _, tc := range m.ToolCalls {
762 wire := chatToolCall{ID: tc.ID, Type: "function"}
763 wire.Function.Name = tc.Name
764 wire.Function.Arguments = tc.Arguments
765 if tc.ThoughtSignature != "" && usesGeminiThoughtSignatures(c.baseURL, c.model) {
766 // Gemini's current OpenAI compatibility schema carries the
767 // opaque signature beside the function payload. Keep the
768 // legacy function.thought_signature field decode-only below so
769 // older gateways remain readable without sending an unknown
770 // function parameter to current Google endpoints.
771 wire.ExtraContent = &chatToolCallExtraContent{}
772 wire.ExtraContent.Google.ThoughtSignature = tc.ThoughtSignature
773 }
774 cm.ToolCalls = append(cm.ToolCalls, wire)
775 }
776 switch {
777 case c.vision && m.Role == provider.RoleUser && len(m.Images) > 0:
778 cm.Content = imageContentParts(m.Content, m.Images, c.visionDetail)
779 case m.Role != provider.RoleAssistant || len(cm.ToolCalls) == 0 || m.Content != "":
780 cm.Content = m.Content
781 }
782 msgs = append(msgs, cm)
783 if c.vision && m.Role == provider.RoleTool {
784 pendingToolImages = append(pendingToolImages, m.Images...)
785 }
786 }
787 flushToolImages()
788
789 tools := encodeChatTools(req, c.mimo)
790
791 maxOutputTokens := req.MaxTokens
792 if maxOutputTokens == 0 {
793 maxOutputTokens = c.maxOutputTokens
794 }
795 if maxOutputTokens < 0 {
796 maxOutputTokens = 0
797 }
798 out := chatRequest{
799 Model: c.model,
800 Messages: msgs,
801 Tools: tools,
802 Stream: true,
803 StreamOptions: &streamOptions{IncludeUsage: true},
804 Temperature: req.Temperature,
805 MaxTokens: maxOutputTokens,
806 ReasoningEffort: kimiK3ReasoningEffort(c.kimiK3, c.requestEffort(req)),
807 ExtraBody: c.extraBody,
808 }
809 c.applyReasoning(&out, req)
810 return out
811 }
812
813 func (c *client) buildPrefixRequest(req provider.Request, content, reasoning string) chatRequest {
814 out := c.buildRequest(req)
815 prefix := chatMessage{Role: "assistant", Content: content, Prefix: true}
816 if c.deepseek && c.thinkingType != "disabled" {
817 prefix.ReasoningContent = &reasoning
818 }
819 out.Messages = append(out.Messages, prefix)
820 return out
821 }
822
823 // readStream parses one SSE response into chunks: text deltas stream live,
824 // tool-call fragments accumulate by index and emit complete on [DONE], and a
825 // ChunkToolCallStart fires the moment a call's name is known. It returns whether
826 // any model output was forwarded (so the caller can decide a replay is safe) and
827 // the first fatal error — a nil error means the stream reached [DONE].
828 func (c *client) readStream(ctx context.Context, resp *http.Response, out chan<- provider.Chunk) (emitted bool, _ error) {
829 defer resp.Body.Close()
830
831 // Close the response body when the context is canceled (user interrupt) or the
832 // stream stalls past c.idleTimeout, so scanner.Scan() unblocks instead of
833 // hanging on a half-open connection. done lets the watchdog exit on a normal
834 // return — otherwise it outlives the call and blocks forever on a non-cancellable
835 // context whose Done() is nil. The watchdog owns the timer; the read loop only
836 // pings the buffered activity channel, so there's no Timer.Reset race.
837 idleTimeout := c.idleTimeout
838 if idleTimeout <= 0 { // zero-value client (constructed without New)
839 idleTimeout = defaultStreamIdleTimeout
840 }
841 done := make(chan struct{})
842 defer close(done)
843 activity := make(chan struct{}, 1)
844 var stalled atomic.Bool
845 go func() {
846 idle := time.NewTimer(idleTimeout)
847 defer idle.Stop()
848 for {
849 select {
850 case <-ctx.Done():
851 resp.Body.Close()
852 return
853 case <-idle.C:
854 stalled.Store(true)
855 resp.Body.Close()
856 return
857 case <-activity:
858 if !idle.Stop() {
859 select {
860 case <-idle.C:
861 default:
862 }
863 }
864 idle.Reset(idleTimeout)
865 case <-done:
866 return
867 }
868 }
869 }()
870
871 acc := map[int]*provider.ToolCall{}
872 started := map[int]bool{}
873 argBucket := map[int]int{}
874 var order []int
875 var lastFinishReason string
876 var sawDone bool
877 var think thinkSplitter
878 var probe sseProbe
879
880 scanner := provider.NewStreamScanner(resp.Body, 1024*1024)
881
882 for scanner.Scan() {
883 select { // ping the idle watchdog; non-blocking so a full buffer is fine
884 case activity <- struct{}{}:
885 default:
886 }
887 line := strings.TrimSpace(scanner.Text())
888 if !probe.dataLine(line) {
889 continue
890 }
891 data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
892 if data == "[DONE]" {
893 sawDone = true
894 break
895 }
896 if data == "" {
897 continue
898 }
899
900 var sr streamResponse
901 if err := json.Unmarshal([]byte(data), &sr); err != nil {
902 return emitted, scanner.DecodeError(c.name, data, err)
903 }
904 if sr.Error != nil {
905 return emitted, fmt.Errorf("%s: %s", c.name, sr.Error.Message)
906 }
907 if len(sr.Choices) > 0 && sr.Choices[0].FinishReason != nil && *sr.Choices[0].FinishReason != "" {
908 lastFinishReason = *sr.Choices[0].FinishReason
909 }
910 if sr.Usage != nil {
911 u := normaliseUsage(sr.Usage)
912 u.FinishReason = lastFinishReason
913 provider.ApplyRequestAttemptCount(ctx, u)
914 emitted = true
915 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkUsage, Usage: u}) {
916 return emitted, ctx.Err()
917 }
918 }
919 if len(sr.Choices) == 0 {
920 continue
921 }
922
923 delta := sr.Choices[0].Delta
924 if sent, err := emitChatReasoning(ctx, out, delta.ReasoningContent, delta.Reasoning); err != nil {
925 return emitted, err
926 } else {
927 emitted = emitted || sent
928 }
929
930 if delta.Content != "" {
931 r, txt := think.push(delta.Content)
932 if r != "" {
933 emitted = true
934 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkReasoning, Text: r}) {
935 return emitted, ctx.Err()
936 }
937 }
938 if txt != "" {
939 emitted = true
940 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkText, Text: txt}) {
941 return emitted, ctx.Err()
942 }
943 }
944 }
945 for _, tc := range delta.ToolCalls {
946 cur, ok := acc[tc.Index]
947 if !ok {
948 cur = &provider.ToolCall{}
949 acc[tc.Index] = cur
950 order = append(order, tc.Index)
951 }
952 if tc.ID != "" {
953 cur.ID = tc.ID
954 }
955 if tc.Function.Name != "" {
956 cur.Name = tc.Function.Name
957 }
958 cur.Arguments += tc.Function.Arguments
959 if thoughtSignature := tc.thoughtSignature(); thoughtSignature != "" {
960 cur.ThoughtSignature = thoughtSignature
961 }
962 // Signal the call's start the moment its name is known, so a frontend
963 // can show the tool card immediately rather than only after its
964 // (possibly large) arguments finish streaming.
965 if !started[tc.Index] && cur.Name != "" {
966 started[tc.Index] = true
967 emitted = true
968 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkToolCallStart, ToolCall: &provider.ToolCall{ID: cur.ID, Name: cur.Name}}) {
969 return emitted, ctx.Err()
970 }
971 }
972 // Progress ticks while a large argument payload streams (a 30KB
973 // write_file body can take a minute-plus): one chunk per 2KB bucket
974 // so the consumer can show liveness without per-delta spam.
975 if started[tc.Index] {
976 if bucket := len(cur.Arguments) / 2048; bucket > argBucket[tc.Index] {
977 argBucket[tc.Index] = bucket
978 emitted = true
979 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkToolCallArgsDelta, ToolCall: &provider.ToolCall{ID: cur.ID, Name: cur.Name}, ArgChars: len(cur.Arguments)}) {
980 return emitted, ctx.Err()
981 }
982 }
983 }
984 }
985 }
986
987 if err := ctx.Err(); err != nil {
988 return emitted, err
989 }
990 if stalled.Load() {
991 // Idle stall is a body-phase cut: wrap so the Agent can replay the
992 // frozen request. Providers no longer reconnect here.
993 return emitted, fmt.Errorf("%s: stream stalled — no data for %s, connection likely dropped: %w", c.name, idleTimeout, io.ErrUnexpectedEOF)
994 }
995 if err := scanner.Err(); err != nil {
996 return emitted, fmt.Errorf("%s: read stream: %w", c.name, err)
997 }
998 // A proxy that idle-closes with a clean FIN ends the scan with no error. Without
999 // this check the turn would be committed as complete — including half-streamed
1000 // tool-call arguments, which then 400 on every replay (#3953). OpenAI Chat
1001 // accepts either [DONE] or a legal finish_reason as a complete terminal.
1002 if !sawDone && lastFinishReason == "" {
1003 return emitted, probe.incompleteErr(c.name, resp.Header.Get("Content-Type"))
1004 }
1005
1006 if r, txt := think.flush(); r != "" || txt != "" {
1007 if r != "" {
1008 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkReasoning, Text: r}) {
1009 return emitted, ctx.Err()
1010 }
1011 }
1012 if txt != "" {
1013 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkText, Text: txt}) {
1014 return emitted, ctx.Err()
1015 }
1016 }
1017 }
1018
1019 sort.Ints(order)
1020 for _, idx := range order {
1021 tc := acc[idx]
1022 if tc.ID == "" {
1023 // Some OpenAI-compatible gateways stream tool calls by index with no id.
1024 // Synthesize a stable one so the result can be paired back to its call —
1025 // an empty tool_call_id collapses multi-tool turns downstream.
1026 tc.ID = fmt.Sprintf("call_%d", idx)
1027 }
1028 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkToolCall, ToolCall: tc}) {
1029 return emitted, ctx.Err()
1030 }
1031 }
1032 if !sendChunk(ctx, out, provider.Chunk{Type: provider.ChunkDone}) {
1033 return emitted, ctx.Err()
1034 }
1035 return emitted, nil
1036 }
1037
1038 // normaliseUsage folds the cache shapes used by OpenAI-compatible providers into
1039 // a single Usage. DeepSeek reports prompt_cache_{hit,miss}_tokens at the top of
1040 // usage; OpenAI and MiMo put cache hits under prompt_tokens_details; some
1041 // compatible gateways return Anthropic-style input/cache counters instead.
1042 // Reasoning tokens land in completion_tokens_details on thinking-mode models.
1043 func normaliseUsage(u *wireUsage) *provider.Usage {
1044 prompt := u.PromptTokens
1045 anthropicPrompt := prompt == 0 &&
1046 (u.InputTokens != 0 || u.CacheCreationInputTokens != 0 || u.CacheReadInputTokens != 0)
1047 if anthropicPrompt {
1048 // Anthropic-style input_tokens excludes both cache reads and cache
1049 // writes, while Reasonix PromptTokens represents the complete input.
1050 prompt = u.InputTokens + u.CacheCreationInputTokens + u.CacheReadInputTokens
1051 }
1052 completion := u.CompletionTokens
1053 if completion == 0 {
1054 completion = u.OutputTokens
1055 }
1056 total := u.TotalTokens
1057 if total == 0 && (prompt != 0 || completion != 0) {
1058 total = prompt + completion
1059 }
1060
1061 hit := u.PromptCacheHitTokens
1062 miss := u.PromptCacheMissTokens
1063 if hit == 0 && u.PromptTokensDetails != nil {
1064 hit = u.PromptTokensDetails.CachedTokens
1065 }
1066 if hit == 0 {
1067 hit = u.CacheReadInputTokens
1068 }
1069 if miss == 0 {
1070 switch {
1071 case anthropicPrompt:
1072 // Cache writes are still uncached input for Reasonix pricing and
1073 // cache-ratio accounting.
1074 miss = u.InputTokens + u.CacheCreationInputTokens
1075 case hit > 0 && prompt > hit:
1076 miss = prompt - hit
1077 }
1078 }
1079 reasoning := 0
1080 if u.CompletionTokensDetails != nil {
1081 reasoning = u.CompletionTokensDetails.ReasoningTokens
1082 }
1083 return &provider.Usage{
1084 PromptTokens: prompt,
1085 CompletionTokens: completion,
1086 TotalTokens: total,
1087 CacheHitTokens: hit,
1088 CacheMissTokens: miss,
1089 ReasoningTokens: reasoning,
1090 }
1091 }
1092
1093 // OpenAI-compatible wire protocol
1094
1095 type chatRequest struct {
1096 Model string `json:"model"`
1097 Messages []chatMessage `json:"messages"`
1098 Tools []chatTool `json:"tools,omitempty"`
1099 Stream bool `json:"stream"`
1100 StreamOptions *streamOptions `json:"stream_options,omitempty"`
1101 Temperature *float64 `json:"temperature,omitempty"`
1102 MaxTokens int `json:"max_tokens,omitempty"`
1103 MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
1104 ReasoningEffort string `json:"reasoning_effort,omitempty"`
1105 Thinking *thinkingMode `json:"thinking,omitempty"`
1106 ExtraBody map[string]any `json:"-"`
1107 }
1108
1109 func omitExtraBodyFields(in map[string]any, names ...string) map[string]any {
1110 if len(in) == 0 {
1111 return nil
1112 }
1113 omit := make(map[string]struct{}, len(names))
1114 for _, name := range names {
1115 omit[strings.ToLower(strings.TrimSpace(name))] = struct{}{}
1116 }
1117 out := make(map[string]any, len(in))
1118 for name, value := range in {
1119 if _, blocked := omit[strings.ToLower(strings.TrimSpace(name))]; !blocked {
1120 out[name] = value
1121 }
1122 }
1123 if len(out) == 0 {
1124 return nil
1125 }
1126 return out
1127 }
1128
1129 func (r chatRequest) MarshalJSON() ([]byte, error) {
1130 type wire chatRequest
1131 baseReq := wire(r)
1132 baseReq.ExtraBody = nil
1133 raw, err := json.Marshal(baseReq)
1134 if err != nil {
1135 return nil, err
1136 }
1137 if len(r.ExtraBody) == 0 {
1138 return raw, nil
1139 }
1140 var body map[string]any
1141 if err := json.Unmarshal(raw, &body); err != nil {
1142 return nil, err
1143 }
1144 maps.Copy(body, cleanExtraBody(r.ExtraBody))
1145 return json.Marshal(body)
1146 }
1147
1148 type thinkingMode struct {
1149 Type string `json:"type"`
1150 }
1151
1152 type streamOptions struct {
1153 IncludeUsage bool `json:"include_usage"`
1154 }
1155
1156 type chatMessage struct {
1157 Role string `json:"role"`
1158 // content is always present (never omitted): DeepSeek's strict deserializer
1159 // rejects a message missing the field. A pure tool_calls assistant turn
1160 // serializes as null (nil here); a string for every other text message
1161 // (empty included — null is rejected by some backends for a tool message);
1162 // and a []chatContentPart array for a vision user turn carrying images.
1163 Content any `json:"content"`
1164 // Prefix is wire-only and is set exclusively on an automatically recovered
1165 // DeepSeek assistant tail. omitempty keeps every ordinary request byte-stable.
1166 Prefix bool `json:"prefix,omitempty"`
1167 // A pointer so the field can serialize as an empty string for a malformed
1168 // tool turn while preserving non-empty reasoning on every assistant turn.
1169 ReasoningContent *string `json:"reasoning_content,omitempty"`
1170 ToolCalls []chatToolCall `json:"tool_calls,omitempty"`
1171 ToolCallID string `json:"tool_call_id,omitempty"`
1172 // Name is the role=tool message's function name. A pointer preserves an
1173 // empty name for strict backends (MiMo); OpenCode Go Chat rejects the key.
1174 Name *string `json:"name,omitempty"`
1175 }
1176
1177 type chatContentPart struct {
1178 Type string `json:"type"`
1179 Text string `json:"text,omitempty"`
1180 ImageURL *chatImageURL `json:"image_url,omitempty"`
1181 FileID string `json:"file_id,omitempty"`
1182 }
1183
1184 type chatImageURL struct {
1185 URL string `json:"url"`
1186 Detail string `json:"detail,omitempty"`
1187 }
1188
1189 func imageContentParts(text string, images []string, detail string) []chatContentPart {
1190 parts := make([]chatContentPart, 0, len(images)+1)
1191 if text != "" {
1192 parts = append(parts, chatContentPart{Type: "text", Text: text})
1193 }
1194 for _, ref := range images {
1195 switch provider.ClassifyImage(ref) {
1196 case provider.ImageFileID:
1197 parts = append(parts, chatContentPart{Type: "file", FileID: ref})
1198 case provider.ImageDataURL, provider.ImageHTTPURL:
1199 parts = append(parts, chatContentPart{Type: "image_url", ImageURL: &chatImageURL{URL: ref, Detail: detail}})
1200 }
1201 }
1202 return parts
1203 }
1204
1205 type chatTool struct {
1206 Type string `json:"type"`
1207 Function chatFunction `json:"function"`
1208 DeferLoading bool `json:"defer_loading,omitempty"`
1209 }
1210
1211 type chatFunction struct {
1212 Name string `json:"name"`
1213 Description string `json:"description,omitempty"`
1214 Parameters json.RawMessage `json:"parameters,omitempty"`
1215 Strict bool `json:"strict,omitempty"`
1216 }
1217
1218 type chatToolCall struct {
1219 Index int `json:"index,omitempty"`
1220 ID string `json:"id,omitempty"`
1221 Type string `json:"type,omitempty"`
1222 ExtraContent *chatToolCallExtraContent `json:"extra_content,omitempty"`
1223 Function struct {
1224 Name string `json:"name"`
1225 Arguments string `json:"arguments"`
1226 // Decode compatibility for the early Gemini OpenAI shape. New requests
1227 // use extra_content.google.thought_signature.
1228 ThoughtSignature string `json:"thought_signature,omitempty"`
1229 } `json:"function"`
1230 }
1231
1232 // thoughtSignature also accepts the early Gemini shape that placed the field in
1233 // function, still emitted by some compatibility gateways and older sessions.
1234 func (tc chatToolCall) thoughtSignature() string {
1235 if tc.ExtraContent != nil && tc.ExtraContent.Google.ThoughtSignature != "" {
1236 return tc.ExtraContent.Google.ThoughtSignature
1237 }
1238 return tc.Function.ThoughtSignature
1239 }
1240
1241 type chatToolCallExtraContent struct {
1242 Google struct {
1243 ThoughtSignature string `json:"thought_signature,omitempty"`
1244 } `json:"google"`
1245 }
1246
1247 type streamResponse struct {
1248 Choices []struct {
1249 Delta struct {
1250 Content string `json:"content"`
1251 ReasoningContent *string `json:"reasoning_content"`
1252 Reasoning string `json:"reasoning"`
1253 ToolCalls []chatToolCall `json:"tool_calls"`
1254 } `json:"delta"`
1255 FinishReason *string `json:"finish_reason"`
1256 } `json:"choices"`
1257 Usage *wireUsage `json:"usage"`
1258 Error *struct {
1259 Message string `json:"message"`
1260 } `json:"error"`
1261 }
1262
1263 // wireUsage covers DeepSeek's top-level cache fields, OpenAI/MiMo's nested
1264 // details, and Anthropic-style fallbacks returned by compatible gateways.
1265 type wireUsage struct {
1266 PromptTokens int `json:"prompt_tokens"`
1267 CompletionTokens int `json:"completion_tokens"`
1268 TotalTokens int `json:"total_tokens"`
1269 InputTokens int `json:"input_tokens"`
1270 OutputTokens int `json:"output_tokens"`
1271 PromptCacheHitTokens int `json:"prompt_cache_hit_tokens"`
1272 PromptCacheMissTokens int `json:"prompt_cache_miss_tokens"`
1273 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
1274 CacheReadInputTokens int `json:"cache_read_input_tokens"`
1275 PromptTokensDetails *struct {
1276 CachedTokens int `json:"cached_tokens"`
1277 } `json:"prompt_tokens_details"`
1278 CompletionTokensDetails *struct {
1279 ReasoningTokens int `json:"reasoning_tokens"`
1280 } `json:"completion_tokens_details"`
1281 }
1282
1282 lines GO