forked from docker/docker-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1026 lines (924 loc) · 35.4 KB
/
client.go
File metadata and controls
1026 lines (924 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package anthropic
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/url"
"strings"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/anthropics/anthropic-sdk-go/packages/param"
"github.com/anthropics/anthropic-sdk-go/packages/ssestream"
"github.com/docker/docker-agent/pkg/chat"
"github.com/docker/docker-agent/pkg/config/latest"
"github.com/docker/docker-agent/pkg/effort"
"github.com/docker/docker-agent/pkg/environment"
"github.com/docker/docker-agent/pkg/httpclient"
"github.com/docker/docker-agent/pkg/model/provider/base"
"github.com/docker/docker-agent/pkg/model/provider/options"
"github.com/docker/docker-agent/pkg/model/provider/providerutil"
"github.com/docker/docker-agent/pkg/tools"
)
// Client represents an Anthropic client wrapper implementing provider.Provider
// It holds the anthropic client and model config
type Client struct {
base.Config
clientFn func(context.Context) (anthropic.Client, error)
fileManager *FileManager
}
// adjustMaxTokensForThinking checks if max_tokens needs adjustment for thinking_budget.
// Anthropic's max_tokens represents the combined budget for thinking + output tokens.
// Returns the adjusted maxTokens value and an error if user-set max_tokens is too low.
//
// Only fixed token budgets need adjustment. Adaptive and effort-based budgets
// don't need it since the model manages its own thinking allocation.
func (c *Client) adjustMaxTokensForThinking(maxTokens int64) (int64, error) {
if c.ModelConfig.ThinkingBudget == nil {
return maxTokens, nil
}
// Adaptive and effort-based budgets: no token adjustment needed.
if _, ok := anthropicThinkingEffort(c.ModelConfig.ThinkingBudget); ok {
return maxTokens, nil
}
thinkingTokens := int64(c.ModelConfig.ThinkingBudget.Tokens)
if thinkingTokens <= 0 {
return maxTokens, nil
}
minRequired := thinkingTokens + 1024 // configured thinking budget + minimum output buffer
if maxTokens <= thinkingTokens {
userSetMaxTokens := c.ModelConfig.MaxTokens != nil
if userSetMaxTokens {
// User explicitly set max_tokens too low - return error
slog.Error("Anthropic: max_tokens must be greater than thinking_budget",
"max_tokens", maxTokens,
"thinking_budget", thinkingTokens)
return 0, fmt.Errorf("anthropic: max_tokens (%d) must be greater than thinking_budget (%d); increase max_tokens to at least %d",
maxTokens, thinkingTokens, minRequired)
}
// Auto-adjust when user didn't set max_tokens
slog.Info("Anthropic: auto-adjusting max_tokens to accommodate thinking_budget",
"original_max_tokens", maxTokens,
"thinking_budget", thinkingTokens,
"new_max_tokens", minRequired)
// return the configured thinking budget + 8192 because that's the default
// max_tokens value for anthropic models when unspecified by the user
return thinkingTokens + 8192, nil
}
return maxTokens, nil
}
// interleavedThinkingEnabled returns false unless explicitly enabled via
// models:provider_opts:interleaved_thinking: true
func (c *Client) interleavedThinkingEnabled() bool {
// Default to false if not provided
if c == nil || len(c.ModelConfig.ProviderOpts) == 0 {
return false
}
v, ok := c.ModelConfig.ProviderOpts["interleaved_thinking"]
if !ok {
return false
}
switch t := v.(type) {
case bool:
return t
case string:
s := strings.TrimSpace(strings.ToLower(t))
return s != "false" && s != "0" && s != "no"
case int:
return t != 0
case int64:
return t != 0
case float64:
return t != 0
default:
return false
}
}
// NewClient creates a new Anthropic client from the provided configuration
func NewClient(ctx context.Context, cfg *latest.ModelConfig, env environment.Provider, opts ...options.Opt) (*Client, error) {
if cfg == nil {
slog.Error("Anthropic client creation failed", "error", "model configuration is required")
return nil, errors.New("model configuration is required")
}
if cfg.Provider != "anthropic" {
slog.Error("Anthropic client creation failed", "error", "model type must be 'anthropic'", "actual_type", cfg.Provider)
return nil, errors.New("model type must be 'anthropic'")
}
if env == nil {
slog.Error("Anthropic client creation failed", "error", "environment provider is required")
return nil, errors.New("environment provider is required")
}
var globalOptions options.ModelOptions
for _, opt := range opts {
if opt != nil {
opt(&globalOptions)
}
}
anthropicClient := &Client{
Config: base.Config{
ModelConfig: *cfg,
ModelOptions: globalOptions,
Env: env,
},
}
if gateway := globalOptions.Gateway(); gateway == "" {
authToken, _ := env.Get(ctx, "ANTHROPIC_API_KEY")
if authToken == "" {
return nil, errors.New("ANTHROPIC_API_KEY environment variable is required")
}
slog.Debug("Anthropic API key found, creating client")
requestOptions := []option.RequestOption{
option.WithAPIKey(authToken),
option.WithHTTPClient(httpclient.NewHTTPClient(ctx)),
}
if cfg.BaseURL != "" {
expandedBaseURL, err := environment.Expand(ctx, cfg.BaseURL, env)
if err != nil {
return nil, fmt.Errorf("expanding base_url: %w", err)
}
requestOptions = append(requestOptions, option.WithBaseURL(expandedBaseURL))
}
// Apply custom headers from provider config if present
if cfg.ProviderOpts != nil {
if headers, exists := cfg.ProviderOpts["headers"]; exists {
headersMap := make(map[string]string)
switch h := headers.(type) {
case map[string]string:
headersMap = h
case map[interface{}]interface{}:
for k, v := range h {
keyStr, okKey := k.(string)
valStr, okVal := v.(string)
if !okKey || !okVal {
return nil, fmt.Errorf("invalid header key/value type: key=%T, value=%T", k, v)
}
headersMap[keyStr] = valStr
}
default:
return nil, fmt.Errorf("invalid headers configuration: expected map[string]string, got %T", headers)
}
for key, value := range headersMap {
expandedValue, err := environment.Expand(ctx, value, env)
if err != nil {
return nil, fmt.Errorf("expanding header %s: %w", key, err)
}
requestOptions = append(requestOptions, option.WithHeader(key, expandedValue))
slog.Debug("Applied custom header", "header", key, "provider", cfg.Provider)
}
}
}
client := anthropic.NewClient(requestOptions...)
anthropicClient.clientFn = func(context.Context) (anthropic.Client, error) {
return client, nil
}
} else {
// Fail fast if Docker Desktop's auth token isn't available
if token, _ := env.Get(ctx, environment.DockerDesktopTokenEnv); token == "" {
slog.Error("Anthropic client creation failed", "error", "failed to get Docker Desktop's authentication token")
return nil, errors.New("sorry, you first need to sign in Docker Desktop to use the Docker AI Gateway")
}
// When using a Gateway, tokens are short-lived.
anthropicClient.clientFn = func(ctx context.Context) (anthropic.Client, error) {
// Query a fresh auth token each time the client is used
authToken, _ := env.Get(ctx, environment.DockerDesktopTokenEnv)
if authToken == "" {
return anthropic.Client{}, errors.New("failed to get Docker Desktop token for Gateway")
}
url, err := url.Parse(gateway)
if err != nil {
return anthropic.Client{}, fmt.Errorf("invalid gateway URL: %w", err)
}
baseURL := fmt.Sprintf("%s://%s%s/", url.Scheme, url.Host, url.Path)
// Configure a custom HTTP client to inject headers and query params used by the Gateway.
httpOptions := []httpclient.Opt{
httpclient.WithProxiedBaseURL(cmp.Or(cfg.BaseURL, "https://api.anthropic.com/")),
httpclient.WithProvider(cfg.Provider),
httpclient.WithModel(cfg.Model),
httpclient.WithModelName(cfg.Name),
httpclient.WithQuery(url.Query()),
}
if globalOptions.GeneratingTitle() {
httpOptions = append(httpOptions, httpclient.WithHeader("X-Cagent-GeneratingTitle", "1"))
}
client := anthropic.NewClient(
option.WithAuthToken(authToken),
option.WithAPIKey(authToken),
option.WithBaseURL(baseURL),
option.WithHTTPClient(httpclient.NewHTTPClient(ctx, httpOptions...)),
)
return client, nil
}
}
slog.Debug("Anthropic client created successfully", "model", cfg.Model)
// Initialize FileManager for file uploads
anthropicClient.fileManager = NewFileManager(anthropicClient.clientFn)
return anthropicClient, nil
}
// hasFileAttachments checks if any messages contain file attachments.
// This is used to determine if we need to use the Beta API (Files API is Beta-only).
func hasFileAttachments(messages []chat.Message) bool {
for i := range messages {
for _, part := range messages[i].MultiContent {
if part.Type == chat.MessagePartTypeFile && part.File != nil {
return true
}
}
}
return false
}
// CreateChatCompletionStream creates a streaming chat completion request
func (c *Client) CreateChatCompletionStream(
ctx context.Context,
messages []chat.Message,
requestTools []tools.Tool,
) (chat.MessageStream, error) {
slog.Debug("Creating Anthropic chat completion stream",
"model", c.ModelConfig.Model,
"message_count", len(messages),
"tool_count", len(requestTools))
// Default to 8192 if maxTokens is not set (0)
// This is a safe default that works for all Anthropic models
maxTokens := c.ModelOptions.MaxTokens()
if maxTokens == 0 {
maxTokens = 8192
}
maxTokens, err := c.adjustMaxTokensForThinking(maxTokens)
if err != nil {
return nil, err
}
client, err := c.clientFn(ctx)
if err != nil {
slog.Error("Failed to create Anthropic client", "error", err)
return nil, err
}
// Use Beta API when:
// 1. Interleaved thinking is enabled, or
// 2. Structured output is configured, or
// 3. Messages contain file attachments (Files API is Beta-only)
// Note: Structured outputs require beta header support (only available on BetaMessageNewParams)
if c.interleavedThinkingEnabled() || c.ModelOptions.StructuredOutput() != nil || hasFileAttachments(messages) {
return c.createBetaStream(ctx, client, messages, requestTools, maxTokens)
}
allTools, err := convertTools(requestTools)
if err != nil {
slog.Error("Failed to convert tools for Anthropic request", "error", err)
return nil, err
}
converted, err := c.convertMessages(ctx, messages)
if err != nil {
slog.Error("Failed to convert messages for Anthropic request", "error", err)
return nil, err
}
// Preflight validation to ensure tool_use/tool_result sequencing is valid
if err := validateAnthropicSequencing(converted); err != nil {
slog.Warn("Invalid message sequencing for Anthropic detected, attempting self-repair", "error", err)
converted = repairAnthropicSequencing(converted)
if err2 := validateAnthropicSequencing(converted); err2 != nil {
slog.Error("Failed to self-repair Anthropic sequencing", "error", err2)
return nil, err
}
}
if len(converted) == 0 {
return nil, errors.New("no messages to send after conversion: all messages were filtered out")
}
sys := extractSystemBlocks(messages)
params := anthropic.MessageNewParams{
Model: c.ModelConfig.Model,
MaxTokens: maxTokens,
System: sys,
Messages: converted,
Tools: allTools,
}
// Apply thinking budget first, as it affects whether we can set temperature
thinkingEnabled := false
if budget := c.ModelConfig.ThinkingBudget; budget != nil {
if effortStr, ok := anthropicThinkingEffort(budget); ok {
adaptive := anthropic.ThinkingConfigAdaptiveParam{}
params.Thinking = anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive}
params.OutputConfig.Effort = anthropic.OutputConfigEffort(effortStr)
thinkingEnabled = true
slog.Debug("Anthropic API using adaptive thinking", "effort", effortStr)
} else if tokens, ok := validThinkingTokens(int64(budget.Tokens), maxTokens); ok {
params.Thinking = anthropic.ThinkingConfigParamOfEnabled(tokens)
thinkingEnabled = true
slog.Debug("Anthropic API using thinking_budget", "budget_tokens", tokens)
}
}
// Temperature and TopP cannot be set when extended thinking is enabled
// (Anthropic requires temperature=1.0 which is the default when thinking is on)
if !thinkingEnabled {
if c.ModelConfig.Temperature != nil {
params.Temperature = param.NewOpt(*c.ModelConfig.Temperature)
}
if c.ModelConfig.TopP != nil {
params.TopP = param.NewOpt(*c.ModelConfig.TopP)
}
} else if c.ModelConfig.Temperature != nil || c.ModelConfig.TopP != nil {
slog.Debug("Anthropic extended thinking enabled, ignoring temperature/top_p settings")
}
// Forward top_k from provider_opts (Anthropic natively supports it)
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok {
params.TopK = param.NewOpt(topK)
slog.Debug("Anthropic provider_opts: set top_k", "value", topK)
}
if len(requestTools) > 0 {
slog.Debug("Adding tools to Anthropic request", "tool_count", len(requestTools))
}
// Log the request details for debugging
slog.Debug("Anthropic chat completion stream request",
"model", params.Model,
"max_tokens", maxTokens,
"message_count", len(params.Messages))
if slog.Default().Enabled(ctx, slog.LevelDebug) {
b, err := json.Marshal(params)
if err != nil {
slog.Error("Failed to marshal Anthropic request", "error", err)
}
slog.Debug("Request", "request", string(b))
}
// Add fine-grained tool streaming beta header
betaHeader := option.WithHeader("anthropic-beta", "fine-grained-tool-streaming-2025-05-14")
stream := client.Messages.NewStreaming(ctx, params, betaHeader)
trackUsage := c.ModelConfig.TrackUsage == nil || *c.ModelConfig.TrackUsage
ad := c.newStreamAdapter(stream, trackUsage)
// Set up single retry for context length errors
ad.retryFn = func() *ssestream.Stream[anthropic.MessageStreamEventUnion] {
used, err := countAnthropicTokens(ctx, client, c.ModelConfig.Model, converted, sys, allTools)
if err != nil {
slog.Warn("Failed to count tokens for retry, skipping", "error", err)
return nil
}
newMaxTokens := clampMaxTokens(anthropicContextLimit(c.ModelConfig.Model), used, maxTokens)
if newMaxTokens >= maxTokens {
slog.Warn("Token count does not require clamping, not retrying")
return nil
}
slog.Warn("Retrying with clamped max_tokens after context length error", "original max_tokens", maxTokens, "clamped max_tokens", newMaxTokens, "used tokens", used)
retryParams := params
retryParams.MaxTokens = newMaxTokens
return client.Messages.NewStreaming(ctx, retryParams, betaHeader)
}
slog.Debug("Anthropic chat completion stream created successfully", "model", c.ModelConfig.Model)
return ad, nil
}
func (c *Client) convertMessages(ctx context.Context, messages []chat.Message) ([]anthropic.MessageParam, error) {
var anthropicMessages []anthropic.MessageParam
// Track whether the last appended assistant message included tool_use blocks
// so we can ensure the immediate next message is the grouped tool_result user message.
pendingAssistantToolUse := false
for i := 0; i < len(messages); i++ {
msg := &messages[i]
if msg.Role == chat.MessageRoleSystem {
// System messages are handled via the top-level params.System
continue
}
if msg.Role == chat.MessageRoleUser {
// Handle MultiContent for user messages (including images and files)
if len(msg.MultiContent) > 0 {
contentBlocks, err := c.convertUserMultiContent(ctx, msg.MultiContent)
if err != nil {
return nil, err
}
if len(contentBlocks) > 0 {
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))
}
} else {
if txt := strings.TrimSpace(msg.Content); txt != "" {
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(anthropic.NewTextBlock(txt)))
}
}
continue
}
if msg.Role == chat.MessageRoleAssistant {
contentBlocks := make([]anthropic.ContentBlockParamUnion, 0)
// Include thinking blocks when present to preserve extended thinking context
if msg.ReasoningContent != "" && msg.ThinkingSignature != "" {
contentBlocks = append(contentBlocks, anthropic.NewThinkingBlock(msg.ThinkingSignature, msg.ReasoningContent))
} else if msg.ThinkingSignature != "" {
contentBlocks = append(contentBlocks, anthropic.NewRedactedThinkingBlock(msg.ThinkingSignature))
}
if len(msg.ToolCalls) > 0 {
blockLen := len(msg.ToolCalls)
msgContent := strings.TrimSpace(msg.Content)
offset := 0
if msgContent != "" {
blockLen++
}
toolUseBlocks := make([]anthropic.ContentBlockParamUnion, blockLen)
// If there is prior thinking, append it first
if len(contentBlocks) > 0 {
toolUseBlocks = append(contentBlocks, toolUseBlocks...)
}
if msgContent != "" {
toolUseBlocks[len(contentBlocks)+offset] = anthropic.NewTextBlock(msgContent)
offset = 1
}
for j, toolCall := range msg.ToolCalls {
var inpts map[string]any
if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &inpts); err != nil {
inpts = map[string]any{}
}
toolUseBlocks[len(contentBlocks)+j+offset] = anthropic.ContentBlockParamUnion{
OfToolUse: &anthropic.ToolUseBlockParam{
ID: toolCall.ID,
Input: inpts,
Name: toolCall.Function.Name,
},
}
}
anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(toolUseBlocks...))
// Mark that we expect the very next message to be the grouped tool_result blocks.
pendingAssistantToolUse = true
} else {
if txt := strings.TrimSpace(msg.Content); txt != "" {
contentBlocks = append(contentBlocks, anthropic.NewTextBlock(txt))
}
if len(contentBlocks) > 0 {
anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(contentBlocks...))
}
// No tool_use in this assistant message
pendingAssistantToolUse = false
}
continue
}
if msg.Role == chat.MessageRoleTool {
// Group consecutive tool results into a single user message.
//
// This is to satisfy Anthropic's requirement that tool_use blocks are immediately followed
// by a single user message containing all corresponding tool_result blocks.
var blocks []anthropic.ContentBlockParamUnion
j := i
for j < len(messages) && messages[j].Role == chat.MessageRoleTool {
tr := convertToolResultBlock(&messages[j])
blocks = append(blocks, tr)
j++
}
if len(blocks) > 0 {
// Only include tool_result blocks if they immediately follow an assistant
// message that contained tool_use. Otherwise, drop them to avoid invalid
// sequencing errors.
if pendingAssistantToolUse {
anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(blocks...))
}
// Whether we used them or not, we've now handled the expected tool_result slot.
pendingAssistantToolUse = false
}
i = j - 1
continue
}
}
// Add ephemeral cache to last 2 messages' last content block
applyMessageCacheControl(anthropicMessages)
return anthropicMessages, nil
}
// convertToolResultBlock converts a tool message to an Anthropic tool_result block.
// If the message contains image content in MultiContent, the images are included
// as image blocks within the tool_result.
func convertToolResultBlock(msg *chat.Message) anthropic.ContentBlockParamUnion {
// If there are no images in MultiContent, use the simple text-only format.
if !hasImageMultiContent(msg.MultiContent) {
return anthropic.NewToolResultBlock(msg.ToolCallID, strings.TrimSpace(msg.Content), msg.IsError)
}
// Build content blocks with text + images for the tool result.
var content []anthropic.ToolResultBlockParamContentUnion
for _, part := range msg.MultiContent {
switch part.Type {
case chat.MessagePartTypeText:
if txt := strings.TrimSpace(part.Text); txt != "" {
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{Text: txt},
})
}
case chat.MessagePartTypeImageURL:
if part.ImageURL == nil {
continue
}
if strings.HasPrefix(part.ImageURL.URL, "data:") {
urlParts := strings.SplitN(part.ImageURL.URL, ",", 2)
if len(urlParts) == 2 {
mediaType := extractMediaType(urlParts[0])
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfImage: &anthropic.ImageBlockParam{
Source: anthropic.ImageBlockParamSourceUnion{
OfBase64: &anthropic.Base64ImageSourceParam{
Data: urlParts[1],
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
},
},
},
})
}
}
}
}
toolBlock := anthropic.ToolResultBlockParam{
ToolUseID: msg.ToolCallID,
Content: content,
IsError: anthropic.Bool(msg.IsError),
}
return anthropic.ContentBlockParamUnion{OfToolResult: &toolBlock}
}
// hasImageMultiContent returns true if the multi-content parts contain any image content.
func hasImageMultiContent(parts []chat.MessagePart) bool {
for _, part := range parts {
if part.Type == chat.MessagePartTypeImageURL && part.ImageURL != nil {
return true
}
}
return false
}
// extractMediaType extracts the media type from a data URL prefix (e.g. "data:image/png;base64").
func extractMediaType(prefix string) string {
switch {
case strings.Contains(prefix, "image/jpeg"):
return "image/jpeg"
case strings.Contains(prefix, "image/png"):
return "image/png"
case strings.Contains(prefix, "image/gif"):
return "image/gif"
case strings.Contains(prefix, "image/webp"):
return "image/webp"
default:
return "image/jpeg"
}
}
// convertUserMultiContent converts user message multi-content parts to Anthropic content blocks.
// It handles text and images (base64 and URL). File uploads are NOT supported in the non-Beta API
// and will return an error - callers should use hasFileAttachments() to route to the Beta API.
func (c *Client) convertUserMultiContent(_ context.Context, parts []chat.MessagePart) ([]anthropic.ContentBlockParamUnion, error) {
contentBlocks := make([]anthropic.ContentBlockParamUnion, 0, len(parts))
for _, part := range parts {
switch part.Type {
case chat.MessagePartTypeText:
if txt := strings.TrimSpace(part.Text); txt != "" {
contentBlocks = append(contentBlocks, anthropic.NewTextBlock(txt))
}
case chat.MessagePartTypeImageURL:
if part.ImageURL == nil {
continue
}
// Handle base64 data URLs (legacy format)
if strings.HasPrefix(part.ImageURL.URL, "data:") {
urlParts := strings.SplitN(part.ImageURL.URL, ",", 2)
if len(urlParts) == 2 {
mediaType := extractMediaType(urlParts[0])
base64Data := urlParts[1]
contentBlocks = append(contentBlocks, anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{
Data: base64Data,
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
}))
}
} else if strings.HasPrefix(part.ImageURL.URL, "http://") || strings.HasPrefix(part.ImageURL.URL, "https://") {
// URL-based images
contentBlocks = append(contentBlocks, anthropic.NewImageBlock(anthropic.URLImageSourceParam{
URL: part.ImageURL.URL,
}))
}
case chat.MessagePartTypeFile:
if part.File == nil {
continue
}
// File uploads require the Beta API - this code path should not be reached
// if hasFileAttachments() correctly routes to createBetaStream().
// Return a clear error if we somehow get here.
return nil, fmt.Errorf("file attachments require the Beta API; use hasFileAttachments() to route correctly (path=%q, file_id=%q)",
part.File.Path, part.File.FileID)
}
}
return contentBlocks, nil
}
// createFileContentBlock creates the appropriate content block for a file based on its MIME type.
// Note: File uploads via the Files API require the Beta API. This function supports images
// (which have OfFile in the Beta API only) and documents. For non-Beta API usage with files,
// the caller should handle the conversion differently or use base64 encoding.
func createFileContentBlock(fileID, mimeType string) (anthropic.ContentBlockParamUnion, error) {
// The standard (non-Beta) API doesn't support file references in ImageBlockParamSourceUnion
// or DocumentBlockParamSourceUnion. Files API is Beta-only.
// For now, we return an error directing users to use the Beta API path.
return anthropic.ContentBlockParamUnion{}, fmt.Errorf("file uploads require the Beta API; file_id=%s, mime_type=%s", fileID, mimeType)
}
// applyMessageCacheControl adds ephemeral cache control to the last content block
// of the last 2 messages for prompt caching.
func applyMessageCacheControl(messages []anthropic.MessageParam) {
for i := len(messages) - 1; i >= 0 && i >= len(messages)-2; i-- {
msg := &messages[i]
if len(msg.Content) == 0 {
continue
}
lastIdx := len(msg.Content) - 1
block := &msg.Content[lastIdx]
cacheCtrl := anthropic.NewCacheControlEphemeralParam()
switch {
case block.OfText != nil:
block.OfText.CacheControl = cacheCtrl
case block.OfToolUse != nil:
block.OfToolUse.CacheControl = cacheCtrl
case block.OfToolResult != nil:
block.OfToolResult.CacheControl = cacheCtrl
case block.OfImage != nil:
block.OfImage.CacheControl = cacheCtrl
case block.OfDocument != nil:
block.OfDocument.CacheControl = cacheCtrl
}
}
}
// extractSystemBlocks converts any system-role messages into Anthropic system text blocks
// to be set on the top-level MessageNewParams.System field.
func extractSystemBlocks(messages []chat.Message) []anthropic.TextBlockParam {
var systemBlocks []anthropic.TextBlockParam
for i := range messages {
msg := &messages[i]
if msg.Role != chat.MessageRoleSystem {
continue
}
if len(msg.MultiContent) > 0 {
for _, part := range msg.MultiContent {
if part.Type == chat.MessagePartTypeText {
if txt := strings.TrimSpace(part.Text); txt != "" {
systemBlocks = append(systemBlocks, anthropic.TextBlockParam{Text: txt})
}
}
}
} else if txt := strings.TrimSpace(msg.Content); txt != "" {
systemBlocks = append(systemBlocks, anthropic.TextBlockParam{
Text: txt,
})
}
if msg.CacheControl {
systemBlocks[len(systemBlocks)-1].CacheControl = anthropic.NewCacheControlEphemeralParam()
}
}
return systemBlocks
}
func convertTools(tooles []tools.Tool) ([]anthropic.ToolUnionParam, error) {
toolParams := make([]anthropic.ToolParam, len(tooles))
for i, tool := range tooles {
inputSchema, err := ConvertParametersToSchema(tool.Parameters)
if err != nil {
return nil, err
}
toolParams[i] = anthropic.ToolParam{
Name: tool.Name,
Description: anthropic.String(tool.Description),
InputSchema: inputSchema,
}
}
anthropicTools := make([]anthropic.ToolUnionParam, len(toolParams))
for i := range toolParams {
anthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParams[i]}
}
return anthropicTools, nil
}
// ConvertParametersToSchema converts parameters to Anthropic Schema format
func ConvertParametersToSchema(params any) (anthropic.ToolInputSchemaParam, error) {
var schema anthropic.ToolInputSchemaParam
if err := tools.ConvertSchema(params, &schema); err != nil {
return anthropic.ToolInputSchemaParam{}, err
}
return schema, nil
}
// CleanupFiles removes all files uploaded during this session from Anthropic's storage.
func (c *Client) CleanupFiles(ctx context.Context) error {
if c.fileManager == nil {
return nil
}
return c.fileManager.CleanupAll(ctx)
}
// FileManager returns the file manager for this client, allowing external cleanup.
// Returns nil if file uploads are not supported or not initialized.
func (c *Client) FileManager() *FileManager {
return c.fileManager
}
// validateAnthropicSequencing verifies that for every assistant message that includes
// one or more tool_use blocks, the immediately following message is a user message
// that includes tool_result blocks for all those tool_use IDs (grouped into that single message).
func validateAnthropicSequencing(msgs []anthropic.MessageParam) error {
return validateSequencing(msgs)
}
// repairAnthropicSequencing inserts a synthetic user message containing tool_result blocks
// immediately after any assistant message that has tool_use blocks missing a corresponding
// tool_result in the next user message. This is a best-effort local repair to keep the
// conversation valid for Anthropic while preserving original messages, to keep the agent loop running.
func repairAnthropicSequencing(msgs []anthropic.MessageParam) []anthropic.MessageParam {
return repairSequencing(msgs, func(toolUseIDs map[string]struct{}) anthropic.MessageParam {
blocks := make([]anthropic.ContentBlockParamUnion, 0, len(toolUseIDs))
for id := range toolUseIDs {
blocks = append(blocks, anthropic.NewToolResultBlock(id, "(tool execution failed)", false))
}
return anthropic.NewUserMessage(blocks...)
})
}
// marshalToMap is a helper that converts any value to a map[string]any via JSON marshaling.
// This is used to inspect SDK union types without depending on their internal structure.
// It's shared by both standard and Beta API validation/repair code.
func marshalToMap(v any) (map[string]any, bool) {
b, err := json.Marshal(v)
if err != nil {
return nil, false
}
var m map[string]any
if json.Unmarshal(b, &m) != nil {
return nil, false
}
return m, true
}
// contentArray extracts the content array from a marshaled message map.
// Used by both standard and Beta API validation/repair code.
func contentArray(m map[string]any) []any {
if a, ok := m["content"].([]any); ok {
return a
}
return nil
}
// validateSequencing generically validates that every assistant message with tool_use blocks
// is immediately followed by a user message with corresponding tool_result blocks.
// It works on both standard (MessageParam) and Beta (BetaMessageParam) types by
// marshaling to map[string]any for inspection.
func validateSequencing[T any](msgs []T) error {
for i := range msgs {
m, ok := marshalToMap(msgs[i])
if !ok || m["role"] != "assistant" {
continue
}
toolUseIDs := collectToolUseIDs(contentArray(m))
if len(toolUseIDs) == 0 {
continue
}
if i+1 >= len(msgs) {
slog.Warn("Anthropic sequencing invalid: assistant tool_use present but no next user tool_result message", "assistant_index", i)
return errors.New("assistant tool_use present but no subsequent user message with tool_result blocks")
}
next, ok := marshalToMap(msgs[i+1])
if !ok || next["role"] != "user" {
slog.Warn("Anthropic sequencing invalid: next message after assistant tool_use is not user", "assistant_index", i, "next_role", next["role"])
return errors.New("assistant tool_use must be followed by a user message containing corresponding tool_result blocks")
}
toolResultIDs := collectToolResultIDs(contentArray(next))
missing := differenceIDs(toolUseIDs, toolResultIDs)
if len(missing) > 0 {
slog.Warn("Anthropic sequencing invalid: missing tool_result for tool_use id in next user message", "assistant_index", i, "tool_use_id", missing[0], "missing_count", len(missing))
return fmt.Errorf("missing tool_result for tool_use id %s in the next user message", missing[0])
}
}
return nil
}
// repairSequencing generically inserts a synthetic user message after any assistant
// tool_use message that is missing corresponding tool_result blocks. The makeSynthetic
// callback builds the appropriate user message type for the remaining tool_use IDs.
func repairSequencing[T any](msgs []T, makeSynthetic func(toolUseIDs map[string]struct{}) T) []T {
if len(msgs) == 0 {
return msgs
}
repaired := make([]T, 0, len(msgs)+2)
for i := range msgs {
repaired = append(repaired, msgs[i])
m, ok := marshalToMap(msgs[i])
if !ok || m["role"] != "assistant" {
continue
}
toolUseIDs := collectToolUseIDs(contentArray(m))
if len(toolUseIDs) == 0 {
continue
}
// Remove any IDs that already have results in the next user message
if i+1 < len(msgs) {
if next, ok := marshalToMap(msgs[i+1]); ok && next["role"] == "user" {
toolResultIDs := collectToolResultIDs(contentArray(next))
for id := range toolResultIDs {
delete(toolUseIDs, id)
}
}
}
if len(toolUseIDs) > 0 {
slog.Debug("Inserting synthetic user message for missing tool_results",
"assistant_index", i,
"missing_count", len(toolUseIDs))
repaired = append(repaired, makeSynthetic(toolUseIDs))
}
}
return repaired
}
func collectToolUseIDs(content []any) map[string]struct{} {
ids := make(map[string]struct{})
for _, c := range content {
if cb, ok := c.(map[string]any); ok {
if t, _ := cb["type"].(string); t == "tool_use" {
if id, _ := cb["id"].(string); id != "" {
ids[id] = struct{}{}
}
}
}
}
return ids
}
func collectToolResultIDs(content []any) map[string]struct{} {
ids := make(map[string]struct{})
for _, c := range content {
if cb, ok := c.(map[string]any); ok {
if t, _ := cb["type"].(string); t == "tool_result" {
if id, _ := cb["tool_use_id"].(string); id != "" {
ids[id] = struct{}{}
}
}
}
}
return ids
}
func differenceIDs(a, b map[string]struct{}) []string {
if len(a) == 0 {
return nil
}
var missing []string
for id := range a {
if _, ok := b[id]; !ok {
missing = append(missing, id)
}
}
return missing
}
// validThinkingTokens validates that the token budget is within the
// acceptable range for Anthropic (>= 1024 and < maxTokens).
// Returns (tokens, true) if valid, or (0, false) with a warning log if not.
func validThinkingTokens(tokens, maxTokens int64) (int64, bool) {
if tokens < 1024 {
slog.Warn("Anthropic thinking_budget below minimum (1024), ignoring", "tokens", tokens)
return 0, false
}
if tokens >= maxTokens {
slog.Warn("Anthropic thinking_budget must be less than max_tokens, ignoring", "tokens", tokens, "max_tokens", maxTokens)
return 0, false
}
return tokens, true
}
// anthropicThinkingEffort returns the Anthropic API effort level for the given
// ThinkingBudget. It covers both explicit adaptive mode and string effort
// levels. Returns ("", false) when the budget uses token counts or is nil.
func anthropicThinkingEffort(b *latest.ThinkingBudget) (string, bool) {
if b == nil {
return "", false
}
if e, ok := b.AdaptiveEffort(); ok {
return e, true
}
l, ok := b.EffortLevel()
if !ok {
return "", false
}
return effort.ForAnthropic(l)
}
// anthropicContextLimit returns a reasonable default context window for Anthropic models.
// We default to 200k tokens, which is what 3.5-4.5 models support; adjust as needed over time.
func anthropicContextLimit(model string) int64 {
_ = model
return 200000
}
// clampMaxTokens returns the effective max_tokens value after capping to the
// remaining context window (limit - used - safety), clamped to at least 1.
func clampMaxTokens(limit, used, configured int64) int64 {
const safety = int64(1024)
remaining := limit - used - safety
remaining = max(remaining, 1)
if configured > remaining {
return remaining
}
return configured
}
// countAnthropicTokens calls Anthropic's Count Tokens API for the provided payload
// and returns the number of input tokens.
func countAnthropicTokens(
ctx context.Context,
client anthropic.Client,
model anthropic.Model,
messages []anthropic.MessageParam,
system []anthropic.TextBlockParam,
anthropicTools []anthropic.ToolUnionParam,
) (int64, error) {
params := anthropic.MessageCountTokensParams{
Model: model,