-
Notifications
You must be signed in to change notification settings - Fork 378
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ai-proxy): support OpenAI format
/v1/models
API; respect `mode…
…l` field in request body in order (#6359) * feat(ai-proxy): support OpenAI format `/v1/models` API; respect `model` field in request body in order * check body at context filter * remove useless code * fix goimport
- Loading branch information
Showing
10 changed files
with
281 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
routes: | ||
- path: /v1/models | ||
method: GET | ||
filters: | ||
- name: openai-v1-models |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
// Copyright (c) 2021 Terminus, Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package openai_v1_models | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
|
||
"github.com/sashabaranov/go-openai" | ||
|
||
richclientpb "github.com/erda-project/erda-proto-go/apps/aiproxy/client/rich_client/pb" | ||
"github.com/erda-project/erda/internal/apps/ai-proxy/common/ctxhelper" | ||
"github.com/erda-project/erda/internal/apps/ai-proxy/handlers/common/akutil" | ||
"github.com/erda-project/erda/internal/apps/ai-proxy/handlers/handler_rich_client" | ||
"github.com/erda-project/erda/internal/apps/ai-proxy/vars" | ||
"github.com/erda-project/erda/pkg/reverseproxy" | ||
) | ||
|
||
const ( | ||
Name = "openai-v1-models" | ||
) | ||
|
||
var ( | ||
_ reverseproxy.RequestFilter = (*Filter)(nil) | ||
) | ||
|
||
func init() { | ||
reverseproxy.RegisterFilterCreator(Name, New) | ||
} | ||
|
||
type Filter struct { | ||
} | ||
|
||
func New(_ json.RawMessage) (reverseproxy.Filter, error) { | ||
return &Filter{}, nil | ||
} | ||
|
||
func (f *Filter) OnRequest(ctx context.Context, w http.ResponseWriter, infor reverseproxy.HttpInfor) (signal reverseproxy.Signal, err error) { | ||
var ( | ||
richClientHandler = ctx.Value(vars.CtxKeyRichClientHandler{}).(*handler_rich_client.ClientHandler) | ||
) | ||
// try set clientId by ak | ||
client, err := akutil.CheckAkOrToken(ctx, infor.Request(), ctxhelper.MustGetDBClient(ctx)) | ||
if err != nil { | ||
http.Error(w, fmt.Sprintf("Failed to get client, err: %v", err), http.StatusInternalServerError) | ||
return reverseproxy.Intercept, nil | ||
} | ||
if client == nil { | ||
http.Error(w, "Client not found", http.StatusUnauthorized) | ||
return reverseproxy.Intercept, nil | ||
} | ||
ctx = context.WithValue(ctx, vars.CtxKeyClient{}, client) | ||
ctx = context.WithValue(ctx, vars.CtxKeyClientId{}, client.Id) | ||
|
||
richClient, err := richClientHandler.GetByAccessKeyId(ctx, &richclientpb.GetByClientAccessKeyIdRequest{AccessKeyId: client.AccessKeyId}) | ||
if err != nil { | ||
http.Error(w, "Failed to get rich client", http.StatusInternalServerError) | ||
return reverseproxy.Intercept, nil | ||
} | ||
// convert to openai /v1/models response, see: https://platform.openai.com/docs/api-reference/models/list | ||
var oaiFormatModels openai.ModelsList | ||
for _, m := range richClient.Models { | ||
oaiFormatModels.Models = append(oaiFormatModels.Models, openai.Model{ | ||
ID: GenerateModelDisplayName(m), | ||
CreatedAt: m.Model.CreatedAt.Seconds, // seconds | ||
Object: "model", // always "model" | ||
OwnedBy: m.Provider.Name, | ||
}) | ||
} | ||
// write response | ||
w.Header().Set("Content-Type", "application/json") | ||
if err := json.NewEncoder(w).Encode(oaiFormatModels); err != nil { | ||
http.Error(w, "Failed to write response", http.StatusInternalServerError) | ||
return reverseproxy.Intercept, nil | ||
} | ||
return reverseproxy.Continue, nil | ||
} |
52 changes: 52 additions & 0 deletions
52
internal/apps/ai-proxy/filters/openai-v1-models/model_name.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// Copyright (c) 2021 Terminus, Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package openai_v1_models | ||
|
||
import ( | ||
"regexp" | ||
|
||
richclientpb "github.com/erda-project/erda-proto-go/apps/aiproxy/client/rich_client/pb" | ||
) | ||
|
||
func GenerateModelDisplayName(model *richclientpb.RichModel) string { | ||
s := model.Model.Name | ||
attrs := []string{} | ||
// provider type | ||
attrs = append(attrs, "T:"+model.Provider.Type.String()) | ||
// provider location | ||
if model.Provider.Metadata != nil && model.Provider.Metadata.Public != nil { | ||
if loc := model.Provider.Metadata.Public["location"]; loc != "" { | ||
attrs = append(attrs, "L:"+loc) | ||
} | ||
} | ||
// model id at last | ||
attrs = append(attrs, "ID:"+model.Model.Id) | ||
|
||
attrs_s := "" | ||
for _, attr := range attrs { | ||
attrs_s += "[" + attr + "]" | ||
} | ||
|
||
return s + " " + attrs_s | ||
} | ||
|
||
func ParseModelUUIDFromDisplayName(s string) string { | ||
regex := regexp.MustCompile(`\[ID:([^]]*)]`) | ||
matches := regex.FindAllStringSubmatch(s, 1) | ||
if len(matches) == 0 { | ||
return "" | ||
} | ||
return matches[0][1] | ||
} |
57 changes: 57 additions & 0 deletions
57
internal/apps/ai-proxy/filters/openai-v1-models/model_name_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// Copyright (c) 2021 Terminus, Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package openai_v1_models | ||
|
||
import "testing" | ||
|
||
func TestParseModelUUIDFromDisplayName(t *testing.T) { | ||
type args struct { | ||
s string | ||
} | ||
tests := []struct { | ||
name string | ||
args args | ||
want string | ||
}{ | ||
{ | ||
name: "test1", | ||
args: args{ | ||
s: "test", | ||
}, | ||
want: "", | ||
}, | ||
{ | ||
name: "test2", | ||
args: args{ | ||
s: "test [ID:123]", | ||
}, | ||
want: "123", | ||
}, | ||
{ | ||
name: "test3", | ||
args: args{ | ||
s: "test [ID:123][ID:456]", | ||
}, | ||
want: "123", | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
if got := ParseModelUUIDFromDisplayName(tt.args.s); got != tt.want { | ||
t.Errorf("ParseModelUUIDFromDisplayName() = %v, want %v", got, tt.want) | ||
} | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.