mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
feat(models): add collision-safe aliases and model echoes (#125)
This commit is contained in:
1 parent
a0fbd6b6cb
commit
9b44a031ca
14 files changed
+443
-23
No files matched your search
@@ -201,6 +201,12 @@ type SecretInput struct {
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
type ModelsUpdate struct {
|
||||
config.ModelsConfig
|
||||
Aliases *map[string]string `json:"aliases,omitempty"`
|
||||
StripFreeSuffix *bool `json:"strip_free_suffix,omitempty"`
|
||||
}
|
||||
|
||||
// ConfigUpdate is the body of PUT /api/config. Secrets carry either a new
|
||||
// value or the ID of the existing one. The WebUI username and password are
|
||||
// not changed here; they go through /api/account.
|
||||
@@ -217,7 +223,7 @@ type ConfigUpdate struct {
|
||||
ProxyBindings map[string]string `json:"proxy_bindings,omitempty"`
|
||||
Upstream config.UpstreamConfig `json:"upstream"`
|
||||
Retry config.RetryConfig `json:"retry"`
|
||||
Models config.ModelsConfig `json:"models"`
|
||||
Models ModelsUpdate `json:"models"`
|
||||
Performance config.PerformanceConfig `json:"performance"`
|
||||
Logging config.LoggingConfig `json:"logging"`
|
||||
Prefer config.Tier `json:"prefer"`
|
||||
@@ -280,7 +286,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
|
||||
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile,
|
||||
ProxyBindings: proxyBindings,
|
||||
KeysDirect: current.KeysDirect,
|
||||
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
|
||||
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
|
||||
Reasoning: reasoning,
|
||||
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
|
||||
}
|
||||
@@ -296,6 +302,14 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if update.KeysDirect != nil {
|
||||
candidate.KeysDirect = *update.KeysDirect
|
||||
}
|
||||
candidate.Models.Aliases = latest.Models.Aliases
|
||||
if update.Models.Aliases != nil {
|
||||
candidate.Models.Aliases = *update.Models.Aliases
|
||||
}
|
||||
candidate.Models.StripFreeSuffix = latest.Models.StripFreeSuffix
|
||||
if update.Models.StripFreeSuffix != nil {
|
||||
candidate.Models.StripFreeSuffix = *update.Models.StripFreeSuffix
|
||||
}
|
||||
candidate.WebUI.Username = latest.WebUI.Username
|
||||
candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash
|
||||
if update.Reasoning == nil {
|
||||
|
||||
@@ -192,8 +192,10 @@ type RetryConfig struct {
|
||||
// catalog refresh interval, and Protocols maps a model ID to the wire protocol
|
||||
// used upstream, overriding the one the catalog reports.
|
||||
type ModelsConfig struct {
|
||||
RefreshSeconds int `json:"refresh_seconds"`
|
||||
Protocols map[string]string `json:"protocols"`
|
||||
RefreshSeconds int `json:"refresh_seconds"`
|
||||
Protocols map[string]string `json:"protocols"`
|
||||
Aliases map[string]string `json:"aliases,omitempty"`
|
||||
StripFreeSuffix bool `json:"strip_free_suffix,omitempty"`
|
||||
// FreeOnly limits discovery and routing to free models, even when Zen or
|
||||
// Go keys could serve paid ones. Free models may still fall back to keys.
|
||||
FreeOnly bool `json:"free_only"`
|
||||
@@ -511,6 +513,9 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if err := normalizeModelAliases(&cfg); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
for model, protocol := range cfg.Models.Protocols {
|
||||
if model == "" || !wire.Valid(wire.Protocol(protocol)) {
|
||||
return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol)
|
||||
@@ -649,6 +654,13 @@ func Clone(cfg Config) Config {
|
||||
}
|
||||
cfg.Models.Protocols = protocols
|
||||
}
|
||||
if cfg.Models.Aliases != nil {
|
||||
aliases := make(map[string]string, len(cfg.Models.Aliases))
|
||||
for public, model := range cfg.Models.Aliases {
|
||||
aliases[public] = model
|
||||
}
|
||||
cfg.Models.Aliases = aliases
|
||||
}
|
||||
if cfg.Reasoning.EffortByModel != nil {
|
||||
efforts := make(map[string]string, len(cfg.Reasoning.EffortByModel))
|
||||
for model, effort := range cfg.Reasoning.EffortByModel {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"opencode2api/internal/oauth"
|
||||
)
|
||||
|
||||
const FreeSuffix = "-free"
|
||||
|
||||
func StripFreeSuffix(model string) (string, bool) {
|
||||
base, found := strings.CutSuffix(model, FreeSuffix)
|
||||
if !found || base == "" {
|
||||
return model, false
|
||||
}
|
||||
return base, true
|
||||
}
|
||||
|
||||
func normalizeModelAliases(cfg *Config) error {
|
||||
if len(cfg.Models.Aliases) == 0 {
|
||||
return nil
|
||||
}
|
||||
aliases := make(map[string]string, len(cfg.Models.Aliases))
|
||||
for public, model := range cfg.Models.Aliases {
|
||||
if strings.ContainsFunc(public, unicode.IsControl) || strings.ContainsFunc(model, unicode.IsControl) {
|
||||
return errors.New("models.aliases must contain nonempty model names without control characters")
|
||||
}
|
||||
public, model = strings.TrimSpace(public), strings.TrimSpace(model)
|
||||
if public == "" || model == "" {
|
||||
return errors.New("models.aliases must contain nonempty model names without control characters")
|
||||
}
|
||||
if existing, found := aliases[public]; found && existing != model {
|
||||
return errors.New("models.aliases contains conflicting entries for the same public name")
|
||||
}
|
||||
if public == cfg.Rotation.SOTA.Alias || public == cfg.Rotation.Sweet.Alias || model == cfg.Rotation.SOTA.Alias || model == cfg.Rotation.Sweet.Alias {
|
||||
return errors.New("models.aliases must not use a rotation group alias as a public name or upstream model")
|
||||
}
|
||||
aliases[public] = model
|
||||
}
|
||||
known := make(map[string]bool, len(aliases)+len(cfg.Models.Protocols))
|
||||
for _, model := range aliases {
|
||||
known[model] = true
|
||||
}
|
||||
for model := range cfg.Models.Protocols {
|
||||
known[model] = true
|
||||
}
|
||||
for _, connection := range []*oauth.Connection{cfg.GoOAuth, cfg.ZenOAuth} {
|
||||
if connection == nil {
|
||||
continue
|
||||
}
|
||||
for model := range connection.Routes {
|
||||
known[model] = true
|
||||
}
|
||||
}
|
||||
for public, model := range aliases {
|
||||
if public != model && known[public] {
|
||||
return fmt.Errorf("models.aliases public name %q shadows an upstream model ID", public)
|
||||
}
|
||||
}
|
||||
cfg.Models.Aliases = aliases
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/models"
|
||||
"opencode2api/internal/oauth"
|
||||
)
|
||||
|
||||
type modelNames struct {
|
||||
public map[string]string
|
||||
resolved map[string]string
|
||||
}
|
||||
|
||||
func (g *Gateway) knownModelName(model string) bool {
|
||||
if g.catalog.Known(model) || g.cfg.Models.Protocols[model] != "" {
|
||||
return true
|
||||
}
|
||||
for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} {
|
||||
if connection != nil {
|
||||
if _, found := connection.Routes[model]; found {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (g *Gateway) validateModelAliases() error {
|
||||
for public, model := range g.cfg.Models.Aliases {
|
||||
if public != model && g.knownModelName(public) {
|
||||
return fmt.Errorf("models.aliases public name %q shadows an upstream model ID", public)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Gateway) modelNames(routes []models.Route) modelNames {
|
||||
names := modelNames{
|
||||
public: make(map[string]string, len(routes)),
|
||||
resolved: make(map[string]string, len(g.cfg.Models.Aliases)+len(routes)),
|
||||
}
|
||||
available := make(map[string]bool, len(routes))
|
||||
reserved := map[string]bool{g.cfg.Rotation.SOTA.Alias: true, g.cfg.Rotation.Sweet.Alias: true}
|
||||
for _, route := range routes {
|
||||
available[route.ID] = true
|
||||
reserved[route.ID] = true
|
||||
names.public[route.ID] = route.ID
|
||||
}
|
||||
aliases := make([]string, 0, len(g.cfg.Models.Aliases))
|
||||
for public := range g.cfg.Models.Aliases {
|
||||
aliases = append(aliases, public)
|
||||
reserved[public] = true
|
||||
reserved[g.cfg.Models.Aliases[public]] = true
|
||||
}
|
||||
slices.Sort(aliases)
|
||||
explicit := make(map[string]bool, len(aliases))
|
||||
for _, public := range aliases {
|
||||
model := g.cfg.Models.Aliases[public]
|
||||
if public != model && (available[public] || g.knownModelName(public)) {
|
||||
continue
|
||||
}
|
||||
names.resolved[public] = model
|
||||
if available[model] && !explicit[model] {
|
||||
names.public[model] = public
|
||||
explicit[model] = true
|
||||
}
|
||||
}
|
||||
if g.cfg.Models.StripFreeSuffix {
|
||||
for _, route := range routes {
|
||||
if explicit[route.ID] {
|
||||
continue
|
||||
}
|
||||
base, stripped := config.StripFreeSuffix(route.ID)
|
||||
if !stripped || reserved[base] || g.knownModelName(base) {
|
||||
continue
|
||||
}
|
||||
names.public[route.ID] = base
|
||||
names.resolved[base] = route.ID
|
||||
reserved[base] = true
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func (g *Gateway) resolveModel(name string) (real, public string) {
|
||||
if len(g.cfg.Models.Aliases) == 0 && !g.cfg.Models.StripFreeSuffix {
|
||||
return name, name
|
||||
}
|
||||
routes, _ := g.availableModels()
|
||||
names := g.modelNames(routes)
|
||||
if model, found := names.resolved[name]; found {
|
||||
return model, name
|
||||
}
|
||||
return name, name
|
||||
}
|
||||
|
||||
func rewriteModelBody(body []byte, model string, stripEnvironment bool) ([]byte, error) {
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encodedModel, err := json.Marshal(model)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload["model"] = encodedModel
|
||||
if stripEnvironment {
|
||||
delete(payload, "client_environment")
|
||||
}
|
||||
return json.Marshal(payload)
|
||||
}
|
||||
+32
-15
@@ -319,6 +319,13 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
g.handleRotation(w, r, external, payload, id, model)
|
||||
return
|
||||
}
|
||||
model, publicModel := g.resolveModel(model)
|
||||
if model != publicModel {
|
||||
payload["model"] = model
|
||||
if meta != nil {
|
||||
meta.Model, meta.ModelAlias = model, publicModel
|
||||
}
|
||||
}
|
||||
oauthModel := false
|
||||
for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} {
|
||||
if connection != nil {
|
||||
@@ -371,15 +378,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
wire.WriteError(w, external, http.StatusBadRequest, "this model uses System One decisions, not chat; send state and typed questions to /v1/systemone", "invalid_request_error", "model")
|
||||
return
|
||||
}
|
||||
if strippedEnvironment {
|
||||
if strippedEnvironment || model != publicModel {
|
||||
// This path forwards raw bytes rather than converting payload.
|
||||
body, err = jsonutil.Marshal(payload)
|
||||
body, err = rewriteModelBody(body, model, strippedEnvironment)
|
||||
if err != nil {
|
||||
wire.WriteError(w, external, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
g.forwardSystemOne(w, r, body, payload, model, route)
|
||||
g.forwardSystemOne(w, r, body, payload, model, publicModel, route)
|
||||
return
|
||||
}
|
||||
bodies, err := g.prepareRouteBodies(external, route, payload)
|
||||
@@ -491,6 +498,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, toolRenames)
|
||||
streamBody = wire.RenameStreamModel(streamBody, model, publicModel)
|
||||
var usage wire.Usage
|
||||
var usageReported bool
|
||||
if external == upstreamRoute.Protocol {
|
||||
@@ -498,10 +506,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
if flusher, ok := w.(http.Flusher); ok {
|
||||
streamWriter = &deferredStreamWriter{ResponseWriter: w, flusher: flusher, status: resp.StatusCode}
|
||||
}
|
||||
usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, model)
|
||||
usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, publicModel)
|
||||
} else {
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model)
|
||||
usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, publicModel)
|
||||
}
|
||||
if meta != nil {
|
||||
meta.Usage, meta.UsageReported = usage, usageReported
|
||||
@@ -551,6 +559,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
}
|
||||
responseBody = wire.RenameResponseModel(responseBody, model, publicModel)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
_, _ = w.Write(responseBody)
|
||||
@@ -604,13 +613,6 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "client_environment")
|
||||
return
|
||||
}
|
||||
if strippedEnvironment {
|
||||
body, err = jsonutil.Marshal(payload)
|
||||
if err != nil {
|
||||
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
model := jsonutil.StringAt(payload, "model")
|
||||
if meta := telemetry.MetaFromRequest(r); meta != nil {
|
||||
meta.Model = model
|
||||
@@ -619,6 +621,17 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "model is required", "invalid_request_error", "model")
|
||||
return
|
||||
}
|
||||
model, publicModel := g.resolveModel(model)
|
||||
if model != publicModel {
|
||||
payload["model"] = model
|
||||
}
|
||||
if strippedEnvironment || model != publicModel {
|
||||
body, err = rewriteModelBody(body, model, strippedEnvironment)
|
||||
if err != nil {
|
||||
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !g.catalog.Supported(model) {
|
||||
// Same split as the chat path: a model the catalog has never heard of
|
||||
// is a bad model NAME (404), a model it knows but cannot serve is a
|
||||
@@ -639,7 +652,7 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, fmt.Sprintf("the model does not use the %s protocol", wire.SystemOne), "invalid_request_error", "model")
|
||||
return
|
||||
}
|
||||
g.forwardSystemOne(w, r, body, payload, model, route)
|
||||
g.forwardSystemOne(w, r, body, payload, model, publicModel, route)
|
||||
}
|
||||
|
||||
// forwardSystemOne relays a System One decision payload verbatim to the
|
||||
@@ -647,10 +660,13 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
// The payload pairs a free-form state with typed questions, which no
|
||||
// message-shaped upstream protocol accepts, so it is never translated. Answers
|
||||
// are non-streaming today; a streaming upstream reply is still relayed.
|
||||
func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model string, route models.Route) {
|
||||
func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model, publicModel string, route models.Route) {
|
||||
meta := telemetry.MetaFromRequest(r)
|
||||
if meta != nil {
|
||||
meta.Model = model
|
||||
if model != publicModel {
|
||||
meta.ModelAlias = publicModel
|
||||
}
|
||||
meta.Tier = string(route.Tier)
|
||||
meta.Protocol = route.Protocol
|
||||
}
|
||||
@@ -720,7 +736,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
_, _ = io.Copy(w, resp.Body)
|
||||
_, _ = io.Copy(w, wire.RenameStreamModel(resp.Body, model, publicModel))
|
||||
return
|
||||
}
|
||||
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1))
|
||||
@@ -735,6 +751,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
|
||||
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
|
||||
meta.Usage, meta.UsageReported = usage, reported
|
||||
}
|
||||
responseBody = wire.RenameResponseModel(responseBody, model, publicModel)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
_, _ = w.Write(responseBody)
|
||||
|
||||
@@ -238,12 +238,13 @@ func (g *Gateway) reasoningEfforts(model string, route modelcatalog.Route) []str
|
||||
func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
|
||||
now := time.Now().Unix()
|
||||
routes, _ := g.availableModels()
|
||||
names := g.modelNames(routes)
|
||||
data := make([]map[string]any, 0, len(routes))
|
||||
for _, route := range routes {
|
||||
model := route.ID
|
||||
model := names.public[route.ID]
|
||||
// Tier-scoped metadata: the advertised context window must match
|
||||
// the tier that will serve the request (anonymous ⇒ Zen).
|
||||
md := g.catalog.MetadataForTier(model, route.Tier)
|
||||
md := g.catalog.MetadataForTier(route.ID, route.Tier)
|
||||
entry := map[string]any{
|
||||
"id": model, "object": "model", "created": now, "owned_by": "opencode",
|
||||
"metadata": md,
|
||||
@@ -269,12 +270,12 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) {
|
||||
if md.Reasoning {
|
||||
entry["reasoning"] = true
|
||||
entry["supports_reasoning"] = true
|
||||
efforts := g.reasoningEfforts(model, route)
|
||||
efforts := g.reasoningEfforts(route.ID, route)
|
||||
entry["reasoning_efforts"] = efforts
|
||||
// OpenClaw and similar harnesses read effort levels from compat
|
||||
// rather than inferring them, and otherwise offer only off/max.
|
||||
entry["compat"] = map[string]any{"supportsReasoningEffort": true, "supportedReasoningEfforts": efforts}
|
||||
if effort := g.resolvedEffort(model, route.Tier, route.Protocol); effort != "" && effort != "none" {
|
||||
if effort := g.resolvedEffort(route.ID, route.Tier, route.Protocol); effort != "" && effort != "none" {
|
||||
entry["default_reasoning_effort"] = effort
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,12 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config,
|
||||
}
|
||||
}
|
||||
runtime.gateway.restoreOAuthCatalog()
|
||||
if err := runtime.gateway.validateModelAliases(); err != nil {
|
||||
if runtime.warpCreated && runtime.warpPool != nil {
|
||||
runtime.warpPool.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil {
|
||||
if runtime.warpCreated && runtime.warpPool != nil {
|
||||
runtime.warpPool.Close()
|
||||
@@ -405,6 +411,12 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) (
|
||||
next.gateway.catalog.CopyState(current.gateway.catalog)
|
||||
}
|
||||
next.gateway.restoreOAuthCatalog()
|
||||
if err := next.gateway.validateModelAliases(); err != nil {
|
||||
if next.warpCreated && next.warpPool != nil {
|
||||
next.warpPool.Close()
|
||||
}
|
||||
return ApplyResult{}, err
|
||||
}
|
||||
if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil {
|
||||
if next.warpCreated && next.warpPool != nil {
|
||||
next.warpPool.Close()
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func RenameResponseModel(body []byte, fromModel, toModel string) []byte {
|
||||
if fromModel == "" || toModel == "" || fromModel == toModel {
|
||||
return body
|
||||
}
|
||||
var payload map[string]any
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&payload) != nil || payload == nil {
|
||||
return body
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return body
|
||||
}
|
||||
rename := func(container map[string]any) bool {
|
||||
model, found := container["model"].(string)
|
||||
if !found || model == "" || model == toModel {
|
||||
return false
|
||||
}
|
||||
container["model"] = toModel
|
||||
return true
|
||||
}
|
||||
changed := rename(payload)
|
||||
eventType, _ := payload["type"].(string)
|
||||
if strings.HasPrefix(eventType, "response.") {
|
||||
response, _ := payload["response"].(map[string]any)
|
||||
changed = rename(response) || changed
|
||||
}
|
||||
if eventType == "message_start" {
|
||||
message, _ := payload["message"].(map[string]any)
|
||||
changed = rename(message) || changed
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
func RenameStreamModel(reader io.Reader, fromModel, toModel string) io.Reader {
|
||||
if fromModel == "" || toModel == "" || fromModel == toModel {
|
||||
return reader
|
||||
}
|
||||
return &modelStreamReader{
|
||||
reader: bufio.NewReaderSize(reader, 64<<10),
|
||||
from: fromModel,
|
||||
to: toModel,
|
||||
}
|
||||
}
|
||||
|
||||
type modelStreamReader struct {
|
||||
reader *bufio.Reader
|
||||
from string
|
||||
to string
|
||||
pending []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (reader *modelStreamReader) Read(data []byte) (int, error) {
|
||||
if len(data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
for len(reader.pending) == 0 {
|
||||
if reader.err != nil {
|
||||
return 0, reader.err
|
||||
}
|
||||
var frame []byte
|
||||
lineStart := 0
|
||||
for {
|
||||
part, err := reader.reader.ReadSlice('\n')
|
||||
if len(frame)+len(part) > maxSSEFrameBytes {
|
||||
reader.err = errSSEFrameTooLarge
|
||||
return 0, reader.err
|
||||
}
|
||||
frame = append(frame, part...)
|
||||
if errors.Is(err, bufio.ErrBufferFull) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
reader.err = err
|
||||
reader.pending = frame
|
||||
break
|
||||
}
|
||||
line := bytes.TrimSuffix(bytes.TrimSuffix(frame[lineStart:], []byte("\n")), []byte("\r"))
|
||||
if len(line) == 0 {
|
||||
reader.pending = reader.rewrite(frame)
|
||||
break
|
||||
}
|
||||
lineStart = len(frame)
|
||||
}
|
||||
}
|
||||
count := copy(data, reader.pending)
|
||||
reader.pending = reader.pending[count:]
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (reader *modelStreamReader) rewrite(frame []byte) []byte {
|
||||
lines := bytes.SplitAfter(frame, []byte("\n"))
|
||||
var payload bytes.Buffer
|
||||
for _, line := range lines {
|
||||
if !bytes.HasPrefix(line, []byte("data:")) {
|
||||
continue
|
||||
}
|
||||
if payload.Len() > 0 {
|
||||
payload.WriteByte('\n')
|
||||
}
|
||||
payload.Write(bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))))
|
||||
}
|
||||
if payload.Len() == 0 {
|
||||
return frame
|
||||
}
|
||||
rewritten := RenameResponseModel(payload.Bytes(), reader.from, reader.to)
|
||||
if bytes.Equal(rewritten, payload.Bytes()) {
|
||||
return frame
|
||||
}
|
||||
var output bytes.Buffer
|
||||
written := false
|
||||
for _, line := range lines {
|
||||
if !bytes.HasPrefix(line, []byte("data:")) {
|
||||
output.Write(line)
|
||||
continue
|
||||
}
|
||||
if written {
|
||||
continue
|
||||
}
|
||||
output.WriteString("data: ")
|
||||
output.Write(rewritten)
|
||||
if bytes.HasSuffix(line, []byte("\r\n")) {
|
||||
output.WriteString("\r\n")
|
||||
} else if bytes.HasSuffix(line, []byte("\n")) {
|
||||
output.WriteByte('\n')
|
||||
}
|
||||
written = true
|
||||
}
|
||||
return output.Bytes()
|
||||
}
|
||||
Reference in new issue
Block a user