Files
TradarrV2/backend/internal/ai/anthropic.go

108 lines
2.7 KiB
Go

package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
)
type anthropicProvider struct {
apiKey string
model string
client *http.Client
}
func newAnthropic(apiKey, model string) *anthropicProvider {
if model == "" {
model = "claude-sonnet-4-6"
}
return &anthropicProvider{
apiKey: apiKey,
model: model,
client: &http.Client{},
}
}
func (p *anthropicProvider) Name() string { return "anthropic" }
func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
maxTokens := opts.MaxOutputTokens
if maxTokens <= 0 {
maxTokens = 4096
}
body := map[string]interface{}{
"model": p.model,
"max_tokens": maxTokens,
"messages": []map[string]string{
{"role": "user", "content": prompt},
},
}
b, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.anthropic.com/v1/messages", bytes.NewReader(b))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", p.apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := p.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
raw, err := readGenerationResponse(resp)
if err != nil {
return "", err
}
var result struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return "", err
}
if len(result.Content) == 0 {
return "", nil
}
return result.Content[0].Text, nil
}
// ListModels checks API authentication using discovery, never generation.
func (p *anthropicProvider) ListModels(ctx context.Context) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.anthropic.com/v1/models", nil)
if err != nil {
return nil, errors.New("model discovery request failed")
}
req.Header.Set("x-api-key", p.apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := p.client.Do(req)
if err != nil {
return nil, errors.New("model discovery unavailable")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &summaryHTTPError{status: resp.StatusCode, err: errors.New("model discovery failed")}
}
var result struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
// Discovery responses are bounded; malformed bodies never reach callers.
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&result); err != nil {
return nil, errors.New("model discovery response invalid")
}
names := make([]string, 0, len(result.Data))
for _, model := range result.Data {
names = append(names, model.ID)
}
return names, nil
}