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				Required:   info.Required,
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			retry, after, retryErr := a.shouldRetry(attempts, err)
295			if retryErr != nil {
296				return nil, retryErr
297			}
298			if retry {
299				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
300				select {
301				case <-ctx.Done():
302					return nil, ctx.Err()
303				case <-time.After(time.Duration(after) * time.Millisecond):
304					continue
305				}
306			}
307			return nil, retryErr
308		}
309
310		content := ""
311		for _, block := range anthropicResponse.Content {
312			if text, ok := block.AsAny().(anthropic.TextBlock); ok {
313				content += text.Text
314			}
315		}
316
317		return &ProviderResponse{
318			Content:   content,
319			ToolCalls: a.toolCalls(*anthropicResponse),
320			Usage:     a.usage(*anthropicResponse),
321		}, nil
322	}
323}
324
325func (a *anthropicClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {
326	attempts := 0
327	eventChan := make(chan ProviderEvent)
328	go func() {
329		for {
330			attempts++
331			// Prepare messages on each attempt in case max_tokens was adjusted
332			preparedMessages := a.preparedMessages(a.convertMessages(messages), a.convertTools(tools))
333
334			var opts []option.RequestOption
335			if a.isThinkingEnabled() {
336				opts = append(opts, option.WithHeaderAdd("anthropic-beta", "interleaved-thinking-2025-05-14"))
337			}
338
339			anthropicStream := a.client.Messages.NewStreaming(
340				ctx,
341				preparedMessages,
342				opts...,
343			)
344			accumulatedMessage := anthropic.Message{}
345
346			currentToolCallID := ""
347			for anthropicStream.Next() {
348				event := anthropicStream.Current()
349				err := accumulatedMessage.Accumulate(event)
350				if err != nil {
351					slog.Warn("Error accumulating message", "error", err)
352					continue
353				}
354
355				switch event := event.AsAny().(type) {
356				case anthropic.ContentBlockStartEvent:
357					switch event.ContentBlock.Type {
358					case "text":
359						eventChan <- ProviderEvent{Type: EventContentStart}
360					case "tool_use":
361						currentToolCallID = event.ContentBlock.ID
362						eventChan <- ProviderEvent{
363							Type: EventToolUseStart,
364							ToolCall: &message.ToolCall{
365								ID:       event.ContentBlock.ID,
366								Name:     event.ContentBlock.Name,
367								Finished: false,
368							},
369						}
370					}
371
372				case anthropic.ContentBlockDeltaEvent:
373					if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
374						eventChan <- ProviderEvent{
375							Type:     EventThinkingDelta,
376							Thinking: event.Delta.Thinking,
377						}
378					} else if event.Delta.Type == "signature_delta" && event.Delta.Signature != "" {
379						eventChan <- ProviderEvent{
380							Type:      EventSignatureDelta,
381							Signature: event.Delta.Signature,
382						}
383					} else if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
384						eventChan <- ProviderEvent{
385							Type:    EventContentDelta,
386							Content: event.Delta.Text,
387						}
388					} else if event.Delta.Type == "input_json_delta" {
389						if currentToolCallID != "" {
390							eventChan <- ProviderEvent{
391								Type: EventToolUseDelta,
392								ToolCall: &message.ToolCall{
393									ID:       currentToolCallID,
394									Finished: false,
395									Input:    event.Delta.PartialJSON,
396								},
397							}
398						}
399					}
400				case anthropic.ContentBlockStopEvent:
401					if currentToolCallID != "" {
402						eventChan <- ProviderEvent{
403							Type: EventToolUseStop,
404							ToolCall: &message.ToolCall{
405								ID: currentToolCallID,
406							},
407						}
408						currentToolCallID = ""
409					} else {
410						eventChan <- ProviderEvent{Type: EventContentStop}
411					}
412
413				case anthropic.MessageStopEvent:
414					content := ""
415					for _, block := range accumulatedMessage.Content {
416						if text, ok := block.AsAny().(anthropic.TextBlock); ok {
417							content += text.Text
418						}
419					}
420
421					eventChan <- ProviderEvent{
422						Type: EventComplete,
423						Response: &ProviderResponse{
424							Content:      content,
425							ToolCalls:    a.toolCalls(accumulatedMessage),
426							Usage:        a.usage(accumulatedMessage),
427							FinishReason: a.finishReason(string(accumulatedMessage.StopReason)),
428						},
429						Content: content,
430					}
431				}
432			}
433
434			err := anthropicStream.Err()
435			if err == nil || errors.Is(err, io.EOF) {
436				close(eventChan)
437				return
438			}
439
440			// If there is an error we are going to see if we can retry the call
441			retry, after, retryErr := a.shouldRetry(attempts, err)
442			if retryErr != nil {
443				eventChan <- ProviderEvent{Type: EventError, Error: retryErr}
444				close(eventChan)
445				return
446			}
447			if retry {
448				slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
449				select {
450				case <-ctx.Done():
451					// context cancelled
452					if ctx.Err() != nil {
453						eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
454					}
455					close(eventChan)
456					return
457				case <-time.After(time.Duration(after) * time.Millisecond):
458					continue
459				}
460			}
461			if ctx.Err() != nil {
462				eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
463			}
464
465			close(eventChan)
466			return
467		}
468	}()
469	return eventChan
470}
471
472func (a *anthropicClient) shouldRetry(attempts int, err error) (bool, int64, error) {
473	var apiErr *anthropic.Error
474	if !errors.As(err, &apiErr) {
475		return false, 0, err
476	}
477
478	if attempts > maxRetries {
479		return false, 0, fmt.Errorf("maximum retry attempts reached for rate limit: %d retries", maxRetries)
480	}
481
482	if apiErr.StatusCode == 401 {
483		a.providerOptions.apiKey, err = config.Get().Resolve(a.providerOptions.config.APIKey)
484		if err != nil {
485			return false, 0, fmt.Errorf("failed to resolve API key: %w", err)
486		}
487		a.client = createAnthropicClient(a.providerOptions, a.tp)
488		return true, 0, nil
489	}
490
491	// Handle context limit exceeded error (400 Bad Request)
492	if apiErr.StatusCode == 400 {
493		if adjusted, ok := a.handleContextLimitError(apiErr); ok {
494			a.adjustedMaxTokens = adjusted
495			slog.Debug("Adjusted max_tokens due to context limit", "new_max_tokens", adjusted)
496			return true, 0, nil
497		}
498	}
499
500	isOverloaded := strings.Contains(apiErr.Error(), "overloaded") || strings.Contains(apiErr.Error(), "rate limit exceeded")
501	if apiErr.StatusCode != 429 && apiErr.StatusCode != 529 && !isOverloaded {
502		return false, 0, err
503	}
504
505	retryMs := 0
506	retryAfterValues := apiErr.Response.Header.Values("Retry-After")
507
508	backoffMs := 2000 * (1 << (attempts - 1))
509	jitterMs := int(float64(backoffMs) * 0.2)
510	retryMs = backoffMs + jitterMs
511	if len(retryAfterValues) > 0 {
512		if _, err := fmt.Sscanf(retryAfterValues[0], "%d", &retryMs); err == nil {
513			retryMs = retryMs * 1000
514		}
515	}
516	return true, int64(retryMs), nil
517}
518
519// handleContextLimitError parses context limit error and returns adjusted max_tokens
520func (a *anthropicClient) handleContextLimitError(apiErr *anthropic.Error) (int, bool) {
521	// Parse error message like: "input length and max_tokens exceed context limit: 154978 + 50000 > 200000"
522	errorMsg := apiErr.Error()
523
524	matches := contextLimitRegex.FindStringSubmatch(errorMsg)
525
526	if len(matches) != 4 {
527		return 0, false
528	}
529
530	inputTokens, err1 := strconv.Atoi(matches[1])
531	contextLimit, err2 := strconv.Atoi(matches[3])
532
533	if err1 != nil || err2 != nil {
534		return 0, false
535	}
536
537	// Calculate safe max_tokens with a buffer of 1000 tokens
538	safeMaxTokens := contextLimit - inputTokens - 1000
539
540	// Ensure we don't go below a minimum threshold
541	safeMaxTokens = max(safeMaxTokens, 1000)
542
543	return safeMaxTokens, true
544}
545
546func (a *anthropicClient) toolCalls(msg anthropic.Message) []message.ToolCall {
547	var toolCalls []message.ToolCall
548
549	for _, block := range msg.Content {
550		switch variant := block.AsAny().(type) {
551		case anthropic.ToolUseBlock:
552			toolCall := message.ToolCall{
553				ID:       variant.ID,
554				Name:     variant.Name,
555				Input:    string(variant.Input),
556				Type:     string(variant.Type),
557				Finished: true,
558			}
559			toolCalls = append(toolCalls, toolCall)
560		}
561	}
562
563	return toolCalls
564}
565
566func (a *anthropicClient) usage(msg anthropic.Message) TokenUsage {
567	return TokenUsage{
568		InputTokens:         msg.Usage.InputTokens,
569		OutputTokens:        msg.Usage.OutputTokens,
570		CacheCreationTokens: msg.Usage.CacheCreationInputTokens,
571		CacheReadTokens:     msg.Usage.CacheReadInputTokens,
572	}
573}
574
575func (a *anthropicClient) Model() catwalk.Model {
576	return a.providerOptions.model(a.providerOptions.modelType)
577}