diff --git a/Sources/SwiftLM/Server.swift b/Sources/SwiftLM/Server.swift index 1ac8a85..6b49919 100644 --- a/Sources/SwiftLM/Server.swift +++ b/Sources/SwiftLM/Server.swift @@ -2604,8 +2604,20 @@ func handleChatCompletion( systemPromptText = "JSON_MODE:" + systemPromptText } + // `tool_choice` decides which of the request's tools the model gets to see. + let offeredTools: [ChatCompletionRequest.ToolDef]? + do { + offeredTools = try chatReq.offeredTools() + } catch let error as DecodingError { + return invalidRequestResponse(error) + } + if chatReq.toolChoice == .required { + // Nothing here can force a call yet. Say so in the log instead of staying silent. + print("[SwiftLM] tool_choice \"required\" is not enforced, handling it as \"auto\"") + } + // Convert OpenAI tools format → [String: any Sendable] for UserInput - let toolSpecs: [[String: any Sendable]]? = chatReq.tools?.map { tool in + let toolSpecs: [[String: any Sendable]]? = offeredTools?.map { tool in var spec: [String: any Sendable] = ["type": tool.type] var fn: [String: any Sendable] = ["name": tool.function.name] if let desc = tool.function.description { fn["description"] = desc } @@ -3028,7 +3040,8 @@ func handleChatCompletion( startGeneration: startGeneration, modelId: modelId, stopSequences: stopSequences, includeUsage: includeUsage, promptTokenCount: promptTokenCount, enableThinking: enableThinking, thinkingPreOpened: thinkingPreOpened, - jsonMode: jsonMode, tokenEcho: config.tokenEcho, slot: slot, + jsonMode: jsonMode, tokenEcho: config.tokenEcho, + allowedToolCalls: chatReq.allowedToolCalls, slot: slot, stats: stats, genStart: genStart, prefillStart: prefillStart, emitPrefillProgress: emitPrefillProgress ) @@ -3044,6 +3057,7 @@ func handleChatCompletion( stream: stream, modelId: modelId, stopSequences: stopSequences, promptTokenCount: promptTokenCount, enableThinking: enableThinking, thinkingPreOpened: thinkingPreOpened, jsonMode: jsonMode, tokenEcho: config.tokenEcho, + allowedToolCalls: chatReq.allowedToolCalls, slot: slot, stats: stats, genStart: genStart, prefillStart: prefillStart, onPrefillDone: onPrefillDone ) @@ -3254,6 +3268,7 @@ func handleChatStreaming( thinkingPreOpened: Bool = false, jsonMode: Bool = false, tokenEcho: Bool = true, + allowedToolCalls: Set? = nil, slot: GenerationSlot, stats: ServerStats, genStart: Date, @@ -3496,6 +3511,11 @@ func handleChatStreaming( // If tracker buffer is holding a partial tag, nothing to emit yet — that's fine. } + case .toolCall(let tc) where allowedToolCalls?.contains(tc.function.name) == false: + // `tool_choice` ruled this call out: "none", or another function was named. + // Handled like a rejected call below: logged, not sent. + print("[SwiftLM] Dropped tool call: tool=\(tc.function.name) is not allowed by tool_choice") + case .toolCall(let tc): hasToolCalls = true let argsJson = serializeToolCallArgs(tc.function.arguments) @@ -3641,6 +3661,7 @@ func handleChatNonStreaming( thinkingPreOpened: Bool = false, jsonMode: Bool = false, tokenEcho: Bool = true, + allowedToolCalls: Set? = nil, slot: GenerationSlot, stats: ServerStats, genStart: Date, @@ -3685,6 +3706,9 @@ func handleChatNonStreaming( print(text, terminator: "") fflush(stdout) } + case .toolCall(let tc) where allowedToolCalls?.contains(tc.function.name) == false: + // See the matching comment in `handleChatStreaming`: ruled out by `tool_choice`. + print("[SwiftLM] Dropped tool call: tool=\(tc.function.name) is not allowed by tool_choice") case .toolCall(let tc): let argsJson = serializeToolCallArgs(tc.function.arguments) collectedToolCalls.append(ToolCallResponse( @@ -4985,6 +5009,7 @@ struct ChatCompletionRequest: Decodable { let frequencyPenalty: Double? let presencePenalty: Double? let tools: [ToolDef]? + let toolChoice: ToolChoice? let stop: StopSequences? let seed: Int? let streamOptions: StreamOptions? @@ -5019,6 +5044,81 @@ struct ChatCompletionRequest: Decodable { case enableThinking = "enable_thinking" case thinkingBudget = "thinking_budget" case kvBits = "kv_bits" + case toolChoice = "tool_choice" + } + + /// The tools this request offers the model once `tool_choice` is applied: none of + /// them for "none", only the named one for a function choice, all of them otherwise. + /// A choice that names a function `tools` does not declare is a client error, thrown + /// as the decode error a bad `tool_choice` value gives so both get the same 400. + func offeredTools() throws -> [ToolDef]? { + switch toolChoice { + case .noTools?: + return nil + case .function(let name)?: + guard let tool = tools?.first(where: { $0.function.name == name }) else { + throw DecodingError.dataCorrupted(.init( + codingPath: [CodingKeys.toolChoice], + debugDescription: "Invalid value for 'tool_choice': the function '\(name)' is not in 'tools'.")) + } + return [tool] + case .auto?, .required?, nil: + return tools + } + } + + /// The function names a reply may call, or nil when `tool_choice` does not narrow + /// them. Leaving a tool out of the prompt does not stop a model from calling it, + /// most of all when the history already holds such calls. + var allowedToolCalls: Set? { + switch toolChoice { + case .noTools?: return [] + case .function(let name)?: return [name] + case .auto?, .required?, nil: return nil + } + } +} + +/// OpenAI's `tool_choice`: "none", "auto" or "required", or an object that names one +/// function. The field was not decoded at all, so "none" could still be answered with a +/// tool call and a misspelt value went unnoticed. +enum ToolChoice: Decodable, Equatable { + /// "none": the model answers in text. Not `.none`, which reads as nil on an optional. + case noTools + /// "auto", also what an absent field means: the model decides. + case auto + /// "required": accepted and handled like "auto". Nothing here can force a call yet. + case required + /// `{"type":"function","function":{"name":"get_weather"}}`: only this function. + case function(String) + + private struct Named: Decodable { + struct Function: Decodable { let name: String } + let type: String + let function: Function + } + + init(from decoder: Swift.Decoder) throws { + let container = try decoder.singleValueContainer() + if let mode = try? container.decode(String.self) { + switch mode { + case "none": self = .noTools + case "auto": self = .auto + case "required": self = .required + default: + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Invalid value for 'tool_choice': '\(mode)'. Expected \"none\", \"auto\", \"required\" or a function object.") + } + return + } + let named = try container.decode(Named.self) + guard named.type == "function" else { + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Invalid value for 'tool_choice': the object type '\(named.type)' is not supported, only 'function'.") + } + self = .function(named.function.name) } } diff --git a/docs/api-response-formats.md b/docs/api-response-formats.md index cd08740..492c79a 100644 --- a/docs/api-response-formats.md +++ b/docs/api-response-formats.md @@ -184,6 +184,7 @@ for await (const chunk of stream) { | `stop` | string[] | [] | Stop sequences | | `response_format` | object | none | `{"type": "json_object"}` for JSON mode | | `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"}`) | diff --git a/tests/SwiftLMTests/ToolChoiceTests.swift b/tests/SwiftLMTests/ToolChoiceTests.swift new file mode 100644 index 0000000..43215ca --- /dev/null +++ b/tests/SwiftLMTests/ToolChoiceTests.swift @@ -0,0 +1,232 @@ +import XCTest +import Foundation +import Hummingbird +import HTTPTypes +import MLXLMCommon +import NIOCore +@testable import SwiftLM + +// MARK: - `tool_choice` is read and honoured +// +// The request type had no `tool_choice` field, so the decoder dropped it: "none" still +// put every tool in the prompt and could come back as a tool call, a named function did +// not narrow anything, and a misspelt value was a normal 200. These cover the decoding, +// which tools reach the prompt, the 400s, and what the two chat handlers do with a tool +// call the choice ruled out (synthetic generation stream, no model needed). +final class ToolChoiceTests: XCTestCase { + + private let messages = #"[{"role":"user","content":"hi"}]"# + private let tools = """ + [{"type":"function","function":{"name":"get_weather","parameters":{"type":"object"}}}, + {"type":"function","function":{"name":"get_time"}}] + """ + + private func decode(_ fields: String) throws -> ChatCompletionRequest { + let json = #"{"messages":\#(messages)\#(fields.isEmpty ? "" : ",")\#(fields)}"# + return try JSONDecoder().decode(ChatCompletionRequest.self, from: Data(json.utf8)) + } + + private func errorObject(_ error: Error) throws -> [String: Any] { + let decodingError = try XCTUnwrap(error as? DecodingError) + let top = try XCTUnwrap(JSONSerialization.jsonObject( + with: Data(invalidRequestJSON(decodingError).utf8)) as? [String: Any]) + return try XCTUnwrap(top["error"] as? [String: Any]) + } + + // MARK: Decoding + + func testTheThreeModesDecode() throws { + XCTAssertEqual(try decode(#""tool_choice":"none""#).toolChoice, .noTools) + XCTAssertEqual(try decode(#""tool_choice":"auto""#).toolChoice, .auto) + XCTAssertEqual(try decode(#""tool_choice":"required""#).toolChoice, .required) + } + + func testANamedFunctionDecodes() throws { + let req = try decode(#""tool_choice":{"type":"function","function":{"name":"get_weather"}}"#) + XCTAssertEqual(req.toolChoice, .function("get_weather")) + } + + func testAbsentAndNullAreNil() throws { + XCTAssertNil(try decode("").toolChoice) + XCTAssertNil(try decode(#""tool_choice":null"#).toolChoice) + } + + // MARK: Values the API does not have are a 400 that names the field + + func testAnUnknownModeIsRejected() throws { + XCTAssertThrowsError(try decode(#""tool_choice":"sometimes""#)) { error in + let payload = try? self.errorObject(error) + XCTAssertEqual(payload?["type"] as? String, "invalid_request_error") + XCTAssertEqual(payload?["param"] as? String, "tool_choice") + XCTAssertEqual((payload?["message"] as? String)?.contains("'sometimes'"), true) + } + } + + func testAnObjectThatIsNotAFunctionIsRejected() throws { + XCTAssertThrowsError(try decode(#""tool_choice":{"type":"tool","function":{"name":"x"}}"#)) { error in + XCTAssertEqual((try? self.errorObject(error))?["param"] as? String, "tool_choice") + } + } + + func testOtherTypesAreRejected() { + XCTAssertThrowsError(try decode(#""tool_choice":1"#)) { XCTAssertTrue($0 is DecodingError) } + XCTAssertThrowsError(try decode(#""tool_choice":{"type":"function"}"#)) { + XCTAssertTrue($0 is DecodingError) + } + } + + // MARK: Which tools reach the prompt + + private func offeredNames(_ choice: String?) throws -> [String]? { + let fields = #""tools":\#(tools)"# + (choice.map { #","tool_choice":\#($0)"# } ?? "") + return try decode(fields).offeredTools()?.map(\.function.name) + } + + func testNoneOffersNoTools() throws { + XCTAssertNil(try offeredNames(#""none""#)) + } + + func testANamedFunctionOffersOnlyThatTool() throws { + XCTAssertEqual( + try offeredNames(#"{"type":"function","function":{"name":"get_time"}}"#), ["get_time"]) + } + + func testAutoRequiredAndAbsentOfferEveryTool() throws { + let all = ["get_weather", "get_time"] + XCTAssertEqual(try offeredNames(nil), all) + XCTAssertEqual(try offeredNames(#""auto""#), all) + XCTAssertEqual(try offeredNames(#""required""#), all) + } + + func testAChoiceWithoutToolsChangesNothing() throws { + XCTAssertNil(try decode(#""tool_choice":"none""#).offeredTools()) + XCTAssertNil(try decode(#""tool_choice":"auto""#).offeredTools()) + XCTAssertNil(try decode(#""tool_choice":"required""#).offeredTools()) + } + + func testAFunctionThatToolsDoesNotDeclareIsA400() throws { + let named = #""tool_choice":{"type":"function","function":{"name":"get_stock"}}"# + for fields in [#""tools":\#(tools),\#(named)"#, named] { + XCTAssertThrowsError(try decode(fields).offeredTools()) { error in + let payload = try? self.errorObject(error) + XCTAssertEqual(payload?["type"] as? String, "invalid_request_error") + XCTAssertEqual(payload?["param"] as? String, "tool_choice") + XCTAssertEqual((payload?["message"] as? String)?.contains("'get_stock'"), true) + } + } + } + + // MARK: Which calls a reply may carry + + func testAllowedToolCallsFollowTheChoice() throws { + XCTAssertNil(try decode("").allowedToolCalls) + XCTAssertNil(try decode(#""tool_choice":"auto""#).allowedToolCalls) + XCTAssertNil(try decode(#""tool_choice":"required""#).allowedToolCalls) + XCTAssertEqual(try decode(#""tool_choice":"none""#).allowedToolCalls, []) + XCTAssertEqual( + try decode(#""tool_choice":{"type":"function","function":{"name":"get_time"}}"#) + .allowedToolCalls, + ["get_time"]) + } + + // MARK: A call the choice ruled out is not sent + + private final class BodySink: @unchecked Sendable { + var data = Data() + } + + private struct CollectingWriter: ResponseBodyWriter { + let sink: BodySink + mutating func write(_ buffer: ByteBuffer) async throws { + sink.data.append(contentsOf: buffer.readableBytesView) + } + consuming func finish(_ trailingHeaders: HTTPFields?) async throws {} + } + + /// A model that calls `get_weather` although it was told not to, then stops. + private func weatherCallStream() -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream() + continuation.yield(.toolCall(ToolCall(function: .init(name: "get_weather", arguments: ["city": "Paris"])))) + continuation.yield(.info(GenerateCompletionInfo( + promptTokenCount: 3, generationTokenCount: 12, + promptTime: 0, generationTime: 0, stopReason: .stop))) + continuation.finish() + return stream + } + + private func acquiredSlot() async -> GenerationSlot { + let semaphore = AsyncSemaphore(limit: 1) + await semaphore.wait() + return GenerationSlot(semaphore: semaphore) + } + + /// The tool calls and the finish reason of a non-streaming reply. + private func nonStreaming(allowed: Set?) async throws -> (toolCalls: Int, finishReason: String?) { + let slot = await acquiredSlot() + let response = try await handleChatNonStreaming( + stream: weatherCallStream(), modelId: "test-model", stopSequences: [], + promptTokenCount: 3, tokenEcho: false, allowedToolCalls: allowed, slot: slot, + stats: ServerStats(), genStart: Date(), prefillStart: Date()) + let sink = BodySink() + try await response.body.write(CollectingWriter(sink: sink)) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sink.data) as? [String: Any]) + let choice = try XCTUnwrap((json["choices"] as? [[String: Any]])?.first) + let message = try XCTUnwrap(choice["message"] as? [String: Any]) + let toolCalls = (message["tool_calls"] as? [[String: Any]]) ?? [] + return (toolCalls.count, choice["finish_reason"] as? String) + } + + /// Same for a streamed reply; the body is drained so the consumer runs to the end. + private func streaming(allowed: Set?) async throws -> (toolCalls: Int, finishReason: String?) { + let stream = weatherCallStream() + let slot = await acquiredSlot() + let response = handleChatStreaming( + startGeneration: { (stream, nil) }, modelId: "test-model", stopSequences: [], + includeUsage: false, promptTokenCount: 3, tokenEcho: false, + allowedToolCalls: allowed, slot: slot, stats: ServerStats(), genStart: Date(), + prefillStart: Date(), emitPrefillProgress: false) + let sink = BodySink() + try await response.body.write(CollectingWriter(sink: sink)) + var toolCalls = 0 + var finishReason: String? + for raw in String(decoding: sink.data, as: UTF8.self).components(separatedBy: "\n") { + let line = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard line.hasPrefix("data: {") else { continue } + let event = try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(line.dropFirst(6).utf8)) as? [String: Any]) + guard let choice = (event["choices"] as? [[String: Any]])?.first else { continue } + if let calls = (choice["delta"] as? [String: Any])?["tool_calls"] as? [[String: Any]] { + toolCalls += calls.count + } + if let reason = choice["finish_reason"] as? String { finishReason = reason } + } + return (toolCalls, finishReason) + } + + func testNoneKeepsAToolCallOutOfTheReply() async throws { + let plain = try await nonStreaming(allowed: []) + XCTAssertEqual(plain.toolCalls, 0) + XCTAssertEqual(plain.finishReason, "stop") + let streamed = try await streaming(allowed: []) + XCTAssertEqual(streamed.toolCalls, 0) + XCTAssertEqual(streamed.finishReason, "stop") + } + + func testACallToAnotherFunctionThanTheNamedOneIsNotSent() async throws { + let plain = try await nonStreaming(allowed: ["get_time"]) + XCTAssertEqual(plain.toolCalls, 0) + let streamed = try await streaming(allowed: ["get_time"]) + XCTAssertEqual(streamed.toolCalls, 0) + } + + func testTheNamedFunctionAndAnUnrestrictedReplyStillCall() async throws { + for allowed in [["get_weather"], nil] as [Set?] { + let plain = try await nonStreaming(allowed: allowed) + XCTAssertEqual(plain.toolCalls, 1) + XCTAssertEqual(plain.finishReason, "tool_calls") + let streamed = try await streaming(allowed: allowed) + XCTAssertEqual(streamed.toolCalls, 1) + XCTAssertEqual(streamed.finishReason, "tool_calls") + } + } +} diff --git a/tests/test-contract.sh b/tests/test-contract.sh index 1e69c97..d0dc0a0 100755 --- a/tests/test-contract.sh +++ b/tests/test-contract.sh @@ -578,6 +578,43 @@ else fail "got HTTP $CODE with error '$ERR_TYPE' (expected 400 invalid_request_error chat_template_kwargs.enable_thinking)" fi +# ── 18. tool_choice decides which tools the model sees ─────────────────────── +# #269: the field was not decoded, so "none" and a named function changed nothing and a +# misspelt value was a normal 200. The CI model cannot be relied on to call a tool, so this +# reads the prompt size instead: the tools the template was given show in `prompt_tokens`. +log "Test 18: tool_choice none and a named function narrow the tools in the prompt" +TC_TOOLS='[{"type":"function","function":{"name":"get_weather","description":"Get weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}},{"type":"function","function":{"name":"get_time","description":"Get the current time in a timezone","parameters":{"type":"object","properties":{"tz":{"type":"string"}},"required":["tz"]}}}]' +tc_prompt() { + chat "{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"Say hi.\"}],\"max_tokens\":4,\"temperature\":0$1}" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["usage"]["prompt_tokens"])' 2>/dev/null || echo 0 +} +P_PLAIN=$(tc_prompt "") +P_ALL=$(tc_prompt ",\"tools\":$TC_TOOLS") +P_NONE=$(tc_prompt ",\"tools\":$TC_TOOLS,\"tool_choice\":\"none\"") +P_ONE=$(tc_prompt ",\"tools\":$TC_TOOLS,\"tool_choice\":{\"type\":\"function\",\"function\":{\"name\":\"get_time\"}}") +if [ "$P_PLAIN" -gt 0 ] && [ "$P_ALL" -gt "$P_PLAIN" ] && [ "$P_NONE" = "$P_PLAIN" ]; then + pass "\"none\" keeps the tools out of the prompt ($P_NONE tokens, $P_ALL with them)" +else + fail "\"none\" prompt is $P_NONE tokens (expected $P_PLAIN as without tools; $P_ALL with them)" +fi +if [ "$P_ONE" -gt "$P_PLAIN" ] && [ "$P_ONE" -lt "$P_ALL" ]; then + pass "a named function offers only that tool ($P_ONE tokens, $P_ALL with both)" +else + fail "named-function prompt is $P_ONE tokens (expected between $P_PLAIN and $P_ALL)" +fi + +log "Test 18b: a tool_choice the API does not have is a 400 that names the param" +for BAD in '"sometimes"' '{"type":"function","function":{"name":"get_stock"}}'; do + CODE=$(curl -s -o /tmp/SwiftLM-contract-toolchoice.json -w '%{http_code}' "$URL/v1/chat/completions" \ + -H 'Content-Type: application/json' -d "{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":4,\"tools\":$TC_TOOLS,\"tool_choice\":$BAD}") + ERR_TYPE=$(python3 -c 'import json; e=json.load(open("/tmp/SwiftLM-contract-toolchoice.json"))["error"]; print(e.get("type"), e.get("param"))' 2>/dev/null || echo "unparseable") + if [ "$CODE" = "400" ] && [ "$ERR_TYPE" = "invalid_request_error tool_choice" ]; then + pass "400 invalid_request_error naming param 'tool_choice' for $BAD" + else + fail "got HTTP $CODE with error '$ERR_TYPE' for $BAD (expected 400 invalid_request_error tool_choice)" + fi +done + log "═══════════════════════════════════════" log "Results: $PASS passed, $FAIL failed, $SKIP skipped, $TOTAL total" log "═══════════════════════════════════════"