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