Spaces:
Paused
Paused
kao0312 commited on
Commit ·
cbe30d3
1
Parent(s): d41adbf
feat: lowercase model ids, add glm-5, socks5 proxy pool, remove arm build
Browse filesFiles changed (14)
- .github/workflows/docker-image.yml+1-1
- .gitignore+2
- Dockerfile+3
- README.md+52-27
- go.mod+3-3
- go.sum+10
- internal/auth/anonymous.go+3-1
- internal/model/mapping.go+39-40
- internal/model/mapping_test.go+69-30
- internal/proxy/pool.goAdded+120
- internal/upstream/client.go+2-1
- internal/upstream/upload.go+3-2
- internal/version/version.go+4-5
- main.go+2
51 unmodified lines5253545551 unmodified lineslabels: ${{ steps.meta.outputs.labels }}cache-from: type=ghacache-to: type=gha,mode=maxplatforms: linux/amd64,linux/arm6451 unmodified lines5253545551 unmodified lineslabels: ${{ steps.meta.outputs.labels }}cache-from: type=ghacache-to: type=gha,mode=maxplatforms: linux/amd64
3 unmodified lines4563 unmodified linesPROJECT_STRUCTURE.mdhello.txtpsychoanalysis.txt3 unmodified lines456783 unmodified linesPROJECT_STRUCTURE.mdhello.txtpsychoanalysis.txtproxies.txtzai-proxy
13 unmodified lines14151617181913 unmodified linesCOPY --from=builder /app/zai-proxy .EXPOSE 8000CMD ["./zai-proxy"]13 unmodified lines14151617181920212213 unmodified linesCOPY --from=builder /app/zai-proxy .# proxies.txt 可通过 docker run -v ./proxies.txt:/app/proxies.txt 挂载VOLUME ["/app/proxies.txt"]EXPOSE 8000CMD ["./zai-proxy"]
52 unmodified lines5354555657585936 unmodified lines969798991001014 unmodified lines10610710810911011111221 unmodified lines13413513613713813914030 unmodified lines1711721731741751761771781791801811821 unmodified line1841851861871881891901911921931941951961971981996 unmodified lines2062072082092102112122132142152161 unmodified line21821922022122222322467 unmodified lines29229329429529629729813 unmodified lines31231331431531631731811 unmodified lines33033133233333433533681 unmodified lines41841942042142242352 unmodified linesghcr.io/yurika0211/zai-proxy:latest```> 镜像支持 `linux/amd64` 和 `linux/arm64` 双平台。#### 可用镜像标签36 unmodified lines支持 `.env` 文件自动加载。## 获取 z.ai Token### 方式一:使用匿名 Token(免登录)4 unmodified linescurl http://localhost:8000/v1/chat/completions \-H "Authorization: Bearer free" \-H "Content-Type: application/json" \-d '{"model": "GLM-4.7", "messages": [{"role": "user", "content": "hello"}]}'```### 方式二:使用个人 Token21 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "GLM-4.7","messages": [{"role": "user", "content": "hello"}],"stream": true}'30 unmodified lines| 模型名称 | 上游模型 | 说明 ||----------|----------|------|| `GLM-4.5` | 0727-360B-API | || `GLM-4.6` | GLM-4-6-API-V1 | || `GLM-4.7` | glm-4.7 | 最新 || `GLM-4.5-V` | glm-4.5v | 视觉 || `GLM-4.6-V` | glm-4.6v | 视觉(最新) || `GLM-4.5-Air` | 0727-106B-API | 轻量 |### Claude 模型名映射1 unmodified line| Claude 模型 | 映射到 | 备注 ||-------------|--------|------|| `claude-opus-4-6` | GLM-4.7 | 自动启用 thinking || `claude-opus-4-5-20250514` | GLM-4.7 | 自动启用 thinking || `claude-sonnet-4-6` | GLM-4.7 | || `claude-sonnet-4-5-20241022` | GLM-4.7 | || `claude-haiku-4-5` | GLM-4.5-Air | || `claude-haiku-4-5-20251001` | GLM-4.5-Air | || `claude-3-5-sonnet-20241022` | GLM-4.7 | || `claude-3-5-haiku-20241022` | GLM-4.5-Air | |> Opus 系列模型始终自动启用 thinking 模式。未识别的模型名会回退到 GLM-4.7。### 模型标签6 unmodified lines| `-tools` | 自动注入内置工具定义,模型可进行函数调用 |组合示例:- `GLM-4.7-thinking`- `GLM-4.7-search`- `GLM-4.7-thinking-search`- `GLM-4.7-tools`- `GLM-4.7-tools-thinking`## 使用示例1 unmodified line```json{"model": "GLM-4.6-V","messages": [{"role": "user",67 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "GLM-4.7-tools","messages": [{"role": "user", "content": "现在几点了?"}],"stream": true}'13 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "GLM-4.7-tools","messages": [{"role": "user", "content": "现在几点了?"},{"role": "assistant", "content": "", "tool_calls": [11 unmodified lines```json{"model": "GLM-4.7","messages": [{"role": "user", "content": "北京天气怎么样?"}],"tools": [{"type": "function",81 unmodified lines│ │ ├── types.go # OpenAI 兼容类型│ │ ├── anthropic.go # Anthropic API 类型│ │ └── mapping.go # 模型名映射与解析│ ├── tools/ # 内置工具定义│ │ ├── builtin.go # 6 个内置工具│ │ └── prompt.go # 工具系统提示词构建52 unmodified lines5354555657585960616263646566676836 unmodified lines1051061071081091101111121131141151161171181191201214 unmodified lines12612712812913013113221 unmodified lines15415515615715815916030 unmodified lines1911921931941951961971981992002012022031 unmodified line2052062072082092102112122132142152162172182192206 unmodified lines2272282292302312322332342352362372382391 unmodified line24124224324424524624767 unmodified lines31531631731831932032113 unmodified lines33533633733833934034111 unmodified lines35335435535635735835981 unmodified lines44144244344444544644744852 unmodified linesghcr.io/yurika0211/zai-proxy:latest```> 镜像仅支持 `linux/amd64` 平台。#### 挂载代理文件(可选)```bashdocker run -d --name zai-proxy \-p 8000:8000 \-v ./proxies.txt:/app/proxies.txt \ghcr.io/yurika0211/zai-proxy:latest```#### 可用镜像标签36 unmodified lines支持 `.env` 文件自动加载。## 代理池(可选)在项目根目录放置 `proxies.txt` 文件,每行一个 SOCKS5 代理,格式:```ip:port:username:passwordip:port```启动时自动加载,每次请求随机选择一个代理。不存在该文件则直连。## 获取 z.ai Token### 方式一:使用匿名 Token(免登录)4 unmodified linescurl http://localhost:8000/v1/chat/completions \-H "Authorization: Bearer free" \-H "Content-Type: application/json" \-d '{"model": "glm-4.7", "messages": [{"role": "user", "content": "hello"}]}'```### 方式二:使用个人 Token21 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "glm-4.7","messages": [{"role": "user", "content": "hello"}],"stream": true}'30 unmodified lines| 模型名称 | 上游模型 | 说明 ||----------|----------|------|| `glm-4.5` | 0727-360B-API | || `glm-4.6` | GLM-4-6-API-V1 | || `glm-4.7` | glm-4.7 | || `glm-5` | glm-5 | 最新 || `glm-4.5-v` | glm-4.5v | 视觉 || `glm-4.6-v` | glm-4.6v | 视觉(最新) || `glm-4.5-air` | 0727-106B-API | 轻量 |### Claude 模型名映射1 unmodified line| Claude 模型 | 映射到 | 备注 ||-------------|--------|------|| `claude-opus-4-6` | glm-4.7 | 自动启用 thinking || `claude-opus-4-5-20250514` | glm-4.7 | 自动启用 thinking || `claude-sonnet-4-6` | glm-4.7 | || `claude-sonnet-4-5-20241022` | glm-4.7 | || `claude-haiku-4-5` | glm-4.5-air | || `claude-haiku-4-5-20251001` | glm-4.5-air | || `claude-3-5-sonnet-20241022` | glm-4.7 | || `claude-3-5-haiku-20241022` | glm-4.5-air | |> Opus 系列模型始终自动启用 thinking 模式。未识别的模型名会回退到 glm-4.7。### 模型标签6 unmodified lines| `-tools` | 自动注入内置工具定义,模型可进行函数调用 |组合示例:- `glm-4.7-thinking`- `glm-4.7-search`- `glm-4.7-thinking-search`- `glm-4.7-tools`- `glm-4.7-tools-thinking`- `glm-5-thinking`- `glm-5-tools`## 使用示例1 unmodified line```json{"model": "glm-4.6-v","messages": [{"role": "user",67 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "glm-4.7-tools","messages": [{"role": "user", "content": "现在几点了?"}],"stream": true}'13 unmodified lines-H "Authorization: Bearer YOUR_ZAI_TOKEN" \-H "Content-Type: application/json" \-d '{"model": "glm-4.7-tools","messages": [{"role": "user", "content": "现在几点了?"},{"role": "assistant", "content": "", "tool_calls": [11 unmodified lines```json{"model": "glm-4.7","messages": [{"role": "user", "content": "北京天气怎么样?"}],"tools": [{"type": "function",81 unmodified lines│ │ ├── types.go # OpenAI 兼容类型│ │ ├── anthropic.go # Anthropic API 类型│ │ └── mapping.go # 模型名映射与解析│ ├── proxy/ # SOCKS5 代理池│ │ └── pool.go # 代理加载与随机选择│ ├── tools/ # 内置工具定义│ │ ├── builtin.go # 6 个内置工具│ │ └── prompt.go # 工具系统提示词构建
12345678910module zai-proxygo 1.21require (github.com/google/uuid v1.6.0github.com/joho/godotenv v1.5.1)require github.com/corpix/uarand v0.2.0 // indirect12345678910module zai-proxygo 1.25.0require (github.com/corpix/uarand v0.2.0github.com/google/uuid v1.6.0github.com/joho/godotenv v1.5.1golang.org/x/net v0.52.0)
123456github.com/corpix/uarand v0.2.0 h1:U98xXwud/AVuCpkpgfPF7J5TQgr7R5tqT8VZP5KWbzE=github.com/corpix/uarand v0.2.0/go.mod h1:/3Z1QIqWkDIhf6XWn/08/uMHoQ8JUoTIKc2iPchBOmM=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=12345678910111213141516github.com/corpix/uarand v0.2.0 h1:U98xXwud/AVuCpkpgfPF7J5TQgr7R5tqT8VZP5KWbzE=github.com/corpix/uarand v0.2.0/go.mod h1:/3Z1QIqWkDIhf6XWn/08/uMHoQ8JUoTIKc2iPchBOmM=github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
3 unmodified lines4567892 unmodified lines121314151617183 unmodified lines"encoding/json""fmt""net/http")type AnonymousAuthResponse struct {2 unmodified lines// GetAnonymousToken 从 z.ai 获取匿名 tokenfunc GetAnonymousToken() (string, error) {resp, err := http.Get("https://chat.z.ai/api/v1/auths/")if err != nil {return "", err}3 unmodified lines45678910112 unmodified lines141516171819203 unmodified lines"encoding/json""fmt""net/http""zai-proxy/internal/proxy")type AnonymousAuthResponse struct {2 unmodified lines// GetAnonymousToken 从 z.ai 获取匿名 tokenfunc GetAnonymousToken() (string, error) {resp, err := proxy.GetHTTPClient().Get("https://chat.z.ai/api/v1/auths/")if err != nil {return "", err}
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162636465666768697071727374757677787932 unmodified lines1121131141151161171 unmodified lineimport "strings"// 基础模型映射(不包含标签后缀)var BaseModelMapping = map[string]string{"GLM-4.5": "0727-360B-API","GLM-4.6": "GLM-4-6-API-V1","GLM-4.7": "glm-4.7","GLM-4.5-V": "glm-4.5v","GLM-4.6-V": "glm-4.6v","GLM-4.5-Air": "0727-106B-API","0808-360B-DR": "0808-360B-DR",}// Claude 模型名到 GLM 基础模型名的映射var ClaudeModelMapping = map[string]string{"claude-opus-4-6": "GLM-4.7","claude-opus-4-5-20250514": "GLM-4.7","claude-sonnet-4-6": "GLM-4.7","claude-sonnet-4-5-20241022": "GLM-4.7","claude-haiku-4-5": "GLM-4.5-Air","claude-haiku-4-5-20251001": "GLM-4.5-Air","claude-3-5-sonnet-20241022": "GLM-4.7","claude-3-5-haiku-20241022": "GLM-4.5-Air",}// ResolveClaudeModel maps a Claude model name to a GLM model name with appropriate tags.// Returns the resolved model name and whether thinking should be enabled.func ResolveClaudeModel(model string, thinkingEnabled bool) (resolvedModel string, enableThinking bool) {base, ok := ClaudeModelMapping[model]if !ok {// Unknown model: fallback to GLM-4.7base = "GLM-4.7"}enableThinking = thinkingEnabled// Opus models always enable thinkingif strings.Contains(model, "opus") {enableThinking = true}1 unmodified lineif enableThinking {resolvedModel += "-thinking"}// Always enable tools for Claude requests (handled via prompt injection)resolvedModel += "-tools"return resolvedModel, enableThinking}// v1/models 返回的模型列表(不包含所有标签组合)var ModelList = []string{"GLM-4.5","GLM-4.6","GLM-4.7","GLM-4.7-thinking","GLM-4.7-thinking-search","GLM-4.7-tools","GLM-4.7-tools-thinking","GLM-4.5-V","GLM-4.6-V","GLM-4.6-V-thinking","GLM-4.5-Air",// "0808-360B-DR",}// 解析模型名称,提取基础模型名和标签// 支持 -thinking、-search 和 -tools 标签的任意排列组合func ParseModelName(model string) (baseModel string, enableThinking bool, enableSearch bool, enableTools bool) {enableThinking = falseenableSearch = falseenableTools = falsebaseModel = model// 检查并移除 -thinking、-search 和 -tools 标签(任意顺序)for {if strings.HasSuffix(baseModel, "-thinking") {enableThinking = true32 unmodified linesif target, ok := BaseModelMapping[baseModel]; ok {return target}// Fallback: unknown models default to glm-4.7return "glm-4.7"}1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839401 unmodified line424344454647484950515253545556575859606162636465666768697071727374757677787932 unmodified lines1121131141151161 unmodified lineimport "strings"// 基础模型映射(key 全部小写,不包含标签后缀)var BaseModelMapping = map[string]string{"glm-4.5": "0727-360B-API","glm-4.6": "GLM-4-6-API-V1","glm-4.7": "glm-4.7","glm-5": "glm-5","glm-4.5-v": "glm-4.5v","glm-4.6-v": "glm-4.6v","glm-4.5-air": "0727-106B-API","0808-360b-dr": "0808-360B-DR",}// Claude 模型名到 GLM 基础模型名的映射var ClaudeModelMapping = map[string]string{"claude-opus-4-6": "glm-4.7","claude-opus-4-5-20250514": "glm-4.7","claude-sonnet-4-6": "glm-4.7","claude-sonnet-4-5-20241022": "glm-4.7","claude-haiku-4-5": "glm-4.5-air","claude-haiku-4-5-20251001": "glm-4.5-air","claude-3-5-sonnet-20241022": "glm-4.7","claude-3-5-haiku-20241022": "glm-4.5-air",}// ResolveClaudeModel maps a Claude model name to a GLM model name with appropriate tags.func ResolveClaudeModel(model string, thinkingEnabled bool) (resolvedModel string, enableThinking bool) {base, ok := ClaudeModelMapping[strings.ToLower(model)]if !ok {base = "glm-4.7"}enableThinking = thinkingEnabledif strings.Contains(strings.ToLower(model), "opus") {enableThinking = true}1 unmodified lineif enableThinking {resolvedModel += "-thinking"}resolvedModel += "-tools"return resolvedModel, enableThinking}// v1/models 返回的模型列表(全部小写)var ModelList = []string{"glm-4.5","glm-4.6","glm-4.7","glm-4.7-thinking","glm-4.7-thinking-search","glm-4.7-tools","glm-4.7-tools-thinking","glm-5","glm-5-thinking","glm-5-thinking-search","glm-5-tools","glm-5-tools-thinking","glm-4.5-v","glm-4.6-v","glm-4.6-v-thinking","glm-4.5-air",}// 解析模型名称,提取基础模型名和标签// 输入大小写不敏感,输出的 baseModel 为小写func ParseModelName(model string) (baseModel string, enableThinking bool, enableSearch bool, enableTools bool) {enableThinking = falseenableSearch = falseenableTools = falsebaseModel = strings.ToLower(model)for {if strings.HasSuffix(baseModel, "-thinking") {enableThinking = true32 unmodified linesif target, ok := BaseModelMapping[baseModel]; ok {return target}return "glm-4.7"}
5 unmodified lines6789101112131415161718192021226 unmodified lines293031323334356 unmodified lines424344454647486 unmodified lines555657585960616 unmodified lines686970717273746 unmodified lines818283848586876 unmodified lines9495969798991003 unmodified lines1041051061071081091101 unmodified line1121131141151161171181191201211221231241251264 unmodified lines1311321331341351361371381393 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731744 unmodified lines1791801811821831841851861871881891905 unmodified linesfunc TestParseModelName_Plain(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7")if base != "GLM-4.7" {t.Errorf("base = %q, want %q", base, "GLM-4.7")}if thinking || search || tools {t.Errorf("flags = (%v, %v, %v), want all false", thinking, search, tools)}}func TestParseModelName_Thinking(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-thinking")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !thinking {6 unmodified linesfunc TestParseModelName_Search(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-search")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !search {6 unmodified linesfunc TestParseModelName_Tools(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !tools {6 unmodified linesfunc TestParseModelName_ThinkingSearch(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-thinking-search")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !thinking || !search {6 unmodified linesfunc TestParseModelName_ToolsThinking(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-thinking")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !tools || !thinking {6 unmodified linesfunc TestParseModelName_ToolsSearch(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-search")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !tools || !search {6 unmodified linesfunc TestParseModelName_AllTags(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-thinking-search")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !thinking || !search || !tools {3 unmodified linesfunc TestParseModelName_ReverseOrder(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-search-thinking-tools")if base != "GLM-4.7" {t.Errorf("base = %q", base)}if !thinking || !search || !tools {1 unmodified line}}// ===== IsToolsModel =====func TestIsToolsModel_True(t *testing.T) {tests := []string{"GLM-4.7-tools","GLM-4.7-tools-thinking","GLM-4.7-tools-search","GLM-4.7-thinking-tools","GLM-4.5-tools",}for _, m := range tests {if !IsToolsModel(m) {4 unmodified linesfunc TestIsToolsModel_False(t *testing.T) {tests := []string{"GLM-4.7","GLM-4.7-thinking","GLM-4.7-search","GLM-4.7-thinking-search",}for _, m := range tests {3 unmodified lines}}// ===== IsThinkingModel / IsSearchModel 不受 -tools 影响 =====func TestIsThinkingModel_WithTools(t *testing.T) {if !IsThinkingModel("GLM-4.7-tools-thinking") {t.Error("IsThinkingModel should be true for GLM-4.7-tools-thinking")}if IsThinkingModel("GLM-4.7-tools") {t.Error("IsThinkingModel should be false for GLM-4.7-tools")}}func TestIsSearchModel_WithTools(t *testing.T) {if !IsSearchModel("GLM-4.7-tools-search") {t.Error("IsSearchModel should be true for GLM-4.7-tools-search")}if IsSearchModel("GLM-4.7-tools") {t.Error("IsSearchModel should be false for GLM-4.7-tools")}}// ===== GetTargetModel with -tools =====func TestGetTargetModel_WithTools(t *testing.T) {target := GetTargetModel("GLM-4.7-tools")if target != "glm-4.7" {t.Errorf("GetTargetModel(GLM-4.7-tools) = %q, want %q", target, "glm-4.7")}}4 unmodified lines}}// ===== ModelList 包含 -tools 变体 =====func TestModelList_ContainsToolsVariants(t *testing.T) {expected := map[string]bool{"GLM-4.7-tools": false,"GLM-4.7-tools-thinking": false,}for _, m := range ModelList {5 unmodified lines678910111213141516171819202122232425262728293031326 unmodified lines394041424344456 unmodified lines525354555657586 unmodified lines656667686970716 unmodified lines787980818283846 unmodified lines919293949596976 unmodified lines1041051061071081091103 unmodified lines1141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621634 unmodified lines1681691701711721731741751763 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102114 unmodified lines2162172182192202212222232242252262272282295 unmodified linesfunc TestParseModelName_Plain(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7")if base != "glm-4.7" {t.Errorf("base = %q, want %q", base, "glm-4.7")}if thinking || search || tools {t.Errorf("flags = (%v, %v, %v), want all false", thinking, search, tools)}}func TestParseModelName_Lowercase(t *testing.T) {base, thinking, _, _ := ParseModelName("glm-4.7-thinking")if base != "glm-4.7" {t.Errorf("base = %q, want %q", base, "glm-4.7")}if !thinking {t.Error("thinking should be true")}}func TestParseModelName_Thinking(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-thinking")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !thinking {6 unmodified linesfunc TestParseModelName_Search(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-search")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !search {6 unmodified linesfunc TestParseModelName_Tools(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !tools {6 unmodified linesfunc TestParseModelName_ThinkingSearch(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-thinking-search")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !thinking || !search {6 unmodified linesfunc TestParseModelName_ToolsThinking(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-thinking")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !tools || !thinking {6 unmodified linesfunc TestParseModelName_ToolsSearch(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-search")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !tools || !search {6 unmodified linesfunc TestParseModelName_AllTags(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-tools-thinking-search")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !thinking || !search || !tools {3 unmodified linesfunc TestParseModelName_ReverseOrder(t *testing.T) {base, thinking, search, tools := ParseModelName("GLM-4.7-search-thinking-tools")if base != "glm-4.7" {t.Errorf("base = %q", base)}if !thinking || !search || !tools {1 unmodified line}}// ===== GLM-5 =====func TestParseModelName_GLM5(t *testing.T) {base, thinking, _, _ := ParseModelName("glm-5")if base != "glm-5" {t.Errorf("base = %q, want %q", base, "glm-5")}if thinking {t.Error("thinking should be false")}}func TestGetTargetModel_GLM5(t *testing.T) {target := GetTargetModel("glm-5")if target != "glm-5" {t.Errorf("GetTargetModel(glm-5) = %q, want %q", target, "glm-5")}}func TestGetTargetModel_GLM5Thinking(t *testing.T) {target := GetTargetModel("glm-5-thinking")if target != "glm-5" {t.Errorf("GetTargetModel(glm-5-thinking) = %q, want %q", target, "glm-5")}}// ===== IsToolsModel =====func TestIsToolsModel_True(t *testing.T) {tests := []string{"glm-4.7-tools","GLM-4.7-tools-thinking","glm-4.7-tools-search","GLM-4.7-thinking-tools","glm-4.5-tools","glm-5-tools",}for _, m := range tests {if !IsToolsModel(m) {4 unmodified linesfunc TestIsToolsModel_False(t *testing.T) {tests := []string{"glm-4.7","GLM-4.7-thinking","glm-4.7-search","GLM-4.7-thinking-search",}for _, m := range tests {3 unmodified lines}}// ===== IsThinkingModel / IsSearchModel =====func TestIsThinkingModel_WithTools(t *testing.T) {if !IsThinkingModel("glm-4.7-tools-thinking") {t.Error("IsThinkingModel should be true for glm-4.7-tools-thinking")}if IsThinkingModel("glm-4.7-tools") {t.Error("IsThinkingModel should be false for glm-4.7-tools")}}func TestIsSearchModel_WithTools(t *testing.T) {if !IsSearchModel("glm-4.7-tools-search") {t.Error("IsSearchModel should be true for glm-4.7-tools-search")}if IsSearchModel("glm-4.7-tools") {t.Error("IsSearchModel should be false for glm-4.7-tools")}}// ===== GetTargetModel =====func TestGetTargetModel_WithTools(t *testing.T) {target := GetTargetModel("glm-4.7-tools")if target != "glm-4.7" {t.Errorf("GetTargetModel(glm-4.7-tools) = %q, want %q", target, "glm-4.7")}}4 unmodified lines}}// ===== ModelList =====func TestModelList_ContainsToolsVariants(t *testing.T) {expected := map[string]bool{"glm-4.7-tools": false,"glm-4.7-tools-thinking": false,"glm-5": false,"glm-5-tools": false,}for _, m := range ModelList {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120package proxy
import ( "bufio" "context" "fmt" "math/rand" "net" "net/http" "os" "strings" "sync"
"golang.org/x/net/proxy"
"zai-proxy/internal/logger")
var ( proxies []string mu sync.RWMutex)
// LoadProxies 从 proxies.txt 文件加载代理列表// 格式: ip:port:username:password 或 ip:portfunc LoadProxies(path string) { file, err := os.Open(path) if err != nil { logger.LogInfo("No proxies.txt found, running without proxy") return } defer file.Close()
var loaded []string scanner := bufio.NewScanner(file) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } loaded = append(loaded, line) }
mu.Lock() proxies = loaded mu.Unlock()
logger.LogInfo("Loaded %d proxies from %s", len(loaded), path)}
type proxyInfo struct { addr string username string password string}
// getRandomProxyInfo 随机返回一个代理信息func getRandomProxyInfo() *proxyInfo { mu.RLock() defer mu.RUnlock()
if len(proxies) == 0 { return nil }
line := proxies[rand.Intn(len(proxies))] parts := strings.Split(line, ":")
switch len(parts) { case 2: return &proxyInfo{addr: fmt.Sprintf("%s:%s", parts[0], parts[1])} case 4: return &proxyInfo{ addr: fmt.Sprintf("%s:%s", parts[0], parts[1]), username: parts[2], password: parts[3], } default: logger.LogWarn("Invalid proxy format: %s", line) return nil }}
// GetHTTPClient 返回一个配置了随机 SOCKS5 代理的 http.Clientfunc GetHTTPClient() *http.Client { info := getRandomProxyInfo() if info == nil { return &http.Client{} }
logger.LogDebug("Using SOCKS5 proxy: %s", info.addr)
var auth *proxy.Auth if info.username != "" { auth = &proxy.Auth{ User: info.username, Password: info.password, } }
dialer, err := proxy.SOCKS5("tcp", info.addr, auth, proxy.Direct) if err != nil { logger.LogWarn("Failed to create SOCKS5 dialer: %v", err) return &http.Client{} }
contextDialer, ok := dialer.(proxy.ContextDialer) if !ok { logger.LogWarn("SOCKS5 dialer does not support ContextDialer") return &http.Client{} }
return &http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return contextDialer.DialContext(ctx, network, addr) }, }, }}13 unmodified lines141516171819223 unmodified lines24324424524624724824913 unmodified lines"zai-proxy/internal/auth""zai-proxy/internal/logger""zai-proxy/internal/model"builtintools "zai-proxy/internal/tools""zai-proxy/internal/version")223 unmodified linesreq.Header.Set("Referer", fmt.Sprintf("https://chat.z.ai/c/%s", uuid.New().String()))req.Header.Set("User-Agent", uarand.GetRandom())client := &http.Client{}resp, err := client.Do(req)if err != nil {return nil, "", err13 unmodified lines14151617181920223 unmodified lines24424524624724824925013 unmodified lines"zai-proxy/internal/auth""zai-proxy/internal/logger""zai-proxy/internal/model""zai-proxy/internal/proxy"builtintools "zai-proxy/internal/tools""zai-proxy/internal/version")223 unmodified linesreq.Header.Set("Referer", fmt.Sprintf("https://chat.z.ai/c/%s", uuid.New().String()))req.Header.Set("User-Agent", uarand.GetRandom())client := proxy.GetHTTPClient()resp, err := client.Do(req)if err != nil {return nil, "", err
13 unmodified lines14151617181967 unmodified lines8788899091929350 unmodified lines14414514614714814915013 unmodified lines"github.com/google/uuid""zai-proxy/internal/logger")// FileUploadResponse z.ai 文件上传响应67 unmodified linesfilename = uuid.New().String()[:12] + ext} else {// 从 URL 下载图片resp, err := http.Get(imageURL)if err != nil {return nil, fmt.Errorf("failed to download image: %v", err)}50 unmodified linesreq.Header.Set("Origin", "https://chat.z.ai")req.Header.Set("Referer", "https://chat.z.ai/")client := &http.Client{}resp, err := client.Do(req)if err != nil {return nil, fmt.Errorf("failed to upload image: %v", err)13 unmodified lines1415161718192067 unmodified lines8889909192939450 unmodified lines14514614714814915015113 unmodified lines"github.com/google/uuid""zai-proxy/internal/logger""zai-proxy/internal/proxy")// FileUploadResponse z.ai 文件上传响应67 unmodified linesfilename = uuid.New().String()[:12] + ext} else {// 从 URL 下载图片resp, err := proxy.GetHTTPClient().Get(imageURL)if err != nil {return nil, fmt.Errorf("failed to download image: %v", err)}50 unmodified linesreq.Header.Set("Origin", "https://chat.z.ai")req.Header.Set("Referer", "https://chat.z.ai/")client := proxy.GetHTTPClient()resp, err := client.Do(req)if err != nil {return nil, fmt.Errorf("failed to upload image: %v", err)
1 unmodified line23456789101112138 unmodified lines2223242526272817 unmodified lines464748495051525354551 unmodified lineimport ("io""net/http""regexp""sync""time""zai-proxy/internal/logger")var (8 unmodified lines}func fetchFeVersion() {resp, err := http.Get("https://chat.z.ai/")if err != nil {logger.LogError("Failed to fetch fe version: %v", err)return17 unmodified lines}func StartVersionUpdater() {fetchFeVersion()ticker := time.NewTicker(1 * time.Hour)go func() {for range ticker.C {fetchFeVersion()}1 unmodified line23456789101112138 unmodified lines2223242526272817 unmodified lines4647484950515253541 unmodified lineimport ("io""regexp""sync""time""zai-proxy/internal/logger""zai-proxy/internal/proxy")var (8 unmodified lines}func fetchFeVersion() {resp, err := proxy.GetHTTPClient().Get("https://chat.z.ai/")if err != nil {logger.LogError("Failed to fetch fe version: %v", err)return17 unmodified lines}func StartVersionUpdater() {go func() {fetchFeVersion()ticker := time.NewTicker(1 * time.Hour)for range ticker.C {fetchFeVersion()}
5 unmodified lines678910111213141516175 unmodified lines"zai-proxy/internal/config""zai-proxy/internal/handler""zai-proxy/internal/logger""zai-proxy/internal/version")func main() {config.LoadConfig()logger.InitLogger()version.StartVersionUpdater()http.HandleFunc("/v1/models", handler.HandleModels)5 unmodified lines6789101112131415161718195 unmodified lines"zai-proxy/internal/config""zai-proxy/internal/handler""zai-proxy/internal/logger""zai-proxy/internal/proxy""zai-proxy/internal/version")func main() {config.LoadConfig()logger.InitLogger()proxy.LoadProxies("proxies.txt")version.StartVersionUpdater()http.HandleFunc("/v1/models", handler.HandleModels)
.github/workflows/docker-image.yml+1-1
.gitignore+2
Dockerfile+3
README.md+52-27
go.mod+3-3
go.sum+10
internal/auth/anonymous.go+3-1
internal/model/mapping.go+39-40
internal/model/mapping_test.go+69-30
internal/proxy/pool.goAdded+120
internal/upstream/client.go+2-1
internal/upstream/upload.go+3-2
internal/version/version.go+4-5
main.go+2