forked from DFanso/commit-msg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude.go
More file actions
94 lines (78 loc) · 2.3 KB
/
claude.go
File metadata and controls
94 lines (78 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package claude
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
httpClient "github.com/dfanso/commit-msg/internal/http"
"github.com/dfanso/commit-msg/pkg/types"
)
const (
claudeModel = "claude-3-5-sonnet-20241022"
claudeMaxTokens = 200
claudeAPIEndpoint = "https://api.anthropic.com/v1/messages"
claudeAPIVersion = "2023-06-01"
contentTypeJSON = "application/json"
anthropicVersionHeader = "anthropic-version"
xAPIKeyHeader = "x-api-key"
)
// ClaudeRequest describes the payload sent to Anthropic's Claude messages API.
type ClaudeRequest struct {
Model string `json:"model"`
Messages []types.Message `json:"messages"`
MaxTokens int `json:"max_tokens"`
}
// ClaudeResponse captures the subset of fields used from Anthropic responses.
type ClaudeResponse struct {
ID string `json:"id"`
Type string `json:"type"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}
// GenerateCommitMessage produces a commit summary using Anthropic's Claude API.
func GenerateCommitMessage(config *types.Config, changes string, apiKey string, opts *types.GenerationOptions) (string, error) {
prompt := types.BuildCommitPrompt(changes, opts)
reqBody := ClaudeRequest{
Model: claudeModel,
MaxTokens: claudeMaxTokens,
Messages: []types.Message{
{
Role: "user",
Content: prompt,
},
},
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return "", err
}
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "POST", claudeAPIEndpoint, bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", contentTypeJSON)
req.Header.Set(xAPIKeyHeader, apiKey)
req.Header.Set(anthropicVersionHeader, claudeAPIVersion)
client := httpClient.GetClient()
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("claude AI response %d", resp.StatusCode)
}
var claudeResponse ClaudeResponse
if err := json.NewDecoder(resp.Body).Decode(&claudeResponse); err != nil {
return "", err
}
if len(claudeResponse.Content) == 0 {
return "", fmt.Errorf("no response generated")
}
commitMsg := claudeResponse.Content[0].Text
return commitMsg, nil
}