feat(api): align provider creation with presets/custom/google sdk

This commit is contained in:
zenfun
2025-12-17 22:19:17 +08:00
parent 174735f152
commit 2b0ed3d3d5
5 changed files with 214 additions and 10 deletions

View File

@@ -169,6 +169,7 @@ func main() {
adminGroup.POST("/providers", handler.CreateProvider)
adminGroup.POST("/providers/preset", handler.CreateProviderPreset)
adminGroup.POST("/providers/custom", handler.CreateProviderCustom)
adminGroup.POST("/providers/google", handler.CreateProviderGoogle)
adminGroup.PUT("/providers/:id", handler.UpdateProvider)
adminGroup.POST("/models", handler.CreateModel)
adminGroup.GET("/models", handler.ListModels)

View File

@@ -46,6 +46,7 @@ func (h *Handler) CreateProvider(c *gin.Context) {
}
providerType := provider.NormalizeType(req.Type)
baseURL := strings.TrimSpace(req.BaseURL)
googleLocation := provider.DefaultGoogleLocation(providerType, req.GoogleLocation)
group := strings.TrimSpace(req.Group)
@@ -62,10 +63,37 @@ func (h *Handler) CreateProvider(c *gin.Context) {
autoBan = *req.AutoBan
}
// CP-side defaults + validation to prevent DP runtime errors.
switch providerType {
case provider.TypeOpenAI:
if baseURL == "" {
baseURL = "https://api.openai.com/v1"
}
case provider.TypeAnthropic, provider.TypeClaude:
if baseURL == "" {
baseURL = "https://api.anthropic.com"
}
case provider.TypeCompatible:
if baseURL == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "base_url required for compatible providers"})
return
}
default:
// Google SDK providers: base_url is not required.
if provider.IsVertexFamily(providerType) && strings.TrimSpace(googleLocation) == "" {
googleLocation = provider.DefaultGoogleLocation(providerType, "")
}
// For Gemini API providers, api_key is required.
if provider.IsGoogleFamily(providerType) && !provider.IsVertexFamily(providerType) && strings.TrimSpace(req.APIKey) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "api_key required for gemini api providers"})
return
}
}
provider := model.Provider{
Name: req.Name,
Type: strings.TrimSpace(req.Type),
BaseURL: req.BaseURL,
BaseURL: baseURL,
APIKey: req.APIKey,
GoogleProject: strings.TrimSpace(req.GoogleProject),
GoogleLocation: googleLocation,
@@ -138,6 +166,10 @@ func (h *Handler) UpdateProvider(c *gin.Context) {
nextType = t
}
nextTypeLower := provider.NormalizeType(nextType)
nextBaseURL := strings.TrimSpace(existing.BaseURL)
if strings.TrimSpace(req.BaseURL) != "" {
nextBaseURL = strings.TrimSpace(req.BaseURL)
}
update := map[string]any{}
if strings.TrimSpace(req.Name) != "" {
@@ -186,6 +218,36 @@ func (h *Handler) UpdateProvider(c *gin.Context) {
update["ban_until"] = nil
}
// Defaults/validation after considering intended type/base_url.
switch nextTypeLower {
case provider.TypeOpenAI:
if nextBaseURL == "" {
update["base_url"] = "https://api.openai.com/v1"
}
case provider.TypeAnthropic, provider.TypeClaude:
if nextBaseURL == "" {
update["base_url"] = "https://api.anthropic.com"
}
case provider.TypeCompatible:
if nextBaseURL == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "base_url required for compatible providers"})
return
}
default:
if provider.IsGoogleFamily(nextTypeLower) && !provider.IsVertexFamily(nextTypeLower) {
// Ensure Gemini API providers have api_key.
// If update does not include api_key, keep existing; otherwise require new one not empty.
apiKey := existing.APIKey
if req.APIKey != "" {
apiKey = req.APIKey
}
if strings.TrimSpace(apiKey) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "api_key required for gemini api providers"})
return
}
}
}
if len(update) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "no fields to update"})
return

View File

