diff --git a/conf/models/zhipu-ai.json b/conf/models/zhipu-ai.json index d1bbac649f..b10f18b5d4 100644 --- a/conf/models/zhipu-ai.json +++ b/conf/models/zhipu-ai.json @@ -9,7 +9,8 @@ "async_result": "async-result", "embedding": "embeddings", "rerank": "rerank", - "files": "files" + "files": "files", + "models": "models" }, "class": "glm", "models": [ diff --git a/internal/entity/models/zhipu-ai.go b/internal/entity/models/zhipu-ai.go index a381105534..742314e4c5 100644 --- a/internal/entity/models/zhipu-ai.go +++ b/internal/entity/models/zhipu-ai.go @@ -456,7 +456,63 @@ func (z *ZhipuAIModel) Embed(modelName *string, texts []string, apiConfig *APICo } func (z *ZhipuAIModel) ListModels(apiConfig *APIConfig) ([]string, error) { - return nil, fmt.Errorf("%s, no such method", z.Name()) + region := "default" + if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { + region = *apiConfig.Region + } + + baseURL := z.BaseURL["default"] + if region != "default" { + if regional, ok := z.BaseURL[region]; ok && regional != "" { + baseURL = regional + } + } + if baseURL == "" { + return nil, fmt.Errorf("zhipu-ai: no base URL configured for default region") + } + + url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), z.URLSuffix.Models) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" { + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) + } + + resp, err := z.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("ZhipuAI models API error: %s, body: %s", resp.Status, string(body)) + } + + var modelList DSModelList + if err = json.Unmarshal(body, &modelList); err != nil { + return nil, fmt.Errorf("failed to parse response: %w", err) + } + + models := make([]string, 0, len(modelList.Models)) + for _, model := range modelList.Models { + modelName := model.ID + if model.OwnedBy != "" { + modelName = model.ID + "@" + model.OwnedBy + } + models = append(models, modelName) + } + + return models, nil } func (z *ZhipuAIModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {