-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclaude.go
54 lines (48 loc) · 1.15 KB
/
claude.go
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
package main
import (
"context"
"errors"
"github.com/liushuangls/go-anthropic"
)
type ClaudeConfig struct {
ApiKey string `env:"ANTHROPIC_API_TOKEN"`
}
type Claude struct {
config *ClaudeConfig
client *anthropic.Client
}
func NewClaude(config *ClaudeConfig) (*Claude, error) {
if config.ApiKey == "" {
return nil, errors.New("please set ANTHROPIC_API_TOKEN")
}
return &Claude{
client: anthropic.NewClient(config.ApiKey),
}, nil
}
func (c *Claude) Generate(ctx context.Context, system, prompt string, ch chan string, errCh chan error) error {
_, err := c.client.CreateMessagesStream(ctx, anthropic.MessagesStreamRequest{
MessagesRequest: anthropic.MessagesRequest{
Model: "claude-3-5-sonnet-latest",
Messages: []anthropic.Message{
{
Role: anthropic.RoleUser,
Content: []anthropic.MessageContent{
{
Type: "text",
Text: &prompt,
},
},
},
},
MaxTokens: 8192,
System: system,
},
OnError: func(response anthropic.ErrorResponse) {
errCh <- response.Error
},
OnContentBlockDelta: func(data anthropic.MessagesEventContentBlockDeltaData) {
ch <- data.Delta.Text
},
})
return err
}