anthropic.go

  1package provider
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"errors"
  7	"fmt"
  8	"io"
  9	"log/slog"
 10	"regexp"
 11	"strconv"
 12	"strings"
 13	"time"
 14
 15	"github.com/anthropics/anthropic-sdk-go"
 16	"github.com/anthropics/anthropic-sdk-go/bedrock"
 17	"github.com/anthropics/anthropic-sdk-go/option"
 18	"github.com/anthropics/anthropic-sdk-go/vertex"
 19	"github.com/charmbracelet/catwalk/pkg/catwalk"
 20	"github.com/charmbracelet/crush/internal/config"
 21	"github.com/charmbracelet/crush/internal/llm/tools"
 22	"github.com/charmbracelet/crush/internal/log"
 23	"github.com/charmbracelet/crush/internal/message"
 24)
 25
 26// Pre-compiled regex for parsing context limit errors.
 27var contextLimitRegex = regexp.MustCompile(`input length and ` + "`max_tokens`" + ` exceed context limit: (\d+) \+ (\d+) > (\d+)`)
 28
 29type anthropicClient struct {
 30	providerOptions   providerClientOptions
 31	tp                AnthropicClientType
 32	client            anthropic.Client
 33	adjustedMaxTokens int // Used when context limit is hit
 34}
 35
 36type AnthropicClient ProviderClient
 37
 38type AnthropicClientType string
 39
 40const (
 41	AnthropicClientTypeNormal  AnthropicClientType = "normal"
 42	AnthropicClientTypeBedrock AnthropicClientType = "bedrock"
 43	AnthropicClientTypeVertex  AnthropicClientType = "vertex"
 44)
 45
 46func newAnthropicClient(opts providerClientOptions, tp AnthropicClientType) AnthropicClient {
 47	return &anthropicClient{
 48		providerOptions: opts,
 49		tp:              tp,
 50		client:          createAnthropicClient(opts, tp),
 51	}
 52}
 53
 54func createAnthropicClient(opts providerClientOptions, tp AnthropicClientType) anthropic.Client {
 55	anthropicClientOptions := []option.RequestOption{}
 56
 57	// Check if Authorization header is provided in extra headers
 58	hasBearerAuth := false
 59	if opts.extraHeaders != nil {
 60		for key := range opts.extraHeaders {
 61			if strings.ToLower(key) == "authorization" {
 62				hasBearerAuth = true
 63				break
 64			}
 65		}
 66	}
 67
 68	isBearerToken := strings.HasPrefix(opts.apiKey, "Bearer ")
 69
 70	if opts.apiKey != "" && !hasBearerAuth {
 71		if isBearerToken {
 72			slog.Debug("API key starts with 'Bearer ', using as Authorization header")
 73			anthropicClientOptions = append(anthropicClientOptions, option.WithHeader("Authorization", opts.apiKey))
 74		} else {
 75			// Use standard X-Api-Key header
 76			anthropicClientOptions = append(anthropicClientOptions, option.WithAPIKey(opts.apiKey))
 77		}
 78	} else if hasBearerAuth {
 79		slog.Debug("Skipping X-Api-Key header because Authorization header is provided")
 80	}
 81
 82	if config.Get().Options.Debug {
 83		httpClient := log.NewHTTPClient()
 84		anthropicClientOptions = append(anthropicClientOptions, option.WithHTTPClient(httpClient))
 85	}
 86
 87	switch tp {
 88	case AnthropicClientTypeBedrock:
 89		anthropicClientOptions = append(anthropicClientOptions, bedrock.WithLoadDefaultConfig(context.Background()))
 90	case AnthropicClientTypeVertex:
 91		project := opts.extraParams["project"]
 92		location := opts.extraParams["location"]
 93		anthropicClientOptions = append(anthropicClientOptions, vertex.WithGoogleAuth(context.Background(), location, project))
 94	}
 95	for key, header := range opts.extraHeaders {
 96		anthropicClientOptions = append(anthropicClientOptions, option.WithHeaderAdd(key, header))
 97	}
 98	for key, value := range opts.extraBody {
 99		anthropicClientOptions = append(anthropicClientOptions, option.WithJSONSet(key, value))
100	}
101	return anthropic.NewClient(anthropicClientOptions...)
102}
103
104func (a *anthropicClient) convertMessages(messages []message.Message) (anthropicMessages []anthropic.MessageParam) {
105	for i, msg := range messages {
106		cache := false
107		if i > len(messages)-3 {
108			cache = true
109		}
110		switch msg.Role {
111		case message.User:
112			content := anthropic.NewTextBlock(msg.Content().String())
113			if cache && !a.providerOptions.disableCache {
114				content.OfText.CacheControl = anthropic.CacheControlEphemeralParam{
115					Type: "ephemeral",
116				}
117			}
118			var contentBlocks []anthropic.ContentBlockParamUnion
119			contentBlocks = append(contentBlocks, content)
120			for _, binaryContent := range msg.BinaryContent() {
121				base64Image := binaryContent.String(catwalk.InferenceProviderAnthropic)
122				imageBlock := anthropic.NewImageBlockBase64(binaryContent.MIMEType, base64Image)
123				contentBlocks = append(contentBlocks, imageBlock)
124			}
125			anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(contentBlocks...))
126
127		case message.Assistant:
128			blocks := []anthropic.ContentBlockParamUnion{}
129
130			// Add thinking blocks first if present (required when thinking is enabled with tool use)
131			if reasoningContent := msg.ReasoningContent(); reasoningContent.Thinking != "" {
132				thinkingBlock := anthropic.NewThinkingBlock(reasoningContent.Signature, reasoningContent.Thinking)
133				blocks = append(blocks, thinkingBlock)
134			}
135
136			if msg.Content().String() != "" {
137				content := anthropic.NewTextBlock(msg.Content().String())
138				if cache && !a.providerOptions.disableCache {
139					content.OfText.CacheControl = anthropic.CacheControlEphemeralParam{
140						Type: "ephemeral",
141					}
142				}
143				blocks = append(blocks, content)
144			}
145
146			for _, toolCall := range msg.ToolCalls() {
147				var inputMap map[string]any
148				err := json.Unmarshal([]byte(toolCall.Input), &inputMap)
149				if err != nil {
150					continue
151				}
152				blocks = append(blocks, anthropic.NewToolUseBlock(toolCall.ID, inputMap, toolCall.Name))
153			}
154
155			if len(blocks) == 0 {
156				continue
157			}
158			anthropicMessages = append(anthropicMessages, anthropic.NewAssistantMessage(blocks...))
159
160		case message.Tool:
161			results := make([]anthropic.ContentBlockParamUnion, len(msg.ToolResults()))
162			for i, toolResult := range msg.ToolResults() {
163				results[i] = anthropic.NewToolResultBlock(toolResult.ToolCallID, toolResult.Content, toolResult.IsError)
164			}
165			anthropicMessages = append(anthropicMessages, anthropic.NewUserMessage(results...))
166		}
167	}
168	return
169}
170
171func (a *anthropicClient) convertTools(tools []tools.BaseTool) []anthropic.ToolUnionParam {
172	if len(tools) == 0 {
173		return nil
174	}
175	anthropicTools := make([]anthropic.ToolUnionParam, len(tools))
176
177	for i, tool := range tools {
178		info := tool.Info()
179		toolParam := anthropic.ToolParam{
180			Name:        info.Name,
181			Description: anthropic.String(info.Description),
182			InputSchema: anthropic.ToolInputSchemaParam{
183				Properties: info.Parameters,
184				Required:   info.Required,
185			},
186		}
187
188		if i == len(tools)-1 && !a.providerOptions.disableCache {
189			toolParam.CacheControl = anthropic.CacheControlEphemeralParam{
190				Type: "ephemeral",
191			}
192		}
193
194		anthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
195	}
196
197	return anthropicTools
198}
199
200func (a *anthropicClient) finishReason(reason string) message.FinishReason {
201	switch reason {
202	case "end_turn":
203		return message.FinishReasonEndTurn
204	case "max_tokens":
205		return message.FinishReasonMaxTokens
206	case "tool_use":
207		return message.FinishReasonToolUse
208	case "stop_sequence":
209		return message.FinishReasonEndTurn
210	default:
211		return message.FinishReasonUnknown
212	}
213}
214
215func (a *anthropicClient) isThinkingEnabled() bool {
216	cfg := config.Get()
217	modelConfig := cfg.Models[config.SelectedModelTypeLarge]
218	if a.providerOptions.modelType == config.SelectedModelTypeSmall {
219		modelConfig = cfg.Models[config.SelectedModelTypeSmall]
220	}
221	return a.Model().CanReason && modelConfig.Think
222}
223
224func (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {
225	model := a.providerOptions.model(a.providerOptions.modelType)
226	var thinkingParam anthropic.ThinkingConfigParamUnion
227	cfg := config.Get()
228	modelConfig := cfg.Models[config.SelectedModelTypeLarge]
229	if a.providerOptions.modelType == config.SelectedModelTypeSmall {
230		modelConfig = cfg.Models[config.SelectedModelTypeSmall]
231	}
232	temperature := anthropic.Float(0)
233
234	maxTokens := model.DefaultMaxTokens
235	if modelConfig.MaxTokens > 0 {
236		maxTokens = modelConfig.MaxTokens
237	}
238	if a.isThinkingEnabled() {
239		thinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(maxTokens) * 0.8))
240		temperature = anthropic.Float(1)
241	}
242	// Override max tokens if set in provider options
243	if a.providerOptions.maxTokens > 0 {
244		maxTokens = a.providerOptions.maxTokens
245	}
246
247	// Use adjusted max tokens if context limit was hit
248	if a.adjustedMaxTokens > 0 {
249		maxTokens = int64(a.adjustedMaxTokens)
250	}
251
252	systemBlocks := []anthropic.TextBlockParam{}
253
254	// Add custom system prompt prefix if configured
255	if a.providerOptions.systemPromptPrefix != "" {
256		systemBlocks = append(systemBlocks, anthropic.TextBlockParam{
257			Text: a.providerOptions.systemPromptPrefix,
258		})
259	}
260
261	systemBlocks = append(systemBlocks, anthropic.TextBlockParam{
262		Text: a.providerOptions.systemMessage,
263		CacheControl: anthropic.CacheControlEphemeralParam{
264			Type: "ephemeral",
265		},
266	})
267
268	return anthropic.MessageNewParams{
269		Model:       anthropic.Model(model.ID),
270		MaxTokens:   maxTokens,
271		Temperature: temperature,
272		Messages:    messages,
273		Tools:       tools,
274		Thinking:    thinkingParam,
275		System:      systemBlocks,
276	}
277}
278
279func (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {
280	attempts := 0
281	for {
282		attempts++
283		// Prepare messages on each attempt in case max_tokens was adjusted
284		preparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))
285
286		var opts []option.RequestOption
287		if a.isThinkingEnabled() {
288			opts = append(opts, option.WithHeaderAdd("anthropic-beta", "interleaved-thinking-2025-05-14"))
289		}
290		anthropicResponse, err := a.client.Messages.New(
291			ctx,
292			preparedMessages,
293			opts...,
294		)
295		// If there is an error we are going to see if we can retry the call
296		if err != nil {
297			retry, after, retryErr := a.shouldRetry(attempts, err)
298			if retryErr != nil {
299				return nil, retryErr
300			}
301			if retry {
302				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
303				select {
304				case <-ctx.Done():
305					return nil, ctx.Err()
306				case <-time.After(time.Duration(after) * time.Millisecond):
307					continue
308				}
309			}
310			return nil, retryErr
311		}
312
313		content := ""
314		for _, block := range anthropicResponse.Content {
315			if text, ok := block.AsAny().(anthropic.TextBlock); ok {
316				content += text.Text
317			}
318		}
319
320		return &ProviderResponse{
321			Content:   content,
322			ToolCalls: a.toolCalls(*anthropicResponse),
323			Usage:     a.usage(*anthropicResponse),
324		}, nil
325	}
326}
327
328func (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {
329	attempts := 0
330	eventChan := make(chan ProviderEvent)
331	go func() {
332		for {
333			attempts++
334			// Prepare messages on each attempt in case max_tokens was adjusted
335			preparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))
336
337			var opts []option.RequestOption
338			if a.isThinkingEnabled() {
339				opts = append(opts, option.WithHeaderAdd("anthropic-beta", "interleaved-thinking-2025-05-14"))
340			}
341
342			anthropicStream := a.client.Messages.NewStreaming(
343				ctx,
344				preparedMessages,
345				opts...,
346			)
347			accumulatedMessage := anthropic.Message{}
348
349			currentToolCallID := ""
350			for anthropicStream.Next() {
351				event := anthropicStream.Current()
352				err := accumulatedMessage.Accumulate(event)
353				if err != nil {
354					slog.Warn("Error accumulating message", "error", err)
355					continue
356				}
357
358				switch event := event.AsAny().(type) {
359				case anthropic.ContentBlockStartEvent:
360					switch event.ContentBlock.Type {
361					case "text":
362						eventChan <- ProviderEvent{Type: EventContentStart}
363					case "tool_use":
364						currentToolCallID = event.ContentBlock.ID
365						eventChan <- ProviderEvent{
366							Type: EventToolUseStart,
367							ToolCall: &message.ToolCall{
368								ID:       event.ContentBlock.ID,
369								Name:     event.ContentBlock.Name,
370								Finished: false,
371							},
372						}
373					}
374
375				case anthropic.ContentBlockDeltaEvent:
376					if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
377						eventChan <- ProviderEvent{
378							Type:     EventThinkingDelta,
379							Thinking: event.Delta.Thinking,
380						}
381					} else if event.Delta.Type == "signature_delta" && event.Delta.Signature != "" {
382						eventChan <- ProviderEvent{
383							Type:      EventSignatureDelta,
384							Signature: event.Delta.Signature,
385						}
386					} else if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
387						eventChan <- ProviderEvent{
388							Type:    EventContentDelta,
389							Content: event.Delta.Text,
390						}
391					} else if event.Delta.Type == "input_json_delta" {
392						if currentToolCallID != "" {
393							eventChan <- ProviderEvent{
394								Type: EventToolUseDelta,
395								ToolCall: &message.ToolCall{
396									ID:       currentToolCallID,
397									Finished: false,
398									Input:    event.Delta.PartialJSON,
399								},
400							}
401						}
402					}
403				case anthropic.ContentBlockStopEvent:
404					if currentToolCallID != "" {
405						eventChan <- ProviderEvent{
406							Type: EventToolUseStop,
407							ToolCall: &message.ToolCall{
408								ID: currentToolCallID,
409							},
410						}
411						currentToolCallID = ""
412					} else {
413						eventChan <- ProviderEvent{Type: EventContentStop}
414					}
415
416				case anthropic.MessageStopEvent:
417					content := ""
418					for _, block := range accumulatedMessage.Content {
419						if text, ok := block.AsAny().(anthropic.TextBlock); ok {
420							content += text.Text
421						}
422					}
423
424					eventChan <- ProviderEvent{
425						Type: EventComplete,
426						Response: &ProviderResponse{
427							Content:      content,
428							ToolCalls:    a.toolCalls(accumulatedMessage),
429							Usage:        a.usage(accumulatedMessage),
430							FinishReason: a.finishReason(string(accumulatedMessage.StopReason)),
431						},
432						Content: content,
433					}
434				}
435			}
436
437			err := anthropicStream.Err()
438			if err == nil || errors.Is(err, io.EOF) {
439				close(eventChan)
440				return
441			}
442
443			// If there is an error we are going to see if we can retry the call
444			retry, after, retryErr := a.shouldRetry(attempts, err)
445			if retryErr != nil {
446				eventChan <- ProviderEvent{Type: EventError, Error: retryErr}
447				close(eventChan)
448				return
449			}
450			if retry {
451				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
452				select {
453				case <-ctx.Done():
454					// context cancelled
455					if ctx.Err() != nil {
456						eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
457					}
458					close(eventChan)
459					return
460				case <-time.After(time.Duration(after) * time.Millisecond):
461					continue
462				}
463			}
464			if ctx.Err() != nil {
465				eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
466			}
467
468			close(eventChan)
469			return
470		}
471	}()
472	return eventChan
473}
474
475func (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {
476	var apiErr *anthropic.Error
477	if !errors.As(err, &apiErr) {
478		return false, 0, err
479	}
480
481	if attempts > maxRetries {
482		return false, 0, fmt.Errorf("maximum retry attempts reached for rate limit: %d retries", maxRetries)
483	}
484
485	if apiErr.StatusCode == 401 {
486		a.providerOptions.apiKey, err = config.Get().Resolve(a.providerOptions.config.APIKey)
487		if err != nil {
488			return false, 0, fmt.Errorf("failed to resolve API key: %w", err)
489		}
490		a.client = createAnthropicClient(a.providerOptions, a.tp)
491		return true, 0, nil
492	}
493
494	// Handle context limit exceeded error (400 Bad Request)
495	if apiErr.StatusCode == 400 {
496		if adjusted, ok := a.handleContextLimitError(apiErr); ok {
497			a.adjustedMaxTokens = adjusted
498			slog.Debug("Adjusted max_tokens due to context limit", "new_max_tokens", adjusted)
499			return true, 0, nil
500		}
501	}
502
503	isOverloaded := strings.Contains(apiErr.Error(), "overloaded") || strings.Contains(apiErr.Error(), "rate limit exceeded")
504	if apiErr.StatusCode != 429 && apiErr.StatusCode != 529 && !isOverloaded {
505		return false, 0, err
506	}
507
508	retryMs := 0
509	retryAfterValues := apiErr.Response.Header.Values("Retry-After")
510
511	backoffMs := 2000 * (1 << (attempts - 1))
512	jitterMs := int(float64(backoffMs) * 0.2)
513	retryMs = backoffMs + jitterMs
514	if len(retryAfterValues) > 0 {
515		if _, err := fmt.Sscanf(retryAfterValues[0], "%d", &retryMs); err == nil {
516			retryMs = retryMs * 1000
517		}
518	}
519	return true, int64(retryMs), nil
520}
521
522// handleContextLimitError parses context limit error and returns adjusted max_tokens
523func (a *anthropicClient) handleContextLimitError(apiErr *anthropic.Error) (int, bool) {
524	// Parse error message like: "input length and max_tokens exceed context limit: 154978 + 50000 > 200000"
525	errorMsg := apiErr.Error()
526
527	matches := contextLimitRegex.FindStringSubmatch(errorMsg)
528
529	if len(matches) != 4 {
530		return 0, false
531	}
532
533	inputTokens, err1 := strconv.Atoi(matches[1])
534	contextLimit, err2 := strconv.Atoi(matches[3])
535
536	if err1 != nil || err2 != nil {
537		return 0, false
538	}
539
540	// Calculate safe max_tokens with a buffer of 1000 tokens
541	safeMaxTokens := contextLimit - inputTokens - 1000
542
543	// Ensure we don't go below a minimum threshold
544	safeMaxTokens = max(safeMaxTokens, 1000)
545
546	return safeMaxTokens, true
547}
548
549func (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {
550	var toolCalls []message.ToolCall
551
552	for _, block := range msg.Content {
553		switch variant := block.AsAny().(type) {
554		case anthropic.ToolUseBlock:
555			toolCall := message.ToolCall{
556				ID:       variant.ID,
557				Name:     variant.Name,
558				Input:    string(variant.Input),
559				Type:     string(variant.Type),
560				Finished: true,
561			}
562			toolCalls = append(toolCalls, toolCall)
563		}
564	}
565
566	return toolCalls
567}
568
569func (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {
570	return TokenUsage{
571		InputTokens:         msg.Usage.InputTokens,
572		OutputTokens:        msg.Usage.OutputTokens,
573		CacheCreationTokens: msg.Usage.CacheCreationInputTokens,
574		CacheReadTokens:     msg.Usage.CacheReadInputTokens,
575	}
576}
577
578func (a *anthropicClient) Model() catwalk.Model {
579	return a.providerOptions.model(a.providerOptions.modelType)
580}