Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/unreleased/custom-endpoint-provider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Add a Custom API provider: one account is one endpoint (base URL + key), with OpenAI Chat Completions, Anthropic Messages, or Responses as the upstream wire and no reverse proxy.
- Custom endpoints get their catalog from `/models` or a manual model list, and their models are routed as `custom/<model>`.

### 中文

- 新增「自定义 API」供应商:一个账号就是一个端点(Base URL + 密钥),上游协议可选 OpenAI Chat Completions、Anthropic Messages 或 Responses,直连不走反代。
- 自定义端点按 `/models` 或手填列表生成 catalog,模型按 `custom/<model>` 路由。
244 changes: 244 additions & 0 deletions internal/providers/custom/catalog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
package custom

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"

"github.com/caigee-cmd/cli2api/internal/providers"
)

// CatalogEntry is one model from GET {base}/models. OpenAI, Anthropic, and most
// compatible gateways share the standard data[].id envelope.
type CatalogEntry struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
Object string `json:"object"`
}

type catalogEnvelope struct {
Data []CatalogEntry `json:"data"`
}

const catalogTTL = 30 * time.Minute

// ParseCatalogJSON maps the upstream model list onto ModelInfo. Public and
// native ids stay equal; the control plane adds the custom/ route prefix.
func ParseCatalogJSON(raw []byte) ([]providers.ModelInfo, error) {
var entries []CatalogEntry
var envelope catalogEnvelope
if err := json.Unmarshal(raw, &envelope); err == nil && len(envelope.Data) > 0 {
entries = envelope.Data
} else {
var bare []CatalogEntry
if err := json.Unmarshal(raw, &bare); err != nil {
return nil, fmt.Errorf("custom catalog: %w", err)
}
entries = bare
}
if len(entries) == 0 {
return nil, fmt.Errorf("custom catalog empty")
}
models := make([]providers.ModelInfo, 0, len(entries))
seen := map[string]struct{}{}
for _, entry := range entries {
id := strings.TrimSpace(entry.ID)
if id == "" {
continue
}
if _, dup := seen[strings.ToLower(id)]; dup {
continue
}
seen[strings.ToLower(id)] = struct{}{}
display := strings.TrimSpace(entry.DisplayName)
if display == "" {
display = id
}
models = append(models, providers.ModelInfo{
NativeModel: id,
PublicModel: id,
DisplayName: display,
Capabilities: modelCapabilities(),
})
}
if len(models) == 0 {
return nil, fmt.Errorf("custom catalog produced no models")
}
return models, nil
}

// modelCapabilities declares only what a generic endpoint certainly supports
// once it serves chat: tools and image parts ride the same request body. The
// endpoint's reasoning dialect is unknown, so no effort levels are invented.
func modelCapabilities() providers.ModelCapabilities {
return providers.ModelCapabilities{Tools: true, Images: true}
}

func manualModels(credential Credential) []providers.ModelInfo {
models := make([]providers.ModelInfo, 0, len(credential.Models))
for _, id := range NormalizeModels(credential.Models) {
models = append(models, providers.ModelInfo{
NativeModel: id,
PublicModel: id,
DisplayName: id,
Capabilities: modelCapabilities(),
})
}
return models
}

func (c *Client) fetchCatalog(ctx context.Context, accountID string, credential Credential) ([]providers.ModelInfo, error) {
base, err := credential.BaseURLValue()
if err != nil {
return nil, err
}
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 20*time.Second)
defer cancel()
}
client, err := c.httpClient(ctx, accountID)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, joinEndpoint(base, pathModels), nil)
if err != nil {
return nil, err
}
applyAuthHeaders(req.Header, credential, ProtocolOpenAI)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil, err
}
if resp.StatusCode >= 300 {
return nil, newProviderError(resp.StatusCode, string(body))
}
return ParseCatalogJSON(body)
}

// Models implements providers.ModelCatalogProvider. A non-empty manual list is
// authoritative and skips the upstream call, so an endpoint without /models
// still serves a stable catalog. It is rebuilt on every call so an edited
// credential is visible immediately.
func (c *Client) Models(ctx context.Context, accountID string) ([]providers.ModelInfo, error) {
credential, err := c.credential(ctx, accountID)
if err != nil {
return nil, err
}
if manual := manualModels(credential); len(manual) > 0 {
return manual, nil
}
if models, ok := c.cachedModels(accountID, time.Now()); ok {
return models, nil
}
models, err := c.fetchCatalog(ctx, accountID, credential)
if err != nil {
return nil, err
}
c.rememberModels(accountID, models, time.Now())
return cloneModels(models), nil
}

func (c *Client) cachedModels(accountID string, now time.Time) ([]providers.ModelInfo, bool) {
c.mu.Lock()
defer c.mu.Unlock()
entry, ok := c.catalogs[accountID]
if !ok || len(entry.models) == 0 || now.Sub(entry.at) > catalogTTL {
return nil, false
}
return cloneModels(entry.models), true
}

func (c *Client) rememberModels(accountID string, models []providers.ModelInfo, at time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
if c.catalogs == nil {
c.catalogs = map[string]catalogCache{}
}
c.catalogs[accountID] = catalogCache{models: cloneModels(models), at: at}
}

func (c *Client) lookupModel(accountID, model string) (providers.ModelInfo, bool) {
want := strings.ToLower(strings.TrimSpace(model))
if want == "" {
return providers.ModelInfo{}, false
}
c.mu.Lock()
defer c.mu.Unlock()
entry, ok := c.catalogs[accountID]
if !ok {
return providers.ModelInfo{}, false
}
for _, info := range entry.models {
if strings.ToLower(info.NativeModel) == want || strings.ToLower(info.PublicModel) == want {
return info, true
}
}
return providers.ModelInfo{}, false
}

func cloneModels(in []providers.ModelInfo) []providers.ModelInfo {
if len(in) == 0 {
return nil
}
out := make([]providers.ModelInfo, len(in))
copy(out, in)
return out
}

// joinEndpoint appends an OpenAI-style path without doubling a version
// segment. A base ending in /v1 (or /v1beta, /v4) gets the bare path; a bare
// origin gets the /v1 form. A base that already ends in the path is returned
// unchanged.
func joinEndpoint(base, endpoint string) string {
base = strings.TrimRight(strings.TrimSpace(base), "/")
endpoint = "/" + strings.TrimLeft(strings.TrimSpace(endpoint), "/")
relative := strings.TrimPrefix(endpoint, "/v1")
lower := strings.ToLower(base)
if strings.HasSuffix(lower, endpoint) || strings.HasSuffix(lower, relative) {
return base
}
if hasVersionSuffix(lower) {
return base + relative
}
return base + endpoint
}

func hasVersionSuffix(base string) bool {
slash := strings.LastIndex(base, "/")
if slash < 0 || slash == len(base)-1 {
return false
}
segment := base[slash+1:]
if len(segment) < 2 || segment[0] != 'v' {
return false
}
digits := segment[1:]
// Accept v1, v4, and pre-release spellings such as v1beta or v2alpha.
if cut := strings.IndexFunc(digits, func(r rune) bool { return r < '0' || r > '9' }); cut >= 0 {
suffix := strings.ToLower(digits[cut:])
if suffix != "beta" && suffix != "alpha" {
return false
}
digits = digits[:cut]
}
if digits == "" {
return false
}
for _, r := range digits {
if r < '0' || r > '9' {
return false
}
}
return true
}
Loading
Loading