@@ -15,7 +15,7 @@ import (
// CreateProviderPreset godoc
// @Summary Create a preset provider
// @Description Create an official OpenAI/Anthropic/Gemini provider (only api_key is typically required)
// @Description Create an official OpenAI/Anthropic provider (only api_key is typically required)
// @Tags admin
// @Accept json
// @Produce json
@@ -43,16 +43,12 @@ func (h *Handler) CreateProviderPreset(c *gin.Context) {
switch preset {
case providerx.TypeOpenAI:
providerType = providerx.TypeOpenAI
baseURL = "https://api.openai.com"
baseURL = "https://api.openai.com/v1"
case providerx.TypeAnthropic, providerx.TypeClaude:
providerType = providerx.TypeAnthropic
baseURL = "https://api.anthropic.com"
case providerx.TypeGemini, providerx.TypeAIStudio, providerx.TypeGoogle:
// Gemini API / AI Studio (SDK transport). BaseURL is optional but we provide the official endpoint.
providerType = providerx.TypeGemini
baseURL = "https://generativelanguage.googleapis.com"
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported preset: " + preset})
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported preset: " + preset + " (use /admin/providers/google for Google SDK providers)"})
return
}
@@ -108,6 +104,104 @@ func (h *Handler) CreateProviderPreset(c *gin.Context) {
c.JSON(http.StatusCreated, p)
}
// CreateProviderGoogle godoc
// @Summary Create a Google SDK provider
// @Description Create a Google SDK provider (Gemini API key or Vertex project/location); base_url is not used
// @Tags admin
// @Accept json
// @Produce json
// @Security AdminAuth
// @Param provider body dto.ProviderGoogleCreateDTO true "Google provider payload"
// @Success 201 {object} model.Provider
// @Failure 400 {object} gin.H
// @Failure 500 {object} gin.H
// @Router /admin/providers/google [post]
func (h *Handler) CreateProviderGoogle(c *gin.Context) {
var req dto.ProviderGoogleCreateDTO
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
pt := providerx.NormalizeType(req.Type)
if pt == "" {
pt = providerx.TypeGemini
}
if !providerx.IsGoogleFamily(pt) {
c.JSON(http.StatusBadRequest, gin.H{"error": "type must be google family"})
return
}
name := strings.TrimSpace(req.Name)
if name == "" {
name = pt + "-" + randomSuffix(4)
}
group := strings.TrimSpace(req.Group)
if group == "" {
group = "default"
}
status := strings.TrimSpace(req.Status)
if status == "" {
status = "active"
}
autoBan := true
if req.AutoBan != nil {
autoBan = *req.AutoBan
}
// Validate fields by type.
apiKey := strings.TrimSpace(req.APIKey)
googleProject := strings.TrimSpace(req.GoogleProject)
googleLocation := providerx.DefaultGoogleLocation(pt, req.GoogleLocation)
if providerx.IsVertexFamily(pt) {
// Vertex uses ADC and project/location; api_key is not required.
if strings.TrimSpace(googleLocation) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "google_location required"})
return
}
apiKey = ""
} else {
// Gemini API requires api_key.
if apiKey == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "api_key required for gemini api"})
return
}
googleProject = ""
googleLocation = ""
}
p := model.Provider{
Name: name,
Type: pt,
BaseURL: "", // intentionally unused for Google SDK
APIKey: apiKey,
GoogleProject: googleProject,
GoogleLocation: googleLocation,
Group: groupx.Normalize(group),
Models: strings.Join(req.Models, ","),
Status: status,
AutoBan: autoBan,
}
if req.Weight > 0 {
p.Weight = req.Weight
}
if err := h.db.Create(&p).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create provider", "details": err.Error()})
return
}
if err := h.sync.SyncProvider(&p); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to sync provider", "details": err.Error()})
return
}
if err := h.sync.SyncBindings(h.db); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to sync bindings", "details": err.Error()})
return
}
c.JSON(http.StatusCreated, p)
}
// CreateProviderCustom godoc
// @Summary Create a custom provider
// @Description Create an OpenAI-compatible provider (base_url + api_key required)

View File

@@ -39,8 +39,8 @@ func TestCreateProviderPreset_OpenAI_SetsBaseURL(t *testing.T) {
if got.Type != "openai" {
t.Fatalf("expected type openai, got %q", got.Type)
}
if got.BaseURL != "https://api.openai.com" {
t.Fatalf("expected base_url=https://api.openai.com, got %q", got.BaseURL)
if got.BaseURL != "https://api.openai.com/v1" {
t.Fatalf("expected base_url=https://api.openai.com/v1, got %q", got.BaseURL)
}
if got.Name == "" {
t.Fatalf("expected generated name")
@@ -68,3 +68,25 @@ func TestCreateProviderCustom_RequiresBaseURL(t *testing.T) {
t.Fatalf("expected 400, got %d body=%s", rr.Code, rr.Body.String())
}
}
func TestCreateProviderGoogle_GeminiRequiresAPIKey(t *testing.T) {
h, _ := newTestHandler(t)
r := gin.New()
r.POST("/admin/providers/google", h.CreateProviderGoogle)
reqBody := map[string]any{
"type": "gemini",
"models": []string{"gemini-2.0-flash"},
}
b, _ := json.Marshal(reqBody)
req := httptest.NewRequest(http.MethodPost, "/admin/providers/google", bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
r.ServeHTTP(rr, req)
if rr.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d body=%s", rr.Code, rr.Body.String())
}
}

View File

@@ -33,3 +33,28 @@ type ProviderCustomCreateDTO struct {
Weight int `json:"weight,omitempty"`
AutoBan *bool `json:"auto_ban,omitempty"`
}
// ProviderGoogleCreateDTO creates a Google SDK provider (Gemini API or Vertex).
// It intentionally does not require base_url.
type ProviderGoogleCreateDTO struct {
// Type must be a Google-family provider type, e.g.:
// - gemini/google/aistudio (Gemini API)
// - vertex/vertex-express (Vertex)
Type string `json:"type"`
// Optional fields.
Name string `json:"name"`
Group string `json:"group"`
Models []string `json:"models"`
// Gemini API
APIKey string `json:"api_key,omitempty"`
// Vertex
GoogleProject string `json:"google_project,omitempty"`
GoogleLocation string `json:"google_location,omitempty"`
Status string `json:"status"`
Weight int `json:"weight,omitempty"`
AutoBan *bool `json:"auto_ban,omitempty"`
}