forked from alibaba/higress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeepl.go
181 lines (159 loc) · 5.92 KB
/
deepl.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
package provider
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/alibaba/higress/plugins/wasm-go/extensions/ai-proxy/util"
"github.com/alibaba/higress/plugins/wasm-go/pkg/wrapper"
"github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types"
)
// deeplProvider is the provider for DeepL service.
const (
deeplHostPro = "api.deepl.com"
deeplHostFree = "api-free.deepl.com"
deeplChatCompletionPath = "/v2/translate"
)
type deeplProviderInitializer struct {
}
type deeplProvider struct {
config ProviderConfig
contextCache *contextCache
}
// spec reference: https://developers.deepl.com/docs/v/zh/api-reference/translate/openapi-spec-for-text-translation
type deeplRequest struct {
// "Model" parameter is used to distinguish which service to use
Model string `json:"model,omitempty"`
Text []string `json:"text"`
SourceLang string `json:"source_lang,omitempty"`
TargetLang string `json:"target_lang"`
Context string `json:"context,omitempty"`
SplitSentences string `json:"split_sentences,omitempty"`
PreserveFormatting bool `json:"preserve_formatting,omitempty"`
Formality string `json:"formality,omitempty"`
GlossaryId string `json:"glossary_id,omitempty"`
TagHandling string `json:"tag_handling,omitempty"`
OutlineDetection bool `json:"outline_detection,omitempty"`
NonSplittingTags []string `json:"non_splitting_tags,omitempty"`
SplittingTags []string `json:"splitting_tags,omitempty"`
IgnoreTags []string `json:"ignore_tags,omitempty"`
}
type deeplResponse struct {
Translations []deeplResponseTranslation `json:"translations,omitempty"`
Message string `json:"message,omitempty"`
}
type deeplResponseTranslation struct {
DetectedSourceLanguage string `json:"detected_source_language"`
Text string `json:"text"`
}
func (d *deeplProviderInitializer) ValidateConfig(config *ProviderConfig) error {
if config.targetLang == "" {
return errors.New("missing targetLang in deepl provider config")
}
return nil
}
func (d *deeplProviderInitializer) CreateProvider(config ProviderConfig) (Provider, error) {
return &deeplProvider{
config: config,
contextCache: createContextCache(&config),
}, nil
}
func (d *deeplProvider) GetProviderType() string {
return providerTypeDeepl
}
func (d *deeplProvider) OnRequestHeaders(ctx wrapper.HttpContext, apiName ApiName, log wrapper.Log) error {
if apiName != ApiNameChatCompletion {
return errUnsupportedApiName
}
d.config.handleRequestHeaders(d, ctx, apiName, log)
return nil
}
func (d *deeplProvider) TransformRequestHeaders(ctx wrapper.HttpContext, apiName ApiName, headers http.Header, log wrapper.Log) {
util.OverwriteRequestPathHeader(headers, deeplChatCompletionPath)
util.OverwriteRequestAuthorizationHeader(headers, "DeepL-Auth-Key "+d.config.GetApiTokenInUse(ctx))
}
func (d *deeplProvider) OnRequestBody(ctx wrapper.HttpContext, apiName ApiName, body []byte, log wrapper.Log) (types.Action, error) {
if apiName != ApiNameChatCompletion {
return types.ActionContinue, errUnsupportedApiName
}
return d.config.handleRequestBody(d, d.contextCache, ctx, apiName, body, log)
}
func (d *deeplProvider) TransformRequestBodyHeaders(ctx wrapper.HttpContext, apiName ApiName, body []byte, headers http.Header, log wrapper.Log) ([]byte, error) {
request := &chatCompletionRequest{}
if err := decodeChatCompletionRequest(body, request); err != nil {
return nil, err
}
ctx.SetContext(ctxKeyFinalRequestModel, request.Model)
err := d.overwriteRequestHost(headers, request.Model)
if err != nil {
return nil, err
}
baiduRequest := d.deeplTextGenRequest(request)
return json.Marshal(baiduRequest)
}
func (d *deeplProvider) TransformResponseBody(ctx wrapper.HttpContext, apiName ApiName, body []byte, log wrapper.Log) ([]byte, error) {
deeplResponse := &deeplResponse{}
if err := json.Unmarshal(body, deeplResponse); err != nil {
return nil, fmt.Errorf("unable to unmarshal deepl response: %v", err)
}
response := d.responseDeepl2OpenAI(ctx, deeplResponse)
return json.Marshal(response)
}
func (d *deeplProvider) responseDeepl2OpenAI(ctx wrapper.HttpContext, deeplResponse *deeplResponse) *chatCompletionResponse {
var choices []chatCompletionChoice
// Fail
if deeplResponse.Message != "" {
choices = make([]chatCompletionChoice, 1)
choices[0] = chatCompletionChoice{
Message: &chatMessage{Role: roleAssistant, Content: deeplResponse.Message},
Index: 0,
}
} else {
// Success
choices = make([]chatCompletionChoice, len(deeplResponse.Translations))
for idx, t := range deeplResponse.Translations {
choices[idx] = chatCompletionChoice{
Index: idx,
Message: &chatMessage{Role: roleAssistant, Content: t.Text, Name: t.DetectedSourceLanguage},
}
}
}
return &chatCompletionResponse{
Created: time.Now().UnixMilli() / 1000,
Object: objectChatCompletion,
Choices: choices,
Model: ctx.GetStringContext(ctxKeyFinalRequestModel, ""),
}
}
func (d *deeplProvider) overwriteRequestHost(headers http.Header, model string) error {
if model == "Pro" {
util.OverwriteRequestHostHeader(headers, deeplHostPro)
} else if model == "Free" {
util.OverwriteRequestHostHeader(headers, deeplHostFree)
} else {
return errors.New(`deepl model should be "Free" or "Pro"`)
}
return nil
}
func (d *deeplProvider) deeplTextGenRequest(request *chatCompletionRequest) *deeplRequest {
deeplRequest := &deeplRequest{
Text: make([]string, 0),
TargetLang: d.config.targetLang,
}
for _, msg := range request.Messages {
if msg.Role == roleSystem {
deeplRequest.Context = msg.StringContent()
} else {
deeplRequest.Text = append(deeplRequest.Text, msg.StringContent())
}
}
return deeplRequest
}
func (d *deeplProvider) GetApiName(path string) ApiName {
if strings.Contains(path, deeplChatCompletionPath) {
return ApiNameChatCompletion
}
return ""
}