diff --git a/THIRD-PARTY-LICENSES.md b/THIRD-PARTY-LICENSES.md index b5ffe7c853..05dca08f96 100644 --- a/THIRD-PARTY-LICENSES.md +++ b/THIRD-PARTY-LICENSES.md @@ -14,6 +14,7 @@ Transitive dependencies should be audited before a final external release. | backend | production | Go | `github.com/Calcium-Ion/go-epay` | `v0.0.5` | MIT | | backend | production | Go | `github.com/Calcium-Ion/moejs` | `v0.1.0-alpha.7` | Apache-2.0 | | backend | production | Go | `github.com/ClickHouse/clickhouse-go/v2` | `v2.46.0` | Apache-2.0 | +| backend | production | Go | `github.com/MoeForge/moego` | `v0.1.0-alpha.1` | MIT | | backend | production | Go | `github.com/abema/go-mp4` | `v1.4.1` | MIT | | backend | test | Go | `github.com/alicebob/miniredis/v2` | `v2.38.0` | MIT | | backend | production | Go | `github.com/andybalholm/brotli` | `v1.2.0` | MIT | @@ -65,7 +66,6 @@ Transitive dependencies should be audited before a final external release. | backend | production | Go | `github.com/tcolgate/mp3` | `v0.0.0-20170426193717-e79c5a46d300` | MIT | | backend | production | Go | `github.com/thanhpk/randstr` | `v1.0.6` | MIT | | backend | production | Go | `github.com/tidwall/gjson` | `v1.19.0` | MIT | -| backend | production | Go | `github.com/tidwall/sjson` | `v1.2.5` | MIT | | backend | production | Go | `github.com/tiktoken-go/tokenizer` | `v0.8.1` | MIT | | backend | production | Go | `github.com/waffo-com/waffo-go` | `v1.3.2` | MIT | | backend | production | Go | `github.com/waffo-com/waffo-pancake-sdk-go` | `v0.3.1` | MIT | diff --git a/common/json_test.go b/common/json_test.go index 735f741c8f..e44faf5928 100644 --- a/common/json_test.go +++ b/common/json_test.go @@ -5,11 +5,11 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/go-playground/validator/v10" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestJsonRawMessageToString(t *testing.T) { @@ -219,18 +219,18 @@ func TestHostJSONCodecConformance(t *testing.T) { encoded, err := Marshal(req) require.NoError(t, err) - messages := gjson.GetBytes(encoded, "messages").Array() + messages := ojson.GetBytes(encoded, "messages").Array() require.Len(t, messages, 2) // Kimi K3 dynamic tool loading: tools survive and no content key is emitted. assert.Equal(t, "system", messages[0].Get("role").String()) - assert.JSONEq(t, gjson.GetBytes(raw, "messages.0.tools").Raw, messages[0].Get("tools").Raw) + assert.JSONEq(t, ojson.GetBytes(raw, "messages.0.tools").Raw, messages[0].Get("tools").Raw) assert.False(t, messages[0].Get("content").Exists()) // Assistant tool-call replay still carries an explicit "content": null. assistantContent := messages[1].Get("content") assert.True(t, assistantContent.Exists()) - assert.Equal(t, gjson.Null, assistantContent.Type) - assert.JSONEq(t, gjson.GetBytes(raw, "messages.1.tool_calls").Raw, messages[1].Get("tool_calls").Raw) + assert.Equal(t, ojson.Null, assistantContent.Type) + assert.JSONEq(t, ojson.GetBytes(raw, "messages.1.tool_calls").Raw, messages[1].Get("tool_calls").Raw) }) } diff --git a/common/log_text.zh-CN.json b/common/log_text.zh-CN.json index bd474c34d7..d7118ebf44 100644 --- a/common/log_text.zh-CN.json +++ b/common/log_text.zh-CN.json @@ -143,9 +143,7 @@ "Redis database: %d": "Redis 数据库: %d", "Redis is enabled": "Redis 已启用", "Redis ping test failed: %s": "Redis 连接测试失败: %s", - "RemoveDisabledFields Marshal error :%s": "RemoveDisabledFields 序列化失败 :%s", "RemoveDisabledFields Unmarshal error :%s": "RemoveDisabledFields 反序列化失败 :%s", - "RemoveGeminiDisabledFields Marshal error: %s": "RemoveGeminiDisabledFields 序列化失败: %s", "RemoveGeminiDisabledFields Unmarshal error: %s": "RemoveGeminiDisabledFields 反序列化失败: %s", "Rerank request body: %s": "重排序请求体: %s", "Resend rejected the email: status=%d name=%q message=%q": "Resend 拒绝发送邮件: status=%d name=%q message=%q", diff --git a/controller/channel-test.go b/controller/channel-test.go index d9e16fda7b..4c5a58221b 100644 --- a/controller/channel-test.go +++ b/controller/channel-test.go @@ -30,8 +30,8 @@ import ( "github.com/QuantumNous/new-api/setting/operation_setting" hosttypes "github.com/QuantumNous/new-api/types" + "github.com/MoeForge/moego/ojson" "github.com/samber/lo" - "github.com/tidwall/gjson" "github.com/gin-gonic/gin" ) @@ -677,16 +677,16 @@ func detectErrorMessageFromJSONBytes(jsonBytes []byte) string { if jsonBytes[0] != '{' && jsonBytes[0] != '[' { return "" } - errVal := gjson.GetBytes(jsonBytes, "error") - if !errVal.Exists() || errVal.Type == gjson.Null { + errVal := ojson.GetBytes(jsonBytes, "error") + if !errVal.Exists() || errVal.Type == ojson.Null { return "" } - message := gjson.GetBytes(jsonBytes, "error.message").String() + message := ojson.GetBytes(jsonBytes, "error.message").String() if message == "" { - message = gjson.GetBytes(jsonBytes, "error.error.message").String() + message = ojson.GetBytes(jsonBytes, "error.error.message").String() } - if message == "" && errVal.Type == gjson.String { + if message == "" && errVal.Type == ojson.String { message = errVal.String() } if message == "" { diff --git a/controller/video_proxy.go b/controller/video_proxy.go index b481866e62..88e9efea12 100644 --- a/controller/video_proxy.go +++ b/controller/video_proxy.go @@ -3,7 +3,6 @@ package controller import ( "bytes" "context" - "encoding/base64" "errors" "fmt" "io" @@ -15,6 +14,8 @@ import ( "sync" "time" + "github.com/MoeForge/moego/base64" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/logger" @@ -24,7 +25,6 @@ import ( "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/setting/system_setting" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" "golang.org/x/net/http/httpguts" ) @@ -360,21 +360,23 @@ func writeTaskMediaContentPath(c *gin.Context, body io.Reader, descriptor *relay message: "Artifact request was rejected", err: errTaskMediaRequestRejected, } } - if !gjson.ValidBytes(raw) { + if !ojson.ValidBytes(raw) { return &taskMediaProxyError{ status: http.StatusBadGateway, code: "artifact_upstream_error", message: "Failed to decode artifact content", } } - operation := gjson.ParseBytes(raw) - if failure := operation.Get("error"); failure.Exists() && failure.Type != gjson.Null { + // The root shares memory with raw, which stays unchanged until the + // artifact is written, so the base64 payload is not copied. + operation := ojson.GetBytesNoCopy(raw, "@this") + if failure := operation.Get("error"); failure.Exists() && failure.Type != ojson.Null { return &taskMediaProxyError{ status: http.StatusBadGateway, code: "artifact_upstream_error", message: "Artifact upstream returned an error", } } // An interaction reports completion through status, not done. - if operation.Get("done").Type != gjson.True && operation.Get("status").String() != "completed" { + if operation.Get("done").Type != ojson.True && operation.Get("status").String() != "completed" { return &taskMediaProxyError{ status: http.StatusConflict, code: "artifact_not_ready", message: "Task artifacts are not ready", @@ -383,7 +385,7 @@ func writeTaskMediaContentPath(c *gin.Context, body io.Reader, descriptor *relay content := operation for _, segment := range descriptor.ContentPath { if key, isKey := segment.(string); isKey && content.IsObject() { - content = content.Get(gjson.Escape(key)) + content = content.Get(ojson.Escape(key)) continue } index := "" @@ -396,12 +398,12 @@ func writeTaskMediaContentPath(c *gin.Context, body io.Reader, descriptor *relay index = strconv.FormatFloat(typed, 'f', -1, 64) } if index == "" || !content.IsArray() { - content = gjson.Result{} + content = ojson.Result{} break } content = content.Get(index) } - if content.Type != gjson.String || content.Str == "" { + if content.Type != ojson.String || content.Str == "" { return &taskMediaProxyError{ status: http.StatusGone, code: "artifact_gone", message: "Artifact content is no longer available", @@ -688,10 +690,10 @@ func writeTaskMediaBase64(c *gin.Context, mimeType, payload string) error { var encoding *base64.Encoding var contentLength int64 for _, candidate := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} { - decodedLength, err := io.Copy(io.Discard, base64.NewDecoder(candidate, strings.NewReader(payload))) + decodedLength, err := candidate.ValidateString(payload) if err == nil { encoding = candidate - contentLength = decodedLength + contentLength = int64(decodedLength) break } } diff --git a/go.mod b/go.mod index e32f080692..57480ace50 100644 --- a/go.mod +++ b/go.mod @@ -46,7 +46,7 @@ require ( github.com/tcolgate/mp3 v0.0.0-20170426193717-e79c5a46d300 github.com/thanhpk/randstr v1.0.6 github.com/tidwall/gjson v1.19.0 - github.com/tidwall/sjson v1.2.5 + github.com/tidwall/sjson v1.2.5 // indirect github.com/tiktoken-go/tokenizer v0.8.1 // indirect github.com/waffo-com/waffo-go v1.3.2 github.com/yapingcat/gomedia v0.0.0-20240906162731-17feea57090c @@ -168,6 +168,7 @@ require ( require ( github.com/Calcium-Ion/moejs v0.1.0-alpha.7 github.com/ClickHouse/clickhouse-go/v2 v2.46.0 + github.com/MoeForge/moego v0.1.0-alpha.1 github.com/QuantumNous/new-api/relaykit v0.0.0 github.com/QuantumNous/new-api/tokenkit v0.0.0 ) diff --git a/go.sum b/go.sum index 2f175446ef..bc6629e83e 100644 --- a/go.sum +++ b/go.sum @@ -674,6 +674,8 @@ github.com/Microsoft/hcsshim v0.9.6/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfy github.com/Microsoft/hcsshim v0.11.0/go.mod h1:OEthFdQv/AD2RAdzR6Mm1N1KPCztGKDurW1Z8b8VGMM= github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU= github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY= +github.com/MoeForge/moego v0.1.0-alpha.1 h1:d+asBZu+2oKnBj1kzdvdANMStbIKw9BLCpknuWjiR28= +github.com/MoeForge/moego v0.1.0-alpha.1/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= diff --git a/middleware/distributor.go b/middleware/distributor.go index f9dfa037a1..8e2af0b81f 100644 --- a/middleware/distributor.go +++ b/middleware/distributor.go @@ -22,8 +22,8 @@ import ( "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/setting/ratio_setting" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) type ModelRequest struct { @@ -291,14 +291,14 @@ func getModelFromJSONBody(c *gin.Context) (*ModelRequest, error) { if err != nil { return nil, err } - if !gjson.ValidBytes(requestBody) { + if !ojson.ValidBytes(requestBody) { return nil, errors.New("invalid JSON request body") } if countTopLevelJSONKey(requestBody, "model") > 1 { return nil, errors.New("model must be provided once") } - values := gjson.GetManyBytes(requestBody, "model", "group") + values := ojson.GetManyBytes(requestBody, "model", "group") model, err := getJSONStringValue(values[0], "model") if err != nil { return nil, err @@ -377,11 +377,11 @@ func countTopLevelJSONKey(data []byte, target string) int { return count } -func getJSONStringValue(result gjson.Result, field string) (string, error) { - if !result.Exists() || result.Type == gjson.Null { +func getJSONStringValue(result ojson.Result, field string) (string, error) { + if !result.Exists() || result.Type == ojson.Null { return "", nil } - if result.Type != gjson.String { + if result.Type != ojson.String { return "", fmt.Errorf("field %s must be a string", field) } return result.String(), nil diff --git a/middleware/task_plugin.go b/middleware/task_plugin.go index a190e7a212..b6240fc280 100644 --- a/middleware/task_plugin.go +++ b/middleware/task_plugin.go @@ -17,6 +17,7 @@ import ( "time" "unicode/utf8" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/dto" @@ -29,7 +30,6 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) const contextKeyTaskPluginEndpointModel = "task_plugin_endpoint_model_request" @@ -704,8 +704,8 @@ func jsonBodyBoolFlags(c *gin.Context) (stream, background bool) { if err != nil { return false, false } - values := gjson.GetManyBytes(requestBody, "stream", "background") - return values[0].Type == gjson.True, values[1].Type == gjson.True + values := ojson.GetManyBytes(requestBody, "stream", "background") + return values[0].Type == ojson.True, values[1].Type == ojson.True } func unsupportedProtocolFormMessage(candidates []pluginruntime.ProtocolBinding, protocol string, stream, background bool) string { diff --git a/middleware/task_plugin_model.go b/middleware/task_plugin_model.go index e7bcba7539..2f6212a686 100644 --- a/middleware/task_plugin_model.go +++ b/middleware/task_plugin_model.go @@ -5,9 +5,9 @@ import ( "mime" "strings" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/gin-gonic/gin" - "github.com/tidwall/sjson" ) // rewriteTaskPluginJSONModel patches the top-level JSON "model" field and @@ -28,7 +28,7 @@ func rewriteTaskPluginJSONModel(c *gin.Context, spelling string) error { if err != nil { return err } - patched, err := sjson.SetBytes(raw, "model", spelling) + patched, err := ojson.SetBytes(raw, "model", spelling) if err != nil { return err } diff --git a/pkg/billingexpr/expr.md b/pkg/billingexpr/expr.md index e1b523f573..7dd4f514fd 100644 --- a/pkg/billingexpr/expr.md +++ b/pkg/billingexpr/expr.md @@ -169,7 +169,7 @@ OpenAI 已于 2026-05-12 下线 DALL·E 2/3;其校验、默认值和倍率保 |----------|-----------|---------| | `tier` | `tier(name, value) → float64` | Records which pricing tier matched; must wrap the cost expression | | `fixed` | `fixed(amount) → float64` | A USD price per request, used only as the complete price in `tier(name, fixed(amount))` | -| `param` | `param(path) → any` | Reads a JSON path from the request body (uses gjson) | +| `param` | `param(path) → any` | Reads a JSON path from the request body (uses ojson, gjson path syntax) | | `header` | `header(key) → string` | Reads a request header value | | `has` | `has(source, substr) → bool` | Substring check | | `hour` | `hour(tz) → int` | Current hour in timezone (0-23) | diff --git a/pkg/billingexpr/run.go b/pkg/billingexpr/run.go index da56b7b84d..0a8c975bf5 100644 --- a/pkg/billingexpr/run.go +++ b/pkg/billingexpr/run.go @@ -8,9 +8,9 @@ import ( "github.com/QuantumNous/new-api/relaykit/dto" + "github.com/MoeForge/moego/ojson" "github.com/expr-lang/expr" "github.com/expr-lang/expr/vm" - "github.com/tidwall/gjson" ) // RunExpr compiles (with cache) and executes an expression string. @@ -117,7 +117,7 @@ func runProgram(prog *vm.Program, requestRules []RequestRuleTrace, usedVars map[ if path == "" || len(request.Body) == 0 { return nil } - result := gjson.GetBytes(request.Body, path) + result := ojson.GetBytes(request.Body, path) if !result.Exists() { return nil } diff --git a/pkg/jsplugin/icon.go b/pkg/jsplugin/icon.go index 03b0fc8144..5f159c0c04 100644 --- a/pkg/jsplugin/icon.go +++ b/pkg/jsplugin/icon.go @@ -2,12 +2,13 @@ package jsplugin import ( "bytes" - "encoding/base64" "encoding/xml" "fmt" "io" "strings" "unicode" + + "github.com/MoeForge/moego/base64" ) // MaxIconDataURIBytes bounds an uploaded plugin logo. It is deliberately diff --git a/pkg/jsplugin/utils.go b/pkg/jsplugin/utils.go index 04cee98986..f10c81170a 100644 --- a/pkg/jsplugin/utils.go +++ b/pkg/jsplugin/utils.go @@ -4,7 +4,6 @@ import ( "context" "crypto/hmac" "crypto/sha256" - "encoding/base64" "encoding/hex" "errors" "fmt" @@ -15,6 +14,7 @@ import ( "time" "github.com/Calcium-Ion/moejs" + "github.com/MoeForge/moego/base64" "github.com/golang-jwt/jwt/v5" "github.com/google/uuid" ) diff --git a/plugins/embed.go b/plugins/embed.go index 5dae529f12..5cb066e74f 100644 --- a/plugins/embed.go +++ b/plugins/embed.go @@ -2,10 +2,10 @@ package plugins import ( "embed" - "encoding/base64" "fmt" "io/fs" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/pkg/jsplugin" ) @@ -66,5 +66,5 @@ func IconDataURI(key string) string { if !ok { return "" } - return "data:" + mediaType + ";base64," + base64.StdEncoding.EncodeToString(data) + return base64.EncodeDataURL(mediaType, data) } diff --git a/relay/alpha_search_handler.go b/relay/alpha_search_handler.go index 52af86112a..af5991ebf7 100644 --- a/relay/alpha_search_handler.go +++ b/relay/alpha_search_handler.go @@ -6,7 +6,6 @@ import ( "io" "net/http" - "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/logger" relaycommon "github.com/QuantumNous/new-api/relay/common" @@ -15,6 +14,7 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" ) @@ -118,10 +118,12 @@ func buildAlphaSearchRequestBody(rawBody []byte, originModel, upstreamModel stri if upstreamModel == "" || upstreamModel == originModel { return rawBody, nil } - var body map[string]any - if err := common.Unmarshal(rawBody, &body); err != nil { + if !ojson.ValidBytes(rawBody) || !ojson.GetBytesNoCopy(rawBody, "@this").IsObject() { + return nil, errors.New("alpha search request body must be a JSON object") + } + body := ojson.NewDoc(rawBody) + if err := relaycommon.SetJSONMember(body, "", "model", upstreamModel); err != nil { return nil, err } - body["model"] = upstreamModel - return common.Marshal(body) + return body.Bytes(), nil } diff --git a/relay/alpha_search_handler_test.go b/relay/alpha_search_handler_test.go index 585dd76210..0bde6ecaf4 100644 --- a/relay/alpha_search_handler_test.go +++ b/relay/alpha_search_handler_test.go @@ -57,6 +57,27 @@ func TestBuildAlphaSearchRequestBodyNoMappingKeepsRawBytes(t *testing.T) { assert.Equal(t, raw, out) } +// A single model is rewritten where it stands. Routing reads the first +// "model" and most upstreams read the last, so a repeated model comes out as +// one member carrying the mapped value. +func TestBuildAlphaSearchRequestBodyRewritesModel(t *testing.T) { + tests := []struct { + name string + raw string + want string + }{ + {"single model keeps its place", `{"model":"gpt-5.1","input":[]}`, `{"model":"gpt-5.1-mapped","input":[]}`}, + {"repeated model collapses", `{"model":"gpt-5.1","input":[],"model":"gpt-5.5-pro"}`, `{"input":[],"model":"gpt-5.1-mapped"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out, err := buildAlphaSearchRequestBody([]byte(tt.raw), "gpt-5.1", "gpt-5.1-mapped") + require.NoError(t, err) + assert.Equal(t, tt.want, string(out)) + }) + } +} + type recordedSettlement struct { settled []int refunded bool diff --git a/relay/channel/advancedcustom/adaptor_test.go b/relay/channel/advancedcustom/adaptor_test.go index c7335d2ff4..b5dddeb8b3 100644 --- a/relay/channel/advancedcustom/adaptor_test.go +++ b/relay/channel/advancedcustom/adaptor_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" relaycommon "github.com/QuantumNous/new-api/relay/common" @@ -21,7 +22,6 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestAdaptorUsesExactRouteAndQueryAuth(t *testing.T) { @@ -1079,7 +1079,7 @@ func TestAdaptorConvertsClaudeAndGeminiRequestsToResponsesUpstream(t *testing.T) require.NoError(t, err) wire, err := common.Marshal(converted) require.NoError(t, err) - assert.JSONEq(t, `[{"type":"web_search"}]`, gjson.GetBytes(wire, "tools").Raw) + assert.JSONEq(t, `[{"type":"web_search"}]`, ojson.GetBytes(wire, "tools").Raw) url, err := adaptor.GetRequestURL(info) require.NoError(t, err) assert.Equal(t, "https://fallback.example/v1/responses", url) diff --git a/relay/channel/ali/adaptor_test.go b/relay/channel/ali/adaptor_test.go index 6e22c630d2..980896c36f 100644 --- a/relay/channel/ali/adaptor_test.go +++ b/relay/channel/ali/adaptor_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relay/constant" @@ -18,7 +19,6 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestConvertOpenAIRequestFiltersThinkingBudgetByUpstreamModel(t *testing.T) { @@ -82,8 +82,8 @@ func TestConvertOpenAIRequestFiltersThinkingBudgetByUpstreamModel(t *testing.T) encoded, err := common.Marshal(converted) require.NoError(t, err) - assert.True(t, gjson.GetBytes(encoded, "enable_thinking").Bool()) - value := gjson.GetBytes(encoded, "thinking_budget") + assert.True(t, ojson.GetBytes(encoded, "enable_thinking").Bool()) + value := ojson.GetBytes(encoded, "thinking_budget") assert.Equal(t, tt.wantBudget, value.Exists()) if tt.wantBudget { assert.Equal(t, tt.wantValue, value.Int()) @@ -128,7 +128,7 @@ func TestConvertOpenAIRequestPreservesExplicitZeroForMappedQwenModel(t *testing. encoded, err := common.Marshal(converted) require.NoError(t, err) - value := gjson.GetBytes(encoded, "thinking_budget") + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, int64(0), value.Int()) } @@ -279,7 +279,7 @@ func TestConvertClaudeRequestWebSearch(t *testing.T) { wire, err := common.Marshal(converted) require.NoError(t, err) for path, want := range tt.want { - value := gjson.GetBytes(wire, path) + value := ojson.GetBytes(wire, path) if want == "" { assert.False(t, value.Exists(), "%s in %s", path, wire) continue diff --git a/relay/channel/ali/web_search.go b/relay/channel/ali/web_search.go index 93e0de9210..8e3b74074c 100644 --- a/relay/channel/ali/web_search.go +++ b/relay/channel/ali/web_search.go @@ -10,7 +10,7 @@ import ( "github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta" "github.com/QuantumNous/new-api/relaykit/types" - "github.com/tidwall/gjson" + "github.com/MoeForge/moego/ojson" ) // DashScope web-search tool-price keys (search_strategy_* prices in @@ -86,13 +86,13 @@ func encodeWebSearch(info *relaycommon.RelayInfo) convmeta.WebSearchEncoder { // aliResponsesToolUsage bills Responses web search by the count DashScope // reports in usage.x_tools.web_search.count (terminal frames carry it under // response.usage) and silences the web_search_call items under the protocol -// keys. gjson truncates fractional values and reads non-numbers as zero; +// keys. ojson truncates fractional values and reads non-numbers as zero; // SetBillableToolCount ignores negatives and settlement applies // MaxBillableToolCallCount. func aliResponsesToolUsage(raw []byte) map[string]int { - count := gjson.GetBytes(raw, "usage.x_tools.web_search.count") + count := ojson.GetBytes(raw, "usage.x_tools.web_search.count") if !count.Exists() { - count = gjson.GetBytes(raw, "response.usage.x_tools.web_search.count") + count = ojson.GetBytes(raw, "response.usage.x_tools.web_search.count") } if !count.Exists() { return nil diff --git a/relay/channel/aws/mantle.go b/relay/channel/aws/mantle.go index 310f1c8b73..218cb86a23 100644 --- a/relay/channel/aws/mantle.go +++ b/relay/channel/aws/mantle.go @@ -4,7 +4,6 @@ import ( "bytes" "crypto/sha256" "encoding/hex" - "encoding/json" "fmt" "io" "net/http" @@ -12,10 +11,11 @@ import ( "strings" "time" - "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/relay/channel" "github.com/QuantumNous/new-api/relay/channel/claude" relaycommon "github.com/QuantumNous/new-api/relay/common" + + "github.com/MoeForge/moego/ojson" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/gin-gonic/gin" @@ -67,11 +67,14 @@ func (a *Adaptor) newMantleRequest(c *gin.Context, info *relaycommon.RelayInfo, if a.IsNova || isNovaModel(getAwsModelID(info.UpstreamModelName)) { return nil, fmt.Errorf("AWS Mantle Messages API requires a Claude model; use InvokeModel for Amazon Nova") } - var payload map[string]json.RawMessage - if err := common.DecodeJson(requestBody, &payload); err != nil { + payload, err := io.ReadAll(requestBody) + if err != nil { return nil, fmt.Errorf("decode AWS Mantle request: %w", err) } - if payload == nil { + if !ojson.ValidBytes(payload) { + return nil, fmt.Errorf("decode AWS Mantle request: invalid JSON") + } + if !ojson.GetBytesNoCopy(payload, "@this").IsObject() { return nil, fmt.Errorf("AWS Mantle request must be a JSON object") } // Use the channel's resolved model even for passthrough requests. Do not @@ -83,16 +86,16 @@ func (a *Adaptor) newMantleRequest(c *gin.Context, info *relaycommon.RelayInfo, if strings.HasPrefix(model, "claude-") { model = "anthropic." + model } - payload["model"], err = common.Marshal(model) - if err != nil { - return nil, err + doc := ojson.NewDoc(payload) + for _, key := range []string{"anthropic_version", "anthropic_beta"} { + if err := relaycommon.DeleteJSONMember(doc, key); err != nil { + return nil, fmt.Errorf("marshal AWS Mantle request: %w", err) + } } - delete(payload, "anthropic_version") - delete(payload, "anthropic_beta") - body, err := common.Marshal(payload) - if err != nil { + if err := relaycommon.SetJSONMember(doc, "", "model", model); err != nil { return nil, fmt.Errorf("marshal AWS Mantle request: %w", err) } + body := doc.Bytes() req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return nil, fmt.Errorf("create AWS Mantle request: %w", err) diff --git a/relay/channel/aws/relay-aws.go b/relay/channel/aws/relay-aws.go index fdc7d2c416..49f0fc9820 100644 --- a/relay/channel/aws/relay-aws.go +++ b/relay/channel/aws/relay-aws.go @@ -18,6 +18,7 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/pkg/errors" @@ -186,14 +187,18 @@ func buildAwsRequestBody(c *gin.Context, info *relaycommon.RelayInfo, awsClaudeR if err != nil { return nil, errors.Wrap(err, "get request body bytes fail") } - // Nested values keep the client's bytes and key order. - var data map[string]json.RawMessage - if err := common.Unmarshal(body, &data); err != nil { - return nil, errors.Wrap(err, "pass-through unmarshal request body fail") + // Only model and stream are removed: the rest keeps the client's bytes + // and key order. The Doc reads body in place and never changes it. + if !ojson.ValidBytes(body) || !ojson.GetBytesNoCopy(body, "@this").IsObject() { + return nil, errors.New("pass-through unmarshal request body fail: request body must be a JSON object") } - delete(data, "model") - delete(data, "stream") - return common.Marshal(data) + data := ojson.NewDoc(body) + for _, key := range []string{"model", "stream"} { + if err := relaycommon.DeleteJSONMember(data, key); err != nil { + return nil, errors.Wrap(err, "pass-through unmarshal request body fail") + } + } + return data.Bytes(), nil } return common.Marshal(awsClaudeReq) } diff --git a/relay/channel/aws/relay_aws_test.go b/relay/channel/aws/relay_aws_test.go index be72f9c587..d9680c18e4 100644 --- a/relay/channel/aws/relay_aws_test.go +++ b/relay/channel/aws/relay_aws_test.go @@ -222,6 +222,21 @@ func TestDoAwsClientRequest_ForwardsThinkingBlockBindingAndBetaList(t *testing.T assert.JSONEq(t, `{"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}}`, string(payload.Thinking)) } +// InvokeModel takes the model and streaming from the request, so the +// pass-through body keeps no copy of either, even when the client repeats them. +func TestBuildAwsRequestBodyPassThroughDropsRepeatedModelAndStream(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"a","stream":true,"max_tokens":8,"stream":false,"model":"b"}`)) + info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{}} + info.ChannelSetting.PassThroughBodyEnabled = true + + body, err := buildAwsRequestBody(c, info, nil) + + require.NoError(t, err) + assert.Equal(t, `{"max_tokens":8}`, string(body)) +} + func TestDoAwsClientRequest_PreservesSafeguards(t *testing.T) { gin.SetMode(gin.TestMode) settings := model_setting.GetGlobalSettings() diff --git a/relay/channel/claude/message_delta_usage_patch_test.go b/relay/channel/claude/message_delta_usage_patch_test.go index d698bf0a52..07570cd9f5 100644 --- a/relay/channel/claude/message_delta_usage_patch_test.go +++ b/relay/channel/claude/message_delta_usage_patch_test.go @@ -3,12 +3,12 @@ package claude import ( "testing" + "github.com/MoeForge/moego/ojson" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/setting/model_setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestPatchClaudeMessageDeltaUsageDataPreserveUnknownFields(t *testing.T) { @@ -21,13 +21,13 @@ func TestPatchClaudeMessageDeltaUsageDataPreserveUnknownFields(t *testing.T) { patchedData := patchClaudeMessageDeltaUsageData(originalData, usage) - require.Equal(t, "message_delta", gjson.Get(patchedData, "type").String()) - require.Equal(t, "end_turn", gjson.Get(patchedData, "delta.stop_reason").String()) - require.Equal(t, "trace_001", gjson.Get(patchedData, "vendor_meta.trace_id").String()) - require.EqualValues(t, 53, gjson.Get(patchedData, "usage.output_tokens").Int()) - require.EqualValues(t, 100, gjson.Get(patchedData, "usage.input_tokens").Int()) - require.EqualValues(t, 30, gjson.Get(patchedData, "usage.cache_read_input_tokens").Int()) - require.EqualValues(t, 50, gjson.Get(patchedData, "usage.cache_creation_input_tokens").Int()) + require.Equal(t, "message_delta", ojson.Get(patchedData, "type").String()) + require.Equal(t, "end_turn", ojson.Get(patchedData, "delta.stop_reason").String()) + require.Equal(t, "trace_001", ojson.Get(patchedData, "vendor_meta.trace_id").String()) + require.EqualValues(t, 53, ojson.Get(patchedData, "usage.output_tokens").Int()) + require.EqualValues(t, 100, ojson.Get(patchedData, "usage.input_tokens").Int()) + require.EqualValues(t, 30, ojson.Get(patchedData, "usage.cache_read_input_tokens").Int()) + require.EqualValues(t, 50, ojson.Get(patchedData, "usage.cache_creation_input_tokens").Int()) } func TestPatchClaudeMessageDeltaUsageDataZeroValueChecks(t *testing.T) { @@ -40,9 +40,9 @@ func TestPatchClaudeMessageDeltaUsageDataZeroValueChecks(t *testing.T) { patchedData := patchClaudeMessageDeltaUsageData(originalData, usage) - require.EqualValues(t, 9, gjson.Get(patchedData, "usage.input_tokens").Int()) - require.EqualValues(t, 30, gjson.Get(patchedData, "usage.cache_read_input_tokens").Int()) - assert.False(t, gjson.Get(patchedData, "usage.cache_creation_input_tokens").Exists()) + require.EqualValues(t, 9, ojson.Get(patchedData, "usage.input_tokens").Int()) + require.EqualValues(t, 30, ojson.Get(patchedData, "usage.cache_read_input_tokens").Int()) + assert.False(t, ojson.Get(patchedData, "usage.cache_creation_input_tokens").Exists()) } func TestShouldSkipClaudeMessageDeltaUsagePatch(t *testing.T) { diff --git a/relay/channel/deepseek/adaptor_test.go b/relay/channel/deepseek/adaptor_test.go index 7707c0ae29..eeb6260d79 100644 --- a/relay/channel/deepseek/adaptor_test.go +++ b/relay/channel/deepseek/adaptor_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relay/constant" @@ -14,7 +15,6 @@ import ( "github.com/QuantumNous/new-api/setting/model_setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) // The -none/-low/-max tails of deepseek-flash and deepseek-v4-* reach DeepSeek @@ -228,7 +228,7 @@ func TestModelModifiersUpstreamFields(t *testing.T) { sent, err = common.Marshal(converted) require.NoError(t, err) } - wire := gjson.ParseBytes(sent) + wire := ojson.ParseBytes(sent) wantModel := "deepseek-flash" if strings.HasPrefix(tt.model, "deepseek-v4-pro") { wantModel = "deepseek-v4-pro" @@ -237,7 +237,7 @@ func TestModelModifiersUpstreamFields(t *testing.T) { if tt.thinking == "" { // No modifier: the client's reasoning fields go out as sent. for _, member := range []string{"thinking", "reasoning_effort", "output_config", "reasoning"} { - assert.Equal(t, gjson.Get(body, member).Raw, wire.Get(member).Raw, "%s %s", format, member) + assert.Equal(t, ojson.Get(body, member).Raw, wire.Get(member).Raw, "%s %s", format, member) } continue } @@ -249,7 +249,7 @@ func TestModelModifiersUpstreamFields(t *testing.T) { case types.RelayFormatClaude: assert.JSONEq(t, `{"type":"`+tt.thinking+`"}`, wire.Get("thinking").Raw, format) assert.Equal(t, tt.effort, wire.Get("output_config.effort").String(), format) - assert.Equal(t, gjson.Get(body, "output_config.format").Raw, wire.Get("output_config.format").Raw, format) + assert.Equal(t, ojson.Get(body, "output_config.format").Raw, wire.Get("output_config.format").Raw, format) assert.Equal(t, int64(64), wire.Get("max_tokens").Int(), format) wantTemperature := 0.7 if strings.Contains(tt.model, "@temperature:0.3") { diff --git a/relay/channel/deepseek/web_search.go b/relay/channel/deepseek/web_search.go index 4796d4eb12..3afe5a61b5 100644 --- a/relay/channel/deepseek/web_search.go +++ b/relay/channel/deepseek/web_search.go @@ -3,7 +3,7 @@ package deepseek import ( "github.com/QuantumNous/new-api/relaykit/dto" - "github.com/tidwall/gjson" + "github.com/MoeForge/moego/ojson" ) // responsesToolUsage bills the Search and Fetch API calls DeepSeek runs for @@ -14,9 +14,9 @@ import ( // replace the web_search_call items counted under the Search key while the // stream was running. An empty output proves nothing, so those counts stay. func responsesToolUsage(raw []byte) map[string]int { - output := gjson.GetBytes(raw, "output") + output := ojson.GetBytes(raw, "output") if !output.Exists() { - output = gjson.GetBytes(raw, "response.output") + output = ojson.GetBytes(raw, "response.output") } items := output.Array() if !output.IsArray() || len(items) == 0 { diff --git a/relay/channel/dify/relay-dify.go b/relay/channel/dify/relay-dify.go index 34ea9fac70..8a6c1253dc 100644 --- a/relay/channel/dify/relay-dify.go +++ b/relay/channel/dify/relay-dify.go @@ -2,7 +2,6 @@ package dify import ( "bytes" - "encoding/base64" "encoding/json" "fmt" "io" @@ -11,6 +10,7 @@ import ( "os" "strings" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" relaycommon "github.com/QuantumNous/new-api/relay/common" diff --git a/relay/channel/gemini/adaptor_responses_test.go b/relay/channel/gemini/adaptor_responses_test.go index ecb53672d3..cd6e358a5d 100644 --- a/relay/channel/gemini/adaptor_responses_test.go +++ b/relay/channel/gemini/adaptor_responses_test.go @@ -4,13 +4,13 @@ import ( "net/http" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestConvertOpenAIResponsesRequestToGeminiInstructionsAndInput(t *testing.T) { @@ -55,8 +55,8 @@ func TestConvertOpenAIResponsesRequestToGeminiFunctionToolAndChoice(t *testing.T tools := got.GetTools() require.Len(t, tools, 1) - assert.Equal(t, "lookup", gjson.GetBytes(got.Tools, "0.functionDeclarations.0.name").String()) - assert.Equal(t, "Lookup data", gjson.GetBytes(got.Tools, "0.functionDeclarations.0.description").String()) + assert.Equal(t, "lookup", ojson.GetBytes(got.Tools, "0.functionDeclarations.0.name").String()) + assert.Equal(t, "Lookup data", ojson.GetBytes(got.Tools, "0.functionDeclarations.0.description").String()) require.NotNil(t, got.ToolConfig) require.NotNil(t, got.ToolConfig.FunctionCallingConfig) assert.Equal(t, dto.FunctionCallingConfigMode("ANY"), got.ToolConfig.FunctionCallingConfig.Mode) @@ -214,5 +214,5 @@ func TestConvertEmbeddingRequestRejectsContentParts(t *testing.T) { require.NoError(t, err) wire, err := common.Marshal(got) require.NoError(t, err) - assert.JSONEq(t, `["a cat","a dog"]`, gjson.GetBytes(wire, "requests.#.content.parts.0.text").Raw) + assert.JSONEq(t, `["a cat","a dog"]`, ojson.GetBytes(wire, "requests.#.content.parts.0.text").Raw) } diff --git a/relay/channel/gemini/relay-gemini-native.go b/relay/channel/gemini/relay-gemini-native.go index f8e179285e..fcebdbb577 100644 --- a/relay/channel/gemini/relay-gemini-native.go +++ b/relay/channel/gemini/relay-gemini-native.go @@ -14,8 +14,8 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) func GeminiTextGenerationHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) { @@ -35,7 +35,7 @@ func GeminiTextGenerationHandler(c *gin.Context, info *relaycommon.RelayInfo, re if err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } - info.ObserveResponseModel(gjson.GetBytes(responseBody, "modelVersion").Str) + info.ObserveResponseModel(ojson.GetBytes(responseBody, "modelVersion").Str) var grounding geminiGroundingCounter grounding.observe(&geminiResponse) grounding.commit(info) diff --git a/relay/channel/gemini/relay-gemini.go b/relay/channel/gemini/relay-gemini.go index 13fbc73dc4..d5e6643048 100644 --- a/relay/channel/gemini/relay-gemini.go +++ b/relay/channel/gemini/relay-gemini.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/logger" @@ -21,7 +22,6 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) func buildUsageFromGeminiMetadata(metadata *dto.GeminiUsageMetadata, fallbackPromptTokens int) dto.Usage { @@ -222,7 +222,7 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http info.PerformanceBusinessRejection = true common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason)) } - info.ObserveResponseModel(gjson.Get(data, "modelVersion").Str) + info.ObserveResponseModel(ojson.Get(data, "modelVersion").Str) for _, candidate := range geminiResponse.Candidates { if candidate.FinishReason == nil || *candidate.FinishReason == "" || *candidate.FinishReason == "FINISH_REASON_UNSPECIFIED" { continue @@ -421,7 +421,7 @@ func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.R if err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } - info.ObserveResponseModel(gjson.GetBytes(responseBody, "modelVersion").Str) + info.ObserveResponseModel(ojson.GetBytes(responseBody, "modelVersion").Str) var grounding geminiGroundingCounter grounding.observe(&geminiResponse) grounding.commit(info) diff --git a/relay/channel/gemini/relay_responses.go b/relay/channel/gemini/relay_responses.go index f2b2230bea..f173090b94 100644 --- a/relay/channel/gemini/relay_responses.go +++ b/relay/channel/gemini/relay_responses.go @@ -6,6 +6,7 @@ import ( "io" "net/http" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/logger" @@ -16,7 +17,6 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) func GeminiResponsesHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) { @@ -32,7 +32,7 @@ func GeminiResponsesHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *h if err := common.Unmarshal(responseBody, &geminiResponse); err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } - info.ObserveResponseModel(gjson.GetBytes(responseBody, "modelVersion").Str) + info.ObserveResponseModel(ojson.GetBytes(responseBody, "modelVersion").Str) var grounding geminiGroundingCounter grounding.observe(&geminiResponse) grounding.commit(info) diff --git a/relay/channel/openai/relay-openai.go b/relay/channel/openai/relay-openai.go index a37f84ec9d..36c4bd86d2 100644 --- a/relay/channel/openai/relay-openai.go +++ b/relay/channel/openai/relay-openai.go @@ -17,6 +17,7 @@ import ( "github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/tokenkit" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" ) @@ -327,13 +328,14 @@ func OpenaiHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo switch info.RelayFormat { case types.RelayFormatOpenAI: if usageModified { - var bodyMap map[string]any - err = common.Unmarshal(responseBody, &bodyMap) + usageJSON, err := common.Marshal(simpleResponse.Usage) + if err != nil { + return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) + } + responseBody, err = ojson.SetRawBytes(responseBody, "usage", usageJSON) if err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } - bodyMap["usage"] = simpleResponse.Usage - responseBody, _ = common.Marshal(bodyMap) } if forceFormat { responseBody, err = common.Marshal(simpleResponse) diff --git a/relay/channel/openai/relay_image.go b/relay/channel/openai/relay_image.go index 3ef47c801b..bbf02e9ac0 100644 --- a/relay/channel/openai/relay_image.go +++ b/relay/channel/openai/relay_image.go @@ -16,9 +16,8 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) // OpenaiImageHandler handles non-streaming OpenAI image responses @@ -60,7 +59,7 @@ func OpenaiImageHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http. // bill nothing. A zero result leaves the requested quantity in place because // UpdateImageCount ignores non-positive counts. func openaiImageResponseCount(responseBody []byte) int64 { - data := gjson.GetBytes(responseBody, "data") + data := ojson.GetBytesNoCopy(responseBody, "data") if data.IsObject() { if openaiImageDataHasField(data, "url") || openaiImageDataHasField(data, "b64_json") { return 1 @@ -71,7 +70,7 @@ func openaiImageResponseCount(responseBody []byte) int64 { return 0 } var urls, b64s int64 - data.ForEach(func(_, item gjson.Result) bool { + data.ForEach(func(_, item ojson.Result) bool { if openaiImageDataHasField(item, "url") { urls++ } @@ -85,9 +84,9 @@ func openaiImageResponseCount(responseBody []byte) int64 { // openaiImageDataHasField reports whether an image data entry carries a // non-empty string value for field. -func openaiImageDataHasField(item gjson.Result, field string) bool { +func openaiImageDataHasField(item ojson.Result, field string) bool { value := item.Get(field) - return value.Type == gjson.String && value.Raw != `""` + return value.Type == ojson.String && value.Raw != `""` } // normalizeOpenAIUsage maps the OpenAI Images usage shape (input_tokens / @@ -283,7 +282,7 @@ func openaiImageJSONAsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, helper.SetEventStreamHeaders(c) c.Status(http.StatusOK) - created := gjson.GetBytes(responseBody, "created").Int() + created := ojson.GetBytes(responseBody, "created").Int() if created == 0 { created = time.Now().Unix() } @@ -300,44 +299,37 @@ func openaiImageJSONAsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, } } - // gjson.Result.Array returns the element list for an array and a single - // element for an object-shaped data, keeping document-relative indexes so - // the zero-copy field forwarding below stays valid for both shapes. - // Entries without url or b64_json carry no image and are not forwarded. + // ojson.Result.Array returns the element list for an array and a single + // element for an object-shaped data. The results share memory with + // responseBody, which stays unchanged here, so the fields are forwarded + // without copying. Entries without url or b64_json carry no image and are + // not forwarded. emitted := 0 - for _, image := range gjson.GetBytes(responseBody, "data").Array() { + for _, image := range ojson.GetBytesNoCopy(responseBody, "data").Array() { if !openaiImageDataHasField(image, "url") && !openaiImageDataHasField(image, "b64_json") { continue } - payload := []byte(`{"type":"image_generation.completed"}`) - payload, err = sjson.SetBytes(payload, "created_at", created) - if err != nil { + payload := ojson.NewDocString(`{"type":"image_generation.completed"}`) + if err := payload.Set("created_at", created); err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } if validUsage { - payload, err = sjson.SetRawBytes(payload, "usage", usageJSON) - if err != nil { + if err := payload.SetRawBytes("usage", usageJSON); err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } } - // b64_json goes last: every sjson.Set* reallocates the whole payload, - // so inserting the large blob after all small fields avoids re-copying - // multi-MB buffers. + // The event keeps its field order with b64_json last. The Doc writes + // the event once, so the large blob is copied only into the output. for _, field := range []string{"url", "revised_prompt", "b64_json"} { value := image.Get(field) - if value.Type != gjson.String || value.Raw == `""` { + if value.Type != ojson.String || value.Raw == `""` { continue } - raw := []byte(value.Raw) - if value.Index > 0 { - raw = responseBody[value.Index : value.Index+len(value.Raw)] - } - payload, err = sjson.SetRawBytes(payload, field, raw) - if err != nil { + if err := payload.SetRaw(field, value.Raw); err != nil { return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) } } - if writeErr := helper.ResponseChunkData(c, dto.ResponsesStreamResponse{Type: "image_generation.completed"}, string(payload)); writeErr != nil { + if writeErr := helper.ResponseChunkData(c, dto.ResponsesStreamResponse{Type: "image_generation.completed"}, payload.String()); writeErr != nil { if info != nil && info.StreamStatus != nil { info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonClientGone, writeErr) } diff --git a/relay/channel/openai/relay_responses.go b/relay/channel/openai/relay_responses.go index 7d98b6eb57..825ff0abb8 100644 --- a/relay/channel/openai/relay_responses.go +++ b/relay/channel/openai/relay_responses.go @@ -14,9 +14,8 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) func OaiResponsesHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) { @@ -109,10 +108,10 @@ func rewriteSGLangResponsesCreatedAt(info *relaycommon.RelayInfo, payload []byte if info.GetChannelType() != constant.ChannelTypeSGLang { return payload } - if !gjson.GetBytes(payload, path).Exists() { + if !ojson.GetBytes(payload, path).Exists() { return payload } - patched, err := sjson.SetBytes(payload, path, int(createdAt)) + patched, err := ojson.SetBytes(payload, path, int(createdAt)) if err != nil { return payload } diff --git a/relay/channel/openai/web_search.go b/relay/channel/openai/web_search.go index 3b32359948..bb2b80504e 100644 --- a/relay/channel/openai/web_search.go +++ b/relay/channel/openai/web_search.go @@ -3,20 +3,20 @@ package openai import ( "github.com/QuantumNous/new-api/relaykit/dto" - "github.com/tidwall/gjson" + "github.com/MoeForge/moego/ojson" ) // azureResponsesToolUsage bills Azure Responses web search by the Bing request // count the service reports (tool_usage.web_search.num_requests, $14 per 1,000 // transactions) under its own key, and silences the web_search_call items: // Azure documents "Use tool_usage.web_search.num_requests" rather than -// counting web_search_call. gjson truncates fractional values and reads +// counting web_search_call. ojson truncates fractional values and reads // non-numbers as zero; SetBillableToolCount ignores negatives and settlement // applies MaxBillableToolCallCount. func azureResponsesToolUsage(raw []byte) map[string]int { - count := gjson.GetBytes(raw, "tool_usage.web_search.num_requests") + count := ojson.GetBytes(raw, "tool_usage.web_search.num_requests") if !count.Exists() { - count = gjson.GetBytes(raw, "response.tool_usage.web_search.num_requests") + count = ojson.GetBytes(raw, "response.tool_usage.web_search.num_requests") } if !count.Exists() { return nil diff --git a/relay/channel/task/jsplugin/adaptor.go b/relay/channel/task/jsplugin/adaptor.go index db8cf9c219..c7bbcb1ed9 100644 --- a/relay/channel/task/jsplugin/adaptor.go +++ b/relay/channel/task/jsplugin/adaptor.go @@ -3,7 +3,6 @@ package jsplugin import ( "bytes" "context" - "encoding/base64" "encoding/json" "errors" "fmt" @@ -22,6 +21,7 @@ import ( "time" "unicode/utf8" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/dto" @@ -539,9 +539,8 @@ func encodeFilePlaceholder(placeholder map[string]any, form *multipart.Form, lim return "", fmt.Errorf("inlined files exceed the %d byte limit", limit) } *total += int64(len(data)) - encoded := base64.StdEncoding.EncodeToString(data) if encoding == "base64" { - return encoded, nil + return base64.StdEncoding.EncodeToString(data), nil } mimeType := "application/octet-stream" if override, ok := placeholder["mimeType"].(string); ok && strings.TrimSpace(override) != "" { @@ -549,7 +548,7 @@ func encodeFilePlaceholder(placeholder map[string]any, form *multipart.Form, lim } else if contentType := header.Header.Get("Content-Type"); contentType != "" { mimeType = contentType } - return "data:" + mimeType + ";base64," + encoded, nil + return base64.EncodeDataURL(mimeType, data), nil } func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, body io.Reader) (*http.Response, error) { diff --git a/relay/channel/volcengine/tts.go b/relay/channel/volcengine/tts.go index 6ea282757b..1802f60547 100644 --- a/relay/channel/volcengine/tts.go +++ b/relay/channel/volcengine/tts.go @@ -2,7 +2,6 @@ package volcengine import ( "context" - "encoding/base64" "encoding/json" "errors" "fmt" @@ -10,6 +9,7 @@ import ( "net/http" "strings" + "github.com/MoeForge/moego/base64" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/types" diff --git a/relay/channel/xai/web_search.go b/relay/channel/xai/web_search.go index 5ee573c166..856a222d7b 100644 --- a/relay/channel/xai/web_search.go +++ b/relay/channel/xai/web_search.go @@ -3,7 +3,7 @@ package xai import ( "github.com/QuantumNous/new-api/relaykit/dto" - "github.com/tidwall/gjson" + "github.com/MoeForge/moego/ojson" ) // xaiResponsesToolUsage reads xAI's billed server-side tool counts from @@ -11,13 +11,13 @@ import ( // cumulative usage under response.usage; num_sources_used is not a billed // count). web_search_calls replaces the web_search_call items and is priced by // the web_search:grok* override; x_search is billed per fetched post and per -// fetched profile. gjson truncates fractional values and reads non-numbers as +// fetched profile. ojson truncates fractional values and reads non-numbers as // zero; SetBillableToolCount ignores negatives and settlement applies // MaxBillableToolCallCount. func xaiResponsesToolUsage(raw []byte) map[string]int { - details := gjson.GetBytes(raw, "usage.server_side_tool_usage_details") + details := ojson.GetBytes(raw, "usage.server_side_tool_usage_details") if !details.Exists() { - details = gjson.GetBytes(raw, "response.usage.server_side_tool_usage_details") + details = ojson.GetBytes(raw, "response.usage.server_side_tool_usage_details") } if !details.IsObject() { return nil diff --git a/relay/channel/zhipu_4v/web_search.go b/relay/channel/zhipu_4v/web_search.go index 6739d4b2a5..d76c36620d 100644 --- a/relay/channel/zhipu_4v/web_search.go +++ b/relay/channel/zhipu_4v/web_search.go @@ -7,7 +7,7 @@ import ( "github.com/QuantumNous/new-api/relaykit/relayconvert/convmeta" "github.com/QuantumNous/new-api/relaykit/types" - "github.com/tidwall/gjson" + "github.com/MoeForge/moego/ojson" ) // zhipuSearchEngine is the documented default search_engine. It is also the @@ -77,7 +77,7 @@ func encodeWebSearch(info *relaycommon.RelayInfo) convmeta.WebSearchEncoder { // response carries the top-level web_search result array. The array lists // results, not searches, so its length is not a count. func zhipuChatToolUsage(raw []byte) map[string]int { - results := gjson.GetBytes(raw, "web_search") + results := ojson.GetBytes(raw, "web_search") if !results.IsArray() || len(results.Array()) == 0 { return nil } diff --git a/relay/common/override.go b/relay/common/override.go index d751e84ba2..5b7dbe75dd 100644 --- a/relay/common/override.go +++ b/relay/common/override.go @@ -12,12 +12,11 @@ import ( "strings" "sync" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" kitreasoning "github.com/QuantumNous/new-api/relaykit/relayconvert/reasoning" "github.com/QuantumNous/new-api/relaykit/types" "github.com/samber/lo" - "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) var negativeIndexRegexp = regexp.MustCompile(`\.(-\d+)`) @@ -165,25 +164,26 @@ func ApplyParamOverride(jsonData []byte, paramOverride map[string]any, condition return jsonData, nil } auditRecorder := getParamOverrideAuditRecorder(conditionContext) + // 新旧两种格式的所有修改都在同一个 Doc 上进行,最后只生成一次输出 + doc := ojson.NewDoc(jsonData) // 尝试断言为操作格式 if operations, ok := tryParseOperations(paramOverride); ok { legacyOverride := buildLegacyParamOverride(paramOverride) - workingJSON := jsonData - var err error if len(legacyOverride) > 0 { - workingJSON, err = applyOperationsLegacy(workingJSON, legacyOverride, auditRecorder) - if err != nil { + if err := applyOperationsLegacy(doc, legacyOverride, auditRecorder); err != nil { return nil, err } } - // 使用新方法(基于 []byte,避免整包 string 拷贝) - return applyOperations(workingJSON, operations, conditionContext) + return applyOperations(doc, operations, conditionContext) } // 直接使用旧方法 - return applyOperationsLegacy(jsonData, paramOverride, auditRecorder) + if err := applyOperationsLegacy(doc, paramOverride, auditRecorder); err != nil { + return nil, err + } + return doc.Bytes(), nil } func buildLegacyParamOverride(paramOverride map[string]any) map[string]any { @@ -249,8 +249,8 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri if effort, exists := firstStringValue(data, "reasoning_effort"); exists && effort != "" { return effort, true } - if enabled := gjson.GetBytes(data, "reasoning.enabled"); enabled.Exists() { - if enabled.Type != gjson.True && enabled.Type != gjson.False { + if enabled := ojson.GetBytes(data, "reasoning.enabled"); enabled.Exists() { + if enabled.Type != ojson.True && enabled.Type != ojson.False { return "", true } if !enabled.Bool() { @@ -259,7 +259,7 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri if effort, exists := firstStringValue(data, "reasoning.effort"); exists && effort != "" { return effort, true } - if budget := gjson.GetBytes(data, "reasoning.max_tokens"); budget.Exists() { + if budget := ojson.GetBytes(data, "reasoning.max_tokens"); budget.Exists() { return reasoningEffortFromBudgetValue(budget) } return string(kitreasoning.EffortHigh), true @@ -267,7 +267,7 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri if effort, exists := firstStringValue(data, "reasoning.effort"); exists && effort != "" { return effort, true } - if budget := gjson.GetBytes(data, "reasoning.max_tokens"); budget.Exists() { + if budget := ojson.GetBytes(data, "reasoning.max_tokens"); budget.Exists() { return reasoningEffortFromBudgetValue(budget) } return "", false @@ -281,7 +281,7 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri if thinkingType == "disabled" { return string(kitreasoning.EffortNone), true } - if budget := gjson.GetBytes(data, "thinking.budget_tokens"); budget.Exists() { + if budget := ojson.GetBytes(data, "thinking.budget_tokens"); budget.Exists() { return reasoningEffortFromBudgetValue(budget) } if thinkingType == "enabled" || thinkingType == "adaptive" { @@ -300,7 +300,7 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri "generationConfig.thinkingConfig.thinkingBudget", "generation_config.thinking_config.thinking_budget", } { - if budget := gjson.GetBytes(data, path); budget.Exists() { + if budget := ojson.GetBytes(data, path); budget.Exists() { return reasoningEffortFromBudgetValue(budget) } } @@ -312,11 +312,11 @@ func extractReasoningEffortFromJSON(format types.RelayFormat, data []byte) (stri func firstStringValue(data []byte, paths ...string) (string, bool) { for _, path := range paths { - value := gjson.GetBytes(data, path) + value := ojson.GetBytes(data, path) if !value.Exists() { continue } - if value.Type != gjson.String { + if value.Type != ojson.String { return "", true } return strings.TrimSpace(value.String()), true @@ -324,8 +324,8 @@ func firstStringValue(data []byte, paths ...string) (string, bool) { return "", false } -func reasoningEffortFromBudgetValue(value gjson.Result) (string, bool) { - if value.Type != gjson.Number { +func reasoningEffortFromBudgetValue(value ojson.Result) (string, bool) { + if value.Type != ojson.Number { return "", true } budget := value.Float() @@ -645,13 +645,13 @@ func tryParseOperations(paramOverride map[string]any) ([]ParamOperation, bool) { return operations, true } -func checkConditions(data []byte, contextJSON string, conditions []ConditionOperation, logic string) (bool, error) { +func checkConditions(doc *ojson.Doc, contextJSON string, conditions []ConditionOperation, logic string) (bool, error) { if len(conditions) == 0 { return true, nil // 没有条件,直接通过 } results := make([]bool, len(conditions)) for i := range conditions { - result, err := checkSingleCondition(data, contextJSON, &conditions[i]) + result, err := checkSingleCondition(doc, contextJSON, &conditions[i]) if err != nil { return false, err } @@ -664,12 +664,12 @@ func checkConditions(data []byte, contextJSON string, conditions []ConditionOper return lo.SomeBy(results, func(item bool) bool { return item }), nil } -func checkSingleCondition(data []byte, contextJSON string, condition *ConditionOperation) (bool, error) { +func checkSingleCondition(doc *ojson.Doc, contextJSON string, condition *ConditionOperation) (bool, error) { // 处理负数索引 - path := processNegativeIndex(data, condition.Path) - value := gjson.GetBytes(data, path) + path := processNegativeIndex(doc, condition.Path) + value := doc.Get(path) if !value.Exists() && contextJSON != "" { - value = gjson.Get(contextJSON, condition.Path) + value = ojson.Get(contextJSON, condition.Path) } if !value.Exists() { if condition.PassMissingKey { @@ -678,12 +678,12 @@ func checkSingleCondition(data []byte, contextJSON string, condition *ConditionO return false, nil } - // 利用gjson的类型解析 + // 利用ojson的类型解析 targetBytes, err := common.Marshal(condition.Value) if err != nil { return false, fmt.Errorf("failed to marshal condition value: %v", err) } - targetValue := gjson.ParseBytes(targetBytes) + targetValue := ojson.ParseBytes(targetBytes) result, err := condition.compareGjsonValues(value, targetValue) if err != nil { @@ -696,7 +696,7 @@ func checkSingleCondition(data []byte, contextJSON string, condition *ConditionO return result, nil } -func processNegativeIndex(data []byte, path string) string { +func processNegativeIndex(doc *ojson.Doc, path string) string { matches := negativeIndexRegexp.FindAllStringSubmatch(path, -1) if len(matches) == 0 { @@ -713,7 +713,7 @@ func processNegativeIndex(data []byte, path string) string { arrayPath = arrayPath[:len(arrayPath)-1] } - array := gjson.GetBytes(data, arrayPath) + array := doc.Get(arrayPath) if array.IsArray() { length := len(array.Array()) actualIndex := length + index @@ -726,8 +726,8 @@ func processNegativeIndex(data []byte, path string) string { return result } -// compareGjsonValues 直接比较两个gjson.Result,支持所有比较模式 -func (condition *ConditionOperation) compareGjsonValues(jsonValue, targetValue gjson.Result) (bool, error) { +// compareGjsonValues 直接比较两个ojson.Result,支持所有比较模式 +func (condition *ConditionOperation) compareGjsonValues(jsonValue, targetValue ojson.Result) (bool, error) { mode := strings.ToLower(condition.Mode) switch mode { case "full": @@ -739,7 +739,7 @@ func (condition *ConditionOperation) compareGjsonValues(jsonValue, targetValue g case "contains": return strings.Contains(jsonValue.String(), targetValue.String()), nil case "regex": - if targetValue.Type != gjson.String { + if targetValue.Type != ojson.String { return false, fmt.Errorf("regex pattern must be a string") } re, err := getParamOverrideRegex(targetValue.String()) @@ -760,15 +760,15 @@ func (condition *ConditionOperation) compareGjsonValues(jsonValue, targetValue g } } -func compareEqual(jsonValue, targetValue gjson.Result) (bool, error) { +func compareEqual(jsonValue, targetValue ojson.Result) (bool, error) { // 对null值特殊处理:两个都是null返回true,一个是null另一个不是返回false - if jsonValue.Type == gjson.Null || targetValue.Type == gjson.Null { - return jsonValue.Type == gjson.Null && targetValue.Type == gjson.Null, nil + if jsonValue.Type == ojson.Null || targetValue.Type == ojson.Null { + return jsonValue.Type == ojson.Null && targetValue.Type == ojson.Null, nil } // 对布尔值特殊处理 - if (jsonValue.Type == gjson.True || jsonValue.Type == gjson.False) && - (targetValue.Type == gjson.True || targetValue.Type == gjson.False) { + if (jsonValue.Type == ojson.True || jsonValue.Type == ojson.False) && + (targetValue.Type == ojson.True || targetValue.Type == ojson.False) { return jsonValue.Bool() == targetValue.Bool(), nil } @@ -778,20 +778,20 @@ func compareEqual(jsonValue, targetValue gjson.Result) (bool, error) { } switch jsonValue.Type { - case gjson.True, gjson.False: + case ojson.True, ojson.False: return jsonValue.Bool() == targetValue.Bool(), nil - case gjson.Number: + case ojson.Number: return jsonValue.Num == targetValue.Num, nil - case gjson.String: + case ojson.String: return jsonValue.String() == targetValue.String(), nil default: return jsonValue.String() == targetValue.String(), nil } } -func compareNumeric(jsonValue, targetValue gjson.Result, operator string) (bool, error) { +func compareNumeric(jsonValue, targetValue ojson.Result, operator string) (bool, error) { // 只有数字类型才支持数值比较 - if jsonValue.Type != gjson.Number || targetValue.Type != gjson.Number { + if jsonValue.Type != ojson.Number || targetValue.Type != ojson.Number { return false, fmt.Errorf("numeric comparison requires both values to be numbers, got %v and %v", jsonValue.Type, targetValue.Type) } @@ -817,33 +817,25 @@ func compareNumeric(jsonValue, targetValue gjson.Result, operator string) (bool, // 旧实现把整个 jsonData unmarshal 成 map[string]interface{} 再 marshal 回来, // 对包含大 base64 字段(如 Gemini inlineData.data)的请求会放大数倍内存 // (interface 装箱、map bucket、再次 marshal)。 -// 这里改成在 []byte 上直接调用 sjson.SetBytes,按顶层 key 逐个写入, +// 这里改成在 ojson.Doc 上按顶层 key 逐个写入, // 不再把 payload 解码到 map[string]interface{}。 // // 语义保持:每个 paramOverride 顶层 key 视为字面 key(不解析点号路径), // 与旧的 reqMap[key] = value 一致。包含 `.` `*` `?` `\` 的 key 会被转义, -// 防止被 sjson 当作嵌套路径或通配符。 -func applyOperationsLegacy(jsonData []byte, paramOverride map[string]any, auditRecorder *paramOverrideAuditRecorder) ([]byte, error) { - if len(paramOverride) == 0 { - return jsonData, nil - } - - result := jsonData +// 防止被 ojson 当作嵌套路径或通配符。 +func applyOperationsLegacy(doc *ojson.Doc, paramOverride map[string]any, auditRecorder *paramOverrideAuditRecorder) error { for key, value := range paramOverride { escaped := escapeSjsonLiteralKey(key) - next, err := sjson.SetBytes(result, escaped, value) - if err != nil { - return nil, err + if err := doc.Set(escaped, value); err != nil { + return err } - result = next auditRecorder.recordOperation("set", key, "", "", value) } - - return result, nil + return nil } -// escapeSjsonLiteralKey 把可能被 sjson 误判为路径或通配符的字符转义, -// 用于把字面 key 安全地传给 sjson.SetBytes / sjson.DeleteBytes。 +// escapeSjsonLiteralKey 把可能被 ojson 误判为路径或通配符的字符转义, +// 用于把字面 key 安全地传给 ojson.Doc.Set。 func escapeSjsonLiteralKey(key string) string { if !strings.ContainsAny(key, ".*?\\") { return key @@ -861,14 +853,16 @@ func escapeSjsonLiteralKey(key string) string { return sb.String() } -// applyOperations 在 []byte 上原地应用所有 param override 操作。 +// applyOperations 在同一个 ojson.Doc 上依次应用所有 param override 操作, +// 返回最终的请求体。 // -// 旧实现走 string-based gjson/sjson,在 ApplyParamOverride 入口会做 -// string(jsonData) 与最终 []byte(result) 各一次整包拷贝,对大 base64 -// payload 来说每次重试都额外多花 2 倍 body 体积的临时内存。 -// 这里改成全程在 []byte 上工作,sjson.SetBytes / gjson.GetBytes 都是 -// 直接读写 []byte,每个操作只会产生一份新 buffer。 -func applyOperations(jsonData []byte, operations []ParamOperation, conditionContext map[string]any) ([]byte, error) { +// 旧实现每个操作都调用一次 sjson.SetBytes,每次都要复制整个请求体, +// 对大 base64 payload(如 Gemini inlineData.data)来说操作越多拷贝越多。 +// ojson.Doc 只拆开编辑经过的对象和数组,其余部分仍是输入的切片; +// 条件、负数索引、keep_origin 等读取都通过 doc.Get 读当前文档, +// 最后由 doc.Bytes() 一次性生成输出。doc.Get 的结果可能指向输入, +// 不能在本次调用之外保留。 +func applyOperations(doc *ojson.Doc, operations []ParamOperation, conditionContext map[string]any) ([]byte, error) { context := ensureContextMap(conditionContext) auditRecorder := getParamOverrideAuditRecorder(context) contextJSON, err := marshalContextJSON(context) @@ -876,10 +870,9 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont return nil, fmt.Errorf("failed to marshal condition context: %v", err) } - result := jsonData for _, op := range operations { // 检查条件是否满足 - ok, err := checkConditions(result, contextJSON, op.Conditions, op.Logic) + ok, err := checkConditions(doc, contextJSON, op.Conditions, op.Logic) if err != nil { return nil, err } @@ -887,10 +880,10 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont continue // 条件不满足,跳过当前操作 } // 处理路径中的负数索引 - opPath := processNegativeIndex(result, op.Path) + opPath := processNegativeIndex(doc, op.Path) var opPaths []string if isPathBasedOperation(op.Mode) { - opPaths, err = resolveOperationPaths(result, opPath) + opPaths, err = resolveOperationPaths(doc, opPath) if err != nil { return nil, err } @@ -902,7 +895,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont switch op.Mode { case "delete": for _, path := range opPaths { - result, err = deleteValue(result, path) + err = deleteValue(doc, path) if err != nil { break } @@ -910,19 +903,19 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "set": for _, path := range opPaths { - if op.KeepOrigin && gjson.GetBytes(result, path).Exists() { + if op.KeepOrigin && doc.Get(path).Exists() { continue } - result, err = sjson.SetBytes(result, path, op.Value) + err = doc.Set(path, op.Value) if err != nil { break } auditRecorder.recordOperation("set", path, "", "", op.Value) } case "move": - opFrom := processNegativeIndex(result, op.From) - opTo := processNegativeIndex(result, op.To) - result, err = moveValue(result, opFrom, opTo) + opFrom := processNegativeIndex(doc, op.From) + opTo := processNegativeIndex(doc, op.To) + err = moveValue(doc, opFrom, opTo) if err == nil { auditRecorder.recordOperation("move", "", opFrom, opTo, nil) } @@ -930,15 +923,15 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont if op.From == "" || op.To == "" { return nil, fmt.Errorf("copy from/to is required") } - opFrom := processNegativeIndex(result, op.From) - opTo := processNegativeIndex(result, op.To) - result, err = copyValue(result, opFrom, opTo) + opFrom := processNegativeIndex(doc, op.From) + opTo := processNegativeIndex(doc, op.To) + err = copyValue(doc, opFrom, opTo) if err == nil { auditRecorder.recordOperation("copy", "", opFrom, opTo, nil) } case "prepend": for _, path := range opPaths { - result, err = modifyValue(result, path, op.Value, op.KeepOrigin, true) + err = modifyValue(doc, path, op.Value, op.KeepOrigin, true) if err != nil { break } @@ -946,7 +939,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "append": for _, path := range opPaths { - result, err = modifyValue(result, path, op.Value, op.KeepOrigin, false) + err = modifyValue(doc, path, op.Value, op.KeepOrigin, false) if err != nil { break } @@ -954,7 +947,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "trim_prefix": for _, path := range opPaths { - result, err = trimStringValue(result, path, op.Value, true) + err = trimStringValue(doc, path, op.Value, true) if err != nil { break } @@ -962,7 +955,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "trim_suffix": for _, path := range opPaths { - result, err = trimStringValue(result, path, op.Value, false) + err = trimStringValue(doc, path, op.Value, false) if err != nil { break } @@ -970,7 +963,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "ensure_prefix": for _, path := range opPaths { - result, err = ensureStringAffix(result, path, op.Value, true) + err = ensureStringAffix(doc, path, op.Value, true) if err != nil { break } @@ -978,7 +971,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "ensure_suffix": for _, path := range opPaths { - result, err = ensureStringAffix(result, path, op.Value, false) + err = ensureStringAffix(doc, path, op.Value, false) if err != nil { break } @@ -986,7 +979,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "trim_space": for _, path := range opPaths { - result, err = transformStringValue(result, path, strings.TrimSpace) + err = transformStringValue(doc, path, strings.TrimSpace) if err != nil { break } @@ -994,7 +987,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "to_lower": for _, path := range opPaths { - result, err = transformStringValue(result, path, strings.ToLower) + err = transformStringValue(doc, path, strings.ToLower) if err != nil { break } @@ -1002,7 +995,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "to_upper": for _, path := range opPaths { - result, err = transformStringValue(result, path, strings.ToUpper) + err = transformStringValue(doc, path, strings.ToUpper) if err != nil { break } @@ -1010,7 +1003,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "replace": for _, path := range opPaths { - result, err = replaceStringValue(result, path, op.From, op.To) + err = replaceStringValue(doc, path, op.From, op.To) if err != nil { break } @@ -1018,7 +1011,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont } case "regex_replace": for _, path := range opPaths { - result, err = regexReplaceStringValue(result, path, op.From, op.To) + err = regexReplaceStringValue(doc, path, op.From, op.To) if err != nil { break } @@ -1033,7 +1026,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont return nil, returnErr case "prune_objects": for _, path := range opPaths { - result, err = pruneObjects(result, path, contextJSON, op.Value) + err = pruneObjects(doc, path, contextJSON, op.Value) if err != nil { break } @@ -1103,7 +1096,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont contextJSON, err = marshalContextJSON(context) } case "sync_fields": - result, err = syncFieldsBetweenTargets(result, context, op.From, op.To) + err = syncFieldsBetweenTargets(doc, context, op.From, op.To) if err == nil { auditRecorder.recordOperation("sync_fields", "", op.From, op.To, nil) contextJSON, err = marshalContextJSON(context) @@ -1115,7 +1108,7 @@ func applyOperations(jsonData []byte, operations []ParamOperation, conditionCont return nil, fmt.Errorf("operation %s failed: %w", op.Mode, err) } } - return result, nil + return doc.Bytes(), nil } func parseParamOverrideReturnError(value any) (*ParamOverrideReturnError, error) { @@ -1546,17 +1539,20 @@ func parseSyncTarget(spec string) (syncTarget, error) { } } -func readSyncTargetValue(data []byte, context map[string]any, target syncTarget) (any, bool, error) { +func readSyncTargetValue(doc *ojson.Doc, context map[string]any, target syncTarget) (any, bool, error) { switch target.kind { case "json": - path := processNegativeIndex(data, target.key) - value := gjson.GetBytes(data, path) - if !value.Exists() || value.Type == gjson.Null { + path := processNegativeIndex(doc, target.key) + value := doc.Get(path) + if !value.Exists() || value.Type == ojson.Null { return nil, false, nil } - if value.Type == gjson.String && strings.TrimSpace(value.String()) == "" { + if value.Type == ojson.String && strings.TrimSpace(value.String()) == "" { return nil, false, nil } + // A header target keeps the value in the context map, so it must not + // point into the request body. + value.Raw, value.Str = strings.Clone(value.Raw), strings.Clone(value.Str) return value.Value(), true, nil case "header": value, ok := getHeaderValueFromContext(context, target.key) @@ -1569,52 +1565,45 @@ func readSyncTargetValue(data []byte, context map[string]any, target syncTarget) } } -func writeSyncTargetValue(data []byte, context map[string]any, target syncTarget, value any) ([]byte, error) { +func writeSyncTargetValue(doc *ojson.Doc, context map[string]any, target syncTarget, value any) error { switch target.kind { case "json": - path := processNegativeIndex(data, target.key) - nextJSON, err := sjson.SetBytes(data, path, value) - if err != nil { - return nil, err - } - return nextJSON, nil + path := processNegativeIndex(doc, target.key) + return doc.Set(path, value) case "header": - if err := setHeaderOverrideInContext(context, target.key, value, false); err != nil { - return nil, err - } - return data, nil + return setHeaderOverrideInContext(context, target.key, value, false) default: - return nil, fmt.Errorf("unsupported sync_fields target kind: %s", target.kind) + return fmt.Errorf("unsupported sync_fields target kind: %s", target.kind) } } -func syncFieldsBetweenTargets(data []byte, context map[string]any, fromSpec string, toSpec string) ([]byte, error) { +func syncFieldsBetweenTargets(doc *ojson.Doc, context map[string]any, fromSpec string, toSpec string) error { fromTarget, err := parseSyncTarget(fromSpec) if err != nil { - return nil, err + return err } toTarget, err := parseSyncTarget(toSpec) if err != nil { - return nil, err + return err } - fromValue, fromExists, err := readSyncTargetValue(data, context, fromTarget) + fromValue, fromExists, err := readSyncTargetValue(doc, context, fromTarget) if err != nil { - return nil, err + return err } - toValue, toExists, err := readSyncTargetValue(data, context, toTarget) + toValue, toExists, err := readSyncTargetValue(doc, context, toTarget) if err != nil { - return nil, err + return err } // If one side exists and the other side is missing, sync the missing side. if fromExists && !toExists { - return writeSyncTargetValue(data, context, toTarget, fromValue) + return writeSyncTargetValue(doc, context, toTarget, fromValue) } if toExists && !fromExists { - return writeSyncTargetValue(data, context, fromTarget, toValue) + return writeSyncTargetValue(doc, context, fromTarget, toValue) } - return data, nil + return nil } func ensureMapKeyInContext(context map[string]any, key string) map[string]any { @@ -1690,24 +1679,23 @@ func syncRuntimeHeaderOverrideFromContext(info *RelayInfo, context map[string]an // moveValue and copyValue write the source's raw bytes: a decoded value // would be re-encoded with sorted object keys. -func moveValue(data []byte, fromPath, toPath string) ([]byte, error) { - sourceValue := gjson.GetBytes(data, fromPath) +func moveValue(doc *ojson.Doc, fromPath, toPath string) error { + sourceValue := doc.Get(fromPath) if !sourceValue.Exists() { - return data, fmt.Errorf("source path does not exist: %s", fromPath) + return fmt.Errorf("source path does not exist: %s", fromPath) } - result, err := sjson.SetRawBytes(data, toPath, []byte(sourceValue.Raw)) - if err != nil { - return nil, err + if err := doc.SetRaw(toPath, sourceValue.Raw); err != nil { + return err } - return sjson.DeleteBytes(result, fromPath) + return doc.Delete(fromPath) } -func copyValue(data []byte, fromPath, toPath string) ([]byte, error) { - sourceValue := gjson.GetBytes(data, fromPath) +func copyValue(doc *ojson.Doc, fromPath, toPath string) error { + sourceValue := doc.Get(fromPath) if !sourceValue.Exists() { - return data, fmt.Errorf("source path does not exist: %s", fromPath) + return fmt.Errorf("source path does not exist: %s", fromPath) } - return sjson.SetRawBytes(data, toPath, []byte(sourceValue.Raw)) + return doc.SetRaw(toPath, sourceValue.Raw) } func isPathBasedOperation(mode string) bool { @@ -1719,16 +1707,16 @@ func isPathBasedOperation(mode string) bool { } } -func resolveOperationPaths(data []byte, path string) ([]string, error) { +func resolveOperationPaths(doc *ojson.Doc, path string) ([]string, error) { if !strings.Contains(path, "*") { return []string{path}, nil } - return expandWildcardPaths(data, path) + return expandWildcardPaths(doc, path) } -func expandWildcardPaths(data []byte, path string) ([]string, error) { +func expandWildcardPaths(doc *ojson.Doc, path string) ([]string, error) { var root any - if err := common.Unmarshal(data, &root); err != nil { + if err := common.Unmarshal(doc.Bytes(), &root); err != nil { return nil, err } @@ -1789,28 +1777,28 @@ func collectWildcardPaths(node any, segments []string, prefix []string) []string } } -func deleteValue(data []byte, path string) ([]byte, error) { +func deleteValue(doc *ojson.Doc, path string) error { if strings.TrimSpace(path) == "" { - return data, nil + return nil } - return sjson.DeleteBytes(data, path) + return doc.Delete(path) } -func modifyValue(data []byte, path string, value any, keepOrigin, isPrepend bool) ([]byte, error) { - current := gjson.GetBytes(data, path) +func modifyValue(doc *ojson.Doc, path string, value any, keepOrigin, isPrepend bool) error { + current := doc.Get(path) switch { case current.IsArray(): - return modifyArray(data, path, value, isPrepend) - case current.Type == gjson.String: - return modifyString(data, path, value, isPrepend) - case current.Type == gjson.JSON: - return mergeObjects(data, path, value, keepOrigin) + return modifyArray(doc, path, value, isPrepend) + case current.Type == ojson.String: + return modifyString(doc, path, value, isPrepend) + case current.Type == ojson.JSON: + return mergeObjects(doc, path, value, keepOrigin) } - return data, fmt.Errorf("operation not supported for type: %v", current.Type) + return fmt.Errorf("operation not supported for type: %v", current.Type) } -func modifyArray(data []byte, path string, value any, isPrepend bool) ([]byte, error) { - current := gjson.GetBytes(data, path) +func modifyArray(doc *ojson.Doc, path string, value any, isPrepend bool) error { + current := doc.Get(path) var newArray []any // 添加新值 addValue := func() { @@ -1822,7 +1810,7 @@ func modifyArray(data []byte, path string, value any, isPrepend bool) ([]byte, e } // 添加原值(保留原始字节,对象键顺序不变) addOriginal := func() { - current.ForEach(func(_, val gjson.Result) bool { + current.ForEach(func(_, val ojson.Result) bool { newArray = append(newArray, common.RawMessage(val.Raw)) return true }) @@ -1834,11 +1822,11 @@ func modifyArray(data []byte, path string, value any, isPrepend bool) ([]byte, e addOriginal() addValue() } - return sjson.SetBytes(data, path, newArray) + return doc.Set(path, newArray) } -func modifyString(data []byte, path string, value any, isPrepend bool) ([]byte, error) { - current := gjson.GetBytes(data, path) +func modifyString(doc *ojson.Doc, path string, value any, isPrepend bool) error { + current := doc.Get(path) valueStr := fmt.Sprintf("%v", value) var newStr string if isPrepend { @@ -1846,17 +1834,17 @@ func modifyString(data []byte, path string, value any, isPrepend bool) ([]byte, } else { newStr = current.String() + valueStr } - return sjson.SetBytes(data, path, newStr) + return doc.Set(path, newStr) } -func trimStringValue(data []byte, path string, value any, isPrefix bool) ([]byte, error) { - current := gjson.GetBytes(data, path) - if current.Type != gjson.String { - return data, fmt.Errorf("operation not supported for type: %v", current.Type) +func trimStringValue(doc *ojson.Doc, path string, value any, isPrefix bool) error { + current := doc.Get(path) + if current.Type != ojson.String { + return fmt.Errorf("operation not supported for type: %v", current.Type) } if value == nil { - return data, fmt.Errorf("trim value is required") + return fmt.Errorf("trim value is required") } valueStr := fmt.Sprintf("%v", value) @@ -1866,69 +1854,69 @@ func trimStringValue(data []byte, path string, value any, isPrefix bool) ([]byte } else { newStr = strings.TrimSuffix(current.String(), valueStr) } - return sjson.SetBytes(data, path, newStr) + return doc.Set(path, newStr) } -func ensureStringAffix(data []byte, path string, value any, isPrefix bool) ([]byte, error) { - current := gjson.GetBytes(data, path) - if current.Type != gjson.String { - return data, fmt.Errorf("operation not supported for type: %v", current.Type) +func ensureStringAffix(doc *ojson.Doc, path string, value any, isPrefix bool) error { + current := doc.Get(path) + if current.Type != ojson.String { + return fmt.Errorf("operation not supported for type: %v", current.Type) } if value == nil { - return data, fmt.Errorf("ensure value is required") + return fmt.Errorf("ensure value is required") } valueStr := fmt.Sprintf("%v", value) if valueStr == "" { - return data, fmt.Errorf("ensure value is required") + return fmt.Errorf("ensure value is required") } currentStr := current.String() if isPrefix { if strings.HasPrefix(currentStr, valueStr) { - return data, nil + return nil } - return sjson.SetBytes(data, path, valueStr+currentStr) + return doc.Set(path, valueStr+currentStr) } if strings.HasSuffix(currentStr, valueStr) { - return data, nil + return nil } - return sjson.SetBytes(data, path, currentStr+valueStr) + return doc.Set(path, currentStr+valueStr) } -func transformStringValue(data []byte, path string, transform func(string) string) ([]byte, error) { - current := gjson.GetBytes(data, path) - if current.Type != gjson.String { - return data, fmt.Errorf("operation not supported for type: %v", current.Type) +func transformStringValue(doc *ojson.Doc, path string, transform func(string) string) error { + current := doc.Get(path) + if current.Type != ojson.String { + return fmt.Errorf("operation not supported for type: %v", current.Type) } - return sjson.SetBytes(data, path, transform(current.String())) + return doc.Set(path, transform(current.String())) } -func replaceStringValue(data []byte, path, from, to string) ([]byte, error) { - current := gjson.GetBytes(data, path) - if current.Type != gjson.String { - return data, fmt.Errorf("operation not supported for type: %v", current.Type) +func replaceStringValue(doc *ojson.Doc, path, from, to string) error { + current := doc.Get(path) + if current.Type != ojson.String { + return fmt.Errorf("operation not supported for type: %v", current.Type) } if from == "" { - return data, fmt.Errorf("replace from is required") + return fmt.Errorf("replace from is required") } - return sjson.SetBytes(data, path, strings.ReplaceAll(current.String(), from, to)) + return doc.Set(path, strings.ReplaceAll(current.String(), from, to)) } -func regexReplaceStringValue(data []byte, path, pattern, replacement string) ([]byte, error) { - current := gjson.GetBytes(data, path) - if current.Type != gjson.String { - return data, fmt.Errorf("operation not supported for type: %v", current.Type) +func regexReplaceStringValue(doc *ojson.Doc, path, pattern, replacement string) error { + current := doc.Get(path) + if current.Type != ojson.String { + return fmt.Errorf("operation not supported for type: %v", current.Type) } if pattern == "" { - return data, fmt.Errorf("regex pattern is required") + return fmt.Errorf("regex pattern is required") } re, err := getParamOverrideRegex(pattern) if err != nil { - return data, err + return err } - return sjson.SetBytes(data, path, re.ReplaceAllString(current.String(), replacement)) + return doc.Set(path, re.ReplaceAllString(current.String(), replacement)) } type pruneObjectsOptions struct { @@ -1937,47 +1925,38 @@ type pruneObjectsOptions struct { recursive bool } -func pruneObjects(data []byte, path, contextJSON string, value any) ([]byte, error) { +// pruneObjects 在原 Doc 上删除 path(为空时为整个请求体)下满足条件的对象, +// 其余内容保持原样。 +func pruneObjects(doc *ojson.Doc, path, contextJSON string, value any) error { options, err := parsePruneObjectsOptions(value) if err != nil { - return nil, err + return err } + target := doc.Get(path) if path == "" { - var root any - if err := common.Unmarshal(data, &root); err != nil { - return nil, err - } - cleaned, _, err := pruneObjectsNode(root, options, contextJSON, true) - if err != nil { - return nil, err - } - return common.Marshal(cleaned) + target = doc.Get("@this") } - - target := gjson.GetBytes(data, path) if !target.Exists() { - return data, nil + return nil } - var targetNode any - if target.Type == gjson.JSON { - if err := common.UnmarshalJsonStr(target.Raw, &targetNode); err != nil { - return nil, err + var pruned []prunedObject + if _, err := collectPrunedObjects(target, path, options, contextJSON, true, &pruned); err != nil { + return err + } + // 从后往前删,前面数组元素的下标不受影响 + for i := len(pruned) - 1; i >= 0; i-- { + if pruned[i].member { + err = DeleteJSONMember(doc, pruned[i].path) + } else { + err = doc.Delete(pruned[i].path) + } + if err != nil { + return err } - } else { - targetNode = target.Value() } - - cleaned, _, err := pruneObjectsNode(targetNode, options, contextJSON, true) - if err != nil { - return nil, err - } - cleanedBytes, err := common.Marshal(cleaned) - if err != nil { - return nil, err - } - return sjson.SetRawBytes(data, path, cleanedBytes) + return nil } func parsePruneObjectsOptions(value any) (pruneObjectsOptions, error) { @@ -2105,84 +2084,87 @@ func parseConditionOperations(raw any) ([]ConditionOperation, error) { } } -func pruneObjectsNode(node any, options pruneObjectsOptions, contextJSON string, isRoot bool) (any, bool, error) { - switch value := node.(type) { - case []any: - result := make([]any, 0, len(value)) - for _, item := range value { - next, drop, err := pruneObjectsNode(item, options, contextJSON, false) +// prunedObject 是 prune_objects 要删除的对象:对象成员按键删除所有副本, +// 数组元素按下标删除。 +type prunedObject struct { + path string + member bool +} + +// collectPrunedObjects 遍历 node:数组逐个检查元素,对象满足条件时(根节点除外) +// 整个删除,recursive 时继续检查对象的成员。要删除的路径按文档顺序追加到 +// pruned,返回值表示 node 本身是否要删除。 +func collectPrunedObjects(node ojson.Result, path string, options pruneObjectsOptions, contextJSON string, isRoot bool, pruned *[]prunedObject) (bool, error) { + prefix := "" + if path != "" { + prefix = path + "." + } + switch { + case node.IsArray(): + for i, item := range node.Array() { + itemPath := prefix + strconv.Itoa(i) + drop, err := collectPrunedObjects(item, itemPath, options, contextJSON, false, pruned) if err != nil { - return nil, false, err + return false, err } if drop { - continue + *pruned = append(*pruned, prunedObject{path: itemPath}) } - result = append(result, next) } - return result, false, nil - case map[string]any: - shouldDrop, err := shouldPruneObject(value, options, contextJSON) + return false, nil + case node.IsObject(): + shouldDrop, err := checkConditions(ojson.NewDocString(node.Raw), contextJSON, options.conditions, options.logic) if err != nil { - return nil, false, err + return false, err } if shouldDrop && !isRoot { - return nil, true, nil + return true, nil } if !options.recursive { - return value, false, nil + return false, nil } - for key, child := range value { - next, drop, err := pruneObjectsNode(child, options, contextJSON, false) + node.ForEach(func(key, child ojson.Result) bool { + childPath := prefix + ojson.Escape(key.Str) + var drop bool + drop, err = collectPrunedObjects(child, childPath, options, contextJSON, false, pruned) if err != nil { - return nil, false, err + return false } if drop { - delete(value, key) - continue + *pruned = append(*pruned, prunedObject{path: childPath, member: true}) } - value[key] = next - } - return value, false, nil - default: - return node, false, nil - } -} - -func shouldPruneObject(node map[string]any, options pruneObjectsOptions, contextJSON string) (bool, error) { - nodeBytes, err := common.Marshal(node) - if err != nil { + return true + }) return false, err + default: + return false, nil } - return checkConditions(nodeBytes, contextJSON, options.conditions, options.logic) } -func mergeObjects(data []byte, path string, value any, keepOrigin bool) ([]byte, error) { - current := gjson.GetBytes(data, path) - var currentMap, newMap map[string]any - - // 解析当前值(current.Raw 是 data 的子串,避免再分配一份) - if err := common.UnmarshalJsonStr(current.Raw, ¤tMap); err != nil { - return nil, err - } - // 解析新值 +// mergeObjects 把 value 的成员写入 path 处的对象:已有成员原地替换,新成员按 +// 键名顺序追加到末尾,其余成员保持原样。 +func mergeObjects(doc *ojson.Doc, path string, value any, keepOrigin bool) error { + var newMap map[string]any switch v := value.(type) { case map[string]any: newMap = v default: jsonBytes, _ := common.Marshal(v) if err := common.Unmarshal(jsonBytes, &newMap); err != nil { - return nil, err + return err } } - // 合并 - result := make(map[string]any) - maps.Copy(result, currentMap) - for k, v := range newMap { - if !keepOrigin || result[k] == nil { - result[k] = v + for _, key := range slices.Sorted(maps.Keys(newMap)) { + if keepOrigin { + if current := doc.Get(path + "." + ojson.Escape(key)); current.Exists() && current.Type != ojson.Null { + continue + } + } + if err := SetJSONMember(doc, path, key, newMap[key]); err != nil { + return err } } - return sjson.SetBytes(data, path, result) + return nil } // BuildParamOverrideContext 提供 ApplyParamOverride 可用的上下文信息。 diff --git a/relay/common/override_test.go b/relay/common/override_test.go index 3ea22275b7..666f493f8e 100644 --- a/relay/common/override_test.go +++ b/relay/common/override_test.go @@ -121,6 +121,73 @@ func TestApplyParamOverrideMixedLegacyAndOperationsConflictPrefersOperations(t * assertJSONEqual(t, `{"model":"op-model","temperature":0.2}`, string(out)) } +func TestApplyParamOverrideLaterOperationsSeeEarlierEdits(t *testing.T) { + input := []byte(`{"model":"gpt-4","messages":[{"type":"text","text":"a"},{"type":"thinking","text":"b"}],"tags":["x"]}`) + override := map[string]any{ + "operations": []any{ + map[string]any{"mode": "prune_objects", "value": "thinking"}, + map[string]any{"path": "model", "mode": "set", "value": "gpt-5"}, + map[string]any{ + "path": "reasoning_effort", + "mode": "set", + "value": "high", + "conditions": []any{map[string]any{"path": "model", "mode": "full", "value": "gpt-5"}}, + }, + map[string]any{"path": "tags", "mode": "append", "value": "y"}, + map[string]any{"path": "tags.-1", "mode": "to_upper"}, + map[string]any{"mode": "move", "from": "reasoning_effort", "to": "effort"}, + map[string]any{"path": "effort", "mode": "set", "value": "low", "keep_origin": true}, + }, + } + + out, err := ApplyParamOverride(input, override, nil) + require.NoError(t, err) + assert.Equal(t, `{"model":"gpt-5","messages":[{"type":"text","text":"a"}],"tags":["x","Y"],"effort":"high"}`, string(out)) +} + +// Object merges and prune_objects edit the body in place: members they do not +// touch keep their order, number spelling and characters. +func TestApplyParamOverrideMergeAndPruneKeepMemberOrder(t *testing.T) { + tests := []struct { + name string + input string + op map[string]any + want string + }{ + { + name: "append merges into the object in place", + input: `{"zeta":1.0,"config":{"y":1e2,"b":"&","keep":1},"model":"m"}`, + op: map[string]any{"path": "config", "mode": "append", "value": map[string]any{"keep": 2, "c": true, "a": "x"}}, + want: `{"zeta":1.0,"config":{"y":1e2,"b":"&","keep":2,"a":"x","c":true},"model":"m"}`, + }, + { + name: "keep_origin leaves existing members", + input: `{"config":{"y":1e2,"keep":1}}`, + op: map[string]any{"path": "config", "mode": "append", "keep_origin": true, "value": map[string]any{"keep": 2, "a": "x"}}, + want: `{"config":{"y":1e2,"keep":1,"a":"x"}}`, + }, + { + name: "prune over the whole body", + input: `{"zeta":1.0,"messages":[{"type":"text","n":1e2},{"type":"thinking"},{"role":"u","content":[{"type":"thinking"},{"type":"text","b":"&"}]}],"model":"m"}`, + op: map[string]any{"mode": "prune_objects", "value": "thinking"}, + want: `{"zeta":1.0,"messages":[{"type":"text","n":1e2},{"role":"u","content":[{"type":"text","b":"&"}]}],"model":"m"}`, + }, + { + name: "prune drops object members", + input: `{"a":{"x":{"type":"thinking"},"y":1.0},"b":2}`, + op: map[string]any{"path": "a", "mode": "prune_objects", "value": "thinking"}, + want: `{"a":{"y":1.0},"b":2}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out, err := ApplyParamOverride([]byte(tt.input), map[string]any{"operations": []any{tt.op}}, nil) + require.NoError(t, err) + assert.Equal(t, tt.want, string(out)) + }) + } +} + func TestApplyParamOverrideTrimRequiresValue(t *testing.T) { // trim_prefix requires value example: // {"operations":[{"path":"model","mode":"trim_prefix"}]} @@ -2341,6 +2408,17 @@ func TestRemoveDisabledFieldsKeepsNestedKeyOrder(t *testing.T) { assert.Equal(t, `{"response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"}}}}},"stream_options":{"include_usage":true}}`, string(out)) } +// Other members keep their bytes and order. A disabled key sent twice is +// removed in every copy, since upstreams read the last one. +func TestRemoveDisabledFieldsKeepsUntouchedBytes(t *testing.T) { + input := `{"model":"m","service_tier":"flex","temperature":1.0,"max_tokens":1e3,"stop":["<|end|>"],"service\u005ftier":"priority","stream_options":{"include_obfuscation":false}}` + + out, err := RemoveDisabledFields([]byte(input), dto.ChannelOtherSettings{}, false) + + require.NoError(t, err) + assert.Equal(t, `{"model":"m","temperature":1.0,"max_tokens":1e3,"stop":["<|end|>"]}`, string(out)) +} + func TestRemoveDisabledFieldsNoControlledFieldsKeepsBody(t *testing.T) { input := `{"model":"gpt-4o","messages":[{"role":"user","content":"hi"}]}` settings := dto.ChannelOtherSettings{} diff --git a/relay/common/relay_info.go b/relay/common/relay_info.go index bd3da24680..8129bdaa0f 100644 --- a/relay/common/relay_info.go +++ b/relay/common/relay_info.go @@ -19,9 +19,9 @@ import ( "github.com/QuantumNous/new-api/setting/model_setting" hosttypes "github.com/QuantumNous/new-api/types" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" - "github.com/tidwall/gjson" ) type ThinkingContentInfo struct { @@ -554,8 +554,8 @@ func reasoningEffortFromRequest(request dto.Request) string { } effort = req.ReasoningEffort if strings.TrimSpace(effort) == "" && len(req.Reasoning) > 0 { - value := gjson.GetBytes(req.Reasoning, "effort") - if value.Type == gjson.String { + value := ojson.GetBytes(req.Reasoning, "effort") + if value.Type == ojson.String { effort = value.String() } } @@ -1138,6 +1138,50 @@ func FailTaskInfo(reason string) *TaskInfo { } } +// DeleteJSONMember removes every copy of the member at path. A client body +// may repeat a key, and most upstream parsers read the last copy, so a +// surviving copy could reach the upstream after the gateway removed or +// replaced the first one. +func DeleteJSONMember(doc *ojson.Doc, path string) error { + for doc.Get(path).Exists() { + size := doc.Len() + if err := doc.Delete(path); err != nil { + return err + } + if doc.Len() == size { + return fmt.Errorf("delete %s: member was not removed", path) + } + } + return nil +} + +// SetJSONMember sets member key of the object at parent ("" for the root) to +// value and leaves one copy. A key that appears once is replaced where it +// stands, so the object keeps its member order; a repeated key is removed +// everywhere, for the reason given on DeleteJSONMember, and written once at +// the end. +func SetJSONMember(doc *ojson.Doc, parent, key string, value any) error { + path := ojson.Escape(key) + object := doc.Get("@this") + if parent != "" { + path = parent + "." + path + object = doc.Get(parent) + } + copies := 0 + object.ForEach(func(member, _ ojson.Result) bool { + if member.Str == key { + copies++ + } + return copies < 2 + }) + if copies > 1 { + if err := DeleteJSONMember(doc, path); err != nil { + return err + } + } + return doc.Set(path, value) +} + // RemoveDisabledFields 从请求 JSON 数据中移除渠道设置中禁用的字段 // service_tier: 服务层级字段,可能导致额外计费(OpenAI、Claude、Responses API 支持) // inference_geo: Claude 数据驻留推理区域字段(仅 Claude 支持,默认过滤) @@ -1153,77 +1197,61 @@ func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOther return jsonData, nil } - // Only top-level members are decoded: nested values keep the client's + // Only the removed members change: everything else keeps the client's // bytes and key order, which upstreams follow when they fill a schema. - var data map[string]json.RawMessage - if err := common.Unmarshal(jsonData, &data); err != nil { - common.SysError(common.LogText("RemoveDisabledFields Unmarshal error :%s", err.Error())) + if !ojson.ValidBytes(jsonData) { + common.SysError(common.LogText("RemoveDisabledFields Unmarshal error :%s", "invalid JSON")) return jsonData, nil } + var disabled []string // 默认移除 service_tier,除非明确允许(避免额外计费风险) if !channelOtherSettings.AllowServiceTier { - if _, exists := data["service_tier"]; exists { - delete(data, "service_tier") - } + disabled = append(disabled, "service_tier") } // 默认移除 inference_geo,除非明确允许(避免在未授权情况下透传数据驻留区域) if !channelOtherSettings.AllowInferenceGeo { - if _, exists := data["inference_geo"]; exists { - delete(data, "inference_geo") - } + disabled = append(disabled, "inference_geo") } // 默认移除 speed,除非明确允许(避免意外切换 Claude 推理速度模式) if !channelOtherSettings.AllowSpeed { - if _, exists := data["speed"]; exists { - delete(data, "speed") - } + disabled = append(disabled, "speed") } // 默认允许 store 透传,除非明确禁用(禁用可能影响 Codex 使用) if channelOtherSettings.DisableStore { - if _, exists := data["store"]; exists { - delete(data, "store") - } + disabled = append(disabled, "store") } // 默认移除 safety_identifier,除非明确允许(保护用户隐私,避免向 OpenAI 报告用户信息) if !channelOtherSettings.AllowSafetyIdentifier { - if _, exists := data["safety_identifier"]; exists { - delete(data, "safety_identifier") - } + disabled = append(disabled, "safety_identifier") } // 默认移除 stream_options.include_obfuscation,除非明确允许(避免关闭响应流混淆保护) - if !channelOtherSettings.AllowIncludeObfuscation { - var streamOptions map[string]json.RawMessage - if err := common.Unmarshal(data["stream_options"], &streamOptions); err == nil && streamOptions != nil { - delete(streamOptions, "include_obfuscation") - if len(streamOptions) == 0 { - delete(data, "stream_options") - } else { - encoded, err := common.Marshal(streamOptions) - if err != nil { - common.SysError(common.LogText("RemoveDisabledFields Marshal error :%s", err.Error())) - return jsonData, nil - } - data["stream_options"] = encoded - } - } + removeObfuscation := !channelOtherSettings.AllowIncludeObfuscation && ojson.GetBytesNoCopy(jsonData, "stream_options").IsObject() + if removeObfuscation { + disabled = append(disabled, "stream_options.include_obfuscation") } - jsonDataAfter, err := common.Marshal(data) - if err != nil { - common.SysError(common.LogText("RemoveDisabledFields Marshal error :%s", err.Error())) - return jsonData, nil + doc := ojson.NewDoc(jsonData) + for _, path := range disabled { + if err := DeleteJSONMember(doc, path); err != nil { + return nil, err + } } - return jsonDataAfter, nil + if removeObfuscation && len(doc.Get("stream_options").Map()) == 0 { + if err := DeleteJSONMember(doc, "stream_options"); err != nil { + return nil, err + } + } + return doc.Bytes(), nil } func hasRemovableDisabledField(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings) bool { - values := gjson.GetManyBytes( + values := ojson.GetManyBytes( jsonData, "service_tier", "inference_geo", @@ -1248,39 +1276,34 @@ func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error) { return jsonData, nil } - var data map[string]any - if err := common.Unmarshal(jsonData, &data); err != nil { - common.SysError(common.LogText("RemoveGeminiDisabledFields Unmarshal error: %s", err.Error())) + if !ojson.ValidBytes(jsonData) { + common.SysError(common.LogText("RemoveGeminiDisabledFields Unmarshal error: %s", "invalid JSON")) return jsonData, nil } - // Process contents array + // Process contents array; only the removed ids change, so inline data + // is never decoded or re-encoded. // Handle both camelCase (functionResponse) and snake_case (function_response) - if contents, ok := data["contents"].([]any); ok { - for _, content := range contents { - if contentMap, ok := content.(map[string]any); ok { - if parts, ok := contentMap["parts"].([]any); ok { - for _, part := range parts { - if partMap, ok := part.(map[string]any); ok { - // Check functionResponse (camelCase) - if funcResp, ok := partMap["functionResponse"].(map[string]any); ok { - delete(funcResp, "id") - } - // Check function_response (snake_case) - if funcResp, ok := partMap["function_response"].(map[string]any); ok { - delete(funcResp, "id") - } - } - } + contents := ojson.GetBytesNoCopy(jsonData, "contents") + if !contents.IsArray() { + return jsonData, nil + } + doc := ojson.NewDoc(jsonData) + for i, content := range contents.Array() { + parts := content.Get("parts") + if !parts.IsArray() { + continue + } + for j, part := range parts.Array() { + for _, field := range []string{"functionResponse", "function_response"} { + if !part.Get(field + ".id").Exists() { + continue + } + if err := DeleteJSONMember(doc, fmt.Sprintf("contents.%d.parts.%d.%s.id", i, j, field)); err != nil { + return nil, err } } } } - - jsonDataAfter, err := common.Marshal(data) - if err != nil { - common.SysError(common.LogText("RemoveGeminiDisabledFields Marshal error: %s", err.Error())) - return jsonData, nil - } - return jsonDataAfter, nil + return doc.Bytes(), nil } diff --git a/relay/common/relay_info_gemini_settings_test.go b/relay/common/relay_info_gemini_settings_test.go index 53c8d973f8..6314a8fec9 100644 --- a/relay/common/relay_info_gemini_settings_test.go +++ b/relay/common/relay_info_gemini_settings_test.go @@ -6,6 +6,7 @@ import ( "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/setting/model_setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRelayInfoConvOptionsUsesNormalizedGeminiSafetySettings(t *testing.T) { @@ -56,3 +57,21 @@ func TestRelayInfoConvOptionsGeminiJSONSchemaSupport(t *testing.T) { }) } } + +// Vertex AI rejects functionResponse.id. Only the ids are removed; inline data +// and every other member keep their bytes and order. +func TestRemoveGeminiDisabledFieldsDropsFunctionResponseIDs(t *testing.T) { + settings := model_setting.GetGeminiSettings() + original := settings.RemoveFunctionResponseIdEnabled + t.Cleanup(func() { + settings.RemoveFunctionResponseIdEnabled = original + }) + settings.RemoveFunctionResponseIdEnabled = true + + input := `{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"iVBO<&>"}}]},{"role":"user","parts":[{"text":"x"},{"functionResponse":{"id":"call_1","name":"f","response":{"n":1.50}}},{"function_response":{"name":"g","id":"call_2"}}]}],"generationConfig":{"temperature":0.0}}` + + out, err := RemoveGeminiDisabledFields([]byte(input)) + + require.NoError(t, err) + assert.Equal(t, `{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"iVBO<&>"}}]},{"role":"user","parts":[{"text":"x"},{"functionResponse":{"name":"f","response":{"n":1.50}}},{"function_response":{"name":"g"}}]}],"generationConfig":{"temperature":0.0}}`, string(out)) +} diff --git a/relay/convert_request_error_test.go b/relay/convert_request_error_test.go index 8002a02c50..78e63717b0 100644 --- a/relay/convert_request_error_test.go +++ b/relay/convert_request_error_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/pkg/billingexpr" @@ -23,7 +24,6 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) type imageReservation struct { @@ -112,7 +112,7 @@ func TestImageRequestReservesFinalQuantityBeforeUpstream(t *testing.T) { assert.Equal(t, http.StatusBadGateway, apiErr.StatusCode) require.Len(t, received, 1) body := <-received - assert.Equal(t, int64(tc.count), gjson.GetBytes(body, "n").Int()) + assert.Equal(t, int64(tc.count), ojson.GetBytes(body, "n").Int()) assert.Equal(t, tc.count*20000, info.PriceData.QuotaToPreConsume) assert.GreaterOrEqual(t, reservation.held, info.PriceData.QuotaToPreConsume) assert.Nil(t, info.BillingImageCount) diff --git a/relay/deepseek_tools_handler.go b/relay/deepseek_tools_handler.go index 37120b6007..8f3e6abffa 100644 --- a/relay/deepseek_tools_handler.go +++ b/relay/deepseek_tools_handler.go @@ -15,8 +15,8 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" ) // DeepSeekToolsHelper relays the DeepSeek Search and Fetch APIs like @@ -110,9 +110,9 @@ func DeepSeekToolsHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIErr var billable bool switch info.RelayMode { case relayconstant.RelayModeToolsFetch: - billable = gjson.GetBytes(responseBody, "content").String() != "" + billable = ojson.GetBytes(responseBody, "content").String() != "" default: - results := gjson.GetBytes(responseBody, "results") + results := ojson.GetBytes(responseBody, "results") billable = results.IsArray() && len(results.Array()) > 0 } if !billable { diff --git a/relay/helper/billing_expr_request_test.go b/relay/helper/billing_expr_request_test.go index 5bc1d6e91b..bff1f2efe0 100644 --- a/relay/helper/billing_expr_request_test.go +++ b/relay/helper/billing_expr_request_test.go @@ -7,13 +7,13 @@ import ( "net/http/httptest" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/gin-gonic/gin" "github.com/samber/lo" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestResolveIncomingBillingExprRequestInput(t *testing.T) { @@ -57,7 +57,7 @@ func TestBuildBillingExprRequestInputFromRequest(t *testing.T) { require.NoError(t, err) require.Equal(t, "application/json", input.Headers["Content-Type"]) require.Equal(t, "1", input.Headers["X-Test"]) - require.True(t, gjson.GetBytes(input.Body, "stream").Bool()) - require.Equal(t, "user", gjson.GetBytes(input.Body, "messages.0.role").String()) - require.Equal(t, float64(3000), gjson.GetBytes(input.Body, "max_tokens").Float()) + require.True(t, ojson.GetBytes(input.Body, "stream").Bool()) + require.Equal(t, "user", ojson.GetBytes(input.Body, "messages.0.role").String()) + require.Equal(t, float64(3000), ojson.GetBytes(input.Body, "max_tokens").Float()) } diff --git a/relay/helper/reasoning_suffix_test.go b/relay/helper/reasoning_suffix_test.go index b1ef965d40..0b2600bd7f 100644 --- a/relay/helper/reasoning_suffix_test.go +++ b/relay/helper/reasoning_suffix_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" relaycommon "github.com/QuantumNous/new-api/relay/common" @@ -16,7 +17,6 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func mustApplyReasoningModelSuffix(t *testing.T, info *relaycommon.RelayInfo, outbound ...dto.Request) { @@ -591,7 +591,7 @@ func TestApplyReasoningModelSuffixThinkingMinusOnePassthrough(t *testing.T) { require.NotNil(t, info.ReasoningConversion.BudgetTokens) assert.Equal(t, -1, *info.ReasoningConversion.BudgetTokens) require.NotEmpty(t, request.Reasoning) - assert.Equal(t, float64(-1), gjson.GetBytes(request.Reasoning, "max_tokens").Num) + assert.Equal(t, float64(-1), ojson.GetBytes(request.Reasoning, "max_tokens").Num) } func TestApplyReasoningModelSuffixPreservesGpt51CodexMax(t *testing.T) { diff --git a/relay/responses_websocket.go b/relay/responses_websocket.go index 5f0d6bd2a3..153a65fe7c 100644 --- a/relay/responses_websocket.go +++ b/relay/responses_websocket.go @@ -28,6 +28,7 @@ import ( "github.com/QuantumNous/new-api/relaykit/types" "github.com/QuantumNous/new-api/service" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) @@ -817,34 +818,36 @@ func newResponsesWSInvalidRequestError(err error) *types.NewAPIError { // normalizeResponsesWSCreateEvent builds the HTTP-shaped request body from a // response.create whose envelope the read loop already parsed and validated. -// The message is decoded once more as a raw map (the body source) and once as -// the typed request; the envelope is not parsed again. +// The body is the message with the WebSocket members removed, and is decoded +// once as the typed request; the envelope is not parsed again. func normalizeResponsesWSCreateEvent(message []byte, event responsesWSCreateEvent, streamID string) (responsesWSCreateRequest, error) { create := responsesWSCreateRequest{StreamID: streamID, Generate: event.Generate} - // Decode the wrapped request on its own so outer fields cannot enter the HTTP body. + // Edit the wrapped request on its own so outer fields cannot enter the HTTP body. source := message if len(event.Request) > 0 { source = event.Request } - var raw map[string]common.RawMessage - if err := common.Unmarshal(source, &raw); err != nil { - return create, err + if !ojson.GetBytesNoCopy(source, "@this").IsObject() { + return create, errors.New("response.create request must be a JSON object") } + doc := ojson.NewDoc(source) if len(event.Request) > 0 { - if len(create.Generate) == 0 { - create.Generate = raw["generate"] + if generate := doc.Get("generate"); len(create.Generate) == 0 && generate.Exists() { + create.Generate = common.RawMessage(generate.Raw) } } else { for _, key := range []string{"type", "event_id", "background", "stream", "stream_options"} { - delete(raw, key) + if err := relaycommon.DeleteJSONMember(doc, key); err != nil { + return create, err + } } } - delete(raw, "generate") - delete(raw, "stream_id") - payload, err := common.Marshal(raw) - if err != nil { - return create, err + for _, key := range []string{"generate", "stream_id"} { + if err := relaycommon.DeleteJSONMember(doc, key); err != nil { + return create, err + } } + payload := doc.Bytes() if err := common.Unmarshal(payload, &create.Request); err != nil { return create, err } @@ -858,33 +861,35 @@ func normalizeResponsesWSCreateEvent(message []byte, event responsesWSCreateEven } func buildResponsesWSCreateEvent(jsonData []byte, generate common.RawMessage, streamID string) ([]byte, error) { - var event map[string]common.RawMessage - if err := common.Unmarshal(jsonData, &event); err != nil { - return nil, err + if !ojson.ValidBytes(jsonData) || !ojson.GetBytesNoCopy(jsonData, "@this").IsObject() { + return nil, errors.New("response.create body must be a JSON object") } - typeData, err := common.Marshal(responsesWSEventTypeResponseCreate) - if err != nil { - return nil, err - } - event["type"] = typeData + event := ojson.NewDoc(jsonData) // The normalized body never carries stream_id; a channel parameter // override may inject one, and it must not shadow the envelope's value. - delete(event, "stream_id") + keys := []string{"type", "stream_id", "event_id", "background", "stream", "stream_options"} + if len(generate) > 0 { + keys = append(keys, "generate") + } + for _, key := range keys { + if err := relaycommon.DeleteJSONMember(event, key); err != nil { + return nil, err + } + } + if err := event.Set("type", responsesWSEventTypeResponseCreate); err != nil { + return nil, err + } if streamID != "" { - streamData, err := common.Marshal(streamID) - if err != nil { + if err := event.Set("stream_id", streamID); err != nil { return nil, err } - event["stream_id"] = streamData } - delete(event, "event_id") - delete(event, "background") - delete(event, "stream") - delete(event, "stream_options") if len(generate) > 0 { - event["generate"] = generate + if err := event.SetRawBytes("generate", generate); err != nil { + return nil, err + } } - return common.Marshal(event) + return event.Bytes(), nil } func buildResponsesWSErrorPayload(eventID, streamID string, apiErr *types.NewAPIError, upstreamURLs ...string) ([]byte, error) { diff --git a/relay/responses_websocket_test.go b/relay/responses_websocket_test.go index d41a80c355..4f3bc7ee9b 100644 --- a/relay/responses_websocket_test.go +++ b/relay/responses_websocket_test.go @@ -472,6 +472,23 @@ func TestNormalizeResponsesWSCreateEventFlat(t *testing.T) { } } +// The HTTP body and the upstream event keep the client's member order and +// number spelling; only the WebSocket members change. +func TestResponsesWSCreateEventKeepsClientBytes(t *testing.T) { + message := []byte(`{"type":"response.create","model":"m","text":{"format":{"type":"json_schema","name":"r","schema":{"properties":{"b":{},"a":{}}}}},"temperature":1.0,"stream":true,"generate":false}`) + + create, _, err := normalizeResponsesWSTestMessage(message) + require.NoError(t, err) + assert.Equal(t, `{"model":"m","text":{"format":{"type":"json_schema","name":"r","schema":{"properties":{"b":{},"a":{}}}}},"temperature":1.0}`, string(create.Body)) + + event, err := buildResponsesWSCreateEvent(create.Body, create.Generate, "s1") + require.NoError(t, err) + assert.Equal(t, `{"model":"m","text":{"format":{"type":"json_schema","name":"r","schema":{"properties":{"b":{},"a":{}}}}},"temperature":1.0,"type":"response.create","stream_id":"s1","generate":false}`, string(event)) + + _, _, err = normalizeResponsesWSTestMessage([]byte(`{"type":"response.create","response":["m"]}`)) + assert.Error(t, err) +} + func TestBuildResponsesWSCreateEventIsFlat(t *testing.T) { payload := []byte(`{ "model": "gpt-5.3-codex-spark", diff --git a/relaykit/dto/openai_request_zero_value_test.go b/relaykit/dto/openai_request_zero_value_test.go index 43c3ed0bbd..4e1d8c207e 100644 --- a/relaykit/dto/openai_request_zero_value_test.go +++ b/relaykit/dto/openai_request_zero_value_test.go @@ -4,10 +4,10 @@ import ( "encoding/json" "testing" + "github.com/MoeForge/moego/ojson" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestGeneralOpenAIRequestPreserveExplicitZeroValues(t *testing.T) { @@ -36,20 +36,20 @@ func TestGeneralOpenAIRequestPreserveExplicitZeroValues(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - require.True(t, gjson.GetBytes(encoded, "stream").Exists()) - require.True(t, gjson.GetBytes(encoded, "max_tokens").Exists()) - require.True(t, gjson.GetBytes(encoded, "max_completion_tokens").Exists()) - require.True(t, gjson.GetBytes(encoded, "top_p").Exists()) - require.True(t, gjson.GetBytes(encoded, "top_k").Exists()) - require.True(t, gjson.GetBytes(encoded, "n").Exists()) - require.True(t, gjson.GetBytes(encoded, "frequency_penalty").Exists()) - require.True(t, gjson.GetBytes(encoded, "presence_penalty").Exists()) - require.True(t, gjson.GetBytes(encoded, "seed").Exists()) - require.True(t, gjson.GetBytes(encoded, "logprobs").Exists()) - require.True(t, gjson.GetBytes(encoded, "top_logprobs").Exists()) - require.True(t, gjson.GetBytes(encoded, "dimensions").Exists()) - require.True(t, gjson.GetBytes(encoded, "return_images").Exists()) - require.True(t, gjson.GetBytes(encoded, "return_related_questions").Exists()) + require.True(t, ojson.GetBytes(encoded, "stream").Exists()) + require.True(t, ojson.GetBytes(encoded, "max_tokens").Exists()) + require.True(t, ojson.GetBytes(encoded, "max_completion_tokens").Exists()) + require.True(t, ojson.GetBytes(encoded, "top_p").Exists()) + require.True(t, ojson.GetBytes(encoded, "top_k").Exists()) + require.True(t, ojson.GetBytes(encoded, "n").Exists()) + require.True(t, ojson.GetBytes(encoded, "frequency_penalty").Exists()) + require.True(t, ojson.GetBytes(encoded, "presence_penalty").Exists()) + require.True(t, ojson.GetBytes(encoded, "seed").Exists()) + require.True(t, ojson.GetBytes(encoded, "logprobs").Exists()) + require.True(t, ojson.GetBytes(encoded, "top_logprobs").Exists()) + require.True(t, ojson.GetBytes(encoded, "dimensions").Exists()) + require.True(t, ojson.GetBytes(encoded, "return_images").Exists()) + require.True(t, ojson.GetBytes(encoded, "return_related_questions").Exists()) } func TestGeneralOpenAIRequestPreserveQwenThinkingBudget(t *testing.T) { @@ -65,7 +65,7 @@ func TestGeneralOpenAIRequestPreserveQwenThinkingBudget(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - value := gjson.GetBytes(encoded, "thinking_budget") + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, int64(0), value.Int()) } @@ -79,7 +79,7 @@ func TestGeneralOpenAIRequestPreserveQwQThinkingBudget(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - value := gjson.GetBytes(encoded, "thinking_budget") + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, int64(128), value.Int()) } @@ -93,7 +93,7 @@ func TestGeneralOpenAIRequestDropsThinkingBudgetForNonQwenModel(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - assert.False(t, gjson.GetBytes(encoded, "thinking_budget").Exists()) + assert.False(t, ojson.GetBytes(encoded, "thinking_budget").Exists()) } func TestIsQwenThinkingBudgetModel(t *testing.T) { @@ -135,12 +135,12 @@ func TestOpenAIResponsesRequestPreserveExplicitZeroValues(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - require.True(t, gjson.GetBytes(encoded, "max_output_tokens").Exists()) - require.True(t, gjson.GetBytes(encoded, "max_tool_calls").Exists()) - require.True(t, gjson.GetBytes(encoded, "stream").Exists()) - require.True(t, gjson.GetBytes(encoded, "top_p").Exists()) - require.True(t, gjson.GetBytes(encoded, "frequency_penalty").Exists()) - require.True(t, gjson.GetBytes(encoded, "presence_penalty").Exists()) + require.True(t, ojson.GetBytes(encoded, "max_output_tokens").Exists()) + require.True(t, ojson.GetBytes(encoded, "max_tool_calls").Exists()) + require.True(t, ojson.GetBytes(encoded, "stream").Exists()) + require.True(t, ojson.GetBytes(encoded, "top_p").Exists()) + require.True(t, ojson.GetBytes(encoded, "frequency_penalty").Exists()) + require.True(t, ojson.GetBytes(encoded, "presence_penalty").Exists()) } func TestOpenAIResponsesRequestPreserveQwenThinkingBudget(t *testing.T) { @@ -152,7 +152,7 @@ func TestOpenAIResponsesRequestPreserveQwenThinkingBudget(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - value := gjson.GetBytes(encoded, "thinking_budget") + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, int64(0), value.Int()) } @@ -166,7 +166,7 @@ func TestOpenAIResponsesRequestPreserveQwQThinkingBudget(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - value := gjson.GetBytes(encoded, "thinking_budget") + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, int64(128), value.Int()) } @@ -180,7 +180,7 @@ func TestOpenAIResponsesRequestDropsThinkingBudgetForNonQwenModel(t *testing.T) encoded, err := kitutil.Marshal(req) require.NoError(t, err) - assert.False(t, gjson.GetBytes(encoded, "thinking_budget").Exists()) + assert.False(t, ojson.GetBytes(encoded, "thinking_budget").Exists()) } func TestGeneralOpenAIRequestGetSystemRoleName(t *testing.T) { @@ -270,10 +270,10 @@ func TestGeneralOpenAIRequestPreserveMessageLevelTools(t *testing.T) { encoded, err := kitutil.Marshal(req) require.NoError(t, err) - messages := gjson.GetBytes(encoded, "messages").Array() + messages := ojson.GetBytes(encoded, "messages").Array() require.Len(t, messages, 5) - assert.Equal(t, "required", gjson.GetBytes(encoded, "tool_choice").String()) - assert.JSONEq(t, gjson.GetBytes(raw, "tools").Raw, gjson.GetBytes(encoded, "tools").Raw) + assert.Equal(t, "required", ojson.GetBytes(encoded, "tool_choice").String()) + assert.JSONEq(t, ojson.GetBytes(raw, "tools").Raw, ojson.GetBytes(encoded, "tools").Raw) // Regular messages keep their content untouched. assert.Equal(t, "You are Kimi.", messages[0].Get("content").String()) @@ -281,22 +281,22 @@ func TestGeneralOpenAIRequestPreserveMessageLevelTools(t *testing.T) { assert.Equal(t, "What time is it in Beijing?", messages[1].Get("content").String()) // Kimi K3 dynamic tool loading message: tools preserved byte-for-byte, no content key at all. - assert.JSONEq(t, gjson.GetBytes(raw, "messages.2.tools").Raw, messages[2].Get("tools").Raw) + assert.JSONEq(t, ojson.GetBytes(raw, "messages.2.tools").Raw, messages[2].Get("tools").Raw) assert.False(t, messages[2].Get("content").Exists()) assert.Equal(t, "system", messages[2].Get("role").String()) // Assistant tool call replay still emits an explicit "content": null. assistantContent := messages[3].Get("content") assert.True(t, assistantContent.Exists()) - assert.Equal(t, gjson.Null, assistantContent.Type) - assert.JSONEq(t, gjson.GetBytes(raw, "messages.3.tool_calls").Raw, messages[3].Get("tool_calls").Raw) + assert.Equal(t, ojson.Null, assistantContent.Type) + assert.JSONEq(t, ojson.GetBytes(raw, "messages.3.tool_calls").Raw, messages[3].Get("tool_calls").Raw) // Explicit empty content next to tools is forwarded as-is for the upstream to judge. emptyContent := messages[4].Get("content") assert.True(t, emptyContent.Exists()) - assert.Equal(t, gjson.String, emptyContent.Type) + assert.Equal(t, ojson.String, emptyContent.Type) assert.Equal(t, "", emptyContent.String()) - assert.JSONEq(t, gjson.GetBytes(raw, "messages.4.tools").Raw, messages[4].Get("tools").Raw) + assert.JSONEq(t, ojson.GetBytes(raw, "messages.4.tools").Raw, messages[4].Get("tools").Raw) // Token estimation sees message-level tools alongside the top-level ones. meta := req.GetTokenCountMeta() diff --git a/relaykit/go.mod b/relaykit/go.mod index 430a745802..b0d7181588 100644 --- a/relaykit/go.mod +++ b/relaykit/go.mod @@ -3,11 +3,10 @@ module github.com/QuantumNous/new-api/relaykit go 1.25.1 require ( + github.com/MoeForge/moego v0.1.0-alpha.1 github.com/google/uuid v1.6.0 github.com/samber/lo v1.53.0 github.com/stretchr/testify v1.11.1 - github.com/tidwall/gjson v1.19.0 - github.com/tidwall/sjson v1.2.5 ) require ( @@ -15,8 +14,6 @@ require ( github.com/kr/pretty v0.3.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/rogpeppe/go-internal v1.10.0 // indirect - github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.0 // indirect golang.org/x/text v0.35.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/relaykit/go.sum b/relaykit/go.sum index 1abb399050..0b64dfd0d6 100644 --- a/relaykit/go.sum +++ b/relaykit/go.sum @@ -1,3 +1,5 @@ +github.com/MoeForge/moego v0.1.0-alpha.1 h1:d+asBZu+2oKnBj1kzdvdANMStbIKw9BLCpknuWjiR28= +github.com/MoeForge/moego v0.1.0-alpha.1/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -20,15 +22,6 @@ github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM= github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU= -github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= -github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/relaykit/relayconvert/internal/claude_messages/to_oai_chat_resp.go b/relaykit/relayconvert/internal/claude_messages/to_oai_chat_resp.go index 5398c8f0d5..9cf49b2d3a 100644 --- a/relaykit/relayconvert/internal/claude_messages/to_oai_chat_resp.go +++ b/relaykit/relayconvert/internal/claude_messages/to_oai_chat_resp.go @@ -6,12 +6,11 @@ import ( "strings" "unicode/utf8" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/reasonmap" sharedclaude "github.com/QuantumNous/new-api/relaykit/relayconvert/internal/shared/claude" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" - "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) type ClaudeResponseInfo struct { @@ -482,12 +481,12 @@ func setMessageDeltaUsageInt(data string, path string, localValue int) string { return data } - upstreamValue := gjson.Get(data, path) + upstreamValue := ojson.Get(data, path) if upstreamValue.Exists() && upstreamValue.Int() > 0 { return data } - patchedData, err := sjson.Set(data, path, localValue) + patchedData, err := ojson.Set(data, path, localValue) if err != nil { return data } diff --git a/relaykit/relayconvert/internal/media/media.go b/relaykit/relayconvert/internal/media/media.go index de002f102e..3660f30d0a 100644 --- a/relaykit/relayconvert/internal/media/media.go +++ b/relaykit/relayconvert/internal/media/media.go @@ -2,12 +2,12 @@ package media import ( "context" - "encoding/base64" "errors" "strings" "sync" "unicode/utf8" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/relaykit/types" ) diff --git a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_req_test.go b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_req_test.go index 77838b007b..5e8c2a413b 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_oai_responses_req_test.go +++ b/relaykit/relayconvert/internal/oai_chat/to_oai_responses_req_test.go @@ -5,12 +5,12 @@ import ( "encoding/json" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/relaykit/dto" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" "github.com/samber/lo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestChatCompletionsRequestToResponsesRequestInstructionsAndTools(t *testing.T) { @@ -34,10 +34,10 @@ func TestChatCompletionsRequestToResponsesRequestInstructionsAndTools(t *testing assert.Equal(t, "gpt-test", got.Model) assert.Equal(t, `"system rules\n\ndeveloper rules"`, string(got.Instructions)) - assert.Equal(t, "input_image", gjson.GetBytes(got.Input, "0.content.1.type").String()) - assert.Equal(t, "function_call", gjson.GetBytes(got.Input, "2.type").String()) - assert.Equal(t, "call_1", gjson.GetBytes(got.Input, "2.call_id").String()) - assert.Equal(t, "function_call_output", gjson.GetBytes(got.Input, "3.type").String()) + assert.Equal(t, "input_image", ojson.GetBytes(got.Input, "0.content.1.type").String()) + assert.Equal(t, "function_call", ojson.GetBytes(got.Input, "2.type").String()) + assert.Equal(t, "call_1", ojson.GetBytes(got.Input, "2.call_id").String()) + assert.Equal(t, "function_call_output", ojson.GetBytes(got.Input, "3.type").String()) } func TestChatCompletionsRequestToResponsesRequestImageDetail(t *testing.T) { @@ -65,8 +65,8 @@ func TestChatCompletionsRequestToResponsesRequestImageDetail(t *testing.T) { }) require.NoError(t, err) - assert.Equal(t, "input_image", gjson.GetBytes(got.Input, "0.content.0.type").String()) - assert.Equal(t, tt.want, gjson.GetBytes(got.Input, "0.content.0.detail").String()) + assert.Equal(t, "input_image", ojson.GetBytes(got.Input, "0.content.0.type").String()) + assert.Equal(t, tt.want, ojson.GetBytes(got.Input, "0.content.0.detail").String()) }) } } @@ -87,7 +87,7 @@ func TestChatCompletionsRequestToResponsesRequestPreservesPromptCacheKey(t *test encoded, err := kitutil.Marshal(got) require.NoError(t, err) - assert.Equal(t, key, gjson.GetBytes(encoded, "prompt_cache_key").String()) + assert.Equal(t, key, ojson.GetBytes(encoded, "prompt_cache_key").String()) }) t.Run("absent", func(t *testing.T) { @@ -99,7 +99,7 @@ func TestChatCompletionsRequestToResponsesRequestPreservesPromptCacheKey(t *test encoded, err := kitutil.Marshal(got) require.NoError(t, err) - assert.False(t, gjson.GetBytes(encoded, "prompt_cache_key").Exists()) + assert.False(t, ojson.GetBytes(encoded, "prompt_cache_key").Exists()) }) } @@ -131,8 +131,8 @@ func TestChatCompletionsRequestToResponsesRequestPreservesQwenThinkingBudget(t * encoded, err := kitutil.Marshal(got) require.NoError(t, err) - assert.True(t, gjson.GetBytes(encoded, "enable_thinking").Bool()) - value := gjson.GetBytes(encoded, "thinking_budget") + assert.True(t, ojson.GetBytes(encoded, "enable_thinking").Bool()) + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, tt.want, value.Int()) }) diff --git a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go index aa401e1e10..445b91ddea 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go +++ b/relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go @@ -5,12 +5,12 @@ import ( "encoding/json" "testing" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/relaykit/dto" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" "github.com/samber/lo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tidwall/gjson" ) func TestResponsesRequestToChatCompletionsRequestInstructionsAndScalarInput(t *testing.T) { @@ -54,7 +54,7 @@ func TestResponsesRequestToChatCompletionsRequestInstructionsAndScalarInput(t *t assert.Equal(t, "medium", got.ReasoningEffort) assert.Equal(t, `"user-1"`, string(got.User)) assert.Equal(t, `false`, string(got.Store)) - assert.Equal(t, "abc", gjson.GetBytes(got.Metadata, "trace").String()) + assert.Equal(t, "abc", ojson.GetBytes(got.Metadata, "trace").String()) } func TestResponsesRequestToChatCompletionsRequestPreservesQwenThinkingBudget(t *testing.T) { @@ -81,8 +81,8 @@ func TestResponsesRequestToChatCompletionsRequestPreservesQwenThinkingBudget(t * encoded, err := kitutil.Marshal(got) require.NoError(t, err) - assert.True(t, gjson.GetBytes(encoded, "enable_thinking").Bool()) - value := gjson.GetBytes(encoded, "thinking_budget") + assert.True(t, ojson.GetBytes(encoded, "enable_thinking").Bool()) + value := ojson.GetBytes(encoded, "thinking_budget") assert.True(t, value.Exists()) assert.Equal(t, tt.want, value.Int()) }) @@ -220,7 +220,7 @@ func TestResponsesRequestToChatCompletionsRequestToolsToolChoiceAndTextFormat(t assert.Equal(t, "function", got.Tools[0].Type) assert.Equal(t, "lookup", got.Tools[0].Function.Name) assert.Equal(t, "Lookup data", got.Tools[0].Function.Description) - assert.Equal(t, "object", gjson.GetBytes(got.Tools[0].Function.Parameters, "type").String()) + assert.Equal(t, "object", ojson.GetBytes(got.Tools[0].Function.Parameters, "type").String()) assert.Equal(t, map[string]any{ "type": "function", "function": map[string]any{ @@ -229,8 +229,8 @@ func TestResponsesRequestToChatCompletionsRequestToolsToolChoiceAndTextFormat(t }, got.ToolChoice) require.NotNil(t, got.ResponseFormat) assert.Equal(t, "json_schema", got.ResponseFormat.Type) - assert.Equal(t, "answer", gjson.GetBytes(got.ResponseFormat.JsonSchema, "name").String()) - assert.True(t, gjson.GetBytes(got.ResponseFormat.JsonSchema, "strict").Bool()) + assert.Equal(t, "answer", ojson.GetBytes(got.ResponseFormat.JsonSchema, "name").String()) + assert.True(t, ojson.GetBytes(got.ResponseFormat.JsonSchema, "strict").Bool()) } func TestResponsesRequestToChatCompletionsRequestEncodesCustomToolHistoryAsFunction(t *testing.T) { @@ -258,7 +258,7 @@ func TestResponsesRequestToChatCompletionsRequestEncodesCustomToolHistoryAsFunct assert.Equal(t, "function", toolCalls[0].Type) assert.Equal(t, "call_custom", toolCalls[0].ID) assert.Equal(t, "exec", toolCalls[0].Function.Name) - assert.Equal(t, `echo "hi" && ls`, gjson.Get(toolCalls[0].Function.Arguments, "input").String()) + assert.Equal(t, `echo "hi" && ls`, ojson.Get(toolCalls[0].Function.Arguments, "input").String()) assert.Empty(t, toolCalls[0].Custom) assert.Equal(t, dto.Message{Role: "tool", ToolCallId: "call_custom", Content: "hi"}, got.Messages[1]) } diff --git a/relaykit/relayconvert/internal/shared/claude/schema.go b/relaykit/relayconvert/internal/shared/claude/schema.go index d1a0119b82..5d167194d3 100644 --- a/relaykit/relayconvert/internal/shared/claude/schema.go +++ b/relaykit/relayconvert/internal/shared/claude/schema.go @@ -3,8 +3,8 @@ package claude import ( "encoding/json" + "github.com/MoeForge/moego/ojson" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" - "github.com/tidwall/sjson" ) // FunctionParametersToInputSchema returns function parameters as a Claude @@ -31,12 +31,12 @@ func FunctionParametersToInputSchema(parameters json.RawMessage) (schema json.Ra schema = parameters var err error if len(fields.Type) == 0 || kitutil.GetJsonType(fields.Type) == "null" { - if schema, err = sjson.SetRawBytes(schema, "type", []byte(`"object"`)); err != nil { + if schema, err = ojson.SetRawBytes(schema, "type", []byte(`"object"`)); err != nil { return empty, false } } if len(fields.Properties) == 0 || kitutil.GetJsonType(fields.Properties) == "null" { - if schema, err = sjson.SetRawBytes(schema, "properties", []byte(`{}`)); err != nil { + if schema, err = ojson.SetRawBytes(schema, "properties", []byte(`{}`)); err != nil { return empty, false } } diff --git a/service/audio.go b/service/audio.go index c4b6f01b2f..779ac1f4cf 100644 --- a/service/audio.go +++ b/service/audio.go @@ -1,9 +1,10 @@ package service import ( - "encoding/base64" "fmt" "strings" + + "github.com/MoeForge/moego/base64" ) func parseAudio(audioBase64 string, format string) (duration float64, err error) { @@ -38,8 +39,8 @@ func DecodeBase64AudioData(audioBase64 string) (string, error) { audioBase64 = audioBase64[idx+1:] } - // 解码 Base64 数据 - _, err := base64.StdEncoding.DecodeString(audioBase64) + // 校验 Base64 数据 + _, err := base64.StdEncoding.ValidateString(audioBase64) if err != nil { return "", fmt.Errorf("base64 decode error: %v", err) } diff --git a/service/channel_affinity.go b/service/channel_affinity.go index 5ccbf63932..2d88735305 100644 --- a/service/channel_affinity.go +++ b/service/channel_affinity.go @@ -9,6 +9,7 @@ import ( "sync" "time" + "github.com/MoeForge/moego/ojson" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/pkg/cachex" @@ -17,7 +18,6 @@ import ( "github.com/QuantumNous/new-api/setting/operation_setting" "github.com/gin-gonic/gin" "github.com/samber/hot" - "github.com/tidwall/gjson" ) const ( @@ -321,12 +321,12 @@ func extractChannelAffinityValue(c *gin.Context, src operation_setting.ChannelAf if err != nil || len(body) == 0 { return "" } - res := gjson.GetBytes(body, src.Path) + res := ojson.GetBytes(body, src.Path) if !res.Exists() { return "" } switch res.Type { - case gjson.String, gjson.Number, gjson.True, gjson.False: + case ojson.String, ojson.Number, ojson.True, ojson.False: return strings.TrimSpace(res.String()) default: return strings.TrimSpace(res.Raw) diff --git a/service/file_service.go b/service/file_service.go index cd8cdc1d5e..184fe0a2ba 100644 --- a/service/file_service.go +++ b/service/file_service.go @@ -2,7 +2,6 @@ package service import ( "bytes" - "encoding/base64" "encoding/binary" "fmt" "image" @@ -13,6 +12,7 @@ import ( "net/http" "strings" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/logger" diff --git a/service/image.go b/service/image.go index f717866f0d..1a39c5890b 100644 --- a/service/image.go +++ b/service/image.go @@ -2,7 +2,6 @@ package service import ( "bytes" - "encoding/base64" "errors" "fmt" "image" @@ -10,6 +9,7 @@ import ( "net/http" "strings" + "github.com/MoeForge/moego/base64" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" diff --git a/service/task_polling.go b/service/task_polling.go index 92af56241d..4d0d6453af 100644 --- a/service/task_polling.go +++ b/service/task_polling.go @@ -19,6 +19,7 @@ import ( "github.com/QuantumNous/new-api/relay/channel/task/taskcommon" relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/MoeForge/moego/ojson" "github.com/bytedance/gopkg/util/gopool" "github.com/samber/lo" ) @@ -646,40 +647,38 @@ func finalizeTerminalTask(ctx context.Context, adaptor TaskPollingAdaptor, task } func redactVideoResponseBody(body []byte) []byte { - var m map[string]any - if err := common.Unmarshal(body, &m); err != nil { + // Only the redacted members change; the rest keeps the upstream bytes. + if !ojson.ValidBytes(body) || !ojson.GetBytesNoCopy(body, "@this").IsObject() { return body } - resp, _ := m["response"].(map[string]any) - if resp != nil { - delete(resp, "bytesBase64Encoded") - if v, ok := resp["video"].(string); ok { - resp["video"] = truncateBase64(v) + doc := ojson.NewDoc(body) + if resp := ojson.GetBytesNoCopy(body, "response"); resp.IsObject() { + _ = doc.Delete("response.bytesBase64Encoded") + if video := resp.Get("video"); video.Type == ojson.String { + _ = doc.Set("response.video", truncateBase64(video.Str)) } - if vs, ok := resp["videos"].([]any); ok { - for i := range vs { - if vm, ok := vs[i].(map[string]any); ok { - delete(vm, "bytesBase64Encoded") + if videos := resp.Get("videos"); videos.IsArray() { + for i, video := range videos.Array() { + if video.IsObject() { + _ = doc.Delete(fmt.Sprintf("response.videos.%d.bytesBase64Encoded", i)) } } } } - if steps, ok := m["steps"].([]any); ok { - for _, step := range steps { - sm, _ := step.(map[string]any) - parts, _ := sm["content"].([]any) - for _, part := range parts { - if pm, ok := part.(map[string]any); ok && pm["type"] == "video" { - delete(pm, "data") + if steps := ojson.GetBytesNoCopy(body, "steps"); steps.IsArray() { + for i, step := range steps.Array() { + parts := step.Get("content") + if !parts.IsArray() { + continue + } + for j, part := range parts.Array() { + if part.Get("type").String() == "video" { + _ = doc.Delete(fmt.Sprintf("steps.%d.content.%d.data", i, j)) } } } } - b, err := common.Marshal(m) - if err != nil { - return body - } - return b + return doc.Bytes() } func truncateBase64(s string) string { diff --git a/service/task_polling_test.go b/service/task_polling_test.go index 2bdfa2581b..cbe4ece171 100644 --- a/service/task_polling_test.go +++ b/service/task_polling_test.go @@ -183,6 +183,12 @@ func TestRedactVideoResponseBodyDropsInteractionInlineVideo(t *testing.T) { assert.Equal(t, "done", content[1].(map[string]any)["text"]) } +func TestRedactVideoResponseBodyKeepsUntouchedBytes(t *testing.T) { + body := []byte(`{"name":"op","response":{"videos":[{"uri":"u","bytesBase64Encoded":"x"}],"durationSeconds":8.0,"bytesBase64Encoded":"y"},"done":true}`) + + assert.Equal(t, `{"name":"op","response":{"videos":[{"uri":"u"}],"durationSeconds":8.0},"done":true}`, string(redactVideoResponseBody(body))) +} + func seedTaskPollingChannel(t *testing.T, id int, disableSleep bool) { t.Helper() ch := &model.Channel{