diff --git a/README.md b/README.md index 86a086f..b48be38 100644 --- a/README.md +++ b/README.md @@ -687,7 +687,7 @@ In addition to the standard OpenAI fields (`temperature`, `top_p`, `max_tokens`, |---|---|---| | `kv_bits` | `int` (4 or 8) | Enable **MLX-native quantized KV cache** for this request. Uses `QuantizedKVCache` (standard group quantization) instead of `KVCacheSimple`. Separate from `--turbo-kv`. Reduces KV memory ~2–4× at mild quality cost. | | `enable_thinking` | `bool` | Force-enable or disable chain-of-thought thinking blocks for Gemma-4 / Qwen3. | -| `chat_template_kwargs` | `object` | Passed to the chat template as sent, any JSON value: `{"thinking": true}` for DeepSeek V3.1, `{"reasoning_effort": "high"}` for gpt-oss. An `enable_thinking` inside it is overridden by the top-level field above. | +| `chat_template_kwargs` | `object` | Passed to the chat template as sent, any JSON value: `{"thinking": true}` for DeepSeek V3.1, `{"reasoning_effort": "high"}` for gpt-oss. An `enable_thinking` inside it has to be a boolean, anything else is a 400 even when the top-level field is set; a valid one is overridden by the top-level field above. `messages`, `tools` and `add_generation_prompt` are set by the server and are a 400 here. A `null` inside a list keeps its place, a `null` object value is dropped. | | `kv_group_size` | `int` | Group size for `kv_bits` quantization (default: `64`). | | `top_k` | `int` | Per-request top-k sampling override (0 = disabled). | | `min_p` | `float` | Per-request min-p sampling threshold (0 = disabled). | diff --git a/Sources/SwiftLM/Server.swift b/Sources/SwiftLM/Server.swift index 9acedd9..e9b88c8 100644 --- a/Sources/SwiftLM/Server.swift +++ b/Sources/SwiftLM/Server.swift @@ -241,8 +241,9 @@ private struct TransformersTokenizerBridge: MLXLMCommon.Tokenizer, Sendable { // Issue #168: JSON `null` in tool schemas decodes to NSNull via AnyCodable. // swift-jinja's Value.init(any:) has no NSNull case, so a single null anywhere // in a tool spec aborted the whole render with a misleading "Optional" - // conversion error that was then mislabeled as a broken template. Strip nulls - // (and unwrap nested optionals) before handing anything to the template engine. + // conversion error that was then mislabeled as a broken template. Take the + // NSNulls out (and unwrap nested optionals) before handing anything to the + // template engine; `sanitizeForJinja` says what happens to each kind of null. return try upstream.applyChatTemplate( messages: messages.map { $0.mapValuesDeep(sanitizeForJinja) }, tools: tools?.map { $0.mapValuesDeep(sanitizeForJinja) }, @@ -259,8 +260,6 @@ private struct TransformersTokenizerBridge: MLXLMCommon.Tokenizer, Sendable { } } -/// Returns `nil` when the value must be dropped (JSON `null` / NSNull), otherwise a -/// structure with every nested null removed. See `TransformersTokenizerBridge.applyChatTemplate`. /// True when a VLM load failed because the checkpoint doesn't match the VLM code: /// its config doesn't decode, its weights don't line up with the module tree, or the /// factory doesn't know the model/processor type. Only these justify retrying an @@ -288,6 +287,17 @@ enum TurboKVNotice { nonisolated(unsafe) static var warnedNoLayers = false } +/// What a JSON `null` inside an array is handed to the template as: a real `nil`, which +/// swift-jinja reads as `none`. `NSNull` itself is a type it cannot convert. +let jinjaNone: any Sendable = Optional.none as any Sendable + +/// Makes a decoded JSON value safe for the chat template engine. A JSON `null` decodes to +/// `NSNull`, which swift-jinja cannot convert (#168), so nulls are dealt with here: +/// - a dictionary entry whose value is null is dropped, the template sees a missing key; +/// - an array element that is null stays where it is and reaches the template as `none`. +/// Dropping it would move every later element up by one (#264). +/// Returns `nil` only when the value itself is null. See +/// `TransformersTokenizerBridge.applyChatTemplate`. func sanitizeForJinja(_ value: any Sendable) -> (any Sendable)? { if value is NSNull { return nil } let mirror = Mirror(reflecting: value) @@ -305,7 +315,7 @@ func sanitizeForJinja(_ value: any Sendable) -> (any Sendable)? { return out } if let arr = value as? [Any] { - return arr.compactMap { sanitizeForJinja($0 as any Sendable) } + return arr.map { sanitizeForJinja($0 as any Sendable) ?? jinjaNone } } return value } @@ -2548,6 +2558,16 @@ func handleChatCompletion( ) } + // ── chat_template_kwargs cannot replace what the server hands the template itself ── + if let name = reservedTemplateKwarg(in: chatReq.chatTemplateKwargs) { + let errBody = "{\"error\":{\"message\":\"'chat_template_kwargs.\(name)' is set by the server and cannot be overridden.\",\"type\":\"invalid_request_error\",\"param\":\"chat_template_kwargs.\(name)\"}}" + return Response( + status: .badRequest, + headers: jsonHeaders(), + body: .init(byteBuffer: ByteBuffer(string: errBody)) + ) + } + // ── chat_template_kwargs is free-form JSON, but enable_thinking stays a boolean ── // It decides the precedence below, so a string or a number there is a client error, // answered the way the whole field used to be answered before it took other types. @@ -4506,13 +4526,24 @@ func resolveThinking(topLevel: Bool?, kwarg: Bool?, serverFlag: Bool) -> Bool { /// value the request's precedence rules decided (top-level field, then the kwarg, then the /// server flag). Templates read their own names here (`thinking`, `reasoning_effort`, /// `model_identity`, …), so nothing but that one key is interpreted by the server. -/// Nulls inside the values are stripped later by `sanitizeForJinja`, as for tools. +/// Nulls inside the values are handled later by `sanitizeForJinja`, as for tools. func chatTemplateContext(kwargs: [String: AnyCodable]?, enableThinking: Bool) -> [String: any Sendable] { var context = AnyCodable.toSendable(kwargs) ?? [:] context["enable_thinking"] = enableThinking return context } +/// The names the tokenizer fills in itself when it renders a chat template. Kwargs are +/// merged into the template context after them, so a `chat_template_kwargs` entry with one +/// of these names would replace the conversation, the tool list or the generation prompt +/// flag the server built for the request (#264). +let reservedTemplateKwargs: Set = ["messages", "tools", "add_generation_prompt"] + +/// The first reserved name a request's `chat_template_kwargs` uses, if any. +func reservedTemplateKwarg(in kwargs: [String: AnyCodable]?) -> String? { + kwargs?.keys.sorted().first { reservedTemplateKwargs.contains($0) } +} + /// The sampler seed for a request `seed`. OpenAI's `seed` is a plain integer, so negative /// values do arrive, and `UInt64(seed)` trapped on them — one such request took the whole /// server down (#219). Taking the bit pattern keeps every distinct Int a distinct seed. diff --git a/docs/api-response-formats.md b/docs/api-response-formats.md index 492c79a..c059b3e 100644 --- a/docs/api-response-formats.md +++ b/docs/api-response-formats.md @@ -186,7 +186,7 @@ for await (const chunk of stream) { | `tools` | array | none | Tool/function definitions | | `tool_choice` | string or object | `auto` | `none` keeps the model from calling tools, `{"type": "function", "function": {"name": "..."}}` offers only that function. `required` is accepted but handled like `auto` | | `enable_thinking` | bool | false | Enable `` reasoning tokens | -| `chat_template_kwargs` | object | none | Passed to the chat template as sent (e.g. `{"thinking": true}`, `{"reasoning_effort": "high"}`) | +| `chat_template_kwargs` | object | none | Passed to the chat template as sent (e.g. `{"thinking": true}`, `{"reasoning_effort": "high"}`). 400 for a non-boolean `enable_thinking` and for the names the server sets itself (`messages`, `tools`, `add_generation_prompt`). A `null` inside a list keeps its place, a `null` object value is dropped | --- diff --git a/tests/SwiftLMTests/ChatRequestParsingTests.swift b/tests/SwiftLMTests/ChatRequestParsingTests.swift index b7eed6c..b6f8e95 100644 --- a/tests/SwiftLMTests/ChatRequestParsingTests.swift +++ b/tests/SwiftLMTests/ChatRequestParsingTests.swift @@ -380,4 +380,48 @@ final class ChatRequestParsingTests: XCTestCase { XCTAssertEqual(context["enable_thinking"] as? Bool, true) XCTAssertEqual(context.count, 1) } + + // MARK: - chat_template_kwargs cannot replace the tokenizer's own variables (#264) + + /// Kwargs are merged into the template context after `messages`, `tools` and + /// `add_generation_prompt`, so a kwarg with one of those names replaced the value the + /// server built. The handler answers such a request with a 400 that names the key. + func testReservedTemplateKwargIsFound() throws { + for name in ["messages", "tools", "add_generation_prompt"] { + let req = try decode(""" + { + "messages": [{"role": "user", "content": "hi"}], + "chat_template_kwargs": {"reasoning_effort": "low", "\(name)": []} + } + """) + XCTAssertEqual(reservedTemplateKwarg(in: req.chatTemplateKwargs), name) + } + } + + func testOrdinaryTemplateKwargsAreNotReserved() throws { + let req = try decode(""" + { + "messages": [{"role": "user", "content": "hi"}], + "chat_template_kwargs": { + "enable_thinking": false, "thinking": true, "reasoning_effort": "high", + "message": "x", "tool": "y", "Messages": [], "bos_token": "" + } + } + """) + XCTAssertNil(reservedTemplateKwarg(in: req.chatTemplateKwargs)) + XCTAssertNil(reservedTemplateKwarg(in: nil)) + XCTAssertNil(reservedTemplateKwarg(in: [:])) + } + + /// With more than one reserved name the first in alphabetical order is reported, so the + /// error does not change with dictionary order from one run to the next. + func testReservedTemplateKwargIsStableWhenSeveralAreSent() throws { + let req = try decode(""" + { + "messages": [{"role": "user", "content": "hi"}], + "chat_template_kwargs": {"tools": [], "messages": [], "add_generation_prompt": false} + } + """) + XCTAssertEqual(reservedTemplateKwarg(in: req.chatTemplateKwargs), "add_generation_prompt") + } } diff --git a/tests/SwiftLMTests/JinjaSanitizerTests.swift b/tests/SwiftLMTests/JinjaSanitizerTests.swift index 3fe38ca..4938faa 100644 --- a/tests/SwiftLMTests/JinjaSanitizerTests.swift +++ b/tests/SwiftLMTests/JinjaSanitizerTests.swift @@ -1,5 +1,6 @@ import XCTest import Foundation +import Jinja @testable import SwiftLM /// Issue #168: JSON `null` (NSNull) in tool schemas used to abort Jinja.Value conversion @@ -38,14 +39,74 @@ final class JinjaSanitizerTests: XCTestCase { XCTAssertEqual(params["type"] as? String, "object") } - func testDropsNullArrayElements() throws { + // MARK: - A null inside an array keeps its place (#264) + + /// The array went through `compactMap`, so `[1, null, 2]` came out as `[1, 2]` and a + /// template reading by index got the value one position over. + func testKeepsNullArrayElementsInPlace() throws { let value: [String: any Sendable] = [ "enum": [1, NSNull(), 2] as [any Sendable] ] let cleaned = try XCTUnwrap(sanitizeForJinja(value) as? [String: any Sendable]) let enumValues = try XCTUnwrap(cleaned["enum"] as? [Any]) - XCTAssertEqual(enumValues.count, 2) - XCTAssertFalse(enumValues.contains { $0 is NSNull }) + guard enumValues.count == 3 else { + return XCTFail("expected 3 elements, got \(enumValues.count)") + } + XCTAssertEqual(enumValues[0] as? Int, 1) + XCTAssertNil(sanitizeForJinja(enumValues[1] as any Sendable), "the middle element is a plain nil") + XCTAssertEqual(enumValues[2] as? Int, 2) + XCTAssertFalse(enumValues.contains { $0 is NSNull }, "NSNull itself must never reach swift-jinja") + } + + func testNullsNestedInsideAnArrayFollowTheSameRules() throws { + let value: [any Sendable] = [ + ["keep": 1, "drop": NSNull()] as [String: any Sendable], + NSNull(), + [NSNull(), "x"] as [any Sendable], + ] + let cleaned = try XCTUnwrap(sanitizeForJinja(value) as? [Any]) + guard cleaned.count == 3 else { + return XCTFail("expected 3 elements, got \(cleaned.count)") + } + let object = try XCTUnwrap(cleaned[0] as? [String: any Sendable]) + XCTAssertEqual(object["keep"] as? Int, 1) + XCTAssertNil(object["drop"], "a null dictionary entry is still dropped") + let inner = try XCTUnwrap(cleaned[2] as? [Any]) + XCTAssertEqual(inner.count, 2) + XCTAssertEqual(inner[1] as? String, "x") + } + + /// The same conversion swift-transformers does before it renders (`Value(any:)`), on a + /// `chat_template_kwargs` list: the template sees three elements with `none` in the middle. + func testTemplateReadsTheNullElementAsNone() throws { + let kwargs: [String: any Sendable] = ["ids": [1, NSNull(), 2] as [any Sendable]] + let context = try kwargs.mapValuesDeep(sanitizeForJinja).mapValues { try Value(any: $0) } + let template = try Template("{{ ids | length }} {{ ids[2] }} {{ ids[1] is none }}") + XCTAssertEqual(try template.render(context), "3 2 true") + } + + /// Tool schemas take the same path. A nullable enum keeps its `null` option in the JSON + /// the model is shown. + func testToolSchemaEnumKeepsItsNullOption() throws { + let tool: [String: any Sendable] = [ + "name": "set_unit", + "parameters": [ + "unit": ["enum": ["c", NSNull(), "f"] as [any Sendable]] as [String: any Sendable] + ] as [String: any Sendable], + ] + let context = ["tool": try Value(any: tool.mapValuesDeep(sanitizeForJinja))] + let template = try Template("{{ tool.parameters.unit.enum | tojson }}") + XCTAssertEqual( + try template.render(context).replacingOccurrences(of: " ", with: ""), #"["c",null,"f"]"#) + } + + func testSanitizingTwiceGivesTheSameResult() throws { + let value: [any Sendable] = [1, NSNull(), ["a": NSNull(), "b": [NSNull()] as [any Sendable]] as [String: any Sendable]] + let once = try XCTUnwrap(sanitizeForJinja(value)) + let twice = try XCTUnwrap(sanitizeForJinja(once)) + XCTAssertEqual(try Value(any: once), try Value(any: twice)) + XCTAssertEqual(try Template("{{ v | tojson }}").render(["v": try Value(any: twice)]) + .replacingOccurrences(of: " ", with: ""), #"[1,null,{"b":[null]}]"#) } func testPreservesScalarsAndStructure() throws { diff --git a/tests/test-contract.sh b/tests/test-contract.sh index cfa7c31..06abd1a 100755 --- a/tests/test-contract.sh +++ b/tests/test-contract.sh @@ -633,6 +633,37 @@ expect_thinking false "top-level false over kwarg true" ',"enable_thinking":fals expect_thinking true "top-level true over kwarg false" ',"enable_thinking":true,"chat_template_kwargs":{"enable_thinking":false}' expect_thinking false "kwarg false over --thinking" ',"chat_template_kwargs":{"enable_thinking":false}' +# ── 20. chat_template_kwargs: reserved names, and nulls inside arrays ──────── +# #264: kwargs are merged into the template context after `messages`, `tools` and +# `add_generation_prompt`, so a kwarg with one of those names replaced what the server had +# built for the request. And a null inside an array was dropped on the way to the template, +# which moved the later elements up by one. The CI model's template prints tools as JSON, +# so the second half reads the prompt size of a tool whose enum has a null in it. +log "Test 20: a chat_template_kwargs name the server sets itself is a 400 that names it" +for NAME in messages tools add_generation_prompt; do + CODE=$(curl -s -o /tmp/SwiftLM-contract-reserved.json -w '%{http_code}' "$URL/v1/chat/completions" \ + -H 'Content-Type: application/json' -d "{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":4,\"chat_template_kwargs\":{\"$NAME\":[]}}") + ERR_TYPE=$(python3 -c 'import json; e=json.load(open("/tmp/SwiftLM-contract-reserved.json"))["error"]; print(e.get("type"), e.get("param"))' 2>/dev/null || echo "unparseable") + if [ "$CODE" = "400" ] && [ "$ERR_TYPE" = "invalid_request_error chat_template_kwargs.$NAME" ]; then + pass "400 invalid_request_error naming param 'chat_template_kwargs.$NAME'" + else + fail "got HTTP $CODE with error '$ERR_TYPE' for $NAME (expected 400 invalid_request_error chat_template_kwargs.$NAME)" + fi +done + +log "Test 20b: a null inside an array reaches the template in place" +enum_prompt() { + chat "{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"Say hi.\"}],\"max_tokens\":4,\"temperature\":0,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"set_unit\",\"description\":\"Set the unit\",\"parameters\":{\"type\":\"object\",\"properties\":{\"unit\":{\"enum\":$1}}}}}]}" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["usage"]["prompt_tokens"])' 2>/dev/null || echo 0 +} +P_TWO=$(enum_prompt '["c","f"]') +P_NULL=$(enum_prompt '["c",null,"f"]') +if [ "$P_TWO" -gt 0 ] && [ "$P_NULL" -gt "$P_TWO" ]; then + pass "the enum keeps its null ($P_NULL prompt tokens, $P_TWO without it)" +else + fail "an enum with a null in it is $P_NULL prompt tokens (expected more than $P_TWO, the same enum without the null)" +fi + log "═══════════════════════════════════════" log "Results: $PASS passed, $FAIL failed, $SKIP skipped, $TOTAL total" log "═══════════════════════════════════════"