/
invoke_model.go
341 lines (270 loc) · 9.87 KB
/
invoke_model.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package actions
import (
"context"
"encoding/json"
"log"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
)
// snippet-start:[gov2.bedrock-runtime.InvokeModelWrapper.complete]
// snippet-start:[gov2.bedrock-runtime.InvokeModelWrapper.struct]
// InvokeModelWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock Runtime client that is used to invoke foundation models.
type InvokeModelWrapper struct {
BedrockRuntimeClient *bedrockruntime.Client
}
// snippet-end:[gov2.bedrock-runtime.InvokeModelWrapper.struct]
// snippet-start:[gov2.bedrock-runtime.InvokeClaude]
// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for Anthropic Claude, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html
type ClaudeRequest struct {
Prompt string `json:"prompt"`
MaxTokensToSample int `json:"max_tokens_to_sample"`
Temperature float64 `json:"temperature,omitempty"`
StopSequences []string `json:"stop_sequences,omitempty"`
}
type ClaudeResponse struct {
Completion string `json:"completion"`
}
// Invokes Anthropic Claude on Amazon Bedrock to run an inference using the input
// provided in the request body.
func (wrapper InvokeModelWrapper) InvokeClaude(prompt string) (string, error) {
modelId := "anthropic.claude-v2"
// Anthropic Claude requires enclosing the prompt as follows:
enclosedPrompt := "Human: " + prompt + "\n\nAssistant:"
body, err := json.Marshal(ClaudeRequest{
Prompt: enclosedPrompt,
MaxTokensToSample: 200,
Temperature: 0.5,
StopSequences: []string{"\n\nHuman:"},
})
if err != nil {
log.Fatal("failed to marshal", err)
}
output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.TODO(), &bedrockruntime.InvokeModelInput{
ModelId: aws.String(modelId),
ContentType: aws.String("application/json"),
Body: body,
})
if err != nil {
ProcessError(err, modelId)
}
var response ClaudeResponse
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
return response.Completion, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeClaude]
// snippet-start:[gov2.bedrock-runtime.InvokeJurassic2]
// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html
type Jurassic2Request struct {
Prompt string `json:"prompt"`
MaxTokens int `json:"maxTokens,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
}
type Jurassic2Response struct {
Completions []Completion `json:"completions"`
}
type Completion struct {
Data Data `json:"data"`
}
type Data struct {
Text string `json:"text"`
}
// Invokes AI21 Labs Jurassic-2 on Amazon Bedrock to run an inference using the input
// provided in the request body.
func (wrapper InvokeModelWrapper) InvokeJurassic2(prompt string) (string, error) {
modelId := "ai21.j2-mid-v1"
body, err := json.Marshal(Jurassic2Request{
Prompt: prompt,
MaxTokens: 200,
Temperature: 0.5,
})
if err != nil {
log.Fatal("failed to marshal", err)
}
output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.TODO(), &bedrockruntime.InvokeModelInput{
ModelId: aws.String(modelId),
ContentType: aws.String("application/json"),
Body: body,
})
if err != nil {
ProcessError(err, modelId)
}
var response Jurassic2Response
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
return response.Completions[0].Data.Text, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeJurassic2]
// snippet-start:[gov2.bedrock-runtime.InvokeLlama2]
// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for Meta Llama 2 Chat, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html
type Llama2Request struct {
Prompt string `json:"prompt"`
MaxGenLength int `json:"max_gen_len,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
}
type Llama2Response struct {
Generation string `json:"generation"`
}
// Invokes Meta Llama 2 Chat on Amazon Bedrock to run an inference using the input
// provided in the request body.
func (wrapper InvokeModelWrapper) InvokeLlama2(prompt string) (string, error) {
modelId := "meta.llama2-13b-chat-v1"
body, err := json.Marshal(Llama2Request{
Prompt: prompt,
MaxGenLength: 512,
Temperature: 0.5,
})
if err != nil {
log.Fatal("failed to marshal", err)
}
output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.TODO(), &bedrockruntime.InvokeModelInput{
ModelId: aws.String(modelId),
ContentType: aws.String("application/json"),
Body: body,
})
if err != nil {
ProcessError(err, modelId)
}
var response Llama2Response
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
return response.Generation, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeLlama2]
// snippet-start:[gov2.bedrock-runtime.InvokeTitanImage]
type TitanImageRequest struct {
TaskType string `json:"taskType"`
TextToImageParams TextToImageParams `json:"textToImageParams"`
ImageGenerationConfig ImageGenerationConfig `json:"imageGenerationConfig"`
}
type TextToImageParams struct {
Text string `json:"text"`
}
type ImageGenerationConfig struct {
NumberOfImages int `json:"numberOfImages"`
Quality string `json:"quality"`
CfgScale float64 `json:"cfgScale"`
Height int `json:"height"`
Width int `json:"width"`
Seed int64 `json:"seed"`
}
type TitanImageResponse struct {
Images []string `json:"images"`
}
// Invokes the Titan Image model to create an image using the input provided
// in the request body.
func (wrapper InvokeModelWrapper) InvokeTitanImage(prompt string, seed int64) (string, error) {
modelId := "amazon.titan-image-generator-v1"
body, err := json.Marshal(TitanImageRequest{
TaskType: "TEXT_IMAGE",
TextToImageParams: TextToImageParams{
Text: prompt,
},
ImageGenerationConfig: ImageGenerationConfig{
NumberOfImages: 1,
Quality: "standard",
CfgScale: 8.0,
Height: 512,
Width: 512,
Seed: seed,
},
})
if err != nil {
log.Fatal("failed to marshal", err)
}
output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.TODO(), &bedrockruntime.InvokeModelInput{
ModelId: aws.String(modelId),
ContentType: aws.String("application/json"),
Body: body,
})
if err != nil {
ProcessError(err, modelId)
}
var response TitanImageResponse
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
base64ImageData := response.Images[0]
return base64ImageData, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeTitanImage]
// snippet-start:[gov2.bedrock-runtime.InvokeTitanText]
// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for Amazon Titan Text, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-text.html
type TitanTextRequest struct {
InputText string `json:"inputText"`
TextGenerationConfig TextGenerationConfig `json:"textGenerationConfig"`
}
type TextGenerationConfig struct {
Temperature float64 `json:"temperature"`
TopP float64 `json:"topP"`
MaxTokenCount int `json:"maxTokenCount"`
StopSequences []string `json:"stopSequences,omitempty"`
}
type TitanTextResponse struct {
InputTextTokenCount int `json:"inputTextTokenCount"`
Results []Result `json:"results"`
}
type Result struct {
TokenCount int `json:"tokenCount"`
OutputText string `json:"outputText"`
CompletionReason string `json:"completionReason"`
}
func (wrapper InvokeModelWrapper) InvokeTitanText(prompt string) (string, error) {
modelId := "amazon.titan-text-express-v1"
body, err := json.Marshal(TitanTextRequest{
InputText: prompt,
TextGenerationConfig: TextGenerationConfig{
Temperature: 0,
TopP: 1,
MaxTokenCount: 4096,
},
})
if err != nil {
log.Fatal("failed to marshal", err)
}
output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.Background(), &bedrockruntime.InvokeModelInput{
ModelId: aws.String(modelId),
ContentType: aws.String("application/json"),
Body: body,
})
if err != nil {
ProcessError(err, modelId)
}
var response TitanTextResponse
if err := json.Unmarshal(output.Body, &response); err != nil {
log.Fatal("failed to unmarshal", err)
}
return response.Results[0].OutputText, nil
}
// snippet-end:[gov2.bedrock-runtime.InvokeTitanText]
func ProcessError(err error, modelId string) {
errMsg := err.Error()
if strings.Contains(errMsg, "no such host") {
log.Printf(`The Bedrock service is not available in the selected region.
Please double-check the service availability for your region at
https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/.\n`)
} else if strings.Contains(errMsg, "Could not resolve the foundation model") {
log.Printf(`Could not resolve the foundation model from model identifier: \"%v\".
Please verify that the requested model exists and is accessible
within the specified region.\n
`, modelId)
} else {
log.Printf("Couldn't invoke model: \"%v\". Here's why: %v\n", modelId, err)
}
}
// snippet-end:[gov2.bedrock-runtime.InvokeModelWrapper.complete]