diff --git a/changelog/unreleased/custom-endpoint-provider.md b/changelog/unreleased/custom-endpoint-provider.md new file mode 100644 index 000000000..e737fc4a9 --- /dev/null +++ b/changelog/unreleased/custom-endpoint-provider.md @@ -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/`. + +### 中文 + +- 新增「自定义 API」供应商:一个账号就是一个端点(Base URL + 密钥),上游协议可选 OpenAI Chat Completions、Anthropic Messages 或 Responses,直连不走反代。 +- 自定义端点按 `/models` 或手填列表生成 catalog,模型按 `custom/` 路由。 diff --git a/internal/providers/custom/catalog.go b/internal/providers/custom/catalog.go new file mode 100644 index 000000000..e2c5a92e9 --- /dev/null +++ b/internal/providers/custom/catalog.go @@ -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 +} diff --git a/internal/providers/custom/chat.go b/internal/providers/custom/chat.go new file mode 100644 index 000000000..bd7193d8b --- /dev/null +++ b/internal/providers/custom/chat.go @@ -0,0 +1,242 @@ +package custom + +import ( + "bytes" + "context" + "io" + "net/http" + "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// ChatStream sends the request to the account's endpoint and returns an +// OpenAI chat-completions SSE body. Anthropic and Responses upstreams are +// translated on the fly, so one gateway dialect reaches every client. +func (c *Client) ChatStream(ctx context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + upstream, protocol, model, err := c.doChat(ctx, accountID, req) + if err != nil { + return nil, providers.ResolvedChat{}, err + } + if protocol == translate.UpstreamOpenAI { + normalized, err := ensureChatSSE(upstream, model) + if err != nil { + return nil, providers.ResolvedChat{}, err + } + return normalized, providers.ResolvedChat{}, nil + } + pr, pw := io.Pipe() + go func() { + defer upstream.Body.Close() + defer pw.Close() + if err := translate.RelayUpstreamStream(pw, upstream.Body, protocol, model); err != nil { + _ = pw.CloseWithError(err) + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "Cache-Control": []string{"no-cache"}}, + Body: pr, + ContentLength: -1, + Request: upstream.Request, + }, providers.ResolvedChat{}, nil +} + +// ChatNonStream forces a stream and collects it, so usage and tool-call +// assembly share one path across all three upstream protocols. +func (c *Client) ChatNonStream(ctx context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + upstream, protocol, model, err := c.doChat(ctx, accountID, req) + if err != nil { + return providers.ChatOutcome{}, err + } + var reader io.Reader + if protocol == translate.UpstreamOpenAI { + normalized, err := ensureChatSSE(upstream, model) + if err != nil { + return providers.ChatOutcome{}, err + } + defer normalized.Body.Close() + reader = normalized.Body + } else { + defer upstream.Body.Close() + pr, pw := io.Pipe() + go func() { + defer pw.Close() + if err := translate.RelayUpstreamStream(pw, upstream.Body, protocol, model); err != nil { + _ = pw.CloseWithError(err) + } + }() + defer pr.Close() + reader = pr + } + outcome, err := collectChatSSE(reader, model) + if err != nil { + return providers.ChatOutcome{}, err + } + outcome.UsageSource = "upstream" + return outcome, nil +} + +func (c *Client) doChat(ctx context.Context, accountID string, req translate.ChatRequest) (*http.Response, translate.UpstreamProtocol, string, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return nil, "", "", err + } + model := strings.TrimSpace(req.Model) + if model == "" { + if known, ok := c.onlyModel(accountID); ok { + model = known + } + } + if model == "" { + return nil, "", "", newProviderError(400, "custom model is required") + } + protocol, upstreamModel, err := resolveRoute(credential, model) + if err != nil { + return nil, "", "", err + } + payload, err := translate.BuildUpstreamBody(protocol, req, upstreamModel) + if err != nil { + return nil, "", "", err + } + base, err := credential.BaseURLValue() + if err != nil { + return nil, "", "", err + } + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, joinEndpoint(base, endpointPath(protocol)), bytes.NewReader(payload)) + if err != nil { + return nil, "", "", err + } + applyAuthHeaders(httpReq.Header, credential, protocol) + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Accept", "text/event-stream, application/json") + httpReq.Header.Set("User-Agent", UserAgent) + client, err := c.httpClient(ctx, accountID) + if err != nil { + return nil, "", "", err + } + resp, err := client.Do(httpReq) + if err != nil { + return nil, "", "", &providers.Error{Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: err.Error()} + } + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + return nil, "", "", newProviderError(resp.StatusCode, string(body)) + } + return resp, protocol, upstreamModel, nil +} + +// onlyModel keeps a chat working when the caller sent no model, but only +// when a manual catalog names exactly one. +func (c *Client) onlyModel(accountID string) (string, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.catalogs[accountID] + if !ok || len(entry.models) != 1 { + return "", false + } + return entry.models[0].NativeModel, true +} + +func endpointPath(protocol translate.UpstreamProtocol) string { + switch protocol { + case translate.UpstreamAnthropic: + return pathMessages + case translate.UpstreamResponses: + return pathResponses + default: + return pathChat + } +} + +// resolveRoute returns the wire and the upstream model id. An explicit +// protocol forwards the id untouched. In auto mode a prefix +// (anthropic/, responses/, openai/) picks the wire and is stripped, so one +// endpoint can mix dialects. +func resolveRoute(credential Credential, model string) (translate.UpstreamProtocol, string, error) { + id := stripProviderPrefix(model) + protocol, err := NormalizeProtocol(credential.Protocol) + if err != nil { + return "", "", err + } + if protocol == ProtocolAuto { + lower := strings.ToLower(id) + protocol = ProtocolOpenAI + for _, prefix := range []string{ProtocolAnthropic, ProtocolResponses, ProtocolOpenAI} { + if strings.HasPrefix(lower, prefix+"/") { + protocol = prefix + id = strings.TrimSpace(id[len(prefix)+1:]) + break + } + } + } + if strings.TrimSpace(id) == "" { + return "", "", newProviderError(400, "custom model is required") + } + switch protocol { + case ProtocolAnthropic: + return translate.UpstreamAnthropic, id, nil + case ProtocolResponses: + return translate.UpstreamResponses, id, nil + default: + return translate.UpstreamOpenAI, id, nil + } +} + +func stripProviderPrefix(model string) string { + trimmed := strings.TrimSpace(model) + lower := strings.ToLower(trimmed) + for _, prefix := range []string{"custom/", "custom-api/", "custom/auto/"} { + if strings.HasPrefix(lower, prefix) { + return strings.TrimSpace(trimmed[len(prefix):]) + } + } + return trimmed +} + +func applyAuthHeaders(header http.Header, credential Credential, protocol translate.UpstreamProtocol) { + key := strings.TrimSpace(credential.APIKey) + if key == "" { + return + } + header.Set("Authorization", "Bearer "+key) + if protocol == translate.UpstreamAnthropic { + header.Set(headerAPIKey, key) + header.Set(headerAnthropicVersion, anthropicVersion) + } +} + +// ensureChatSSE turns a non-streaming Chat Completions JSON body into the SSE +// dialect the gateway relays. An upstream event stream is returned as-is. +func ensureChatSSE(resp *http.Response, model string) (*http.Response, error) { + if resp == nil { + return nil, newProviderError(502, "custom upstream returned no response") + } + ctype := strings.ToLower(resp.Header.Get("Content-Type")) + if strings.Contains(ctype, "text/event-stream") { + return resp, nil + } + raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + resp.Body.Close() + if err != nil { + return nil, err + } + trimmed := strings.TrimSpace(string(raw)) + if strings.HasPrefix(trimmed, "data:") { + resp.Body = io.NopCloser(strings.NewReader(trimmed + "\n")) + resp.Header.Set("Content-Type", "text/event-stream") + return resp, nil + } + sse, err := jsonCompletionToSSE(raw, model) + if err != nil { + return nil, err + } + resp.Body = io.NopCloser(bytes.NewReader(sse)) + resp.Header.Set("Content-Type", "text/event-stream") + resp.ContentLength = -1 + return resp, nil +} diff --git a/internal/providers/custom/client.go b/internal/providers/custom/client.go new file mode 100644 index 000000000..c67390c53 --- /dev/null +++ b/internal/providers/custom/client.go @@ -0,0 +1,174 @@ +package custom + +import ( + "context" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + proxyutil "github.com/caigee-cmd/cli2api/internal/proxy" +) + +// Store is the persistence surface this adapter needs. It never imports +// internal/store. +type Store interface { + Get(ctx context.Context, id string) (accounts.Account, error) + LoadCredentialPayload(ctx context.Context, accountID string) (string, []byte, error) + SaveCredentialPayload(ctx context.Context, accountID, format string, payload []byte) error + Observe(ctx context.Context, id, remoteUID, status, lastError, lastKind string) error +} + +// SecretReader is optional. Missing it means no global proxy. +type SecretReader interface { + GetSecret(context.Context, string) (string, bool, error) +} + +type catalogCache struct { + models []providers.ModelInfo + at time.Time +} + +// Client is the in-process generic endpoint adapter. One client serves every +// account; credentials and catalogs stay keyed by account id, because each +// account is its own base URL and key. +type Client struct { + store Store + http *http.Client + + transports proxyutil.TransportCache + + mu sync.Mutex + catalogs map[string]catalogCache +} + +func NewClient(store Store) *Client { + return &Client{ + store: store, + http: &http.Client{ + Timeout: 0, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + }, + catalogs: map[string]catalogCache{}, + } +} + +func (c *Client) globalProxy(ctx context.Context) (string, error) { + store, ok := c.store.(SecretReader) + if !ok { + return "", nil + } + value, found, err := store.GetSecret(ctx, "proxy_url") + if err != nil { + return "", fmt.Errorf("load global proxy setting: %w", err) + } + if !found { + return "", nil + } + return strings.TrimSpace(value), nil +} + +func (c *Client) effectiveProxy(ctx context.Context, accountID string) (string, error) { + if strings.TrimSpace(accountID) == "" { + return c.globalProxy(ctx) + } + account, err := c.store.Get(ctx, accountID) + if err != nil { + return "", err + } + if value := strings.TrimSpace(account.ProxyURL); value != "" { + return value, nil + } + return c.globalProxy(ctx) +} + +func (c *Client) httpClient(ctx context.Context, accountID string) (*http.Client, error) { + rawProxy, err := c.effectiveProxy(ctx, accountID) + if err != nil { + return nil, err + } + client := *c.http + transport, err := c.transports.Get(rawProxy) + if err != nil { + return nil, err + } + if transport != nil { + client.Transport = transport + } + return &client, nil +} + +func (c *Client) credential(ctx context.Context, accountID string) (Credential, error) { + _, payload, err := c.store.LoadCredentialPayload(ctx, accountID) + if err != nil { + return Credential{}, err + } + cred, err := DecodeCredential(payload) + if err != nil { + return Credential{}, err + } + if !cred.Ready() { + return cred, fmt.Errorf("custom credential incomplete; paste a base url") + } + return cred, nil +} + +// Probe checks that the endpoint answers. Endpoints without a /models route +// are still ready when the operator supplied a manual catalog: a 404/405 on +// that display-only route is not evidence the endpoint is down. +func (c *Client) Probe(ctx context.Context, accountID string) (providers.AccountHealth, error) { + credential, err := c.credential(ctx, accountID) + if err != nil { + return providers.AccountHealth{LastError: err.Error()}, nil + } + if _, err := c.fetchCatalog(ctx, accountID, credential); err != nil { + if len(NormalizeModels(credential.Models)) > 0 && catalogMissing(err) { + _ = c.store.Observe(ctx, accountID, "", "ready", "", "") + return providers.AccountHealth{Ready: true, Hot: true}, nil + } + if providerErr, ok := err.(*providers.Error); ok { + return providers.AccountHealth{LastError: providerErr.Message}, nil + } + return providers.AccountHealth{LastError: err.Error()}, nil + } + _ = c.store.Observe(ctx, accountID, "", "ready", "", "") + return providers.AccountHealth{Ready: true, Hot: true}, nil +} + + +func catalogMissing(err error) bool { + providerErr, ok := err.(*providers.Error) + if !ok { + return false + } + return providerErr.Status == http.StatusNotFound || providerErr.Status == http.StatusMethodNotAllowed +} + +// Adapter wires the capability surface. Login is absent: the only auth is a +// pasted base URL and key, exposed through the PAT tab. +func (c *Client) Adapter() providers.Adapter { + return providers.Adapter{ + ID: ProviderID, + Credential: credentialCodec{}, + Chat: c, + Models: c, + Classifier: classifier{}, + ImportExport: importer{}, + Prober: c, + } +} + +type credentialCodec struct{} + +func (credentialCodec) Validate(payload []byte) error { return ValidateCredential(payload) } + +type classifier struct{} + +func (classifier) Classify(status int, body string) providers.ClassifiedError { + return Classify(status, body) +} diff --git a/internal/providers/custom/constants.go b/internal/providers/custom/constants.go new file mode 100644 index 000000000..2c12cb382 --- /dev/null +++ b/internal/providers/custom/constants.go @@ -0,0 +1,36 @@ +package custom + +// Custom is the generic OpenAI-compatible provider family: one account is one +// endpoint (base URL + key), so an operator can point cli2api at any hosted +// gateway, relay, Ollama/vLLM server, or vendor API without a reverse proxy. +const ( + // ProviderID is the family id registered in the control plane. + ProviderID = "custom" + // CredentialFormat is the canonical stored credential format. + CredentialFormat = "custom-api-v1" + // RegionAPI is the single pseudo-region. It exists because accounts and + // provider policies are keyed by provider×region; the real address lives in + // each account's credential. + RegionAPI = "api" + + // ProtocolAuto lets a model id carry its wire: anthropic/, + // responses/, or openai/. Without a prefix it stays on chat + // completions. + ProtocolAuto = "auto" + ProtocolOpenAI = "openai" + ProtocolAnthropic = "anthropic" + ProtocolResponses = "responses" + + pathChat = "/v1/chat/completions" + pathMessages = "/v1/messages" + pathResponses = "/v1/responses" + pathModels = "/v1/models" + + headerAPIKey = "x-api-key" + headerAnthropicVersion = "anthropic-version" + anthropicVersion = "2023-06-01" + + // UserAgent identifies the gateway to upstreams that screen library + // defaults. + UserAgent = "cli2api-custom/1.0" +) diff --git a/internal/providers/custom/credential.go b/internal/providers/custom/credential.go new file mode 100644 index 000000000..cc5c92bd5 --- /dev/null +++ b/internal/providers/custom/credential.go @@ -0,0 +1,191 @@ +package custom + +import ( + "encoding/json" + "fmt" + "net/url" + "strings" +) + +// Credential is the canonical storage payload for provider=custom. +// +// One credential is one endpoint: BaseURL plus the key the endpoint expects. +// Protocol pins the wire (openai, anthropic, responses, or auto) and Models is +// the optional manual catalog, used when the endpoint has no useful /models +// route. +type Credential struct { + Format string `json:"format"` + APIKey string `json:"api_key,omitempty"` + BaseURL string `json:"base_url"` + Protocol string `json:"protocol,omitempty"` + Models []string `json:"models,omitempty"` +} + +// FormatAPIKey trims a pasted key and an accidental Bearer prefix. +func FormatAPIKey(raw string) string { + key := strings.TrimSpace(raw) + key = strings.TrimPrefix(key, "Bearer ") + key = strings.TrimPrefix(key, "bearer ") + return strings.TrimSpace(key) +} + +// DecodeCredential accepts the canonical form plus common aliases so a pasted +// {"apiKey":…,"apiBase":…} still imports. The key is optional: local gateways +// such as Ollama need no credential. +func DecodeCredential(payload []byte) (Credential, error) { + var alias struct { + Format string `json:"format"` + APIKey string `json:"api_key"` + APIKeyCamel string `json:"apiKey"` + Key string `json:"key"` + Token string `json:"token"` + BaseURL string `json:"base_url"` + BaseURLCamel string `json:"baseUrl"` + APIBase string `json:"api_base"` + APIBaseCamel string `json:"apiBase"` + Endpoint string `json:"endpoint"` + Protocol string `json:"protocol"` + WireAPI string `json:"wire_api"` + Models []string `json:"models"` + } + if err := json.Unmarshal(payload, &alias); err != nil { + return Credential{}, fmt.Errorf("custom credential is not valid json") + } + base := firstNonEmpty(alias.BaseURL, alias.BaseURLCamel, alias.APIBase, alias.APIBaseCamel, alias.Endpoint) + if strings.TrimSpace(base) == "" { + return Credential{}, fmt.Errorf("custom credential requires a base url") + } + protocol, err := NormalizeProtocol(firstNonEmpty(alias.Protocol, alias.WireAPI)) + if err != nil { + return Credential{}, err + } + credential := Credential{ + Format: firstNonEmpty(alias.Format, CredentialFormat), + APIKey: FormatAPIKey(firstNonEmpty(alias.APIKey, alias.APIKeyCamel, alias.Key, alias.Token)), + BaseURL: strings.TrimRight(strings.TrimSpace(base), "/"), + Protocol: protocol, + Models: NormalizeModels(alias.Models), + } + if _, err := credential.BaseURLValue(); err != nil { + return Credential{}, err + } + return credential, nil +} + +func (c Credential) Encode() ([]byte, error) { + c.Format = CredentialFormat + c.APIKey = FormatAPIKey(c.APIKey) + c.BaseURL = strings.TrimRight(strings.TrimSpace(c.BaseURL), "/") + c.Protocol = firstNonEmpty(c.Protocol, ProtocolOpenAI) + c.Models = NormalizeModels(c.Models) + return json.Marshal(c) +} + +// Ready reports whether the credential can reach an endpoint at all. An empty +// key is allowed for unauthenticated local gateways. +func (c Credential) Ready() bool { + return strings.TrimSpace(c.BaseURL) != "" +} + +// NormalizeProtocol accepts the four wire selectors. An empty value is +// OpenAI chat completions, the dialect nearly every compatible endpoint speaks. +func NormalizeProtocol(raw string) (string, error) { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "", ProtocolOpenAI: + return ProtocolOpenAI, nil + case ProtocolAnthropic: + return ProtocolAnthropic, nil + case ProtocolResponses: + return ProtocolResponses, nil + case ProtocolAuto: + return ProtocolAuto, nil + default: + return "", fmt.Errorf("custom protocol must be openai, anthropic, responses, or auto") + } +} + +// NormalizeModels trims, deduplicates, and keeps the operator's order. +func NormalizeModels(raw []string) []string { + if len(raw) == 0 { + return nil + } + out := make([]string, 0, len(raw)) + seen := map[string]struct{}{} + for _, model := range raw { + id := strings.TrimSpace(model) + if id == "" { + continue + } + key := strings.ToLower(id) + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + out = append(out, id) + } + if len(out) == 0 { + return nil + } + return out +} + +// acceptBaseURL allows http for local gateways (Ollama, LM Studio, a LAN +// relay) and rejects credentials, queries, and fragments in the address. +var acceptBaseURL = func(parsed *url.URL) bool { + if parsed == nil || parsed.Host == "" { + return false + } + switch strings.ToLower(parsed.Scheme) { + case "http", "https": + return true + default: + return false + } +} + +// BaseURL validates and returns the endpoint root. It is a base address, not +// a full request path. +func (c Credential) BaseURLValue() (string, error) { + raw := strings.TrimRight(strings.TrimSpace(c.BaseURL), "/") + if raw == "" { + return "", fmt.Errorf("custom credential requires a base url") + } + parsed, err := url.Parse(raw) + if err != nil || !acceptBaseURL(parsed) { + return "", fmt.Errorf("custom base_url must be an http or https URL") + } + if parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return "", fmt.Errorf("custom base_url must not carry credentials, a query, or a fragment") + } + if path := strings.TrimRight(parsed.Path, "/"); strings.HasSuffix(strings.ToLower(path), "/chat/completions") || + strings.HasSuffix(strings.ToLower(path), "/messages") || + strings.HasSuffix(strings.ToLower(path), "/responses") { + return "", fmt.Errorf("custom base_url must not include a request path such as /chat/completions") + } + return raw, nil +} + +// ValidateCredential is the CredentialCodec entry point. +func ValidateCredential(payload []byte) error { + credential, err := DecodeCredential(payload) + if err != nil { + return err + } + if !credential.Ready() { + return fmt.Errorf("custom credential requires a base url") + } + if _, err := credential.BaseURLValue(); err != nil { + return err + } + _, err = NormalizeProtocol(credential.Protocol) + return err +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/internal/providers/custom/custom_test.go b/internal/providers/custom/custom_test.go new file mode 100644 index 000000000..b95884223 --- /dev/null +++ b/internal/providers/custom/custom_test.go @@ -0,0 +1,271 @@ +package custom + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type fakeStore struct { + format string + payload []byte +} + +func (s *fakeStore) Get(_ context.Context, id string) (accounts.Account, error) { + return accounts.Account{ID: id, Provider: ProviderID, ProviderRegion: RegionAPI}, nil +} + +func (s *fakeStore) LoadCredentialPayload(_ context.Context, _ string) (string, []byte, error) { + return s.format, s.payload, nil +} + +func (s *fakeStore) SaveCredentialPayload(context.Context, string, string, []byte) error { return nil } + +func (s *fakeStore) Observe(context.Context, string, string, string, string, string) error { + return nil +} + +func (s *fakeStore) GetSecret(context.Context, string) (string, bool, error) { return "", false, nil } + +func newTestClient(credential Credential) (*Client, string, func()) { + encoded, _ := credential.Encode() + store := &fakeStore{format: CredentialFormat, payload: encoded} + return NewClient(store), "acc", func() {} +} + +func TestDecodeCredentialAliasesAndValidation(t *testing.T) { + credential, err := DecodeCredential([]byte(`{"apiKey":"Bearer sk-x","apiBase":"https://api.example.com/v1","protocol":"auto"}`)) + if err != nil { + t.Fatalf("decode: %v", err) + } + if credential.APIKey != "sk-x" || credential.BaseURL != "https://api.example.com/v1" || credential.Protocol != ProtocolAuto { + t.Fatalf("unexpected credential: %+v", credential) + } + if _, err := DecodeCredential([]byte(`{"api_key":"k","base_url":"https://api.example.com/v1/chat/completions"}`)); err == nil { + t.Fatal("a full request path must be rejected") + } + if _, err := DecodeCredential([]byte(`{"api_key":"k","base_url":"https://api.example.com","protocol":"grpc"}`)); err == nil { + t.Fatal("an unknown protocol must be rejected") + } + if _, err := DecodeCredential([]byte(`{"api_key":"k"}`)); err == nil { + t.Fatal("a missing base url must be rejected") + } + if err := ValidateCredential([]byte(`{"api_key":"k","base_url":"http://127.0.0.1:11434"}`)); err != nil { + t.Fatalf("local http endpoint should be accepted: %v", err) + } +} + +func TestJoinEndpoint(t *testing.T) { + cases := []struct{ base, endpoint, want string }{ + {"https://api.example.com", "/v1/chat/completions", "https://api.example.com/v1/chat/completions"}, + {"https://api.example.com/v1", "/v1/chat/completions", "https://api.example.com/v1/chat/completions"}, + {"https://api.example.com/v1/", "/v1/chat/completions", "https://api.example.com/v1/chat/completions"}, + {"https://api.example.com", "/v1/models", "https://api.example.com/v1/models"}, + {"https://api.example.com/v4", "/v1/chat/completions", "https://api.example.com/v4/chat/completions"}, + {"https://generativelanguage.example.com/v1beta", "/v1/models", "https://generativelanguage.example.com/v1beta/models"}, + {"https://api.example.com/v1", "/chat/completions", "https://api.example.com/v1/chat/completions"}, + {"https://api.example.com/v1/chat/completions", "/v1/chat/completions", "https://api.example.com/v1/chat/completions"}, + {"https://api.anthropic.com", "/v1/messages", "https://api.anthropic.com/v1/messages"}, + {"https://api.anthropic.com/v1", "/messages", "https://api.anthropic.com/v1/messages"}, + } + for _, tc := range cases { + if got := joinEndpoint(tc.base, tc.endpoint); got != tc.want { + t.Errorf("joinEndpoint(%q, %q) = %q, want %q", tc.base, tc.endpoint, got, tc.want) + } + } +} + +func TestResolveRoute(t *testing.T) { + credential := Credential{BaseURL: "https://api.example.com", Protocol: ProtocolAuto} + protocol, model, err := resolveRoute(credential, "custom/anthropic/claude-sonnet-4") + if err != nil || protocol != translate.UpstreamAnthropic || model != "claude-sonnet-4" { + t.Fatalf("auto prefix: %v %q %v", protocol, model, err) + } + protocol, model, err = resolveRoute(credential, "responses/gpt-5") + if err != nil || protocol != translate.UpstreamResponses || model != "gpt-5" { + t.Fatalf("responses prefix: %v %q %v", protocol, model, err) + } + protocol, model, err = resolveRoute(credential, "llama3.2") + if err != nil || protocol != translate.UpstreamOpenAI || model != "llama3.2" { + t.Fatalf("auto default: %v %q %v", protocol, model, err) + } + explicit := Credential{BaseURL: "https://api.example.com", Protocol: ProtocolOpenAI} + _, model, _ = resolveRoute(explicit, "openai/gpt-4o") + if model != "openai/gpt-4o" { + t.Fatalf("explicit protocol must not strip a vendor prefix, got %q", model) + } +} + +func TestParseCatalogJSON(t *testing.T) { + models, err := ParseCatalogJSON([]byte(`{"data":[{"id":"gpt-4o"},{"id":"claude-sonnet-4","display_name":"Claude"}]}`)) + if err != nil || len(models) != 2 { + t.Fatalf("catalog: %v %v", models, err) + } + if models[1].DisplayName != "Claude" || !models[0].Capabilities.Tools { + t.Fatalf("unexpected entry: %+v", models[1]) + } + if _, err := ParseCatalogJSON([]byte(`[]`)); err == nil { + t.Fatal("an empty bare array must fail") + } +} + +func chatRequest(model string) translate.ChatRequest { + return translate.ChatRequest{ + Model: model, + Messages: []translate.ChatMessage{{Role: "system", Content: "be brief"}, {Role: "user", Content: "hi"}}, + } +} + +func TestChatNonStreamOpenAI(t *testing.T) { + const completion = `data: {"choices":[{"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}]}` + "\n\n" + + `data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}` + "\n\n" + + "data: [DONE]\n\n" + var path, auth, body string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, auth = r.URL.Path, r.Header.Get("Authorization") + raw, _ := io.ReadAll(r.Body) + body = string(raw) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, completion) + })) + defer server.Close() + client, accountID, _ := newTestClient(Credential{APIKey: "sk-test", BaseURL: server.URL, Protocol: ProtocolOpenAI}) + outcome, err := client.ChatNonStream(context.Background(), accountID, chatRequest("gpt-4o")) + if err != nil { + t.Fatalf("chat: %v", err) + } + if path != "/v1/chat/completions" || auth != "Bearer sk-test" { + t.Fatalf("unexpected request: %s %s", path, auth) + } + if !strings.Contains(body, `"model":"gpt-4o"`) || !strings.Contains(body, `"stream":true`) { + t.Fatalf("unexpected body: %s", body) + } + if outcome.Content != "Hello" || outcome.PromptTokens != 3 || outcome.CompletionTokens != 2 || outcome.FinishReason != "stop" { + t.Fatalf("unexpected outcome: %+v", outcome) + } +} + +func TestChatNonStreamAnthropic(t *testing.T) { + const stream = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10}}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"hmm\"}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hello there\"}}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + var path, apiKey, version, body string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path, apiKey, version = r.URL.Path, r.Header.Get("x-api-key"), r.Header.Get("anthropic-version") + raw, _ := io.ReadAll(r.Body) + body = string(raw) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, stream) + })) + defer server.Close() + client, accountID, _ := newTestClient(Credential{APIKey: "sk-ant", BaseURL: server.URL + "/v1", Protocol: ProtocolAnthropic}) + outcome, err := client.ChatNonStream(context.Background(), accountID, chatRequest("claude-sonnet-4")) + if err != nil { + t.Fatalf("chat: %v", err) + } + if path != "/v1/messages" || apiKey != "sk-ant" || version != anthropicVersion { + t.Fatalf("unexpected request: %s %s %s", path, apiKey, version) + } + if !strings.Contains(body, `"system":"be brief"`) || !strings.Contains(body, `"max_tokens":8192`) { + t.Fatalf("unexpected body: %s", body) + } + if outcome.Content != "Hello there" || outcome.Reasoning != "hmm" || outcome.PromptTokens != 10 || outcome.CompletionTokens != 5 { + t.Fatalf("unexpected outcome: %+v", outcome) + } +} + +func TestChatStreamAnthropicRelaysChatDeltas(t *testing.T) { + const stream = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":4}}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hi\"}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, stream) + })) + defer server.Close() + client, accountID, _ := newTestClient(Credential{APIKey: "k", BaseURL: server.URL, Protocol: ProtocolAnthropic}) + resp, _, err := client.ChatStream(context.Background(), accountID, chatRequest("claude-sonnet-4")) + if err != nil { + t.Fatalf("stream: %v", err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + text := string(raw) + if !strings.Contains(text, `"content":"Hi"`) || !strings.Contains(text, `"finish_reason":"stop"`) || !strings.Contains(text, "data: [DONE]") { + t.Fatalf("unexpected relayed stream: %s", text) + } +} + +func TestChatNonStreamResponsesCollectsToolCalls(t *testing.T) { + const stream = "event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"id\":\"fc_1\",\"call_id\":\"call_1\",\"name\":\"lookup\",\"arguments\":\"\"}}\n\n" + + "event: response.function_call_arguments.delta\ndata: {\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"item_id\":\"fc_1\",\"delta\":\"{\\\"q\\\":\\\"x\\\"}\"}\n\n" + + "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":7,\"output_tokens\":3},\"output\":[]}}\n\n" + var path, body string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path = r.URL.Path + raw, _ := io.ReadAll(r.Body) + body = string(raw) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, stream) + })) + defer server.Close() + client, accountID, _ := newTestClient(Credential{APIKey: "k", BaseURL: server.URL + "/v1", Protocol: ProtocolResponses}) + outcome, err := client.ChatNonStream(context.Background(), accountID, chatRequest("gpt-5")) + if err != nil { + t.Fatalf("chat: %v", err) + } + if path != "/v1/responses" { + t.Fatalf("unexpected path: %s", path) + } + if !strings.Contains(body, `"instructions":"be brief"`) || !strings.Contains(body, `"input_text"`) { + t.Fatalf("unexpected body: %s", body) + } + if !strings.Contains(string(outcome.ToolCalls), "lookup") || outcome.FinishReason != "tool_calls" { + t.Fatalf("unexpected outcome: %+v tools=%s", outcome, outcome.ToolCalls) + } + if outcome.PromptTokens != 7 || outcome.CompletionTokens != 3 { + t.Fatalf("unexpected usage: %+v", outcome) + } +} + +func TestProbeManualCatalogWithoutModelsRoute(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + defer server.Close() + client, accountID, _ := newTestClient(Credential{APIKey: "k", BaseURL: server.URL, Models: []string{"m1"}}) + health, err := client.Probe(context.Background(), accountID) + if err != nil || !health.Ready { + t.Fatalf("probe: %+v %v", health, err) + } + models, err := client.Models(context.Background(), accountID) + if err != nil || len(models) != 1 || models[0].NativeModel != "m1" { + t.Fatalf("manual catalog: %+v %v", models, err) + } +} + +func TestClassify(t *testing.T) { + if got := Classify(401, "bad key"); got.Kind != accounts.KindAuth { + t.Fatalf("401 kind: %+v", got) + } + if got := Classify(429, ""); got.Kind != accounts.KindRateLimit { + t.Fatalf("429 kind: %+v", got) + } + if got := Classify(502, "bad gateway"); got.Kind != accounts.KindUnavailable { + t.Fatalf("502 kind: %+v", got) + } + if got := Classify(400, "tool schema invalid"); got.Kind != accounts.KindInvalidRequest { + t.Fatalf("400 kind: %+v", got) + } +} + +var _ providers.ModelCatalogProvider = (*Client)(nil) diff --git a/internal/providers/custom/doc.go b/internal/providers/custom/doc.go new file mode 100644 index 000000000..d83b2d499 --- /dev/null +++ b/internal/providers/custom/doc.go @@ -0,0 +1,20 @@ +// Package custom implements the generic custom-endpoint provider. +// +// One account is one endpoint: a base URL plus the key that endpoint expects. +// There is no child process, no browser login, and no reverse proxy; chat goes +// straight from this process to the address the operator pasted. The family +// covers OpenAI-compatible relays, hosted gateways, Ollama/vLLM servers, and +// vendor APIs that already speak one of the three wire protocols. +// +// The wire is pinned per endpoint (openai, anthropic, responses) or left on +// auto, where a model prefix (anthropic/, responses/, openai/) selects it for +// one call. ChatStream always returns OpenAI chat-completions deltas: Anthropic +// and Responses upstreams are translated on the fly, so every client sees one +// dialect. /v1/responses clients use the shared chat-form translation instead +// of native passthrough. +// +// The catalog comes from GET {base}/models, or from the operator's manual list +// when one is saved. A manual list is authoritative: it skips the upstream +// call, so endpoints without a model route still work. Reasoning levels are +// not invented for this family; the account catalog declares none. +package custom diff --git a/internal/providers/custom/errors.go b/internal/providers/custom/errors.go new file mode 100644 index 000000000..68a70b3cc --- /dev/null +++ b/internal/providers/custom/errors.go @@ -0,0 +1,86 @@ +package custom + +import ( + "regexp" + "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" +) + +var bearerPattern = regexp.MustCompile(`(?i)bearer\s+\S+`) + +func redactSecrets(text string) string { + if text == "" { + return text + } + return bearerPattern.ReplaceAllString(text, "Bearer [redacted]") +} + +// Classify maps endpoint HTTP errors onto the executor taxonomy. 401/403 cool +// the account as auth. 429 is a rate limit. 402 and an explicit balance or +// quota message are quota. Other 4xx are the request, not the account. +func Classify(status int, body string) providers.ClassifiedError { + safe := redactSecrets(strings.TrimSpace(body)) + text := strings.ToLower(safe) + switch { + case status == 401 || status == 403 || + strings.Contains(text, "invalid api key") || + strings.Contains(text, "unauthorized") || + strings.Contains(text, "authentication"): + return providers.ClassifiedError{ + Kind: accounts.KindAuth, + Status: firstStatus(status, 401), + Message: firstNonEmpty(safe, "custom endpoint rejected the credential"), + } + case status == 429 || strings.Contains(text, "rate limit") || strings.Contains(text, "too many requests"): + return providers.ClassifiedError{ + Kind: accounts.KindRateLimit, + Status: firstStatus(status, 429), + Message: firstNonEmpty(safe, "custom endpoint rate limited"), + } + case status == 402 || + strings.Contains(text, "insufficient") || + strings.Contains(text, "balance") || + strings.Contains(text, "quota") || + strings.Contains(text, "余额") || + strings.Contains(text, "额度"): + return providers.ClassifiedError{ + Kind: accounts.KindQuota, + Status: firstStatus(status, 402), + Message: firstNonEmpty(safe, "custom endpoint quota exhausted"), + } + case status == 404: + return providers.ClassifiedError{Kind: accounts.KindModelNotAvailable, Status: 404, Message: safe} + case status == 400 || status == 422 || accounts.IsInvalidRequestText(safe) || accounts.IsPromptLimitText(safe): + return providers.ClassifiedError{Kind: accounts.KindInvalidRequest, Status: firstStatus(status, 400), Message: safe} + case status == 499 || strings.Contains(text, "canceled"): + return providers.ClassifiedError{Kind: accounts.KindCanceled, Status: 499, Message: safe} + case status >= 500 || status == 0: + return providers.ClassifiedError{ + Kind: accounts.KindUnavailable, + Status: firstStatus(status, 502), + Message: firstNonEmpty(safe, "custom endpoint unavailable"), + } + } + if safe != "" && status >= 400 { + return providers.ClassifiedError{Kind: accounts.KindUnavailable, Status: status, Message: safe} + } + return providers.ClassifiedError{} +} + +func newProviderError(status int, body string) *providers.Error { + classified := Classify(status, body) + return &providers.Error{ + Kind: classified.Kind, + Status: classified.Status, + Message: classified.Message, + } +} + +func firstStatus(status, fallback int) int { + if status > 0 { + return status + } + return fallback +} diff --git a/internal/providers/custom/import.go b/internal/providers/custom/import.go new file mode 100644 index 000000000..8b4da9d4c --- /dev/null +++ b/internal/providers/custom/import.go @@ -0,0 +1,32 @@ +package custom + +import ( + "context" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func (credentialCodec) Format() string { return CredentialFormat } + +func (credentialCodec) PrepareImport(payload []byte) (providers.CredentialImport, error) { + if err := ValidateCredential(payload); err != nil { + return providers.CredentialImport{}, err + } + credential, err := DecodeCredential(payload) + if err != nil { + return providers.CredentialImport{}, err + } + encoded, err := credential.Encode() + if err != nil { + return providers.CredentialImport{}, err + } + return providers.CredentialImport{Payload: encoded, Ready: credential.Ready()}, nil +} + +type importer struct{} + +func (importer) ValidateImport(payload []byte) error { return ValidateCredential(payload) } + +func (importer) Export(context.Context, string) (map[string]any, error) { + return nil, providers.ErrUnsupported +} diff --git a/internal/providers/custom/outcome.go b/internal/providers/custom/outcome.go new file mode 100644 index 000000000..d3562f6ba --- /dev/null +++ b/internal/providers/custom/outcome.go @@ -0,0 +1,256 @@ +package custom + +import ( + "encoding/json" + "fmt" + "io" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +type sseAggregate struct { + content strings.Builder + reasoning strings.Builder + tools map[int]*collectedTool + order []int + usage streamUsage + finish string +} + +type collectedTool struct { + id string + name string + args strings.Builder +} + +type streamUsage struct { + prompt int + completion int + cacheRead int +} + +func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) { + raw, err := io.ReadAll(io.LimitReader(body, 16<<20)) + if err != nil { + return providers.ChatOutcome{}, err + } + agg := &sseAggregate{tools: map[int]*collectedTool{}, finish: "stop"} + sawDone, sawFinish := false, false + for _, line := range strings.Split(string(raw), "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, "data:") { + continue + } + data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true + continue + } + var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` + Choices []struct { + Delta struct { + Content string `json:"content"` + ReasoningContent string `json:"reasoning_content"` + ToolCalls []struct { + Index int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + Usage struct { + PromptTokens int `json:"prompt_tokens"` + CompletionTokens int `json:"completion_tokens"` + PromptDetails struct { + CachedTokens int `json:"cached_tokens"` + } `json:"prompt_tokens_details"` + } `json:"usage"` + } + if json.Unmarshal([]byte(data), &chunk) != nil { + continue + } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("custom stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("custom stream: %s", message) + } + if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { + agg.usage.prompt = chunk.Usage.PromptTokens + agg.usage.completion = chunk.Usage.CompletionTokens + agg.usage.cacheRead = chunk.Usage.PromptDetails.CachedTokens + } + for _, choice := range chunk.Choices { + agg.content.WriteString(choice.Delta.Content) + agg.reasoning.WriteString(choice.Delta.ReasoningContent) + if choice.FinishReason != "" { + agg.finish = choice.FinishReason + sawFinish = true + } + for _, call := range choice.Delta.ToolCalls { + state := agg.tools[call.Index] + if state == nil { + state = &collectedTool{} + agg.tools[call.Index] = state + agg.order = append(agg.order, call.Index) + } + if call.ID != "" { + state.id = call.ID + } + if call.Function.Name != "" { + state.name = call.Function.Name + } + state.args.WriteString(call.Function.Arguments) + } + } + } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("custom stream ended without a terminal frame") + } + outcome := providers.ChatOutcome{ + Model: model, + Content: agg.content.String(), + Reasoning: agg.reasoning.String(), + FinishReason: agg.finish, + PromptTokens: agg.usage.prompt, + CompletionTokens: agg.usage.completion, + } + if agg.usage.cacheRead > 0 { + cached := agg.usage.cacheRead + outcome.CacheReadTokens = &cached + } + if len(agg.order) > 0 { + calls := make([]map[string]any, 0, len(agg.order)) + for _, index := range agg.order { + state := agg.tools[index] + calls = append(calls, map[string]any{ + "id": state.id, + "type": "function", + "function": map[string]any{ + "name": state.name, + "arguments": state.args.String(), + }, + }) + } + encoded, err := json.Marshal(calls) + if err != nil { + return providers.ChatOutcome{}, err + } + outcome.ToolCalls = encoded + } + return outcome, nil +} + +// jsonCompletionToSSE rewrites a one-shot chat completion into chat deltas for +// endpoints that ignore stream=true. +func jsonCompletionToSSE(raw []byte, model string) ([]byte, error) { + var completion struct { + Error *struct { + Message string `json:"message"` + } `json:"error"` + Choices []struct { + Message struct { + Content string `json:"content"` + ReasoningContent string `json:"reasoning_content"` + ToolCalls []struct { + ID string `json:"id"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"message"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + Usage struct { + PromptTokens int `json:"prompt_tokens"` + CompletionTokens int `json:"completion_tokens"` + } `json:"usage"` + } + if err := json.Unmarshal(raw, &completion); err != nil { + return nil, newProviderError(502, string(raw)) + } + if completion.Error != nil && completion.Error.Message != "" { + return nil, newProviderError(502, completion.Error.Message) + } + var buf strings.Builder + id := "chatcmpl-custom" + created := time.Now().Unix() + write := func(delta map[string]any, finish string, usage map[string]any) { + choice := map[string]any{"index": 0, "delta": delta} + if finish != "" { + choice["finish_reason"] = finish + } + chunk := map[string]any{ + "id": id, "object": "chat.completion.chunk", "created": created, + "model": model, "choices": []any{choice}, + } + if usage != nil { + chunk["usage"] = usage + } + encoded, _ := json.Marshal(chunk) + buf.WriteString("data: ") + buf.Write(encoded) + buf.WriteString("\n\n") + } + if len(completion.Choices) == 0 { + write(map[string]any{"role": "assistant"}, "stop", nil) + buf.WriteString("data: [DONE]\n\n") + return []byte(buf.String()), nil + } + choice := completion.Choices[0] + delta := map[string]any{"role": "assistant"} + if choice.Message.Content != "" { + delta["content"] = choice.Message.Content + } + if choice.Message.ReasoningContent != "" { + delta["reasoning_content"] = choice.Message.ReasoningContent + } + if len(choice.Message.ToolCalls) > 0 { + calls := make([]any, 0, len(choice.Message.ToolCalls)) + for i, call := range choice.Message.ToolCalls { + calls = append(calls, map[string]any{ + "index": i, + "id": call.ID, + "type": "function", + "function": map[string]any{ + "name": call.Function.Name, + "arguments": call.Function.Arguments, + }, + }) + } + delta["tool_calls"] = calls + } + finish := choice.FinishReason + if len(choice.Message.ToolCalls) > 0 && (finish == "" || finish == "stop") { + finish = "tool_calls" + } + if finish == "" { + finish = "stop" + } + var usage map[string]any + if completion.Usage.PromptTokens > 0 || completion.Usage.CompletionTokens > 0 { + usage = map[string]any{ + "prompt_tokens": completion.Usage.PromptTokens, + "completion_tokens": completion.Usage.CompletionTokens, + "total_tokens": completion.Usage.PromptTokens + completion.Usage.CompletionTokens, + } + } + write(delta, finish, usage) + buf.WriteString("data: [DONE]\n\n") + return []byte(buf.String()), nil +} diff --git a/internal/providers/custom/quota.go b/internal/providers/custom/quota.go new file mode 100644 index 000000000..57b4683dc --- /dev/null +++ b/internal/providers/custom/quota.go @@ -0,0 +1,13 @@ +package custom + +import ( + "context" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +// Quota is absent: a custom endpoint exposes no portable subscription or +// balance surface, and inventing one from the model route would be fiction. +func (c *Client) Quota(context.Context, string) (*providers.QuotaInfo, error) { + return nil, nil +} diff --git a/internal/translate/upstream_body.go b/internal/translate/upstream_body.go new file mode 100644 index 000000000..36ec2a4ed --- /dev/null +++ b/internal/translate/upstream_body.go @@ -0,0 +1,646 @@ +package translate + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "strings" +) + +// UpstreamProtocol names the wire dialect a provider endpoint expects. +// It is provider-local metadata: the gateway always speaks chat completions. +type UpstreamProtocol string + +const ( + UpstreamOpenAI UpstreamProtocol = "openai" + UpstreamAnthropic UpstreamProtocol = "anthropic" + UpstreamResponses UpstreamProtocol = "responses" +) + +// upstreamDefaultMaxTokens is the Anthropic and Responses default when the +// client omits max_tokens. It is a wire default, not a catalog ceiling. +const upstreamDefaultMaxTokens = 8192 + +// BuildUpstreamBody serializes the internal chat request for one upstream +// protocol. OpenAI chat keeps the body mostly as-is (the gateway dialect is +// OpenAI), Anthropic and Responses are rebuilt from the chat form. +func BuildUpstreamBody(protocol UpstreamProtocol, req ChatRequest, model string) ([]byte, error) { + switch protocol { + case UpstreamAnthropic: + return buildAnthropicBody(req, model) + case UpstreamResponses: + return buildResponsesBody(req, model) + default: + return buildOpenAIChatBody(req, model) + } +} + +// buildOpenAIChatBody serializes the internal chat request for Chat +// Completions. Developer roles become system. Gateway-only fields are removed +// so the upstream sees a plain OpenAI chat body. +func buildOpenAIChatBody(req ChatRequest, model string) ([]byte, error) { + body, err := json.Marshal(req) + if err != nil { + return nil, err + } + var obj map[string]any + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + if err := decoder.Decode(&obj); err != nil { + return nil, err + } + obj["model"] = model + obj["stream"] = true + for _, key := range []string{ + "is_reasoning", "enable_thinking", "enable_reasoning", "thinking", + "reasoning_budget_tokens", "context_length", "max_input_tokens", "is_max_mode", + } { + delete(obj, key) + } + for key, value := range obj { + if value == nil { + delete(obj, key) + } + } + if effort, _ := obj["reasoning_effort"].(string); strings.EqualFold(strings.TrimSpace(effort), "none") { + delete(obj, "reasoning_effort") + } + rewriteUpstreamDeveloperRoles(obj) + return json.Marshal(obj) +} + +func rewriteUpstreamDeveloperRoles(obj map[string]any) { + messages, ok := obj["messages"].([]any) + if !ok { + return + } + for _, item := range messages { + message, ok := item.(map[string]any) + if !ok { + continue + } + role, _ := message["role"].(string) + if strings.EqualFold(strings.TrimSpace(role), "developer") { + message["role"] = "system" + } + } +} + +func buildAnthropicBody(req ChatRequest, model string) ([]byte, error) { + systemParts := []string{} + messages := make([]any, 0, len(req.Messages)) + for _, msg := range req.Messages { + switch strings.ToLower(strings.TrimSpace(msg.Role)) { + case "system", "developer": + if text := upstreamMessageText(msg.Content); strings.TrimSpace(text) != "" { + systemParts = append(systemParts, text) + } + case "tool", "function": + result := map[string]any{ + "type": "tool_result", + "tool_use_id": upstreamFirstNonEmpty(msg.ToolCallID, msg.Name, "tool"), + "content": upstreamToolResultContent(msg), + } + if msg.ToolResultIsError { + result["is_error"] = true + } + messages = appendUpstreamTurn(messages, "user", []any{result}) + case "assistant": + messages = appendUpstreamTurn(messages, "assistant", upstreamAssistantBlocks(msg)) + default: + messages = appendUpstreamTurn(messages, "user", upstreamContentBlocks(msg.Content)) + } + } + body := map[string]any{ + "model": model, + "max_tokens": upstreamRequestMaxTokens(req), + "messages": messages, + "stream": true, + } + if len(systemParts) > 0 { + body["system"] = strings.Join(systemParts, "\n\n") + } + applyUpstreamSampling(body, req, true) + if tools, choice, send := upstreamAnthropicTools(req); send { + if len(tools) > 0 { + body["tools"] = tools + } + if choice != nil { + body["tool_choice"] = choice + } + } + return json.Marshal(body) +} + +// appendUpstreamTurn keeps Anthropic's alternating roles. Parallel tool +// results, and a user note that follows them, belong in one user message. +func appendUpstreamTurn(messages []any, role string, blocks []any) []any { + if len(blocks) == 0 { + return messages + } + if n := len(messages); n > 0 { + if prev, ok := messages[n-1].(map[string]any); ok && prev["role"] == role { + if content, ok := prev["content"].([]any); ok { + prev["content"] = append(content, blocks...) + return messages + } + } + } + return append(messages, map[string]any{"role": role, "content": blocks}) +} + +func upstreamAssistantBlocks(msg ChatMessage) []any { + blocks := make([]any, 0) + if text := upstreamMessageText(msg.Content); strings.TrimSpace(text) != "" { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + if len(msg.ToolCalls) == 0 { + return blocks + } + var calls []map[string]any + if json.Unmarshal(msg.ToolCalls, &calls) != nil { + return blocks + } + for _, call := range calls { + id, _ := call["id"].(string) + function, _ := call["function"].(map[string]any) + name, _ := function["name"].(string) + arguments, _ := function["arguments"].(string) + var input any = map[string]any{} + if strings.TrimSpace(arguments) != "" { + if json.Unmarshal([]byte(arguments), &input) != nil { + input = map[string]any{} + } + } + blocks = append(blocks, map[string]any{ + "type": "tool_use", + "id": upstreamFirstNonEmpty(id, upstreamNewID("toolu_")), + "name": upstreamFirstNonEmpty(name, "tool"), + "input": input, + }) + } + return blocks +} + +func buildResponsesBody(req ChatRequest, model string) ([]byte, error) { + instructions := []string{} + input := make([]any, 0, len(req.Messages)) + for _, msg := range req.Messages { + switch strings.ToLower(strings.TrimSpace(msg.Role)) { + case "system", "developer": + if text := upstreamMessageText(msg.Content); strings.TrimSpace(text) != "" { + instructions = append(instructions, text) + } + case "tool", "function": + input = append(input, map[string]any{ + "type": "function_call_output", + "call_id": upstreamFirstNonEmpty(msg.ToolCallID, msg.Name, "tool"), + "output": upstreamMessageText(msg.Content), + }) + case "assistant": + if text := upstreamMessageText(msg.Content); strings.TrimSpace(text) != "" { + input = append(input, map[string]any{ + "role": "assistant", + "content": []any{map[string]any{"type": "output_text", "text": text}}, + }) + } + input = append(input, upstreamResponseFunctionCalls(msg.ToolCalls)...) + default: + input = append(input, map[string]any{ + "role": "user", + "content": upstreamResponseUserContent(msg.Content), + }) + } + } + body := map[string]any{ + "model": model, + "input": input, + "stream": true, + } + if len(instructions) > 0 { + body["instructions"] = strings.Join(instructions, "\n\n") + } + if len(req.MaxTokens) > 0 || len(req.MaxCompletionTokens) > 0 { + body["max_output_tokens"] = upstreamRequestMaxTokens(req) + } + applyUpstreamSampling(body, req, false) + if effort := upstreamForwardedEffort(req); effort != "" { + body["reasoning"] = map[string]any{"effort": effort} + } + if tools, choice, send := upstreamResponseTools(req); send { + if len(tools) > 0 { + body["tools"] = tools + } + if choice != nil { + body["tool_choice"] = choice + } + } + return json.Marshal(body) +} + +func upstreamResponseFunctionCalls(raw json.RawMessage) []any { + if len(raw) == 0 { + return nil + } + var calls []map[string]any + if json.Unmarshal(raw, &calls) != nil { + return nil + } + out := make([]any, 0, len(calls)) + for _, call := range calls { + id, _ := call["id"].(string) + function, _ := call["function"].(map[string]any) + name, _ := function["name"].(string) + arguments, _ := function["arguments"].(string) + if strings.TrimSpace(arguments) == "" { + arguments = "{}" + } + out = append(out, map[string]any{ + "type": "function_call", + "call_id": upstreamFirstNonEmpty(id, upstreamNewID("call_")), + "name": upstreamFirstNonEmpty(name, "tool"), + "arguments": arguments, + }) + } + return out +} + +func upstreamResponseUserContent(content any) []any { + switch value := content.(type) { + case string: + return []any{map[string]any{"type": "input_text", "text": value}} + case []any: + parts := make([]any, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + continue + } + if text, ok := part["text"].(string); ok && strings.TrimSpace(text) != "" { + parts = append(parts, map[string]any{"type": "input_text", "text": text}) + continue + } + if url := upstreamImageURLValue(part["image_url"]); url != "" { + parts = append(parts, map[string]any{"type": "input_image", "image_url": url}) + } + } + if len(parts) > 0 { + return parts + } + } + return []any{map[string]any{"type": "input_text", "text": ""}} +} + +func upstreamForwardedEffort(req ChatRequest) string { + raw := strings.TrimSpace(string(req.ReasoningEffort)) + if raw == "" || raw == "null" { + return "" + } + var text string + if json.Unmarshal(req.ReasoningEffort, &text) == nil { + text = strings.TrimSpace(text) + if text == "" || strings.EqualFold(text, "none") { + return "" + } + return text + } + return "" +} + +func applyUpstreamSampling(body map[string]any, req ChatRequest, anthropic bool) { + if value, ok := upstreamJSONNumber(req.Temperature); ok { + body["temperature"] = value + } + if value, ok := upstreamJSONNumber(req.TopP); ok { + body["top_p"] = value + } + if stops := upstreamJSONStrings(req.Stop); len(stops) > 0 { + if anthropic { + body["stop_sequences"] = stops + } else { + body["stop"] = stops + } + } +} + +func upstreamAnthropicTools(req ChatRequest) ([]any, map[string]any, bool) { + tools := upstreamDecodeTools(req.Tools) + choice, send := upstreamAnthropicToolChoice(req.ToolChoice, req.ParallelToolCalls) + if !send { + return nil, nil, false + } + out := make([]any, 0, len(tools)) + for _, tool := range tools { + typ, _ := tool["type"].(string) + function, _ := tool["function"].(map[string]any) + name, _ := function["name"].(string) + if !strings.EqualFold(typ, "function") || strings.TrimSpace(name) == "" { + continue + } + params := function["parameters"] + if params == nil { + params = map[string]any{"type": "object", "properties": map[string]any{}} + } + entry := map[string]any{"name": name, "input_schema": params} + if description, _ := function["description"].(string); description != "" { + entry["description"] = description + } + out = append(out, entry) + } + return out, choice, true +} + +func upstreamResponseTools(req ChatRequest) ([]any, any, bool) { + tools := upstreamDecodeTools(req.Tools) + choice, send := upstreamResponseToolChoice(req.ToolChoice) + if !send { + return nil, nil, false + } + out := make([]any, 0, len(tools)) + for _, tool := range tools { + typ, _ := tool["type"].(string) + function, _ := tool["function"].(map[string]any) + name, _ := function["name"].(string) + if !strings.EqualFold(typ, "function") || strings.TrimSpace(name) == "" { + continue + } + params := function["parameters"] + if params == nil { + params = map[string]any{"type": "object", "properties": map[string]any{}} + } + entry := map[string]any{"type": "function", "name": name, "parameters": params} + if description, _ := function["description"].(string); description != "" { + entry["description"] = description + } + out = append(out, entry) + } + return out, choice, true +} + +func upstreamDecodeTools(raw json.RawMessage) []map[string]any { + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + return nil + } + var tools []map[string]any + if json.Unmarshal(raw, &tools) != nil { + return nil + } + return tools +} + +func upstreamAnthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, bool) { + parallelDisabled := parallel != nil && !*parallel + choice := map[string]any{} + if len(raw) > 0 && strings.TrimSpace(string(raw)) != "null" { + var text string + if json.Unmarshal(raw, &text) == nil { + switch strings.ToLower(strings.TrimSpace(text)) { + case "none": + choice["type"] = "none" + case "required", "any": + choice["type"] = "any" + case "auto": + choice["type"] = "auto" + } + } else { + var object map[string]any + if json.Unmarshal(raw, &object) == nil { + typ, _ := object["type"].(string) + switch strings.ToLower(strings.TrimSpace(typ)) { + case "none": + choice["type"] = "none" + case "function", "custom": + function, _ := object["function"].(map[string]any) + name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } + if name = strings.TrimSpace(name); name != "" { + choice["type"] = "tool" + choice["name"] = name + } + } + } + } + } + if len(choice) == 0 { + if !parallelDisabled { + return nil, true + } + return map[string]any{"type": "auto", "disable_parallel_tool_use": true}, true + } + if parallelDisabled && choice["type"] != "none" { + choice["disable_parallel_tool_use"] = true + } + return choice, true +} + +func upstreamResponseToolChoice(raw json.RawMessage) (any, bool) { + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + return nil, true + } + var text string + if json.Unmarshal(raw, &text) == nil { + switch strings.ToLower(strings.TrimSpace(text)) { + case "none": + return "none", true + case "required", "any": + return "required", true + case "auto": + return "auto", true + } + return nil, true + } + var object map[string]any + if json.Unmarshal(raw, &object) != nil { + return nil, true + } + typ, _ := object["type"].(string) + if strings.EqualFold(typ, "function") || strings.EqualFold(typ, "custom") { + function, _ := object["function"].(map[string]any) + name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } + if name = strings.TrimSpace(name); name != "" { + return map[string]any{"type": "function", "name": name}, true + } + } + if strings.EqualFold(typ, "none") { + return "none", true + } + return nil, true +} + +func upstreamMessageText(content any) string { + switch value := content.(type) { + case string: + return value + case []any: + parts := make([]string, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + continue + } + if text, ok := part["text"].(string); ok { + parts = append(parts, text) + } + } + return strings.Join(parts, "\n") + default: + return "" + } +} + +func upstreamContentBlocks(content any) []any { + switch value := content.(type) { + case string: + return []any{map[string]any{"type": "text", "text": value}} + case []any: + blocks := make([]any, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + continue + } + if block, ok := upstreamAnthropicImageBlock(part); ok { + blocks = append(blocks, block) + continue + } + if text, ok := part["text"].(string); ok { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + } + if len(blocks) > 0 { + return blocks + } + } + return []any{map[string]any{"type": "text", "text": ""}} +} + +func upstreamToolResultContent(msg ChatMessage) any { + text := upstreamMessageText(msg.Content) + if len(msg.ToolResultImages) == 0 { + return text + } + blocks := make([]any, 0, len(msg.ToolResultImages)+1) + if strings.TrimSpace(text) != "" { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + for _, raw := range msg.ToolResultImages { + part, ok := raw.(map[string]any) + if !ok { + continue + } + if block, ok := upstreamAnthropicImageBlock(part); ok { + blocks = append(blocks, block) + } + } + if len(blocks) == 0 { + return text + } + return blocks +} + +func upstreamAnthropicImageBlock(part map[string]any) (map[string]any, bool) { + if blockType, _ := part["type"].(string); blockType == "image" { + if source, ok := part["source"].(map[string]any); ok { + return map[string]any{"type": "image", "source": source}, true + } + } + url := upstreamImageURLValue(part["image_url"]) + if url == "" { + return nil, false + } + if mediaType, data, ok := strings.Cut(strings.TrimPrefix(url, "data:"), ";base64,"); ok && mediaType != "" && data != "" { + return map[string]any{ + "type": "image", + "source": map[string]any{"type": "base64", "media_type": mediaType, "data": data}, + }, true + } + if strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://") { + return map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": url}}, true + } + return nil, false +} + +func upstreamImageURLValue(value any) string { + switch typed := value.(type) { + case string: + return typed + case map[string]any: + url, _ := typed["url"].(string) + return url + default: + return "" + } +} + +func upstreamRequestMaxTokens(req ChatRequest) int { + raw := req.MaxTokens + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + raw = req.MaxCompletionTokens + } + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + return upstreamDefaultMaxTokens + } + var value int + if err := json.Unmarshal(raw, &value); err != nil || value <= 0 { + return upstreamDefaultMaxTokens + } + return value +} + +func upstreamJSONNumber(raw json.RawMessage) (float64, bool) { + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + return 0, false + } + var value float64 + if json.Unmarshal(raw, &value) == nil { + return value, true + } + return 0, false +} + +func upstreamJSONStrings(raw json.RawMessage) []string { + if len(raw) == 0 || strings.TrimSpace(string(raw)) == "null" { + return nil + } + var single string + if json.Unmarshal(raw, &single) == nil { + if text := strings.TrimSpace(single); text != "" { + return []string{text} + } + return nil + } + var list []string + if json.Unmarshal(raw, &list) != nil { + return nil + } + out := make([]string, 0, len(list)) + for _, item := range list { + if text := strings.TrimSpace(item); text != "" { + out = append(out, text) + } + } + return out +} + +func upstreamNewID(prefix string) string { + var buf [8]byte + if _, err := rand.Read(buf[:]); err != nil { + return prefix + "fallback" + } + return prefix + hex.EncodeToString(buf[:]) +} + +func upstreamFirstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/internal/translate/upstream_stream.go b/internal/translate/upstream_stream.go new file mode 100644 index 000000000..6a1b263d8 --- /dev/null +++ b/internal/translate/upstream_stream.go @@ -0,0 +1,582 @@ +package translate + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "strings" + "time" +) + +// RelayUpstreamStream turns one upstream SSE dialect into OpenAI chat +// completions deltas. The OpenAI protocol is copied unchanged; Anthropic and +// Responses are decoded and re-emitted, so the gateway can relay one shape. +func RelayUpstreamStream(dst io.Writer, src io.Reader, protocol UpstreamProtocol, model string) error { + switch protocol { + case UpstreamAnthropic: + return writeOpenAIChatStream(dst, src, model, decodeUpstreamAnthropic) + case UpstreamResponses: + return writeOpenAIChatStream(dst, src, model, decodeUpstreamResponses) + default: + _, err := io.Copy(dst, src) + return err + } +} + +type upstreamFrameDecoder func(eventType, payload string, state *upstreamDecodeState) ([]upstreamDelta, bool, error) + +type upstreamDelta struct { + content string + reasoning string + tools []upstreamToolDelta + role bool +} + +type upstreamToolDelta struct { + index int + id string + name string + args string + hasID bool + nameSet bool +} + +type upstreamUsage struct { + prompt int + completion int + cacheRead int +} + +type upstreamDecodeState struct { + finish string + usage upstreamUsage + toolIndex int + toolByID map[string]int + sentRole bool + sawTool bool + toolNamed map[int]bool + toolArgued map[int]bool + toolDone map[int]bool + blockTool map[int]int +} + +func writeOpenAIChatStream(dst io.Writer, src io.Reader, model string, decode upstreamFrameDecoder) error { + state := &upstreamDecodeState{toolIndex: -1, toolByID: map[string]int{}} + id := upstreamNewID("chatcmpl-") + created := time.Now().Unix() + emit := func(delta map[string]any, finish any, usage map[string]any) error { + choice := map[string]any{"index": 0, "delta": delta} + if finish != nil && finish != "" { + choice["finish_reason"] = finish + } + chunk := map[string]any{ + "id": id, "object": "chat.completion.chunk", "created": created, + "model": model, "choices": []any{choice}, + } + if usage != nil { + chunk["usage"] = usage + } + raw, err := json.Marshal(chunk) + if err != nil { + return err + } + _, err = fmt.Fprintf(dst, "data: %s\n\n", raw) + return err + } + err := readUpstreamSSE(src, func(eventType, data string) (bool, error) { + deltas, done, err := decode(eventType, data, state) + if err != nil { + return false, err + } + for _, delta := range deltas { + out := map[string]any{} + if delta.role && !state.sentRole { + out["role"] = "assistant" + state.sentRole = true + } + if delta.content != "" { + out["content"] = delta.content + } + if delta.reasoning != "" { + out["reasoning_content"] = delta.reasoning + } + if len(delta.tools) > 0 { + state.sawTool = true + calls := make([]any, 0, len(delta.tools)) + for _, call := range delta.tools { + function := map[string]any{} + if call.nameSet { + function["name"] = call.name + } + if call.args != "" { + function["arguments"] = call.args + } + entry := map[string]any{"index": call.index, "type": "function", "function": function} + if call.hasID { + entry["id"] = call.id + } + calls = append(calls, entry) + } + out["tool_calls"] = calls + } + if len(out) == 0 { + continue + } + if err := emit(out, nil, nil); err != nil { + return false, err + } + } + return done, nil + }) + if err != nil && err != io.EOF { + return err + } + finish := state.finish + // A tool call that ended "normally" must be tool_calls. length and + // content_filter stay as they are; clients that only read finish_reason + // otherwise treat the call as plain text. + if state.sawTool && (finish == "" || finish == "stop") { + finish = "tool_calls" + } + if finish == "" { + finish = "stop" + } + if err := emit(map[string]any{}, finish, state.usage.asMap()); err != nil { + return err + } + _, err = io.WriteString(dst, "data: [DONE]\n\n") + return err +} + +func (u upstreamUsage) asMap() map[string]any { + if u.prompt <= 0 && u.completion <= 0 && u.cacheRead <= 0 { + return nil + } + usage := map[string]any{ + "prompt_tokens": u.prompt, + "completion_tokens": u.completion, + "total_tokens": u.prompt + u.completion, + } + if u.cacheRead > 0 { + usage["prompt_tokens_details"] = map[string]any{"cached_tokens": u.cacheRead} + } + return usage +} + +func decodeUpstreamAnthropic(eventType, payload string, state *upstreamDecodeState) ([]upstreamDelta, bool, error) { + var event map[string]any + if json.Unmarshal([]byte(payload), &event) != nil { + return nil, false, nil + } + kind := upstreamJSONString(event, "type") + if kind == "" { + kind = eventType + } + switch kind { + case "message_start": + if message, ok := event["message"].(map[string]any); ok { + state.observeAnthropicUsage(message["usage"]) + } + return []upstreamDelta{{role: true}}, false, nil + case "content_block_start": + block, _ := event["content_block"].(map[string]any) + if upstreamJSONString(block, "type") != "tool_use" { + return nil, false, nil + } + state.toolIndex++ + state.rememberBlock(event, state.toolIndex) + id := upstreamJSONString(block, "id") + if id == "" { + id = upstreamNewID("toolu_") + } + return []upstreamDelta{{tools: []upstreamToolDelta{{ + index: state.toolIndex, id: id, name: upstreamJSONString(block, "name"), hasID: true, nameSet: true, + }}}}, false, nil + case "content_block_delta": + delta, _ := event["delta"].(map[string]any) + switch upstreamJSONString(delta, "type") { + case "text_delta": + if text := upstreamJSONString(delta, "text"); text != "" { + return []upstreamDelta{{content: text}}, false, nil + } + case "thinking_delta": + if text := upstreamJSONString(delta, "thinking"); text != "" { + return []upstreamDelta{{reasoning: text}}, false, nil + } + case "input_json_delta": + index := state.toolForBlock(event) + if partial := upstreamJSONString(delta, "partial_json"); partial != "" && index >= 0 { + return []upstreamDelta{{tools: []upstreamToolDelta{{index: index, args: partial}}}}, false, nil + } + } + case "message_delta": + state.observeAnthropicUsage(event["usage"]) + delta, _ := event["delta"].(map[string]any) + if reason := upstreamJSONString(delta, "stop_reason"); reason != "" { + state.finish = upstreamAnthropicStop(reason) + } + case "message_stop": + return nil, true, nil + case "error": + errObject, _ := event["error"].(map[string]any) + message := upstreamFirstNonEmpty(upstreamJSONString(errObject, "message"), upstreamJSONString(event, "message"), "upstream stream error") + return nil, false, fmt.Errorf("upstream stream: %s", message) + } + return nil, false, nil +} + +func decodeUpstreamResponses(eventType, payload string, state *upstreamDecodeState) ([]upstreamDelta, bool, error) { + var event map[string]any + if json.Unmarshal([]byte(payload), &event) != nil { + return nil, false, nil + } + kind := upstreamJSONString(event, "type") + if kind == "" { + kind = eventType + } + switch kind { + case "response.output_text.delta": + if text := upstreamJSONString(event, "delta"); text != "" { + return []upstreamDelta{{content: text}}, false, nil + } + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + if text := upstreamJSONString(event, "delta"); text != "" { + return []upstreamDelta{{reasoning: text}}, false, nil + } + case "response.output_item.added", "response.output_item.done": + item, _ := event["item"].(map[string]any) + if upstreamJSONString(item, "type") != "function_call" { + return nil, false, nil + } + mode := "open" + if kind == "response.output_item.done" { + mode = "done" + } + id := upstreamFirstNonEmpty(upstreamResponsePublicID(item, event), upstreamJSONString(item, "id")) + return state.oneTool(state.bindTool(upstreamResponseToolKeys(event, item)...), id, upstreamJSONString(item, "name"), upstreamJSONString(item, "arguments"), mode), false, nil + case "response.function_call_arguments.delta": + partial := upstreamJSONString(event, "delta") + if partial == "" { + return nil, false, nil + } + return state.oneTool(state.bindTool(upstreamResponseToolKeys(event, nil)...), "", "", partial, "delta"), false, nil + case "response.function_call_arguments.done": + return state.oneTool(state.bindTool(upstreamResponseToolKeys(event, nil)...), upstreamResponsePublicID(nil, event), upstreamJSONString(event, "name"), upstreamJSONString(event, "arguments"), "done"), false, nil + case "response.completed": + state.observeResponsesUsage(event["response"]) + if state.finish == "" { + state.finish = "stop" + } + return state.completedFunctionCalls(event), true, nil + case "response.incomplete": + state.finish = "length" + state.observeResponsesUsage(event["response"]) + return state.completedFunctionCalls(event), true, nil + case "response.failed", "error": + message := upstreamJSONString(event, "message") + if errObject, ok := event["error"].(map[string]any); ok { + message = upstreamFirstNonEmpty(upstreamJSONString(errObject, "message"), message) + } + if response, ok := event["response"].(map[string]any); ok { + if errObject, ok := response["error"].(map[string]any); ok { + message = upstreamFirstNonEmpty(upstreamJSONString(errObject, "message"), message) + } + } + if message == "" { + message = "upstream stream error" + } + return nil, false, fmt.Errorf("upstream stream: %s", message) + } + return nil, false, nil +} + +// bindTool keeps one OpenAI tool index for a Responses call. output_index, +// item id, and call_id arrive on different events and must share that index, +// otherwise argument deltas land on a second empty call. +func (s *upstreamDecodeState) bindTool(keys ...string) int { + if s.toolByID == nil { + s.toolByID = map[string]int{} + } + usable := make([]string, 0, len(keys)) + index := -1 + for _, key := range keys { + if key == "" { + continue + } + usable = append(usable, key) + if found, ok := s.toolByID[key]; ok && index < 0 { + index = found + } + } + if index < 0 { + if len(usable) == 0 && s.toolIndex >= 0 { + return s.toolIndex + } + s.toolIndex++ + index = s.toolIndex + } + for _, key := range usable { + s.toolByID[key] = index + } + return index +} + +func (s *upstreamDecodeState) rememberBlock(event map[string]any, toolIndex int) { + n, ok := upstreamJSONIntOK(event["index"]) + if !ok { + return + } + if s.blockTool == nil { + s.blockTool = map[int]int{} + } + s.blockTool[n] = toolIndex +} + +func (s *upstreamDecodeState) toolForBlock(event map[string]any) int { + if n, ok := upstreamJSONIntOK(event["index"]); ok && s.blockTool != nil { + if index, found := s.blockTool[n]; found { + return index + } + } + return s.toolIndex +} + +func upstreamResponseToolKeys(event, item map[string]any) []string { + keys := make([]string, 0, 4) + if event != nil { + if n, ok := upstreamJSONIntOK(event["output_index"]); ok { + keys = append(keys, fmt.Sprintf("out:%d", n)) + } + if id := upstreamJSONString(event, "item_id"); id != "" { + keys = append(keys, "item:"+id) + } + if id := upstreamJSONString(event, "call_id"); id != "" { + keys = append(keys, "call:"+id) + } + } + if item != nil { + if id := upstreamJSONString(item, "id"); id != "" { + keys = append(keys, "item:"+id) + } + if id := upstreamJSONString(item, "call_id"); id != "" { + keys = append(keys, "call:"+id) + } + } + return keys +} + +func upstreamResponsePublicID(item, event map[string]any) string { + if item != nil { + if id := upstreamJSONString(item, "call_id"); id != "" { + return id + } + } + if event != nil { + if id := upstreamJSONString(event, "call_id"); id != "" { + return id + } + } + return "" +} + +func (s *upstreamDecodeState) oneTool(index int, id, name, args, mode string) []upstreamDelta { + call, ok := s.announceTool(index, id, name, args, mode) + if !ok { + return nil + } + return []upstreamDelta{{tools: []upstreamToolDelta{call}}} +} + +// announceTool emits the next OpenAI tool delta. Delta events append +// fragments. A later done or completed snapshot supplies the full arguments +// only when no fragment arrived, so the client does not see them twice. +func (s *upstreamDecodeState) announceTool(index int, id, name, args, mode string) (upstreamToolDelta, bool) { + if s.toolNamed == nil { + s.toolNamed = map[int]bool{} + } + if s.toolArgued == nil { + s.toolArgued = map[int]bool{} + } + if s.toolDone == nil { + s.toolDone = map[int]bool{} + } + call := upstreamToolDelta{index: index} + send := false + if mode == "delta" { + if args != "" && !s.toolDone[index] { + call.args = args + s.toolArgued[index] = true + send = true + } + } else if !s.toolNamed[index] && (id != "" || name != "") { + if id != "" { + call.id = id + call.hasID = true + } + if name != "" { + call.name = name + call.nameSet = true + } + s.toolNamed[index] = true + send = true + } + if mode != "delta" && args != "" && !s.toolArgued[index] { + call.args = args + s.toolArgued[index] = true + s.toolDone[index] = true + send = true + } + if !send { + return upstreamToolDelta{}, false + } + s.sawTool = true + return call, true +} + +func (s *upstreamDecodeState) completedFunctionCalls(event map[string]any) []upstreamDelta { + response, _ := event["response"].(map[string]any) + output, _ := response["output"].([]any) + calls := make([]upstreamToolDelta, 0, len(output)) + for _, raw := range output { + item, ok := raw.(map[string]any) + if !ok || upstreamJSONString(item, "type") != "function_call" { + continue + } + id := upstreamResponsePublicID(item, nil) + if id == "" { + id = upstreamJSONString(item, "id") + } + call, ok := s.announceTool(s.bindTool(upstreamResponseToolKeys(nil, item)...), id, upstreamJSONString(item, "name"), upstreamJSONString(item, "arguments"), "done") + if ok { + calls = append(calls, call) + } + } + if len(calls) == 0 { + return nil + } + return []upstreamDelta{{tools: calls}} +} + +func (s *upstreamDecodeState) observeAnthropicUsage(raw any) { + usage, ok := raw.(map[string]any) + if !ok { + return + } + if value := upstreamJSONInt(usage["input_tokens"]); value > 0 { + s.usage.prompt = value + } + if value := upstreamJSONInt(usage["output_tokens"]); value > 0 { + s.usage.completion = value + } + if value := upstreamJSONInt(usage["cache_read_input_tokens"]); value > 0 { + s.usage.cacheRead = value + } +} + +func (s *upstreamDecodeState) observeResponsesUsage(raw any) { + response, ok := raw.(map[string]any) + if !ok { + return + } + usage, ok := response["usage"].(map[string]any) + if !ok { + return + } + if value := upstreamJSONInt(usage["input_tokens"]); value > 0 { + s.usage.prompt = value + } + if value := upstreamJSONInt(usage["output_tokens"]); value > 0 { + s.usage.completion = value + } + if details, ok := usage["input_tokens_details"].(map[string]any); ok { + if value := upstreamJSONInt(details["cached_tokens"]); value > 0 { + s.usage.cacheRead = value + } + } +} + +func upstreamAnthropicStop(reason string) string { + switch reason { + case "max_tokens": + return "length" + case "tool_use": + return "tool_calls" + case "refusal": + return "content_filter" + default: + return "stop" + } +} + +func upstreamJSONString(obj map[string]any, key string) string { + if obj == nil { + return "" + } + value, _ := obj[key].(string) + return value +} + +func upstreamJSONInt(raw any) int { + n, ok := upstreamJSONIntOK(raw) + if !ok { + return 0 + } + return n +} + +func upstreamJSONIntOK(raw any) (int, bool) { + switch value := raw.(type) { + case float64: + return int(value), true + case int: + return value, true + case json.Number: + n, err := value.Int64() + return int(n), err == nil + default: + return 0, false + } +} + +func readUpstreamSSE(src io.Reader, handle func(eventType, data string) (bool, error)) error { + reader := bufio.NewReaderSize(src, 64<<10) + var eventType string + var dataLines []string + dispatch := func() (bool, error) { + if eventType == "" && len(dataLines) == 0 { + return false, nil + } + payload := strings.Join(dataLines, "\n") + event, data := eventType, payload + eventType, dataLines = "", nil + if strings.TrimSpace(payload) == "" { + return false, nil + } + return handle(event, data) + } + for { + line, err := reader.ReadString('\n') + line = strings.TrimRight(line, "\r\n") + if line == "" { + done, handleErr := dispatch() + if handleErr != nil { + return handleErr + } + if done { + return nil + } + } else if strings.HasPrefix(line, "event:") { + eventType = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + } else if strings.HasPrefix(line, "data:") { + dataLines = append(dataLines, strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + } + if err != nil { + if err == io.EOF { + _, handleErr := dispatch() + return handleErr + } + return err + } + } +}