|
| 1 | +package provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/alibaba/higress/plugins/wasm-go/extensions/ai-proxy/util" |
| 10 | + "github.com/alibaba/higress/plugins/wasm-go/pkg/wrapper" |
| 11 | + "github.com/higress-group/proxy-wasm-go-sdk/proxywasm" |
| 12 | + "github.com/higress-group/proxy-wasm-go-sdk/proxywasm/types" |
| 13 | +) |
| 14 | + |
| 15 | +// deeplProvider is the provider for DeepL service. |
| 16 | +const ( |
| 17 | + deeplHostPro = "api.deepl.com" |
| 18 | + deeplHostFree = "api-free.deepl.com" |
| 19 | + deeplChatCompletionPath = "/v2/translate" |
| 20 | +) |
| 21 | + |
| 22 | +type deeplProviderInitializer struct { |
| 23 | +} |
| 24 | + |
| 25 | +type deeplProvider struct { |
| 26 | + config ProviderConfig |
| 27 | + contextCache *contextCache |
| 28 | +} |
| 29 | + |
| 30 | +// spec reference: https://developers.deepl.com/docs/v/zh/api-reference/translate/openapi-spec-for-text-translation |
| 31 | +type deeplRequest struct { |
| 32 | + // "Model" parameter is used to distinguish which service to use |
| 33 | + Model string `json:"model,omitempty"` |
| 34 | + Text []string `json:"text"` |
| 35 | + SourceLang string `json:"source_lang,omitempty"` |
| 36 | + TargetLang string `json:"target_lang"` |
| 37 | + Context string `json:"context,omitempty"` |
| 38 | + SplitSentences string `json:"split_sentences,omitempty"` |
| 39 | + PreserveFormatting bool `json:"preserve_formatting,omitempty"` |
| 40 | + Formality string `json:"formality,omitempty"` |
| 41 | + GlossaryId string `json:"glossary_id,omitempty"` |
| 42 | + TagHandling string `json:"tag_handling,omitempty"` |
| 43 | + OutlineDetection bool `json:"outline_detection,omitempty"` |
| 44 | + NonSplittingTags []string `json:"non_splitting_tags,omitempty"` |
| 45 | + SplittingTags []string `json:"splitting_tags,omitempty"` |
| 46 | + IgnoreTags []string `json:"ignore_tags,omitempty"` |
| 47 | +} |
| 48 | + |
| 49 | +type deeplResponse struct { |
| 50 | + Translations []deeplResponseTranslation `json:"translations,omitempty"` |
| 51 | + Message string `json:"message,omitempty"` |
| 52 | +} |
| 53 | + |
| 54 | +type deeplResponseTranslation struct { |
| 55 | + DetectedSourceLanguage string `json:"detected_source_language"` |
| 56 | + Text string `json:"text"` |
| 57 | +} |
| 58 | + |
| 59 | +func (d *deeplProviderInitializer) ValidateConfig(config ProviderConfig) error { |
| 60 | + if config.targetLang == "" { |
| 61 | + return errors.New("missing targetLang in deepl provider config") |
| 62 | + } |
| 63 | + return nil |
| 64 | +} |
| 65 | + |
| 66 | +func (d *deeplProviderInitializer) CreateProvider(config ProviderConfig) (Provider, error) { |
| 67 | + return &deeplProvider{ |
| 68 | + config: config, |
| 69 | + contextCache: createContextCache(&config), |
| 70 | + }, nil |
| 71 | +} |
| 72 | + |
| 73 | +func (d *deeplProvider) GetProviderType() string { |
| 74 | + return providerTypeDeepl |
| 75 | +} |
| 76 | + |
| 77 | +func (d *deeplProvider) OnRequestHeaders(ctx wrapper.HttpContext, apiName ApiName, log wrapper.Log) (types.Action, error) { |
| 78 | + if apiName != ApiNameChatCompletion { |
| 79 | + return types.ActionContinue, errUnsupportedApiName |
| 80 | + } |
| 81 | + _ = util.OverwriteRequestPath(deeplChatCompletionPath) |
| 82 | + _ = util.OverwriteRequestAuthorization("DeepL-Auth-Key " + d.config.GetRandomToken()) |
| 83 | + _ = proxywasm.RemoveHttpRequestHeader("Content-Length") |
| 84 | + _ = proxywasm.RemoveHttpRequestHeader("Accept-Encoding") |
| 85 | + return types.HeaderStopIteration, nil |
| 86 | +} |
| 87 | + |
| 88 | +func (d *deeplProvider) OnRequestBody(ctx wrapper.HttpContext, apiName ApiName, body []byte, log wrapper.Log) (types.Action, error) { |
| 89 | + if apiName != ApiNameChatCompletion { |
| 90 | + return types.ActionContinue, errUnsupportedApiName |
| 91 | + } |
| 92 | + if d.config.protocol == protocolOriginal { |
| 93 | + request := &deeplRequest{} |
| 94 | + if err := json.Unmarshal(body, request); err != nil { |
| 95 | + return types.ActionContinue, fmt.Errorf("unable to unmarshal request: %v", err) |
| 96 | + } |
| 97 | + if err := d.overwriteRequestHost(request.Model); err != nil { |
| 98 | + return types.ActionContinue, err |
| 99 | + } |
| 100 | + ctx.SetContext(ctxKeyFinalRequestModel, request.Model) |
| 101 | + return types.ActionContinue, replaceJsonRequestBody(request, log) |
| 102 | + } else { |
| 103 | + originRequest := &chatCompletionRequest{} |
| 104 | + if err := decodeChatCompletionRequest(body, originRequest); err != nil { |
| 105 | + return types.ActionContinue, err |
| 106 | + } |
| 107 | + if err := d.overwriteRequestHost(originRequest.Model); err != nil { |
| 108 | + return types.ActionContinue, err |
| 109 | + } |
| 110 | + ctx.SetContext(ctxKeyFinalRequestModel, originRequest.Model) |
| 111 | + deeplRequest := &deeplRequest{ |
| 112 | + Text: make([]string, 0), |
| 113 | + TargetLang: d.config.targetLang, |
| 114 | + } |
| 115 | + for _, msg := range originRequest.Messages { |
| 116 | + if msg.Role == roleSystem { |
| 117 | + deeplRequest.Context = msg.Content |
| 118 | + } else { |
| 119 | + deeplRequest.Text = append(deeplRequest.Text, msg.Content) |
| 120 | + } |
| 121 | + } |
| 122 | + return types.ActionContinue, replaceJsonRequestBody(deeplRequest, log) |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +func (d *deeplProvider) OnResponseHeaders(ctx wrapper.HttpContext, apiName ApiName, log wrapper.Log) (types.Action, error) { |
| 127 | + _ = proxywasm.RemoveHttpResponseHeader("Content-Length") |
| 128 | + return types.ActionContinue, nil |
| 129 | +} |
| 130 | + |
| 131 | +func (d *deeplProvider) OnResponseBody(ctx wrapper.HttpContext, apiName ApiName, body []byte, log wrapper.Log) (types.Action, error) { |
| 132 | + deeplResponse := &deeplResponse{} |
| 133 | + if err := json.Unmarshal(body, deeplResponse); err != nil { |
| 134 | + return types.ActionContinue, fmt.Errorf("unable to unmarshal deepl response: %v", err) |
| 135 | + } |
| 136 | + response := d.responseDeepl2OpenAI(ctx, deeplResponse) |
| 137 | + return types.ActionContinue, replaceJsonResponseBody(response, log) |
| 138 | +} |
| 139 | + |
| 140 | +func (d *deeplProvider) responseDeepl2OpenAI(ctx wrapper.HttpContext, deeplResponse *deeplResponse) *chatCompletionResponse { |
| 141 | + var choices []chatCompletionChoice |
| 142 | + // Fail |
| 143 | + if deeplResponse.Message != "" { |
| 144 | + choices = make([]chatCompletionChoice, 1) |
| 145 | + choices[0] = chatCompletionChoice{ |
| 146 | + Message: &chatMessage{Role: roleAssistant, Content: deeplResponse.Message}, |
| 147 | + Index: 0, |
| 148 | + } |
| 149 | + } else { |
| 150 | + // Success |
| 151 | + choices = make([]chatCompletionChoice, len(deeplResponse.Translations)) |
| 152 | + for idx, t := range deeplResponse.Translations { |
| 153 | + choices[idx] = chatCompletionChoice{ |
| 154 | + Index: idx, |
| 155 | + Message: &chatMessage{Role: roleAssistant, Content: t.Text, Name: t.DetectedSourceLanguage}, |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + return &chatCompletionResponse{ |
| 160 | + Created: time.Now().UnixMilli() / 1000, |
| 161 | + Object: objectChatCompletion, |
| 162 | + Choices: choices, |
| 163 | + Model: ctx.GetStringContext(ctxKeyFinalRequestModel, ""), |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +func (d *deeplProvider) overwriteRequestHost(model string) error { |
| 168 | + if model == "Pro" { |
| 169 | + _ = util.OverwriteRequestHost(deeplHostPro) |
| 170 | + } else if model == "Free" { |
| 171 | + _ = util.OverwriteRequestHost(deeplHostFree) |
| 172 | + } else { |
| 173 | + return errors.New(`deepl model should be "Free" or "Pro"`) |
| 174 | + } |
| 175 | + return nil |
| 176 | +} |
0 commit comments