|
| 1 | +// Package anthropic implements the Anthropic Messages API client (design doc §7.1, issue #69). |
| 2 | +package anthropic |
| 3 | + |
| 4 | +import ( |
| 5 | + "bytes" |
| 6 | + "context" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + defaultBaseURL = "https://api.anthropic.com" |
| 17 | + apiVersion = "2023-06-01" |
| 18 | + defaultMaxTok = 4096 |
| 19 | +) |
| 20 | + |
| 21 | +// ChatMessage is one user or assistant turn for the Messages API (roles user|assistant only). |
| 22 | +type ChatMessage struct { |
| 23 | + Role string |
| 24 | + Content string |
| 25 | +} |
| 26 | + |
| 27 | +// Client calls POST /v1/messages. |
| 28 | +type Client struct { |
| 29 | + APIKey string |
| 30 | + BaseURL string |
| 31 | + HTTPClient *http.Client |
| 32 | +} |
| 33 | + |
| 34 | +func (c *Client) base() string { |
| 35 | + if c != nil && strings.TrimSpace(c.BaseURL) != "" { |
| 36 | + return strings.TrimRight(strings.TrimSpace(c.BaseURL), "/") |
| 37 | + } |
| 38 | + return defaultBaseURL |
| 39 | +} |
| 40 | + |
| 41 | +func (c *Client) http() *http.Client { |
| 42 | + if c != nil && c.HTTPClient != nil { |
| 43 | + return c.HTTPClient |
| 44 | + } |
| 45 | + return http.DefaultClient |
| 46 | +} |
| 47 | + |
| 48 | +// Generate performs one non-streaming Messages request. system may be empty. |
| 49 | +// Returns assistant text (concatenated text blocks), token usage when present, and duration in ms. |
| 50 | +func (c *Client) Generate(ctx context.Context, model, system string, messages []ChatMessage) (text string, inputTokens, outputTokens int, durationMs int64, err error) { |
| 51 | + if c == nil || strings.TrimSpace(c.APIKey) == "" { |
| 52 | + return "", 0, 0, 0, fmt.Errorf("anthropic: client not configured") |
| 53 | + } |
| 54 | + if strings.TrimSpace(model) == "" { |
| 55 | + return "", 0, 0, 0, fmt.Errorf("anthropic: empty model") |
| 56 | + } |
| 57 | + start := time.Now() |
| 58 | + |
| 59 | + type msg struct { |
| 60 | + Role string `json:"role"` |
| 61 | + Content string `json:"content"` |
| 62 | + } |
| 63 | + payload := struct { |
| 64 | + Model string `json:"model"` |
| 65 | + MaxTokens int `json:"max_tokens"` |
| 66 | + System string `json:"system,omitempty"` |
| 67 | + Messages []msg `json:"messages"` |
| 68 | + }{ |
| 69 | + Model: model, |
| 70 | + MaxTokens: defaultMaxTok, |
| 71 | + System: strings.TrimSpace(system), |
| 72 | + } |
| 73 | + for _, m := range messages { |
| 74 | + role := strings.ToLower(strings.TrimSpace(m.Role)) |
| 75 | + if role != "user" && role != "assistant" { |
| 76 | + return "", 0, 0, 0, fmt.Errorf("anthropic: message role %q is not user or assistant", m.Role) |
| 77 | + } |
| 78 | + payload.Messages = append(payload.Messages, msg{Role: role, Content: m.Content}) |
| 79 | + } |
| 80 | + if len(payload.Messages) == 0 { |
| 81 | + return "", 0, 0, 0, fmt.Errorf("anthropic: no messages") |
| 82 | + } |
| 83 | + |
| 84 | + body, err := json.Marshal(payload) |
| 85 | + if err != nil { |
| 86 | + return "", 0, 0, 0, err |
| 87 | + } |
| 88 | + url := c.base() + "/v1/messages" |
| 89 | + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) |
| 90 | + if err != nil { |
| 91 | + return "", 0, 0, 0, err |
| 92 | + } |
| 93 | + httpReq.Header.Set("Content-Type", "application/json") |
| 94 | + httpReq.Header.Set("x-api-key", c.APIKey) |
| 95 | + httpReq.Header.Set("anthropic-version", apiVersion) |
| 96 | + |
| 97 | + resp, err := c.http().Do(httpReq) |
| 98 | + if err != nil { |
| 99 | + return "", 0, 0, 0, err |
| 100 | + } |
| 101 | + defer resp.Body.Close() |
| 102 | + b, err := io.ReadAll(resp.Body) |
| 103 | + if err != nil { |
| 104 | + return "", 0, 0, 0, err |
| 105 | + } |
| 106 | + durationMs = time.Since(start).Milliseconds() |
| 107 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 108 | + return "", 0, 0, durationMs, fmt.Errorf("anthropic: HTTP %d: %s", resp.StatusCode, truncateErrBody(b)) |
| 109 | + } |
| 110 | + |
| 111 | + var out struct { |
| 112 | + Content []struct { |
| 113 | + Type string `json:"type"` |
| 114 | + Text string `json:"text"` |
| 115 | + } `json:"content"` |
| 116 | + Usage *struct { |
| 117 | + InputTokens int `json:"input_tokens"` |
| 118 | + OutputTokens int `json:"output_tokens"` |
| 119 | + } `json:"usage"` |
| 120 | + } |
| 121 | + if err := json.Unmarshal(b, &out); err != nil { |
| 122 | + return "", 0, 0, durationMs, fmt.Errorf("anthropic: decode response: %w", err) |
| 123 | + } |
| 124 | + var parts []string |
| 125 | + for _, block := range out.Content { |
| 126 | + if block.Type == "text" && block.Text != "" { |
| 127 | + parts = append(parts, block.Text) |
| 128 | + } |
| 129 | + } |
| 130 | + text = strings.Join(parts, "") |
| 131 | + if text == "" { |
| 132 | + return "", 0, 0, durationMs, fmt.Errorf("anthropic: no text content in response") |
| 133 | + } |
| 134 | + if out.Usage != nil { |
| 135 | + inputTokens = out.Usage.InputTokens |
| 136 | + outputTokens = out.Usage.OutputTokens |
| 137 | + } |
| 138 | + return text, inputTokens, outputTokens, durationMs, nil |
| 139 | +} |
| 140 | + |
| 141 | +func truncateErrBody(b []byte) string { |
| 142 | + const n = 500 |
| 143 | + s := string(b) |
| 144 | + if len(s) <= n { |
| 145 | + return s |
| 146 | + } |
| 147 | + return s[:n] + "..." |
| 148 | +} |
0 commit comments