返回 DeepSeek-Reasonix
anthropic.go
根目录 / internal / provider / anthropic / anthropic.go
1 // Package anthropic implements the Anthropic Messages API provider (POST
2 // /v1/messages, SSE streaming) with a hand-written net/http client — no SDK. It
3 // self-registers under the "anthropic" kind, so any Claude model is a config
4 // instance rather than code.
5 //
6 // Two notes, both rooted in the transport-agnostic provider.Message abstraction:
7 //
8 // - Extended thinking is opt-in (provider config thinking="adaptive"). Anthropic
9 // requires the *signed* thinking block be replayed on the next turn when a tool
10 // call followed thinking, so Message carries ReasoningSignature alongside
11 // ReasoningContent and this provider replays the signed block on the next
12 // request. DeepSeek's Anthropic endpoint instead uses unsigned thinking blocks,
13 // thinking.type enabled|disabled, and output_config.effort; requests carrying
14 // tools must replay all provider reasoning. Some other compatible gateways such
15 // as LongCat use the binary toggle without output_config. (redacted_thinking
16 // blocks are not yet captured/replayed.)
17 // - Native Anthropic requests omit temperature/top_p. Current Claude models
18 // (Opus 4.8/4.7) reject sampling parameters with a 400; Anthropic steers
19 // behavior via prompting instead. DeepSeek's compatible endpoint accepts the
20 // caller's temperature, so that field is preserved only for DeepSeek.
21 package anthropic
22
23 import (
24 "bytes"
25 "context"
26 "encoding/json"
27 "fmt"
28 "net/http"
29 "strings"
30 "sync"
31 "sync/atomic"
32 "time"
33
34 "reasonix/internal/netclient"
35 "reasonix/internal/provider"
36 "reasonix/internal/provider/openai"
37 )
38
39 // defaultStreamIdleTimeout caps how long a started SSE stream may go silent before
40 // it's treated as a dropped connection — a half-open TCP connection (proxy switched
41 // mid-stream) sends no RST, so scanner.Scan() would block forever. Generous on
42 // purpose; live streams emit far more often. Stored per-client (client.idleTimeout)
43 // so a test can shorten it without a shared global that races other watchdogs.
44 const defaultStreamIdleTimeout = 300 * time.Second
45
46 const (
47 // anthropicVersion is the required API version header value.
48 anthropicVersion = "2023-06-01"
49 // defaultBaseURL is the first-party endpoint; config may override it (e.g. a
50 // gateway). Bedrock/Vertex use a different request shape and are out of scope.
51 defaultBaseURL = "https://api.anthropic.com"
52 // defaultMaxTokens is the mandatory Anthropic fallback when neither config
53 // nor request supplies max_tokens. Native Anthropic stays at 16K; official
54 // DeepSeek sends the documented 384K ceiling because budget_tokens is ignored.
55 defaultMaxTokens = provider.DefaultOrdinaryOutputTokens
56 )
57
58 func init() {
59 provider.RegisterReasoning("anthropic", ReasoningForConfig)
60 provider.Register("anthropic", New)
61 }
62
63 // New builds an Anthropic provider from a resolved config.
64 func New(cfg provider.Config) (provider.Provider, error) {
65 cfg = provider.ApplyOpenCodeGoContract("anthropic", cfg)
66 if cfg.Model == "" {
67 return nil, fmt.Errorf("anthropic: model is required for provider %q", cfg.Name)
68 }
69 name := cfg.Name
70 if name == "" {
71 name = "anthropic"
72 }
73 baseURL := cfg.BaseURL
74 if baseURL == "" {
75 baseURL = defaultBaseURL
76 }
77 root, requestURL := resolveEndpoints(baseURL, cfg.Extra)
78 officialDeepSeek := openai.IsDeepSeek(root)
79 reasoningProtocol, _ := cfg.Extra["reasoning_protocol"].(string)
80 reasoningProtocol = strings.ToLower(strings.TrimSpace(reasoningProtocol))
81 deepSeekReplay := officialDeepSeek
82 switch reasoningProtocol {
83 case "deepseek":
84 deepSeekReplay = true
85 case "none":
86 deepSeekReplay = false
87 }
88 keyEnv, _ := cfg.Extra["api_key_env"].(string) // for actionable auth errors
89 keySource, _ := cfg.Extra["api_key_source"].(string)
90 thinking, _ := cfg.Extra["thinking"].(string)
91 thinking = strings.ToLower(strings.TrimSpace(thinking))
92 effort, err := configuredEffort(cfg)
93 if err != nil {
94 return nil, err
95 }
96 vision, _ := cfg.Extra["vision"].(bool)
97 modelInfo := provider.ModelInfo{ID: cfg.Model, InputModalities: []provider.ModelModality{provider.ModalityText}}
98 if cfg.ModelInfo != nil {
99 modelInfo = *cfg.ModelInfo
100 modelInfo.ID = cfg.Model
101 }
102 if cfg.ModelInfo != nil {
103 vision = modelInfo.SupportsInput(provider.ModalityImage)
104 }
105 // Official DeepSeek image input is pinned to one SKU even when metadata
106 // claims otherwise.
107 vision = openai.DeepSeekImageInputAllowed(officialDeepSeek, requestURL, cfg.Model, cfg.ModelInfo != nil, vision)
108 if vision {
109 modelInfo.InputModalities = []provider.ModelModality{provider.ModalityText, provider.ModalityImage}
110 } else if modelInfo.SupportsInput(provider.ModalityImage) {
111 modelInfo.InputModalities = []provider.ModelModality{provider.ModalityText}
112 }
113 webSearch, _ := cfg.Extra["web_search"].(bool)
114 clientWebSearch, _ := cfg.Extra["client_web_search"].(bool)
115 headers, _ := cfg.Extra["headers"].(map[string]string)
116 authHeader, _ := cfg.Extra["auth_header"].(bool)
117 maxOutputTokens, _ := cfg.Extra["max_output_tokens"].(int)
118 if maxOutputTokens <= 0 {
119 // Messages requires max_tokens. 0 = automatic; negative also falls back
120 // because the wire field is mandatory.
121 if officialDeepSeek {
122 maxOutputTokens = provider.DeepSeekMaxOutputTokens
123 } else {
124 // Native Anthropic and unknown gateways: conservative ordinary default.
125 maxOutputTokens = defaultMaxTokens
126 if strings.EqualFold(thinking, "adaptive") || strings.EqualFold(thinking, "enabled") {
127 maxOutputTokens = provider.AutoOutputBudget(true, effort)
128 }
129 }
130 }
131 httpClient, err := newHTTPClient(cfg)
132 if err != nil {
133 return nil, fmt.Errorf("anthropic: network: %w", err)
134 }
135 if reject, _ := cfg.Extra["reject_redirects"].(bool); reject {
136 httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
137 }
138 return &client{
139 identityHeaders: provider.NewClientIdentityHeaders(),
140 reasoning: ReasoningForConfig(cfg),
141 name: name,
142 identity: provider.RequestIdentity{Provider: name, DisplayName: cfg.DisplayName, Protocol: cfg.Protocol},
143 apiKey: cfg.APIKey,
144 keyEnv: keyEnv,
145 keySource: keySource,
146 baseURL: root,
147 requestURL: requestURL,
148 model: cfg.Model,
149 nativeAnthropic: strings.EqualFold(root, defaultBaseURL),
150 deepseek: deepSeekReplay,
151 thinking: thinking,
152 effort: effort,
153 vision: vision,
154 modelInfo: modelInfo,
155 mimo: provider.IsMiMoEndpoint(root),
156 search: provider.SearchPolicy{NativeEnabled: webSearch, ClientEnabled: clientWebSearch},
157 headers: cleanCustomHeaders(headers),
158 authHeader: authHeader,
159 defaultMaxTokens: maxOutputTokens,
160 http: httpClient, // no overall timeout; lifecycle is ctx-driven
161 idleTimeout: defaultStreamIdleTimeout,
162 }, nil
163 }
164
165 func newHTTPClient(cfg provider.Config) (*http.Client, error) {
166 if cfg.HTTPClient != nil {
167 return cfg.HTTPClient, nil
168 }
169 spec, _ := cfg.Extra["proxy_spec"].(netclient.ProxySpec)
170 client, err := netclient.NewHTTPClient(spec, netclient.TransportOptions{
171 DialTimeout: 30 * time.Second,
172 KeepAlive: 30 * time.Second,
173 TLSHandshakeTimeout: 15 * time.Second,
174 ResponseHeaderTimeout: 300 * time.Second,
175 })
176 if err != nil {
177 return nil, err
178 }
179 return provider.WithProtocolCompatibility(client, provider.RequestIdentity{Provider: cfg.Name, Protocol: "anthropic"}), nil
180 }
181
182 type client struct {
183 identityHeaders http.Header
184 reasoning provider.ReasoningCapability
185 name string
186 identity provider.RequestIdentity
187 apiKey string
188 keyEnv string // api_key_env name, surfaced in auth errors
189 keySource string // source of keyEnv, surfaced in auth errors
190 baseURL string
191 requestURL string
192 model string
193 nativeAnthropic bool // first-party endpoint: documented default-5m cache-write pricing applies
194 deepseek bool // official DeepSeek Anthropic endpoint: unsigned reasoning replay + automatic cache
195 thinking string // "adaptive" enables extended thinking; "" = off (config-driven)
196 effort string // output_config.effort: low|medium|high|xhigh|max; "" = provider default
197 vision bool // model accepts image input — embed attached images as base64 image blocks
198 modelInfo provider.ModelInfo
199 mimo bool // true for MiMo — upgrades legacy tuple schemas to Draft 2020-12
200 search provider.SearchPolicy
201 headers map[string]string
202 authHeader bool // send Authorization: Bearer instead of Anthropic's x-api-key header
203 defaultMaxTokens int
204 http *http.Client
205 idleTimeout time.Duration // SSE stall watchdog window; defaultStreamIdleTimeout unless a test overrides
206 authed atomic.Bool // a request has succeeded — gate transient-401 retry
207 }
208
209 func (c *client) Name() string { return c.name }
210
211 func (c *client) ModelInfo() provider.ModelInfo {
212 if c == nil {
213 return provider.ModelInfo{}
214 }
215 info := c.modelInfo
216 info.InputModalities = append([]provider.ModelModality(nil), info.InputModalities...)
217 return info
218 }
219
220 func (c *client) deepSeekThinkingEnabled() bool {
221 return c != nil && c.deepseek && c.thinking != "disabled" && c.effort != "disabled"
222 }
223
224 func (c *client) RequiresAssistantReasoningReplay(m provider.Message) bool {
225 if c == nil {
226 return false
227 }
228 if !c.deepseek {
229 return c.requiresReceivedReasoning(m)
230 }
231 // A turn carrying provider-issued reasoning must replay it, tools or not:
232 // DeepSeek's thinking mode 400s when a stored thinking block is not passed
233 // back. Without stored reasoning there is nothing to replay — plain text
234 // turns stay out of projection so healthy histories keep their backing.
235 if strings.TrimSpace(m.ReasoningContent) != "" {
236 return true
237 }
238 activity := len(m.ToolCalls) > 0 || len(m.ServerSearch) > 0
239 return activity && c.deepSeekThinkingEnabled()
240 }
241
242 func (c *client) AllowsEmptyReasoningFallback() bool { return false }
243
244 func (c *client) MissingToolCallReasoningWarningIdentity() string {
245 if c == nil {
246 return ""
247 }
248 protocol := "anthropic"
249 if c.deepseek {
250 protocol = "deepseek-anthropic"
251 }
252 return strings.Join([]string{
253 "anthropic", strings.TrimSpace(c.name), strings.TrimSpace(c.requestURL),
254 strings.TrimSpace(c.model), protocol, strings.TrimSpace(c.thinking), strings.TrimSpace(c.effort),
255 }, "\x00")
256 }
257
258 func (c *client) sendOpts() provider.SendOptions {
259 return provider.SendOptions{
260 Provider: c.name,
261 ProviderDisplayName: c.identity.DisplayName,
262 Protocol: c.identity.Protocol,
263 KeyEnv: c.keyEnv,
264 KeySource: c.keySource,
265 KeyPresent: c.apiKey != "",
266 RetryAuth: c.authed.Load(),
267 }
268 }
269
270 func cleanCustomHeaders(in map[string]string) map[string]string {
271 if len(in) == 0 {
272 return nil
273 }
274 out := make(map[string]string, len(in))
275 for name, value := range in {
276 name = strings.TrimSpace(name)
277 if name == "" || reservedCustomHeader(name) {
278 continue
279 }
280 out[name] = strings.TrimSpace(value)
281 }
282 if len(out) == 0 {
283 return nil
284 }
285 return out
286 }
287
288 func reservedCustomHeader(name string) bool {
289 switch strings.ToLower(strings.TrimSpace(name)) {
290 case "content-type", "accept", "x-api-key", "authorization", "anthropic-version", "anthropic-beta":
291 return true
292 default:
293 return false
294 }
295 }
296
297 func applyCustomHeaders(h http.Header, headers map[string]string) {
298 for name, value := range cleanCustomHeaders(headers) {
299 h.Set(name, value)
300 }
301 }
302
303 // bufPool reuses byte buffers for JSON-marshalled request bodies, reducing GC
304 // churn from repeated alloc/free of ~10-100KB buffers per turn.
305 var bufPool = sync.Pool{
306 New: func() any { return new(bytes.Buffer) },
307 }
308
309 func (c *client) Stream(ctx context.Context, req provider.Request) (<-chan provider.Chunk, error) {
310 if err := c.reasoning.Validate(c.model, req.EffortOverride); err != nil {
311 return nil, err
312 }
313 requestCtx := provider.WithRequestAttemptCounter(ctx)
314 buf := bufPool.Get().(*bytes.Buffer)
315 buf.Reset()
316 if err := json.NewEncoder(buf).Encode(c.buildRequest(requestCtx, req)); err != nil {
317 bufPool.Put(buf)
318 return nil, fmt.Errorf("%s: marshal request: %w", c.name, err)
319 }
320 body := make([]byte, buf.Len())
321 copy(body, buf.Bytes())
322 bufPool.Put(buf)
323
324 newReq := func(ctx context.Context) (*http.Request, error) {
325 httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.requestURL, bytes.NewReader(body))
326 if err != nil {
327 return nil, err
328 }
329 httpReq.Header.Set("Content-Type", "application/json")
330 httpReq.Header.Set("Accept", "text/event-stream")
331 if c.authHeader {
332 httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
333 } else {
334 httpReq.Header.Set("x-api-key", c.apiKey)
335 }
336 httpReq.Header.Set("anthropic-version", anthropicVersion)
337 if visionRequestUsesFileID(req) {
338 httpReq.Header.Set("anthropic-beta", "files-api-2025-04-14")
339 }
340 applyCustomHeaders(httpReq.Header, c.headers)
341 provider.ApplyOpenCodeGoHeaders(httpReq, c.baseURL, c.identityHeaders)
342 return httpReq, nil
343 }
344 resp, err := provider.SendWithRetry(requestCtx, c.http, c.sendOpts(), newReq)
345 if err != nil {
346 return nil, provider.AnnotateToolSchemaError(err, req.Tools)
347 }
348 c.authed.Store(true)
349
350 out := make(chan provider.Chunk)
351 go c.readStream(requestCtx, resp, out)
352 return out, nil
353 }
354
355 // buildRequest converts the transport-agnostic Request into the Messages API shape:
356 // RoleSystem messages lift to the top-level `system` field; assistant tool calls
357 // become `tool_use` blocks; RoleTool results become `tool_result` blocks in a user
358 // turn. Consecutive same-role messages are coalesced because the API requires
359 // alternating user/assistant turns (tool results are user turns).
360 func (c *client) buildRequest(ctx context.Context, req provider.Request) anthRequest {
361 system, msgs := c.buildMessages(req.Messages)
362
363 tools := encodeAnthTools(c, req)
364 if !c.deepseek {
365 markPromptCacheBreakpoints(system, tools, msgs)
366 }
367
368 maxTokens := req.MaxTokens
369 if maxTokens <= 0 {
370 maxTokens = c.defaultMaxTokens
371 if maxTokens <= 0 {
372 maxTokens = defaultMaxTokens
373 }
374 }
375 r := anthRequest{
376 Model: c.model,
377 MaxTokens: maxTokens,
378 System: system,
379 Messages: msgs,
380 Tools: tools,
381 Stream: true,
382 }
383 effort := c.effort
384 if req.EffortOverride != "" {
385 effort = req.EffortOverride
386 }
387 // Extended thinking is provider-specific. DeepSeek defaults to enabled and
388 // accepts output_config.effort alongside its binary toggle. Anthropic proper
389 // uses type=adaptive plus display/output_config. LongCat-style compatible
390 // gateways use the simpler enabled|disabled knob and reject output_config.
391 if c.deepseek {
392 c.applyDeepSeekThinking(&r, req)
393 } else {
394 thinking := c.thinking
395 if effort != "" && thinking == "" {
396 thinking = "adaptive"
397 }
398 switch thinking {
399 case "adaptive":
400 r.Thinking = &thinkingConfig{Type: "adaptive", Display: "summarized"}
401 if effort != "" {
402 r.OutputConfig = &outputConfig{Effort: effort}
403 }
404 case "enabled", "disabled":
405 t := c.thinking
406 if effort == "enabled" || effort == "disabled" {
407 t = effort
408 }
409 r.Thinking = &thinkingConfig{Type: t}
410 }
411 }
412 return r
413 }
414
415 // readStream parses the Messages API SSE stream into Chunks. Text deltas emit live;
416 // each tool_use content block emits a ChunkToolCallStart when its id+name are known
417 // and a complete ChunkToolCall when the block closes; usage is assembled from
418 // message_start/message_delta usage (compatible gateways may put every counter
419 // in the final delta) and emitted once before ChunkDone.
420 func (c *client) readStream(ctx context.Context, resp *http.Response, out chan<- provider.Chunk) {
421 defer resp.Body.Close()
422 defer close(out)
423
424 // Close the body if the stream stalls past c.idleTimeout so scanner.Scan()
425 // unblocks instead of hanging on a half-open connection. The watchdog owns the
426 // timer; the read loop only pings the buffered activity channel (no Timer.Reset
427 // race). A context cancel already unblocks the scan via the transport.
428 idleTimeout := c.idleTimeout
429 if idleTimeout <= 0 { // zero-value client (constructed without New)
430 idleTimeout = defaultStreamIdleTimeout
431 }
432 done := make(chan struct{})
433 defer close(done)
434 activity := make(chan struct{}, 1)
435 var stalled atomic.Bool
436 go func() {
437 idle := time.NewTimer(idleTimeout)
438 defer idle.Stop()
439 for {
440 select {
441 case <-ctx.Done():
442 resp.Body.Close()
443 return
444 case <-idle.C:
445 stalled.Store(true)
446 resp.Body.Close()
447 return
448 case <-activity:
449 if !idle.Stop() {
450 select {
451 case <-idle.C:
452 default:
453 }
454 }
455 idle.Reset(idleTimeout)
456 case <-done:
457 return
458 }
459 }
460 }()
461
462 send := func(chunk provider.Chunk) bool {
463 return sendChunk(ctx, out, chunk)
464 }
465
466 tools := map[int]*provider.ToolCall{} // tool_use blocks, keyed by content index
467 searches := newSearchStream()
468 thinking := map[int]*provider.ThinkingBlock{}
469 argBuckets := map[int]int{} // last emitted 2KB progress bucket per block
470 var inTok, outTok, cacheCreate, cacheRead int
471 var stopReason string
472 haveUsage := false
473 mergeUsage := func(usage *wireUsage) {
474 if usage == nil {
475 return
476 }
477 // The native Anthropic stream reports input/cache counters in
478 // message_start and output_tokens in message_delta. Compatible gateways
479 // such as LongCat report all counters in message_delta instead. Counters
480 // are cumulative and non-negative, so retaining the largest value also
481 // tolerates gateways that repeat partial usage in both events.
482 inTok = max(inTok, usage.InputTokens)
483 outTok = max(outTok, usage.OutputTokens)
484 cacheCreate = max(cacheCreate, usage.CacheCreationInputTokens)
485 cacheRead = max(cacheRead, usage.CacheReadInputTokens)
486 haveUsage = true
487 }
488
489 scanner := provider.NewStreamScanner(resp.Body, 1024*1024)
490
491 for scanner.Scan() {
492 select { // ping the idle watchdog; non-blocking so a full buffer is fine
493 case activity <- struct{}{}:
494 default:
495 }
496 line := strings.TrimSpace(scanner.Text())
497 // SSE carries `event:` and `data:` lines; the data JSON's own `type` field
498 // is authoritative, so we only need the data payloads.
499 if !strings.HasPrefix(line, "data:") {
500 continue
501 }
502 data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
503 if data == "" {
504 continue
505 }
506
507 var ev streamEvent
508 if err := json.Unmarshal([]byte(data), &ev); err != nil {
509 send(provider.Chunk{Type: provider.ChunkError, Err: scanner.DecodeError(c.name, data, err)})
510 return
511 }
512
513 if !updateThinkingStream(thinking, ev, send) {
514 return
515 }
516 switch ev.Type {
517 case "message_start":
518 if ev.Message != nil && ev.Message.Usage != nil {
519 mergeUsage(ev.Message.Usage)
520 }
521 case "content_block_start":
522 if chunk := beginContentBlock(ev.Index, ev.ContentBlock, tools, searches); chunk != nil {
523 if !send(*chunk) {
524 return
525 }
526 }
527 case "content_block_delta":
528 if ev.Delta == nil {
529 continue
530 }
531 switch ev.Delta.Type {
532 case "text_delta":
533 if ev.Delta.Text != "" {
534 if !send(provider.Chunk{Type: provider.ChunkText, Text: ev.Delta.Text}) {
535 return
536 }
537 }
538 case "input_json_delta":
539 if tc := tools[ev.Index]; tc != nil {
540 tc.Arguments += ev.Delta.PartialJSON
541 // Progress ticks for large streaming argument payloads, one
542 // per 2KB bucket (see the openai provider for rationale).
543 if bucket := len(tc.Arguments) / 2048; bucket > argBuckets[ev.Index] {
544 argBuckets[ev.Index] = bucket
545 if !send(provider.Chunk{Type: provider.ChunkToolCallArgsDelta, ToolCall: &provider.ToolCall{ID: tc.ID, Name: tc.Name}, ArgChars: len(tc.Arguments)}) {
546 return
547 }
548 }
549 }
550 if next := searches.argsDelta(ev.Index, ev.Delta.PartialJSON); next != nil {
551 if !send(provider.Chunk{Type: provider.ChunkServerSearch, ServerSearch: next}) {
552 return
553 }
554 }
555 case "web_search_tool_result_delta":
556 // Some DeepSeek-compatible streams deliver the result array in a
557 // delta instead of the block-start content; without this the card
558 // stays empty and the model-written source list is all that shows.
559 if next := searches.resultsDelta(ev.Index, ev.Delta.WebSearchResults); next != nil {
560 if !send(provider.Chunk{Type: provider.ChunkServerSearch, ServerSearch: next}) {
561 return
562 }
563 }
564 }
565 case "content_block_stop":
566 if tc := tools[ev.Index]; tc != nil {
567 if !send(provider.Chunk{Type: provider.ChunkToolCall, ToolCall: tc}) {
568 return
569 }
570 delete(tools, ev.Index)
571 }
572 case "message_delta":
573 if ev.Delta != nil && ev.Delta.StopReason != "" {
574 stopReason = ev.Delta.StopReason
575 }
576 mergeUsage(ev.Usage)
577 case "message_stop":
578 // Anthropic's terminal event. Tool blocks may already have closed;
579 // without this, the attempt stays speculative and is not committed.
580 // Stop reading immediately so a post-terminal connection reset cannot
581 // reclassify a complete response as interrupted.
582 goto finalize
583 case "error":
584 msg := "stream error"
585 if ev.Error != nil && ev.Error.Message != "" {
586 msg = ev.Error.Message
587 }
588 send(provider.Chunk{Type: provider.ChunkError, Err: fmt.Errorf("%s: %s", c.name, msg)})
589 return
590 }
591 }
592
593 if ctx.Err() != nil {
594 return
595 }
596 if err := streamScanEndError(c.name, idleTimeout, stalled.Load(), scanner.Err(), stopReason); err != nil {
597 send(provider.Chunk{Type: provider.ChunkError, Err: err})
598 return
599 }
600 goto finalize
601
602 finalize:
603 if len(thinking) > 0 {
604 send(provider.Chunk{Type: provider.ChunkReasoning, ReasoningState: provider.ReasoningIncomplete})
605 }
606 if haveUsage {
607 cacheWriteBilledTokens := 0.0
608 if cacheCreate > 0 && c.nativeAnthropic {
609 cacheWriteBilledTokens = float64(cacheCreate) * cacheWrite5MinuteInputMultiplier
610 }
611 usage := &provider.Usage{
612 PromptTokens: inTok + cacheCreate + cacheRead,
613 CompletionTokens: outTok,
614 TotalTokens: inTok + cacheCreate + cacheRead + outTok,
615 CacheHitTokens: cacheRead,
616 CacheMissTokens: inTok + cacheCreate,
617 CacheWriteTokens: cacheCreate,
618 CacheWriteBilledTokens: cacheWriteBilledTokens,
619 FinishReason: mapStopReason(stopReason),
620 }
621 provider.ApplyRequestAttemptCount(ctx, usage)
622 if !send(provider.Chunk{Type: provider.ChunkUsage, Usage: usage}) {
623 return
624 }
625 }
626 send(provider.Chunk{Type: provider.ChunkDone})
627 }
628
629 func sendChunk(ctx context.Context, out chan<- provider.Chunk, chunk provider.Chunk) bool {
630 select {
631 case out <- chunk:
632 return true
633 default:
634 }
635 select {
636 case <-ctx.Done():
637 return false
638 case out <- chunk:
639 return true
640 }
641 }
642
643 // mapStopReason translates Anthropic stop reasons to the OpenAI-style finish
644 // reasons the agent already recognises (it surfaces abnormal ones like "length").
645 func mapStopReason(s string) string {
646 switch s {
647 case "end_turn", "stop_sequence":
648 return "stop"
649 case "tool_use":
650 return "tool_calls"
651 case "max_tokens":
652 return "length"
653 default:
654 return s // "refusal", "pause_turn", "" — pass through
655 }
656 }
657
658 // Messages API wire protocol
659
660 const cacheWrite5MinuteInputMultiplier = 1.25
661
662 func ephemeral() *cacheControl { return &cacheControl{Type: "ephemeral"} }
663
664 type cacheControl struct {
665 Type string `json:"type"`
666 }
667
668 type anthRequest struct {
669 Model string `json:"model"`
670 MaxTokens int `json:"max_tokens"`
671 System []textBlock `json:"system,omitempty"`
672 Messages []anthMessage `json:"messages"`
673 Tools []anthTool `json:"tools,omitempty"`
674 Temperature *float64 `json:"temperature,omitempty"`
675 Thinking *thinkingConfig `json:"thinking,omitempty"`
676 OutputConfig *outputConfig `json:"output_config,omitempty"`
677 Stream bool `json:"stream"`
678 }
679
680 type thinkingConfig struct {
681 Type string `json:"type"` // "adaptive"
682 Display string `json:"display,omitempty"` // "summarized" to stream the reasoning text
683 }
684
685 type outputConfig struct {
686 Effort string `json:"effort,omitempty"` // low | high | max
687 }
688
689 type textBlock struct {
690 Type string `json:"type"`
691 Text string `json:"text"`
692 CacheControl *cacheControl `json:"cache_control,omitempty"`
693 }
694
695 type anthMessage struct {
696 Role string `json:"role"`
697 Content []contentBlock `json:"content"`
698 }
699
700 // contentBlock is the union of the block kinds we emit in a request: text,
701 // tool_use (echoing a prior assistant call), and tool_result. Unused fields are
702 // omitted so each block serialises to its canonical shape.
703 type contentBlock struct {
704 Data string `json:"data,omitempty"`
705 Type string `json:"type"`
706 Text string `json:"text,omitempty"` // text
707 Thinking string `json:"thinking,omitempty"` // thinking
708 Signature string `json:"signature,omitempty"` // thinking
709 ID string `json:"id,omitempty"` // tool_use
710 Name string `json:"name,omitempty"` // tool_use
711 Input json.RawMessage `json:"input,omitempty"` // tool_use
712 ToolUseID string `json:"tool_use_id,omitempty"` // tool_result
713 Content any `json:"content,omitempty"` // tool_result: string, or []contentBlock when the result carries images
714 Source *imageSource `json:"source,omitempty"` // image
715 CacheControl *cacheControl `json:"cache_control,omitempty"`
716 }
717
718 type imageSource struct {
719 Type string `json:"type"` // base64 | url | file
720 MediaType string `json:"media_type,omitempty"`
721 Data string `json:"data,omitempty"`
722 URL string `json:"url,omitempty"`
723 FileID string `json:"file_id,omitempty"`
724 }
725
726 // toolResultBlocks builds array content for a tool_result whose message carries
727 // images: the text first, then one image block per parseable data URL. It
728 // returns nil when nothing parses, so text-only results keep plain string
729 // content — byte-identical serialization to previous releases.
730 func toolResultBlocks(text string, images []string) []contentBlock {
731 var imgs []contentBlock
732 for _, url := range images {
733 if mt, data, ok := provider.ParseImageDataURL(url); ok {
734 imgs = append(imgs, contentBlock{Type: "image", Source: &imageSource{Type: "base64", MediaType: mt, Data: data}})
735 }
736 }
737 if imgs == nil {
738 return nil
739 }
740 return append([]contentBlock{{Type: "text", Text: text}}, imgs...)
741 }
742
743 type anthTool struct {
744 Type string `json:"type,omitempty"` // "web_search" for server-side search; empty for named tools
745 Name string `json:"name,omitempty"`
746 Description string `json:"description,omitempty"`
747 InputSchema json.RawMessage `json:"input_schema,omitempty"`
748 Strict bool `json:"strict,omitempty"`
749 DeferLoading bool `json:"defer_loading,omitempty"`
750 CacheControl *cacheControl `json:"cache_control,omitempty"`
751 }
752
753 // streamEvent is the discriminated SSE event; read the fields matching Type.
754 type streamEvent struct {
755 Type string `json:"type"`
756 Index int `json:"index"`
757 Message *struct {
758 Usage *wireUsage `json:"usage"`
759 } `json:"message"`
760 ContentBlock *streamContentBlock `json:"content_block"`
761 Delta *struct {
762 Type string `json:"type"` // text_delta | thinking_delta | signature_delta | input_json_delta | web_search_tool_result_delta
763 Text string `json:"text"` // text_delta
764 Thinking string `json:"thinking"` // thinking_delta
765 Signature string `json:"signature"` // signature_delta
766 PartialJSON string `json:"partial_json"` // input_json_delta
767 StopReason string `json:"stop_reason"` // message_delta
768 WebSearchResults json.RawMessage `json:"results"` // web_search_tool_result_delta
769 } `json:"delta"`
770 Usage *wireUsage `json:"usage"` // message_delta (cumulative output_tokens)
771 Error *struct {
772 Type string `json:"type"`
773 Message string `json:"message"`
774 } `json:"error"`
775 }
776
777 type wireUsage struct {
778 InputTokens int `json:"input_tokens"`
779 OutputTokens int `json:"output_tokens"`
780 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
781 CacheReadInputTokens int `json:"cache_read_input_tokens"`
782 }
783
783 lines GO