Add upstream model list fetching and a Codex-specific model section

This commit is contained in:
kate522 committed 2026-10-18 19:33:32 +08:00
1 parent d759fe5e5d
commit f3bf1472e7
12 files changed
+339 -16

No files matched your search

+47
View File
@@ -1,10 +1,15 @@
package gateway
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"gitea.rutua.cn/kate522/CrossRelay/internal/chatcmpl"
"gitea.rutua.cn/kate522/CrossRelay/internal/claudecfg"
"gitea.rutua.cn/kate522/CrossRelay/internal/codexcfg"
"gitea.rutua.cn/kate522/CrossRelay/internal/config"
@@ -71,6 +76,48 @@ func (s *Server) handleListProviders(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
type fetchModelsInput struct {
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
}
// handleFetchModels proxies the upstream model catalog so the UI can
// offer a picker without talking to the provider directly.
func (s *Server) handleFetchModels(w http.ResponseWriter, r *http.Request) {
var in fetchModelsInput
if err := decodeJSON(r, &in, 1<<20); err != nil {
writeAPIError(w, http.StatusBadRequest, "invalid request body: "+err.Error())
return
}
in.BaseURL = strings.TrimSpace(in.BaseURL)
in.APIKey = strings.TrimSpace(in.APIKey)
if in.BaseURL == "" || in.APIKey == "" {
writeAPIError(w, http.StatusBadRequest, "base URL and API key are required")
return
}
if u, err := url.Parse(in.BaseURL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
writeAPIError(w, http.StatusBadRequest, "base URL must be an http(s) URL")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
list, err := chatcmpl.NewClient(in.BaseURL, in.APIKey).ListModels(ctx)
if err != nil {
var ue *chatcmpl.UpstreamError
if errors.As(err, &ue) {
writeAPIError(w, http.StatusBadGateway, fmt.Sprintf("upstream %d: %s", ue.StatusCode, ue.Message))
return
}
writeAPIError(w, http.StatusBadGateway, fmt.Sprintf("upstream request failed: %v", err))
return
}
items := []chatcmpl.ModelInfo{}
if list != nil {
items = list.Data
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
func (s *Server) handleCreateProvider(w http.ResponseWriter, r *http.Request) {
var in providerInput
if err := decodeJSON(r, &in, 1<<20); err != nil {