|
1 | 1 | package zhipu_4v |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "github.com/golang-jwt/jwt" |
5 | | - "one-api/common" |
6 | 4 | "one-api/dto" |
7 | 5 | "strings" |
8 | | - "sync" |
9 | | - "time" |
10 | 6 | ) |
11 | 7 |
|
12 | | -// https://open.bigmodel.cn/doc/api#chatglm_std |
13 | | -// chatglm_std, chatglm_lite |
14 | | -// https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_std/invoke |
15 | | -// https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_std/sse-invoke |
16 | | - |
17 | | -var zhipuTokens sync.Map |
18 | | -var expSeconds int64 = 24 * 3600 |
19 | | - |
20 | | -func getZhipuToken(apikey string) string { |
21 | | - data, ok := zhipuTokens.Load(apikey) |
22 | | - if ok { |
23 | | - tokenData := data.(tokenData) |
24 | | - if time.Now().Before(tokenData.ExpiryTime) { |
25 | | - return tokenData.Token |
26 | | - } |
27 | | - } |
28 | | - |
29 | | - split := strings.Split(apikey, ".") |
30 | | - if len(split) != 2 { |
31 | | - common.SysError("invalid zhipu key: " + apikey) |
32 | | - return "" |
33 | | - } |
34 | | - |
35 | | - id := split[0] |
36 | | - secret := split[1] |
37 | | - |
38 | | - expMillis := time.Now().Add(time.Duration(expSeconds)*time.Second).UnixNano() / 1e6 |
39 | | - expiryTime := time.Now().Add(time.Duration(expSeconds) * time.Second) |
40 | | - |
41 | | - timestamp := time.Now().UnixNano() / 1e6 |
42 | | - |
43 | | - payload := jwt.MapClaims{ |
44 | | - "api_key": id, |
45 | | - "exp": expMillis, |
46 | | - "timestamp": timestamp, |
47 | | - } |
48 | | - |
49 | | - token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload) |
50 | | - |
51 | | - token.Header["alg"] = "HS256" |
52 | | - token.Header["sign_type"] = "SIGN" |
53 | | - |
54 | | - tokenString, err := token.SignedString([]byte(secret)) |
55 | | - if err != nil { |
56 | | - return "" |
57 | | - } |
58 | | - |
59 | | - zhipuTokens.Store(apikey, tokenData{ |
60 | | - Token: tokenString, |
61 | | - ExpiryTime: expiryTime, |
62 | | - }) |
63 | | - |
64 | | - return tokenString |
65 | | -} |
66 | | - |
67 | 8 | func requestOpenAI2Zhipu(request dto.GeneralOpenAIRequest) *dto.GeneralOpenAIRequest { |
68 | 9 | messages := make([]dto.Message, 0, len(request.Messages)) |
69 | 10 | for _, message := range request.Messages { |
|
0 commit comments