perf: read and edit request JSON and base64 with moego (#8148)

* perf: read and edit request JSON and base64 with moego

Switch gjson/sjson to moego/ojson and base64 on media, file and plugin
paths to moego/base64. Both keep the same results on valid input.

- Param overrides apply every edit to one ojson.Doc and write the body
  once, instead of copying the whole body for each edit.
- The video proxy and the audio check validate base64 without decoding
  it; plugin icons and inlined plugin files build data URLs directly.
- Login, password, OAuth and signature code keeps gjson and
  encoding/base64.

* perf: rewrite request fields without re-encoding the whole body

Removing disabled fields, the Responses WebSocket create event, AWS Mantle
and pass-through bodies, the OpenAI usage patch, alpha search, video result
redaction and image SSE events now edit the body with ojson.Doc instead of
decoding it into a map and encoding it again. Everything the gateway does
not touch keeps the client's member order, number spelling and characters.

- A key the client repeats is removed or rewritten in every copy, so an
  upstream that reads the last copy sees the same value the gateway routed
  and billed. A key that appears once is rewritten in place.
- Image responses and the video proxy read large values without copying
  them.

* perf: keep member order in param override merges and prune_objects

Merging an object (append/prepend) now replaces existing members where
they stand and appends new members, sorted by key, at the end. prune_objects
deletes the matching objects from the body in place instead of encoding
the pruned part, or the whole body, again. Everything else keeps the
client's member order, number spelling and characters.
This commit is contained in:
Calcium-Ion authored and GitHub committed 2026-11-01 21:56:17 +08:00
1 parent d0abbf6e0d
commit 70e6af6429
63 files changed
+805 -644

No files matched your search

+1 -1
View File
@@ -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 |
+5 -5
View File
@@ -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)
})
}
-2
View File
@@ -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",
+6 -6
View File
@@ -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 == "" {
+13 -11
View File
@@ -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
}
}
+2 -1
View File
@@ -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
)
+2
View File
@@ -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=
+6 -6
View File
@@ -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
+3 -3
View File
@@ -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 {
+2 -2
View File
@@ -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
}
+1 -1
View File
@@ -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) |
+2 -2
View File
@@ -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
}
+2 -1
View File
@@ -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
+1 -1
View File
@@ -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"
)
+2 -2
View File
@@ -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)
}
+7 -5
View File
@@ -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
}
+21
View File
@@ -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
+2 -2
View File
@@ -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)
+5 -5
View File
@@ -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
+4 -4
View File
@@ -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
+15 -12
View File
@@ -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)
+12 -7
View File
@@ -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)
}
+15
View File
@@ -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()
@@ -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) {
+4 -4
View File
@@ -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") {
+3 -3
View File
@@ -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 {
+1 -1
View File
@@ -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"
@@ -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)
}
+2 -2
View File
@@ -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)
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -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)
+6 -4
View File
@@ -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)
+20 -28
View File
@@ -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)
}
+3 -4
View File
@@ -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
}
+4 -4
View File
@@ -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
+3 -4
View File
@@ -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) {
+1 -1
View File
@@ -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"
+4 -4
View File
@@ -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
+2 -2
View File
@@ -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
}
+247 -265
View File
File diff suppressed because it is too large. Load diff
+78
View File
@@ -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":"<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":"<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":"<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":"<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{}
+93 -70
View File
@@ -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
}
@@ -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))
}
+2 -2
View File
@@ -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)
+3 -3
View File
@@ -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 {
+4 -4
View File
@@ -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())
}
+2 -2
View File
@@ -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) {
+37 -32
View File
@@ -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) {
+17
View File
@@ -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",
+35 -35
View File
@@ -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()
+1 -4
View File
@@ -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
+2 -9
View File
@@ -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=
@@ -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
}
@@ -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"
)
@@ -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())
})
@@ -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])
}
@@ -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
}
}
+4 -3
View File
@@ -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)
}
+3 -3
View File
@@ -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)
+1 -1
View File
@@ -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"
+1 -1
View File
@@ -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"
+22 -23
View File
@@ -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 {
+6
View File
@@ -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{