// Package claude is the Anthropic client and the one call every Claude // caller here makes. // // Reading a job posting (posting.go), scoring a lead (score.go) and // classifying an email (email.go) are the same shape of call: one prompt // asking for bare JSON, one reply to parse. That whole sequence is askJSON // below, so a caller is a prompt, a reply struct and three error strings, and // the handling around the call cannot drift between them. // // Ported from the main site's Python service (python/app/claude.py and the // modules that used it), where these calls lived until the tracker became // its own app. The behaviour is deliberately the same: the same prompts, the // same per-model request shaping, the same user-facing messages. // // Errors come in three kinds, and callers branch on them: // - *ReadError: Claude failed for this input. The message is one of the // caller's fixed strings and is safe to show a person. // - ErrNotConfigured: no API key. Nothing will work until one is set. // - anything else wraps the context's error: the caller gave up. package claude import ( "context" "encoding/json" "errors" "fmt" "log" "strings" "time" "github.com/anthropics/anthropic-sdk-go" "github.com/anthropics/anthropic-sdk-go/option" ) // DefaultModel is used when CLAUDE_MODEL is blank. The main site's admin // panel offers claude-haiku-4-5, claude-sonnet-5-5 and claude-opus-5-5; // another id is passed through as it is and treated as a model that thinks // (see modelOptions). If the API does not know it, every call fails with its // `failed` message and the reason is in the log. const DefaultModel = "claude-sonnet-5-5" // noEffortPrefixes are models that take no output_config.effort and do not // think unless asked to. Everything newer thinks by default, and that changes // two things in the request — see modelOptions. var noEffortPrefixes = []string{"claude-haiku-4-5"} // thinkingHeadroom is added to a caller's max_tokens on a model that thinks. // Thinking is billed against max_tokens like the reply is, and the callers' // ceilings are sized for the reply alone (a few hundred tokens of JSON), so // without this a posting worth a moment's thought could use the whole // allowance and leave no room for the answer. const thinkingHeadroom = 4000 // effort: every call here is extraction or classification — read something, // return a small JSON object. "low" is the level meant for that, and it is // set explicitly because the default differs between models. const effort = anthropic.OutputConfigEffortLow // attemptTimeout bounds each attempt. The SDK retries twice on top // (429/5xx/connection), so the worst case is roughly three of these plus // backoff. const attemptTimeout = 30 * time.Second // ErrNotConfigured means CLAUDE_API_KEY is not set. It is not a ReadError: // it says nothing about the input, so a caller must not count it against one. var ErrNotConfigured = errors.New("CLAUDE_API_KEY is not set") // ReadError is a failure Claude had with this particular input. Msg is // always one of the calling function's fixed strings, never text from the API // or the model, so it is safe to show the admin. The detail went to the log. type ReadError struct{ Msg string } func (e *ReadError) Error() string { return e.Msg } // Client makes the tracker's Claude calls. The zero value is unusable; build // one with New. type Client struct { api *anthropic.Client // nil when there is no key model string } // New builds a client for apiKey and model (blank means DefaultModel). A // blank key is not an error here: the tracker must still boot without one, // and each call then answers ErrNotConfigured. opts are extra SDK options; // the tests use them to point the client at a fake API. func New(apiKey, model string, opts ...option.RequestOption) *Client { model = strings.TrimSpace(model) if model == "" { model = DefaultModel } c := &Client{model: model} if apiKey != "" { opts = append([]option.RequestOption{ option.WithAPIKey(apiKey), option.WithRequestTimeout(attemptTimeout), }, opts...) api := anthropic.NewClient(opts...) c.api = &api } return c } // Model is the model id every call uses. func (c *Client) Model() string { return c.model } // modelOptions sets the parts of the request that depend on the model. // maxTokens is the caller's ceiling on the reply. A model that thinks gets // thinkingHeadroom on top and an explicit effort; Haiku 4.5 gets neither, // because it rejects output_config.effort and does not think unless a budget // is requested, which nothing here does. func modelOptions(params *anthropic.MessageNewParams, model string, maxTokens int64) { for _, p := range noEffortPrefixes { if strings.HasPrefix(model, p) { params.MaxTokens = maxTokens return } } params.MaxTokens = maxTokens + thinkingHeadroom params.OutputConfig = anthropic.OutputConfigParam{Effort: effort} } // messages are the three ReadError texts a caller words for its own user. type messages struct { failed string // the API call itself failed, or Claude declined empty string // the reply had no text block unparseable string // the reply was not the JSON asked for } // askJSON sends one prompt that asks for a bare JSON object and decodes the // reply into T, then has validate (which may be nil) tidy and check it. // A validate error counts as unparseable. func askJSON[T any](ctx context.Context, c *Client, system, user string, maxTokens int64, msgs messages, validate func(*T) error) (T, error) { var zero T if c == nil || c.api == nil { return zero, ErrNotConfigured } params := anthropic.MessageNewParams{ Model: anthropic.Model(c.model), System: []anthropic.TextBlockParam{{Text: system}}, Messages: []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(user))}, } modelOptions(¶ms, c.model, maxTokens) message, err := c.api.Messages.New(ctx, params) if err != nil { // The caller gave up (a cancelled sync, a run out of time). Wrapped, // not replaced, so errors.Is(err, context.Canceled) still holds: the // email pipeline must not count an abandoned sync against the email. if ctx.Err() != nil { return zero, fmt.Errorf("claude call abandoned: %w", ctx.Err()) } var apiErr *anthropic.Error if errors.As(err, &apiErr) { log.Printf("[Claude] API error %d: %v", apiErr.StatusCode, err) } else { log.Printf("[Claude] API unreachable: %v", err) } return zero, &ReadError{msgs.failed} } // A refusal is an ordinary 200 whose content is not the answer. Say so in // the log rather than letting it surface as an "empty" or "unparseable" // reply, which would point at the prompt instead of at the classifier. if message.StopReason == anthropic.StopReasonRefusal { log.Printf("[Claude] declined the request: category=%q %s", message.StopDetails.Category, message.StopDetails.Explanation) return zero, &ReadError{msgs.failed} } // By type, not position: on a model that thinks, the first block can be a // (possibly empty) thinking block. var text string found := false for _, block := range message.Content { if b, ok := block.AsAny().(anthropic.TextBlock); ok { text, found = b.Text, true break } } if !found { if message.StopReason == anthropic.StopReasonMaxTokens { log.Printf("[Claude] ran out of tokens before answering (max_tokens=%d)", params.MaxTokens) } return zero, &ReadError{msgs.empty} } var out T if err := json.Unmarshal([]byte(stripMarkdownFence(text)), &out); err != nil { log.Printf("[Claude] unparseable model output %q: %v", text, err) return zero, &ReadError{msgs.unparseable} } if validate != nil { if err := validate(&out); err != nil { log.Printf("[Claude] model output %q rejected: %v", text, err) return zero, &ReadError{msgs.unparseable} } } return out, nil } // stripMarkdownFence removes a surrounding markdown code fence from a reply. // The prompts ask for bare JSON and the model fences it anyway often enough // to matter. "```json" is tried before a plain "```", and unfenced input // comes back unchanged apart from surrounding whitespace. func stripMarkdownFence(raw string) string { raw = strings.TrimSpace(raw) raw = strings.TrimPrefix(raw, "```json") raw = strings.TrimPrefix(raw, "```") raw = strings.TrimSuffix(raw, "```") return strings.TrimSpace(raw) }