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	anthropicTools := make([]anthropic.ToolUnionParam, len(tools))
173
174	for i, tool := range tools {
175		info := tool.Info()
176		toolParam := anthropic.ToolParam{
177			Name:        info.Name,
178			Description: anthropic.String(info.Description),
179			InputSchema: anthropic.ToolInputSchemaParam{
180				Properties: info.Parameters,
181				// TODO: figure out how we can tell claude the required fields?
182			},
183		}
184
185		if i == len(tools)-1 && !a.providerOptions.disableCache {
186			toolParam.CacheControl = anthropic.CacheControlEphemeralParam{
187				Type: "ephemeral",
188			}
189		}
190
191		anthropicTools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
192	}
193
194	return anthropicTools
195}
196
197func (a *anthropicClient) finishReason(reason string) message.FinishReason {
198	switch reason {
199	case "end_turn":
200		return message.FinishReasonEndTurn
201	case "max_tokens":
202		return message.FinishReasonMaxTokens
203	case "tool_use":
204		return message.FinishReasonToolUse
205	case "stop_sequence":
206		return message.FinishReasonEndTurn
207	default:
208		return message.FinishReasonUnknown
209	}
210}
211
212func (a *anthropicClient) isThinkingEnabled() bool {
213	cfg := config.Get()
214	modelConfig := cfg.Models[config.SelectedModelTypeLarge]
215	if a.providerOptions.modelType == config.SelectedModelTypeSmall {
216		modelConfig = cfg.Models[config.SelectedModelTypeSmall]
217	}
218	return a.Model().CanReason && modelConfig.Think
219}
220
221func (a *anthropicClient) preparedMessages(messages []anthropic.MessageParam, tools []anthropic.ToolUnionParam) anthropic.MessageNewParams {
222	model := a.providerOptions.model(a.providerOptions.modelType)
223	var thinkingParam anthropic.ThinkingConfigParamUnion
224	cfg := config.Get()
225	modelConfig := cfg.Models[config.SelectedModelTypeLarge]
226	if a.providerOptions.modelType == config.SelectedModelTypeSmall {
227		modelConfig = cfg.Models[config.SelectedModelTypeSmall]
228	}
229	temperature := anthropic.Float(0)
230
231	maxTokens := model.DefaultMaxTokens
232	if modelConfig.MaxTokens > 0 {
233		maxTokens = modelConfig.MaxTokens
234	}
235	if a.isThinkingEnabled() {
236		thinkingParam = anthropic.ThinkingConfigParamOfEnabled(int64(float64(maxTokens) * 0.8))
237		temperature = anthropic.Float(1)
238	}
239	// Override max tokens if set in provider options
240	if a.providerOptions.maxTokens > 0 {
241		maxTokens = a.providerOptions.maxTokens
242	}
243
244	// Use adjusted max tokens if context limit was hit
245	if a.adjustedMaxTokens > 0 {
246		maxTokens = int64(a.adjustedMaxTokens)
247	}
248
249	systemBlocks := []anthropic.TextBlockParam{}
250
251	// Add custom system prompt prefix if configured
252	if a.providerOptions.systemPromptPrefix != "" {
253		systemBlocks = append(systemBlocks, anthropic.TextBlockParam{
254			Text: a.providerOptions.systemPromptPrefix,
255		})
256	}
257
258	systemBlocks = append(systemBlocks, anthropic.TextBlockParam{
259		Text: a.providerOptions.systemMessage,
260		CacheControl: anthropic.CacheControlEphemeralParam{
261			Type: "ephemeral",
262		},
263	})
264
265	return anthropic.MessageNewParams{
266		Model:       anthropic.Model(model.ID),
267		MaxTokens:   maxTokens,
268		Temperature: temperature,
269		Messages:    messages,
270		Tools:       tools,
271		Thinking:    thinkingParam,
272		System:      systemBlocks,
273	}
274}
275
276func (a *anthropicClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (response *ProviderResponse, err error) {
277	attempts := 0
278	for {
279		attempts++
280		// Prepare messages on each attempt in case max_tokens was adjusted
281		preparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))
282
283		var opts []option.RequestOption
284		if a.isThinkingEnabled() {
285			opts = append(opts, option.WithHeaderAdd("anthropic-beta", "interleaved-thinking-2025-05-14"))
286		}
287		anthropicResponse, err := a.client.Messages.New(
288			ctx,
289			preparedMessages,
290			opts...,
291		)
292		// If there is an error we are going to see if we can retry the call
293		if err != nil {
294			slog.Error("Anthropic API error", "error", err.Error(), "attempt", attempts, "max_retries", maxRetries)
295			retry, after, retryErr := a.shouldRetry(attempts, err)
296			if retryErr != nil {
297				return nil, retryErr
298			}
299			if retry {
300				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries)
301				select {
302				case <-ctx.Done():
303					return nil, ctx.Err()
304				case <-time.After(time.Duration(after) * time.Millisecond):
305					continue
306				}
307			}
308			return nil, retryErr
309		}
310
311		content := ""
312		for _, block := range anthropicResponse.Content {
313			if text, ok := block.AsAny().(anthropic.TextBlock); ok {
314				content += text.Text
315			}
316		}
317
318		return &ProviderResponse{
319			Content:   content,
320			ToolCalls: a.toolCalls(*anthropicResponse),
321			Usage:     a.usage(*anthropicResponse),
322		}, nil
323	}
324}
325
326func (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {
327	attempts := 0
328	eventChan := make(chan ProviderEvent)
329	go func() {
330		for {
331			attempts++
332			// Prepare messages on each attempt in case max_tokens was adjusted
333			preparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))
334
335			opts := []option.RequestOption{option.WithRequestTimeout(time.Minute)}
336			if a.isThinkingEnabled() {
337				opts = append(opts, option.WithHeaderAdd("anthropic-beta", "interleaved-thinking-2025-05-14"))
338			}
339
340			anthropicStream := a.client.Messages.NewStreaming(
341				ctx,
342				preparedMessages,
343				opts...,
344			)
345			accumulatedMessage := anthropic.Message{}
346
347			currentToolCallID := ""
348			for anthropicStream.Next() {
349				event := anthropicStream.Current()
350				err := accumulatedMessage.Accumulate(event)
351				if err != nil {
352					slog.Warn("Error accumulating message", "error", err)
353					continue
354				}
355
356				switch event := event.AsAny().(type) {
357				case anthropic.ContentBlockStartEvent:
358					switch event.ContentBlock.Type {
359					case "text":
360						eventChan <- ProviderEvent{Type: EventContentStart}
361					case "tool_use":
362						currentToolCallID = event.ContentBlock.ID
363						eventChan <- ProviderEvent{
364							Type: EventToolUseStart,
365							ToolCall: &message.ToolCall{
366								ID:       event.ContentBlock.ID,
367								Name:     event.ContentBlock.Name,
368								Finished: false,
369							},
370						}
371					}
372
373				case anthropic.ContentBlockDeltaEvent:
374					if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
375						eventChan <- ProviderEvent{
376							Type:     EventThinkingDelta,
377							Thinking: event.Delta.Thinking,
378						}
379					} else if event.Delta.Type == "signature_delta" && event.Delta.Signature != "" {
380						eventChan <- ProviderEvent{
381							Type:      EventSignatureDelta,
382							Signature: event.Delta.Signature,
383						}
384					} else if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
385						eventChan <- ProviderEvent{
386							Type:    EventContentDelta,
387							Content: event.Delta.Text,
388						}
389					} else if event.Delta.Type == "input_json_delta" {
390						if currentToolCallID != "" {
391							eventChan <- ProviderEvent{
392								Type: EventToolUseDelta,
393								ToolCall: &message.ToolCall{
394									ID:       currentToolCallID,
395									Finished: false,
396									Input:    event.Delta.PartialJSON,
397								},
398							}
399						}
400					}
401				case anthropic.ContentBlockStopEvent:
402					if currentToolCallID != "" {
403						eventChan <- ProviderEvent{
404							Type: EventToolUseStop,
405							ToolCall: &message.ToolCall{
406								ID: currentToolCallID,
407							},
408						}
409						currentToolCallID = ""
410					} else {
411						eventChan <- ProviderEvent{Type: EventContentStop}
412					}
413
414				case anthropic.MessageStopEvent:
415					content := ""
416					for _, block := range accumulatedMessage.Content {
417						if text, ok := block.AsAny().(anthropic.TextBlock); ok {
418							content += text.Text
419						}
420					}
421
422					eventChan <- ProviderEvent{
423						Type: EventComplete,
424						Response: &ProviderResponse{
425							Content:      content,
426							ToolCalls:    a.toolCalls(accumulatedMessage),
427							Usage:        a.usage(accumulatedMessage),
428							FinishReason: a.finishReason(string(accumulatedMessage.StopReason)),
429						},
430						Content: content,
431					}
432				}
433			}
434
435			err := anthropicStream.Err()
436			if err == nil || errors.Is(err, io.EOF) {
437				close(eventChan)
438				return
439			}
440
441			// If there is an error we are going to see if we can retry the call
442			retry, after, retryErr := a.shouldRetry(attempts, err)
443			if retryErr != nil {
444				eventChan <- ProviderEvent{Type: EventError, Error: retryErr}
445				close(eventChan)
446				return
447			}
448			if retry {
449				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries)
450				select {
451				case <-ctx.Done():
452					// context cancelled
453					if ctx.Err() != nil {
454						eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
455					}
456					close(eventChan)
457					return
458				case <-time.After(time.Duration(after) * time.Millisecond):
459					continue
460				}
461			}
462			if ctx.Err() != nil {
463				eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
464			}
465
466			close(eventChan)
467			return
468		}
469	}()
470	return eventChan
471}
472
473func (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {
474	var apiErr *anthropic.Error
475	if !errors.As(err, &apiErr) {
476		return false, 0, err
477	}
478
479	if attempts > maxRetries {
480		return false, 0, fmt.Errorf("maximum retry attempts reached for rate limit: %d retries", maxRetries)
481	}
482
483	if apiErr.StatusCode == 401 {
484		a.providerOptions.apiKey, err = config.Get().Resolve(a.providerOptions.config.APIKey)
485		if err != nil {
486			return false, 0, fmt.Errorf("failed to resolve API key: %w", err)
487		}
488		a.client = createAnthropicClient(a.providerOptions, a.tp)
489		return true, 0, nil
490	}
491
492	// Handle context limit exceeded error (400 Bad Request)
493	if apiErr.StatusCode == 400 {
494		if adjusted, ok := a.handleContextLimitError(apiErr); ok {
495			a.adjustedMaxTokens = adjusted
496			slog.Debug("Adjusted max_tokens due to context limit", "new_max_tokens", adjusted)
497			return true, 0, nil
498		}
499	}
500
501	isOverloaded := strings.Contains(apiErr.Error(), "overloaded") || strings.Contains(apiErr.Error(), "rate limit exceeded")
502	if apiErr.StatusCode != 429 && apiErr.StatusCode != 529 && !isOverloaded {
503		return false, 0, err
504	}
505
506	retryMs := 0
507	retryAfterValues := apiErr.Response.Header.Values("Retry-After")
508
509	backoffMs := 2000 * (1 << (attempts - 1))
510	jitterMs := int(float64(backoffMs) * 0.2)
511	retryMs = backoffMs + jitterMs
512	if len(retryAfterValues) > 0 {
513		if _, err := fmt.Sscanf(retryAfterValues[0], "%d", &retryMs); err == nil {
514			retryMs = retryMs * 1000
515		}
516	}
517	return true, int64(retryMs), nil
518}
519
520// handleContextLimitError parses context limit error and returns adjusted max_tokens
521func (a *anthropicClient) handleContextLimitError(apiErr *anthropic.Error) (int, bool) {
522	// Parse error message like: "input length and max_tokens exceed context limit: 154978 + 50000 > 200000"
523	errorMsg := apiErr.Error()
524
525	matches := contextLimitRegex.FindStringSubmatch(errorMsg)
526
527	if len(matches) != 4 {
528		return 0, false
529	}
530
531	inputTokens, err1 := strconv.Atoi(matches[1])
532	contextLimit, err2 := strconv.Atoi(matches[3])
533
534	if err1 != nil || err2 != nil {
535		return 0, false
536	}
537
538	// Calculate safe max_tokens with a buffer of 1000 tokens
539	safeMaxTokens := contextLimit - inputTokens - 1000
540
541	// Ensure we don't go below a minimum threshold
542	safeMaxTokens = max(safeMaxTokens, 1000)
543
544	return safeMaxTokens, true
545}
546
547func (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {
548	var toolCalls []message.ToolCall
549
550	for _, block := range msg.Content {
551		switch variant := block.AsAny().(type) {
552		case anthropic.ToolUseBlock:
553			toolCall := message.ToolCall{
554				ID:       variant.ID,
555				Name:     variant.Name,
556				Input:    string(variant.Input),
557				Type:     string(variant.Type),
558				Finished: true,
559			}
560			toolCalls = append(toolCalls, toolCall)
561		}
562	}
563
564	return toolCalls
565}
566
567func (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {
568	return TokenUsage{
569		InputTokens:         msg.Usage.InputTokens,
570		OutputTokens:        msg.Usage.OutputTokens,
571		CacheCreationTokens: msg.Usage.CacheCreationInputTokens,
572		CacheReadTokens:     msg.Usage.CacheReadInputTokens,
573	}
574}
575
576func (a *anthropicClient) Model() catwalk.Model {
577	return a.providerOptions.model(a.providerOptions.modelType)
578}