-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
168 lines (139 loc) · 3.82 KB
/
main.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
bedrockruntimetypes "github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types"
)
type Embeddings struct {
Embeddings []float64 `json:"embedding"`
InputTextTokenCount int `json:"inputTextTokenCount"`
}
func EmbeddingsDemo(ctx context.Context, prompt string, bedrockSvc *bedrockruntime.Client) {
// {"inputText": "This is a test"} as bytes
body, err := json.Marshal(map[string]interface{}{
"inputText": prompt,
})
if err != nil {
panic(err)
}
modelInput := &bedrockruntime.InvokeModelInput{
ModelId: aws.String("amazon.titan-embed-text-v1"),
Accept: aws.String("*/*"),
ContentType: aws.String("application/json"),
Body: body,
}
result, err := bedrockSvc.InvokeModel(ctx, modelInput)
if err != nil {
panic(err)
}
var response Embeddings
json.Unmarshal(result.Body, &response)
// Print the embeddings
fmt.Println("Embeddings: ", response.Embeddings)
}
func ClaudeInvokeStreamingDemo(
ctx context.Context,
bedrockSvc *bedrockruntime.Client,
conv Conversation,
convAppend string,
outChannel chan<- string) {
var err error
defer close(outChannel)
jsonInput, err := json.Marshal(AnthropicInput{
Prompt: conv.ToString() + convAppend,
MaxTokensToSample: 2048,
Temperature: 0.0,
TopK: 250,
TopP: 0.999,
StopSequences: []string{"Human:", "```"},
})
if err != nil {
panic(err)
}
modelInput := &bedrockruntime.InvokeModelWithResponseStreamInput{
ModelId: aws.String("anthropic.claude-v2"),
Accept: aws.String("*/*"),
ContentType: aws.String("application/json"),
Body: jsonInput,
}
result, err := bedrockSvc.InvokeModelWithResponseStream(ctx, modelInput)
if err != nil {
panic(err)
}
fmt.Println("Response: ", result)
reader := result.GetStream().Reader
eventsChannel := reader.Events()
var modelOutput AnthropicOutput
for event := range eventsChannel {
x := event.(*bedrockruntimetypes.ResponseStreamMemberChunk)
json.Unmarshal(x.Value.Bytes, &modelOutput)
outChannel <- modelOutput.Completion
}
}
func main() {
// 5 mins timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer func () {
println("Canceling context")
cancel()
}()
// start timer
start := time.Now()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
panic(err)
}
bedrockSvc := bedrockruntime.NewFromConfig(cfg)
prompts := []string{
"Write an essay on the topic of 'The History of the United States'.",
"Write an essay on the topic of 'The Battle of Gettysburg'.",
"Why an essay on the topic of 'French Revolution'",
"When was the Declaration of Independence signed?",
"Who was the first president of the United States?",
"What is the capital of the United States?",
"Explain nuclear fusion.",
"Tell me about Napoleon Bonaparte.",
}
conversations := make([]Conversation, len(prompts))
k := len(prompts)
// create output channels
outchannels := make([]chan string, k)
wg := sync.WaitGroup{}
// create goroutines
for i := 0; i < k; i++ {
outchannels[i] = make(chan string)
conv := Conversation{}
conv.AddMessage("Human", prompts[i])
conversations[i] = conv
// use markdown for formatting
go ClaudeInvokeStreamingDemo(ctx, bedrockSvc, conv, "\n\nAssistant: ```md", outchannels[i])
}
os.Mkdir("out", 0777)
// read from the output channels
for i := 0; i < k; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
outfile := fmt.Sprintf("out/output%d.md", i)
f, err := os.Create(outfile)
if err != nil {
panic(err)
}
for out := range outchannels[i] {
fmt.Println("Prompt ", i, ": ", out)
f.WriteString(out)
}
}(i)
}
wg.Wait()
// stop timer
elapsed := time.Since(start)
fmt.Printf("Time taken: %s\n", elapsed)
}