You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by ni...@apache.org on 2026/04/18 01:43:47 UTC

(apisix) branch master updated: fix: add null_as_nil option to core.json.decode for AI plugins (#13231)

This is an automated email from the ASF dual-hosted git repository.

nic-6443 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new 4223a07e7 fix: add null_as_nil option to core.json.decode for AI plugins (#13231)
4223a07e7 is described below

commit 4223a07e7049f6f15e4f8d868d31f72aab9239c3
Author: Nic <qi...@api7.ai>
AuthorDate: Sat Apr 18 09:43:41 2026 +0800

    fix: add null_as_nil option to core.json.decode for AI plugins (#13231)
---
 apisix/core/json.lua                               |  37 +++-
 apisix/plugins/ai-protocols/anthropic-messages.lua |   8 +-
 apisix/plugins/ai-protocols/openai-chat.lua        |   2 +-
 apisix/plugins/ai-protocols/openai-responses.lua   |   4 +-
 apisix/plugins/ai-providers/base.lua               |   2 +-
 t/core/json.t                                      |  42 +++++
 t/plugin/ai-proxy-anthropic.t                      | 197 ++++++++++++++++++++-
 7 files changed, 282 insertions(+), 10 deletions(-)

diff --git a/apisix/core/json.lua b/apisix/core/json.lua
index 4341c4682..397b80191 100644
--- a/apisix/core/json.lua
+++ b/apisix/core/json.lua
@@ -21,6 +21,8 @@
 
 local cjson = require("cjson.safe")
 local json_encode = cjson.encode
+local json_decode = cjson.decode
+local cjson_null = cjson.null
 local clear_tab = require("table.clear")
 local ngx = ngx
 local tostring = tostring
@@ -34,7 +36,7 @@ cjson.decode_array_with_array_mt(true)
 local _M = {
     version = 0.1,
     array_mt = cjson.array_mt,
-    decode = cjson.decode,
+    null = cjson_null,
     -- This method produces the same encoded string when the input is not changed.
     -- Different calls with cjson.encode will produce different string because
     -- it doesn't maintain the object key order.
@@ -42,6 +44,39 @@ local _M = {
 }
 
 
+local function strip_nulls(t)
+    for k, v in pairs(t) do
+        if v == cjson_null then
+            t[k] = nil
+        elseif type(v) == "table" then
+            strip_nulls(v)
+        end
+    end
+    return t
+end
+_M.strip_nulls = strip_nulls
+
+
+--- Decode a JSON string.
+-- @tparam string str The JSON string to decode.
+-- @tparam[opt] table opts Options table.
+--   null_as_nil: if true, recursively replace cjson.null with nil.
+-- @return The decoded Lua value, or nil on error.
+-- @return Error string on failure.
+function _M.decode(str, opts)
+    local obj, err = json_decode(str)
+    if obj and opts and opts.null_as_nil then
+        if obj == cjson_null then
+            return nil, err
+        end
+        if type(obj) == "table" then
+            strip_nulls(obj)
+        end
+    end
+    return obj, err
+end
+
+
 local function serialise_obj(data)
     if type(data) == "function" or type(data) == "userdata"
        or type(data) == "cdata"
diff --git a/apisix/plugins/ai-protocols/anthropic-messages.lua b/apisix/plugins/ai-protocols/anthropic-messages.lua
index 8e5ccbe46..a78d0c26e 100644
--- a/apisix/plugins/ai-protocols/anthropic-messages.lua
+++ b/apisix/plugins/ai-protocols/anthropic-messages.lua
@@ -52,7 +52,7 @@ end
 -- Used when the provider natively supports Anthropic protocol.
 function _M.parse_sse_event(event, ctx, state)
     if event.type == "content_block_delta" then
-        local data, err = core.json.decode(event.data)
+        local data, err = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             core.log.warn("failed to decode SSE data: ", err)
             return { type = "skip" }
@@ -67,7 +67,7 @@ function _M.parse_sse_event(event, ctx, state)
         return { type = "skip" }
 
     elseif event.type == "message_delta" then
-        local data, err = core.json.decode(event.data)
+        local data, err = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             core.log.warn("failed to decode message_delta: ", err)
             return { type = "skip" }
@@ -90,7 +90,7 @@ function _M.parse_sse_event(event, ctx, state)
         return { type = "done" }
 
     elseif event.type == "message_start" then
-        local data = core.json.decode(event.data)
+        local data = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             return { type = "skip" }
         end
@@ -109,7 +109,7 @@ function _M.parse_sse_event(event, ctx, state)
         return { type = "skip" }
 
     elseif event.type == "error" then
-        local err_data = core.json.decode(event.data)
+        local err_data = core.json.decode(event.data, { null_as_nil = true })
         local err_type = err_data and err_data.error and err_data.error.type or "unknown"
         local err_msg = err_data and err_data.error and err_data.error.message or "unknown"
         core.log.warn("Anthropic SSE error: type=", err_type, ", message=", err_msg)
diff --git a/apisix/plugins/ai-protocols/openai-chat.lua b/apisix/plugins/ai-protocols/openai-chat.lua
index 1875b4908..da9191736 100644
--- a/apisix/plugins/ai-protocols/openai-chat.lua
+++ b/apisix/plugins/ai-protocols/openai-chat.lua
@@ -69,7 +69,7 @@ function _M.parse_sse_event(event, ctx, state)
             return { type = "done" }
         end
 
-        local data, err = core.json.decode(event.data)
+        local data, err = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             core.log.warn("failed to decode SSE data: ", err)
             return { type = "skip" }
diff --git a/apisix/plugins/ai-protocols/openai-responses.lua b/apisix/plugins/ai-protocols/openai-responses.lua
index 2c2165d00..9e05e99a7 100644
--- a/apisix/plugins/ai-protocols/openai-responses.lua
+++ b/apisix/plugins/ai-protocols/openai-responses.lua
@@ -48,7 +48,7 @@ end
 
 function _M.parse_sse_event(event, ctx, state)
     if event.type == "response.output_text.delta" then
-        local data, err = core.json.decode(event.data)
+        local data, err = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             core.log.warn("failed to decode SSE data: ", err)
             return { type = "skip" }
@@ -63,7 +63,7 @@ function _M.parse_sse_event(event, ctx, state)
 
     elseif event.type == "response.completed" then
         local result = { type = "done" }
-        local data, err = core.json.decode(event.data)
+        local data, err = core.json.decode(event.data, { null_as_nil = true })
         if not data then
             core.log.warn("failed to decode response.completed SSE data: ", err)
             return result
diff --git a/apisix/plugins/ai-providers/base.lua b/apisix/plugins/ai-providers/base.lua
index b037924ee..db07dff70 100644
--- a/apisix/plugins/ai-providers/base.lua
+++ b/apisix/plugins/ai-providers/base.lua
@@ -209,7 +209,7 @@ function _M.parse_response(self, ctx, res, client_proto, converter)
     ctx.var.llm_time_to_first_token = math.floor((ngx_now() - ctx.llm_request_start_time) * 1000)
     ctx.var.apisix_upstream_response_time = ctx.var.llm_time_to_first_token
 
-    local res_body, decode_err = core.json.decode(raw_res_body)
+    local res_body, decode_err = core.json.decode(raw_res_body, { null_as_nil = true })
     if decode_err then
         core.log.warn("failed to decode response from ai service, err: ", decode_err,
             ", it will cause token usage not available")
diff --git a/t/core/json.t b/t/core/json.t
index e946bc64a..1409f54f1 100644
--- a/t/core/json.t
+++ b/t/core/json.t
@@ -151,3 +151,45 @@ qr/\{"b":\{"a":\{"b":"table: 0x[\w]+"\}\}\}/
 --- response_body
 encode: {"test":"/test"}
 data: /test
+
+
+
+=== TEST 8: decode with null_as_nil option
+--- config
+    location /t {
+        content_by_lua_block {
+            local core = require("apisix.core")
+
+            -- without null_as_nil: cjson.null is preserved
+            local data = core.json.decode('{"a": null, "b": {"c": null, "d": 1}}')
+            ngx.say("without opt, a is nil: ", data.a == nil)
+            ngx.say("without opt, a is null: ", data.a == core.json.null)
+
+            -- with null_as_nil: cjson.null becomes nil
+            local data2 = core.json.decode(
+                '{"a": null, "b": {"c": null, "d": 1}, "e": "text"}',
+                { null_as_nil = true }
+            )
+            ngx.say("a: ", data2.a)
+            ngx.say("b.c: ", data2.b.c)
+            ngx.say("b.d: ", data2.b.d)
+            ngx.say("e: ", data2.e)
+
+            -- verify the or-default pattern works after stripping
+            local val = data2.a or "default"
+            ngx.say("a or default: ", val)
+
+            -- top-level null becomes nil
+            local data3 = core.json.decode('null', { null_as_nil = true })
+            ngx.say("top-level null: ", data3)
+        }
+    }
+--- response_body
+without opt, a is nil: false
+without opt, a is null: true
+a: nil
+b.c: nil
+b.d: 1
+e: text
+a or default: default
+top-level null: nil
diff --git a/t/plugin/ai-proxy-anthropic.t b/t/plugin/ai-proxy-anthropic.t
index a5126b099..3223785b0 100644
--- a/t/plugin/ai-proxy-anthropic.t
+++ b/t/plugin/ai-proxy-anthropic.t
@@ -15,6 +15,10 @@
 # limitations under the License.
 #
 
+BEGIN {
+    $ENV{TEST_ENABLE_CONTROL_API_V1} = "0";
+}
+
 use t::APISIX 'no_plan';
 
 log_level("info");
@@ -42,7 +46,6 @@ add_block_preprocessor(sub {
     my $user_yaml_config = <<_EOC_;
 plugins:
   - ai-proxy-multi
-  - prometheus
 _EOC_
     $block->set_value("extra_yaml_config", $user_yaml_config);
 
@@ -75,6 +78,91 @@ _EOC_
                             ngx.say("model options feature doesn't work")
                         end
                         return
+                    elseif test_type == "null-details" then
+                        ngx.status = 200
+                        ngx.say([[{
+                            "id": "chatcmpl-null-test",
+                            "object": "chat.completion",
+                            "model": "test-model",
+                            "choices": [{
+                                "index": 0,
+                                "message": {
+                                    "role": "assistant",
+                                    "content": "Hello!"
+                                },
+                                "finish_reason": "stop"
+                            }],
+                            "usage": {
+                                "prompt_tokens": 10,
+                                "completion_tokens": 5,
+                                "total_tokens": 15,
+                                "prompt_tokens_details": null,
+                                "completion_tokens_details": null
+                            }
+                        }]])
+                        return
+                    elseif test_type == "null-usage" then
+                        ngx.status = 200
+                        ngx.say([[{
+                            "id": "chatcmpl-null-usage",
+                            "object": "chat.completion",
+                            "model": "test-model",
+                            "choices": [{
+                                "index": 0,
+                                "message": {
+                                    "role": "assistant",
+                                    "content": "Hello!"
+                                },
+                                "finish_reason": "stop"
+                            }],
+                            "usage": null
+                        }]])
+                        return
+                    elseif test_type == "null-message" then
+                        ngx.status = 200
+                        ngx.say([[{
+                            "id": "chatcmpl-null-msg",
+                            "object": "chat.completion",
+                            "model": "test-model",
+                            "choices": [{
+                                "index": 0,
+                                "message": null,
+                                "finish_reason": "stop"
+                            }],
+                            "usage": {
+                                "prompt_tokens": 5,
+                                "completion_tokens": 3,
+                                "total_tokens": 8,
+                                "prompt_tokens_details": null
+                            }
+                        }]])
+                        return
+                    elseif test_type == "null-function" then
+                        ngx.status = 200
+                        ngx.say([[{
+                            "id": "chatcmpl-null-fn",
+                            "object": "chat.completion",
+                            "model": "test-model",
+                            "choices": [{
+                                "index": 0,
+                                "message": {
+                                    "role": "assistant",
+                                    "content": null,
+                                    "tool_calls": [{
+                                        "id": "call_1",
+                                        "type": "function",
+                                        "function": null
+                                    }]
+                                },
+                                "finish_reason": "tool_calls"
+                            }],
+                            "usage": {
+                                "prompt_tokens": 5,
+                                "completion_tokens": 3,
+                                "total_tokens": 8
+                            }
+                        }]])
+                        return
                     end
 
                     local header_auth = ngx.req.get_headers()["authorization"]
@@ -295,3 +383,110 @@ passed
     }
 --- response_body_like eval
 qr/6data: \[DONE\]\n\n/
+
+
+
+=== TEST 5: set route for Anthropic null-field tests
+--- config
+    location /t {
+        content_by_lua_block {
+            local t = require("lib.test_admin").test
+            local code, body = t('/apisix/admin/routes/1',
+                 ngx.HTTP_PUT,
+                 [[{
+                    "uri": "/v1/messages",
+                    "plugins": {
+                        "ai-proxy-multi": {
+                            "instances": [
+                                {
+                                    "name": "openai-compat",
+                                    "provider": "openai-compatible",
+                                    "weight": 1,
+                                    "auth": {
+                                        "header": {
+                                            "Authorization": "Bearer token"
+                                        }
+                                    },
+                                    "options": {
+                                        "model": "test-model"
+                                    },
+                                    "override": {
+                                        "endpoint": "http://localhost:6724"
+                                    }
+                                }
+                            ],
+                            "ssl_verify": false
+                        }
+                    }
+                }]]
+            )
+
+            if code >= 300 then
+                ngx.status = code
+            end
+            ngx.say(body)
+        }
+    }
+--- response_body
+passed
+
+
+
+=== TEST 6: Anthropic conversion handles null prompt_tokens_details
+Test that cjson.null (from JSON null) does not crash the converter.
+--- request
+POST /v1/messages
+{"model":"test-model","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}
+--- more_headers
+Content-Type: application/json
+test-type: null-details
+--- error_code: 200
+--- response_body_like eval
+qr/"input_tokens":10.*"output_tokens":5/
+--- no_error_log
+[error]
+
+
+
+=== TEST 7: Anthropic conversion handles null usage object
+--- request
+POST /v1/messages
+{"model":"test-model","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}
+--- more_headers
+Content-Type: application/json
+test-type: null-usage
+--- error_code: 200
+--- response_body_like eval
+qr/"input_tokens":0/
+--- no_error_log
+[error]
+
+
+
+=== TEST 8: Anthropic conversion handles null message fields
+--- request
+POST /v1/messages
+{"model":"test-model","max_tokens":100,"messages":[{"role":"user","content":"test"}]}
+--- more_headers
+Content-Type: application/json
+test-type: null-message
+--- error_code: 200
+--- response_body_like eval
+qr/"type":"text"/
+--- no_error_log
+[error]
+
+
+
+=== TEST 9: Anthropic conversion handles null function in tool_calls
+--- request
+POST /v1/messages
+{"model":"test-model","max_tokens":100,"messages":[{"role":"user","content":"call tool"}]}
+--- more_headers
+Content-Type: application/json
+test-type: null-function
+--- error_code: 200
+--- response_body_like eval
+qr/"type":"tool_use"/
+--- no_error_log
+[error]