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 RoleUser:
303 content := buildOAIUserContent(msg.Content, textOnly)
304 out.Messages = append(out.Messages, oaiMessage{Role: "user", Content: content})
305 case RoleAssistant:
306 am := oaiMessage{Role: "assistant"}
307 var text strings.Builder
308 var reasoning strings.Builder
309 for _, b := range msg.Content {
310 switch v := b.(type) {
311 case TextBlock:
312 if strings.TrimSpace(v.Text) == "" {
313 continue
314 }
315 if text.Len() > 0 {
316 text.WriteString("\n")
317 }
318 text.WriteString(v.Text)
319 case ToolCallBlock:
320 args := v.Arguments
321 if len(args) == 0 || !json.Valid(args) {
322 args = json.RawMessage("{}")
323 }
324 am.ToolCalls = append(am.ToolCalls, oaiToolCall{
325 ID: v.ID,
326 Type: "function",
327 Function: oaiToolCallFn{
328 Name: v.Name,
329 Arguments: string(args),
330 },
331 })
332 case ReasoningBlock:
333 if v.Summary != "" {
334 if reasoning.Len() > 0 {
335 reasoning.WriteString("\n")
336 }
337 reasoning.WriteString(v.Summary)
338 }
339 }
340 }
341 if text.Len() > 0 {
342 am.Content = text.String()
343 }
344 if reasoning.Len() > 0 && len(am.ToolCalls) > 0 {
345 am.ReasoningContent = reasoning.String()
346 }
347 // Kimi rejects assistant messages with neither visible text nor
348 // tool calls ("assistant must not be empty"). This can happen when
349 // a previous stream produced only reasoning_content, which zut keeps
350 // internally for provider replay but cannot send back as standalone
351 // assistant content on OpenAI-compatible chat-completions APIs.
352 if am.Content == nil && len(am.ToolCalls) == 0 {
353 continue
354 }
355 out.Messages = append(out.Messages, am)
356 case RoleTool:
357 // Each ToolResultBlock becomes its own tool message. Preserve
358 // image blocks for vision-capable OpenAI models instead of
359 // flattening the tool output to plain text.
360 for _, b := range msg.Content {
361 if tr, ok := b.(ToolResultBlock); ok {
362 content := buildOAIToolContent(tr.Content, tr.IsError, textOnly)
363 out.Messages = append(out.Messages, oaiMessage{
364 Role: "tool",
365 ToolCallID: tr.CallID,
366 Content: content,
367 })
368 }
369 }
370 }
371 if deferredMode {
372 var loaded []oaiTool
373 for _, name := range msg.AddedToolNames {
374 if t, ok := toolByName[name]; ok && t.Deferred {
375 loaded = append(loaded, makeOAITool(t))
376 }
377 }
378 if len(loaded) > 0 {
379 out.Messages = append(out.Messages, oaiMessage{Role: "system", Tools: loaded})
380 }
381 }
382 }
383
384 for _, t := range req.Tools {
385 if t.Deferred && (deferredMode || !activatedTools[t.Name]) {
386 continue
387 }
388 out.Tools = append(out.Tools, makeOAITool(t))
389 }
390 if len(out.Tools) > 0 {
391 out.ToolChoice = "auto"
392 }
393
394 return out, nil
395}
396
397func isKimiDeferredModel(model string) bool {
398 model = strings.ToLower(model)
399 return model == "kimi-k3" || strings.HasSuffix(model, "/kimi-k3")
400}
401
402func makeOAITool(t Tool) oaiTool {
403 var tool oaiTool
404 tool.Type = "function"
405 tool.Function.Name = t.Name
406 tool.Function.Description = t.Description
407 tool.Function.Parameters = t.Schema
408 return tool
409}
410
411func buildOAIUserContent(blocks []Content, textOnly bool) interface{} {
412 hasImage := false
413 for _, b := range blocks {
414 if _, ok := b.(ImageBlock); ok {
415 hasImage = true
416 break
417 }
418 }
419 if textOnly || !hasImage {
420 // Keep multiple text blocks structured. The core provider projection
421 // adds message-time annotations as a separate block; collapsing that
422 // block with the user text changes the wire representation of the
423 // original prompt and can make consumers misclassify the request.
424 if !textOnly && len(blocks) > 1 {
425 return buildOAIContentBlocks(blocks, false)
426 }
427 var sb strings.Builder
428 for _, b := range blocks {
429 if tb, ok := b.(TextBlock); ok {
430 if sb.Len() > 0 {
431 sb.WriteString("\n")
432 }
433 sb.WriteString(tb.Text)
434 }
435 }
436 return sb.String()
437 }
438 return buildOAIContentBlocks(blocks, false)
439}
440
441func buildOAIToolContent(blocks []Content, isError, textOnly bool) interface{} {
442 hasImage := false
443 for _, b := range blocks {
444 if _, ok := b.(ImageBlock); ok {
445 hasImage = true
446 break
447 }
448 }
449 if textOnly || !hasImage {
450 var sb strings.Builder
451 for _, b := range blocks {
452 if tb, ok := b.(TextBlock); ok {
453 if sb.Len() > 0 {
454 sb.WriteString("\n")
455 }
456 sb.WriteString(tb.Text)
457 }
458 }
459 if isError && sb.Len() > 0 {
460 sb.WriteString(" [error]")
461 }
462 return sb.String()
463 }
464 return buildOAIContentBlocks(blocks, isError)
465}
466
467func buildOAIContentBlocks(blocks []Content, isError bool) []interface{} {
468 var arr []interface{}
469 for _, b := range blocks {
470 switch v := b.(type) {
471 case TextBlock:
472 arr = append(arr, oaiContentText{Type: "text", Text: v.Text})
473 case ImageBlock:
474 var img oaiContentImage
475 img.Type = "image_url"
476 img.ImageURL.URL = "data:" + v.MimeType + ";base64," + base64.StdEncoding.EncodeToString(v.Data)
477 arr = append(arr, img)
478 }
479 }
480 if isError {
481 arr = append(arr, oaiContentText{Type: "text", Text: "[error]"})
482 }
483 return arr
484}
485
486// ---- streaming ----
487
488func (c *openaiClient) chatCompletionsURL() string {
489 if c.chatCompletionsPath != "" {
490 return strings.TrimRight(c.baseURL, "/") + "/" + strings.TrimLeft(c.chatCompletionsPath, "/")
491 }
492 return chatCompletionsURL(c.baseURL)
493}
494
495func (c *openaiClient) Stream(ctx context.Context, req Request) (<-chan Event, error) {
496 endpoint := c.chatCompletionsURL()
497 wire, err := c.buildRequest(req)
498 if err != nil {
499 return nil, err
500 }
501 body, err := json.Marshal(wire)
502 if err != nil {
503 return nil, err
504 }
505 newReq := func() (*http.Request, error) {
506 httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
507 if err != nil {
508 return nil, err
509 }
510 httpReq.Header.Set("content-type", "application/json")
511 httpReq.Header.Set("accept", "text/event-stream")
512 httpReq.Header.Set("authorization", "Bearer "+c.apiKey)
513 for k, v := range c.headers {
514 httpReq.Header.Set(k, v)
515 }
516 return httpReq, nil
517 }
518
519 resp, err := doStreamWithRetry(ctx, c.http, newReq, req.Lifecycle)
520 if err != nil {
521 return nil, fmt.Errorf("%s: %w", c.Name(), err)
522 }
523 if resp.StatusCode != http.StatusOK {
524 b, _ := io.ReadAll(resp.Body)
525 resp.Body.Close()
526 return nil, fmt.Errorf("%s: http %d: %s", c.Name(), resp.StatusCode, strings.TrimSpace(string(b)))
527 }
528
529 out := make(chan Event, 16)
530 go c.runStream(ctx, resp, req, out)
531 return out, nil
532}
533
534func (c *openaiClient) runStream(ctx context.Context, resp *http.Response, req Request, out chan<- Event) {
535 defer close(out)
536 defer resp.Body.Close()
537
538 model, _ := FindModel("", req.Model)
539 out <- EventStart{Model: req.Model, Provider: c.Name()}
540
541 raw := make(chan sseEvent, 16)
542 go readSSE(resp.Body, raw)
543
544 // Interleaved block tracking: text and tool_calls preserve their
545 // emission order so the assistant message renders in the same order
546 // the model produced it. The builder fires one kind of block at a
547 // time — incoming text deltas after a tool_call split into a fresh
548 // text block; subsequent tool_calls each get their own slot.
549 type blockEntry struct {
550 kind string // "text" | "tool_use"
551 textBuf strings.Builder
552 toolID string
553 toolName string
554 toolArgs strings.Builder
555 announced bool
556 }
557 var (
558 blocks []*blockEntry
559 currentText *blockEntry // most-recent text block, nil if none
560 toolByIdx = map[int]*blockEntry{} // openai tool_call index -> block
561 reasoningBuf strings.Builder
562 usage Usage
563 stop = StopEnd
564 finalErr error
565 )
566
567 appendText := func(delta string) {
568 if currentText == nil {
569 currentText = &blockEntry{kind: "text"}
570 blocks = append(blocks, currentText)
571 }
572 currentText.textBuf.WriteString(delta)
573 }
574
575 getOrCreateTool := func(idx int) *blockEntry {
576 if t, ok := toolByIdx[idx]; ok {
577 return t
578 }
579 t := &blockEntry{kind: "tool_use"}
580 toolByIdx[idx] = t
581 blocks = append(blocks, t)
582 // A new tool block breaks the current text block. Subsequent text
583 // deltas will start a fresh text block after this tool.
584 currentText = nil
585 return t
586 }
587
588 assembleMsg := func() Message {
589 content := []Content{}
590 for _, b := range blocks {
591 switch b.kind {
592 case "text":
593 if b.textBuf.Len() > 0 {
594 content = append(content, TextBlock{Text: b.textBuf.String()})
595 }
596 case "tool_use":
597 args := b.toolArgs.String()
598 if args == "" || !json.Valid([]byte(args)) {
599 args = "{}"
600 }
601 content = append(content, ToolCallBlock{
602 ID: b.toolID, Name: b.toolName, Arguments: json.RawMessage(args),
603 })
604 }
605 }
606 if reasoningBuf.Len() > 0 {
607 content = append(content, ReasoningBlock{Summary: reasoningBuf.String()})
608 }
609 return Message{Role: RoleAssistant, Content: content, Time: time.Now()}
610 }
611
612 sendDone := func() {
613 usage.CostUSD = ComputeCost(model, usage)
614 out <- EventUsage{Usage: usage}
615 out <- EventDone{Stop: stop, Err: finalErr, Message: assembleMsg()}
616 }
617
618 for {
619 select {
620 case <-ctx.Done():
621 stop = StopAborted
622 finalErr = ctx.Err()
623 sendDone()
624 return
625 case ev, ok := <-raw:
626 if !ok {
627 sendDone()
628 return
629 }
630 if ev.Err != nil {
631 stop = StopError
632 finalErr = fmt.Errorf("read SSE: %w", ev.Err)
633 sendDone()
634 return
635 }
636 if ev.Data == "[DONE]" {
637 sendDone()
638 return
639 }
640 var chunk struct {
641 Choices []struct {
642 Index int `json:"index"`
643 Delta struct {
644 Content string `json:"content"`
645 ReasoningContent string `json:"reasoning_content"`
646 ToolCalls []struct {
647 Index int `json:"index"`
648 ID string `json:"id"`
649 Type string `json:"type"`
650 Function struct {
651 Name string `json:"name"`
652 Arguments string `json:"arguments"`
653 } `json:"function"`
654 } `json:"tool_calls"`
655 } `json:"delta"`
656 FinishReason string `json:"finish_reason"`
657 } `json:"choices"`
658 Usage *struct {
659 PromptTokens int `json:"prompt_tokens"`
660 CompletionTokens int `json:"completion_tokens"`
661 PromptTokensDetails struct {
662 CachedTokens int `json:"cached_tokens"`
663 } `json:"prompt_tokens_details"`
664 CompletionTokensDetails *struct {
665 ReasoningTokens int `json:"reasoning_tokens"`
666 } `json:"completion_tokens_details"`
667 } `json:"usage"`
668 Error *struct {
669 Message string `json:"message"`
670 Type string `json:"type"`
671 } `json:"error"`
672 }
673 if err := json.Unmarshal([]byte(ev.Data), &chunk); err != nil {
674 continue
675 }
676 if chunk.Error != nil {
677 stop = StopError
678 finalErr = fmt.Errorf("openai: %s", chunk.Error.Message)
679 sendDone()
680 return
681 }
682 if chunk.Usage != nil {
683 usage.InputTokens = chunk.Usage.PromptTokens - chunk.Usage.PromptTokensDetails.CachedTokens
684 if usage.InputTokens < 0 {
685 usage.InputTokens = chunk.Usage.PromptTokens
686 }
687 usage.OutputTokens = chunk.Usage.CompletionTokens
688 usage.CacheReadTokens = chunk.Usage.PromptTokensDetails.CachedTokens
689 if details := chunk.Usage.CompletionTokensDetails; details != nil {
690 usage.ReasoningTokens = details.ReasoningTokens
691 usage.ReasoningTokensKnown = true
692 }
693 }
694 for _, ch := range chunk.Choices {
695 if ch.Delta.ReasoningContent != "" {
696 reasoningBuf.WriteString(ch.Delta.ReasoningContent)
697 }
698 if ch.Delta.Content != "" {
699 appendText(ch.Delta.Content)
700 out <- EventTextDelta{Delta: ch.Delta.Content}
701 }
702 for _, tc := range ch.Delta.ToolCalls {
703 t := getOrCreateTool(tc.Index)
704 if tc.ID != "" {
705 t.toolID = tc.ID
706 }
707 if tc.Function.Name != "" {
708 t.toolName = tc.Function.Name
709 }
710 if !t.announced && t.toolID != "" && t.toolName != "" {
711 t.announced = true
712 out <- EventToolStart{ID: t.toolID, Name: t.toolName}
713 }
714 if tc.Function.Arguments != "" {
715 t.toolArgs.WriteString(tc.Function.Arguments)
716 if t.announced {
717 out <- EventToolArgs{ID: t.toolID, Delta: tc.Function.Arguments}
718 }
719 }
720 }
721 switch ch.FinishReason {
722 case "stop":
723 stop = StopEnd
724 case "length":
725 stop = StopLength
726 case "tool_calls", "function_call":
727 stop = StopToolUse
728 for _, b := range blocks {
729 if b.kind == "tool_use" && b.announced {
730 out <- EventToolEnd{ID: b.toolID}
731 }
732 }
733 }
734 }
735 }
736 }
737}