package ai import ( "context" "errors" "fmt" "strings" "github.com/anthropics/anthropic-sdk-go/v2" "github.com/anthropics/anthropic-sdk-go/v2/option" ) type anthropicClient struct { client anthropic.Client cfg Config } func newAnthropic(apiKey string, cfg Config) *anthropicClient { return &anthropicClient{ client: anthropic.NewClient(option.WithAPIKey(apiKey)), cfg: cfg, } } // Models that accept server-side refusal fallbacks. On these, a request a // safety classifier declines is re-served by another model in the same call // instead of failing. var fallbackModels = map[string]bool{ "claude-fable-5-2": true, "claude-fable-5-1": true, "claude-opus-5-5": true, "claude-opus-5": true, "claude-sonnet-5-5": true, } func (a *anthropicClient) Generate(ctx context.Context, req Request) (string, error) { model := a.cfg.ModelFor(req.Task) maxTokens := req.MaxTokens if maxTokens <= 0 { maxTokens = 16000 } params := anthropic.BetaMessageNewParams{ Model: anthropic.Model(model), MaxTokens: int64(maxTokens), Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(req.Prompt)), }, } if req.System != "" { params.System = []anthropic.BetaTextBlockParam{{Text: req.System}} } // Thinking is left unset: on current models it runs adaptively, and effort // is the control. Set effort explicitly, since defaults differ by model. if effort := a.cfg.Effort; effort != "" { params.OutputConfig.Effort = anthropic.BetaOutputConfigEffort(effort) } if req.Schema != nil { params.OutputConfig.Format = anthropic.BetaJSONOutputFormatParam{Schema: req.Schema} } if fallbackModels[model] { params.Betas = append(params.Betas, anthropic.AnthropicBetaServerSideFallback2026_07_01) params.Fallbacks = anthropic.BetaFallbacksParamOfDefault() } msg, err := a.client.Beta.Messages.New(ctx, params) if err != nil { var apierr *anthropic.Error if errors.As(err, &apierr) { switch apierr.StatusCode { case 401: return "", fmt.Errorf("Anthropic rejected the API key (401); check it in Settings") case 404: return "", fmt.Errorf("Anthropic doesn't know the model %q (404); choose another in Settings", model) case 429: return "", fmt.Errorf("Anthropic rate limit reached (429); try again shortly") } } return "", fmt.Errorf("Anthropic: %w", err) } switch msg.StopReason { case anthropic.BetaStopReasonRefusal: return "", fmt.Errorf("the model declined this request (%s)", msg.StopDetails.Category) case anthropic.BetaStopReasonMaxTokens: return "", fmt.Errorf("the reply was cut off at %d tokens", maxTokens) } var b strings.Builder for _, block := range msg.Content { if t, ok := block.AsAny().(anthropic.BetaTextBlock); ok { b.WriteString(t.Text) } } text := strings.TrimSpace(b.String()) if text == "" { return "", fmt.Errorf("the model returned no text (stop reason %s)", msg.StopReason) } return text, nil } // Research runs a prompt with Claude's web search tool and returns the // reply with every page the model saw (search results and citations), so // callers can check that what it reports came from a real page. func (a *anthropicClient) Research(ctx context.Context, req ResearchRequest) (*ResearchResult, error) { model := a.cfg.ModelFor(req.Task) maxTokens := req.MaxTokens if maxTokens <= 0 { maxTokens = 16000 } maxSearches := req.MaxSearches if maxSearches <= 0 { maxSearches = 5 } search := anthropic.BetaWebSearchTool20260209Param{MaxUses: anthropic.Int(int64(maxSearches))} if len(req.BlockedDomains) > 0 { search.BlockedDomains = req.BlockedDomains } params := anthropic.BetaMessageNewParams{ Model: anthropic.Model(model), MaxTokens: int64(maxTokens), Tools: []anthropic.BetaToolUnionParam{{OfWebSearchTool20260209: &search}}, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(req.Prompt)), }, } if req.System != "" { params.System = []anthropic.BetaTextBlockParam{{Text: req.System}} } if effort := a.cfg.Effort; effort != "" { params.OutputConfig.Effort = anthropic.BetaOutputConfigEffort(effort) } if fallbackModels[model] { params.Betas = append(params.Betas, anthropic.AnthropicBetaServerSideFallback2026_07_01) params.Fallbacks = anthropic.BetaFallbacksParamOfDefault() } res := &ResearchResult{} seen := map[string]bool{} addSource := func(url, title string) { if url != "" && !seen[url] { seen[url] = true res.Sources = append(res.Sources, Source{URL: url, Title: title}) } } // The server runs the searches; a long run pauses (pause_turn) and is // resumed by sending its reply back as it was. for turn := 0; turn < 6; turn++ { msg, err := a.client.Beta.Messages.New(ctx, params) if err != nil { var apierr *anthropic.Error if errors.As(err, &apierr) { switch apierr.StatusCode { case 401: return nil, fmt.Errorf("Anthropic rejected the API key (401); check it in Settings") case 404: return nil, fmt.Errorf("Anthropic doesn't know the model %q (404); choose another in Settings", model) case 429: return nil, fmt.Errorf("Anthropic rate limit reached (429); try again shortly") } } return nil, fmt.Errorf("Anthropic: %w", err) } res.Searches += int(msg.Usage.ServerToolUse.WebSearchRequests) var text strings.Builder for _, block := range msg.Content { switch b := block.AsAny().(type) { case anthropic.BetaTextBlock: text.WriteString(b.Text) for _, c := range b.Citations { if loc, ok := c.AsAny().(anthropic.BetaCitationsWebSearchResultLocation); ok { addSource(loc.URL, loc.Title) } } case anthropic.BetaWebSearchToolResultBlock: // On success the content is a list of results; on failure // it's an error object. for _, r := range b.Content.OfBetaWebSearchResultBlockArray { addSource(r.URL, r.Title) } if b.Content.ErrorCode != "" { res.SearchErrors = append(res.SearchErrors, string(b.Content.ErrorCode)) } } } if t := strings.TrimSpace(text.String()); t != "" { res.Text = t // the last turn's text holds the answer } switch msg.StopReason { case anthropic.BetaStopReasonPauseTurn: params.Messages = append(params.Messages, msg.ToParam()) continue case anthropic.BetaStopReasonRefusal: return res, fmt.Errorf("the model declined this request (%s)", msg.StopDetails.Category) case anthropic.BetaStopReasonMaxTokens: return res, fmt.Errorf("the reply was cut off at %d tokens", maxTokens) } if res.Text == "" { return res, fmt.Errorf("the model returned no text (stop reason %s)", msg.StopReason) } return res, nil } return res, errors.New("the research didn't finish after several continuations") }