-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcloudflare_ai_worker_api.go
210 lines (177 loc) · 5.34 KB
/
cloudflare_ai_worker_api.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
package chatmodels
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"github.com/jackmcguire1/alexa-chatgpt/internal/pkg/utils"
)
const (
CF_LLAMA_2_7B_CHAT_INT8_MODEL = "@cf/meta/llama-2-7b-chat-int8"
CF_LLAMA_3_8B_INSTRUCT_MODEL = "@cf/meta/llama-3-8b-instruct"
CF_LLAMA_3_1_INSTRUCT_MODEL = "@cf/meta/llama-3.1-8b-instruct"
CF_SQL_MODEL = "@cf/defog/sqlcoder-7b-2"
CF_AWQ_MODEL = "@hf/thebloke/llama-2-13b-chat-awq"
CF_OPEN_CHAT_MODEL = "@cf/openchat/openchat-3.5-0106"
CF_STABLE_DIFFUSION = "@cf/stabilityai/stable-diffusion-xl-base-1.0"
CF_META_TRANSLATION_MODEL = "@cf/meta/m2m100-1.2b"
CF_QWEN_MODEL = "@cf/qwen/qwen1.5-1.8b-chat"
)
var CHAT_MODEL_TO_CF_MODEL = map[ChatModel]string{
CHAT_MODEL_SQL: CF_SQL_MODEL,
CHAT_MODEL_AWQ: CF_AWQ_MODEL,
CHAT_MODEL_META: CF_LLAMA_3_1_INSTRUCT_MODEL,
CHAT_MODEL_OPEN: CF_OPEN_CHAT_MODEL,
CHAT_MODEL_STABLE_DIFFUSION: CF_STABLE_DIFFUSION,
CHAT_MODEL_TRANSLATIONS: CF_META_TRANSLATION_MODEL,
CHAT_MODEL_QWEN: CF_QWEN_MODEL,
}
type Response struct {
Result struct {
Response string `json:"response"`
} `json:"result,omitempty"`
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors,omitempty"`
Messages []string `json:"messages,omitempty"`
Success bool `json:"success"`
}
type TranslateResponse struct {
Result struct {
TranslatedText string `json:"translated_text"`
} `json:"result"`
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors,omitempty"`
Messages []string `json:"messages,omitempty"`
Success bool `json:"success"`
}
type CloudflareApiClient struct {
AccountID string
APIKey string
}
func NewCloudflareApiClient(accountID, apiKey string) *CloudflareApiClient {
return &CloudflareApiClient{
AccountID: accountID,
APIKey: apiKey,
}
}
func (api *CloudflareApiClient) GenerateText(ctx context.Context, prompt string, model string) (string, error) {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s", api.AccountID, model)
payload := map[string]string{
"prompt": prompt,
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+api.APIKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var result *Response
err = json.Unmarshal(data, &result)
if err != nil {
err = fmt.Errorf("failed to unmarshal cloudflare response body %s", string(data))
return "", err
}
if !result.Success {
err = fmt.Errorf("didn't get success from result %v http-status: %d", utils.ToJSON(result), resp.StatusCode)
return "", err
}
return result.Result.Response, nil
}
func (api *CloudflareApiClient) GenerateImage(ctx context.Context, prompt string, model string) ([]byte, error) {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s", api.AccountID, model)
payload := map[string]string{
"prompt": prompt,
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+api.APIKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}
type GenerateTranslationRequest struct {
SourceLanguage string
TargetLanguage string
Prompt string
Model string
}
func (api *CloudflareApiClient) GenerateTranslation(ctx context.Context, req *GenerateTranslationRequest) (string, error) {
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s", api.AccountID, req.Model)
if req.SourceLanguage == "" {
req.SourceLanguage = "en"
}
payload := map[string]string{
"text": req.Prompt,
"source_lang": req.SourceLanguage,
"target_lang": req.TargetLanguage,
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return "", err
}
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return "", err
}
httpReq.Header.Set("Authorization", "Bearer "+api.APIKey)
httpReq.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(httpReq)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
slog.
With("response", string(data)).
Info("generated translation response")
var response *TranslateResponse
err = json.Unmarshal(data, &response)
if err != nil {
return "", err
}
if !response.Success {
err = fmt.Errorf("didn't get success from result %v http-status: %d", utils.ToJSON(response), resp.StatusCode)
return "", err
}
return response.Result.TranslatedText, nil
}