Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 69 additions & 15 deletions Libraries/MLXLMCommon/Chat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,45 @@ public enum Chat {
/// Array of audio data associated with the message.
public var audios: [UserInput.Audio]

/// Tool-call metadata associated with this message.
public var tool: Tool?

public struct Tool: Sendable {
fileprivate enum Storage: Sendable {
case calls([ToolCall])
case result(id: String)
}

fileprivate let storage: Storage

private init(storage: Storage) {
self.storage = storage
}

/// Tool calls emitted by an assistant message.
public static func calls(_ calls: [ToolCall]) -> Self {
Self(storage: .calls(calls))
}

/// Id of the assistant tool call answered by a tool message.
public static func result(id: String) -> Self {
Self(storage: .result(id: id))
}
}

public init(
role: Role, content: String,
images: [UserInput.Image] = [],
videos: [UserInput.Video] = [],
audios: [UserInput.Audio] = []
audios: [UserInput.Audio] = [],
tool: Tool? = nil
) {
self.role = role
self.content = content
self.images = images
self.videos = videos
self.audios = audios
self.tool = tool
}

public static func system(
Expand All @@ -37,9 +65,14 @@ public enum Chat {
}

public static func assistant(
_ content: String, images: [UserInput.Image] = [], videos: [UserInput.Video] = []
_ content: String,
images: [UserInput.Image] = [],
videos: [UserInput.Video] = [],
toolCalls: [ToolCall]? = nil
) -> Self {
Self(role: .assistant, content: content, images: images, videos: videos)
Self(
role: .assistant, content: content, images: images, videos: videos,
tool: toolCalls.map { .calls($0) })
}

public static func user(
Expand All @@ -51,8 +84,8 @@ public enum Chat {
Self(role: .user, content: content, images: images, videos: videos, audios: audios)
}

public static func tool(_ content: String) -> Self {
Self(role: .tool, content: content)
public static func tool(_ content: String, id: String? = nil) -> Self {
Self(role: .tool, content: content, tool: id.map { .result(id: $0) })
}

public enum Role: String, Sendable {
Expand Down Expand Up @@ -90,10 +123,38 @@ public protocol MessageGenerator: Sendable {
extension MessageGenerator {

public func generate(message: Chat.Message) -> Message {
[
var dictionary: Message = [
"role": message.role.rawValue,
"content": message.content,
]

addToolMetadata(to: &dictionary, for: message)

return dictionary
}

/// Adds tool-call metadata from a structured message to a raw message dictionary.
public func addToolMetadata(to dictionary: inout Message, for message: Chat.Message) {
switch message.tool?.storage {
case .calls(let calls):
dictionary["tool_calls"] = calls.map { toolCall -> [String: any Sendable] in
var entry: [String: any Sendable] = [
"type": "function",
"function": [
"name": toolCall.function.name,
"arguments": toolCall.function.argumentsObject,
] as [String: any Sendable],
]
if let id = toolCall.id {
entry["id"] = id
}
return entry
}
case .result(let id):
dictionary["tool_call_id"] = id
case nil:
break
}
}

public func generate(messages: [Chat.Message]) -> [Message] {
Expand All @@ -119,8 +180,8 @@ extension MessageGenerator {
}
}

/// Default implementation of ``MessageGenerator`` that produces a
/// `role` and `content`.
/// Default implementation of ``MessageGenerator`` that produces `role` and
/// `content`, plus `tool_call_id` and `tool_calls` when present.
///
/// ```swift
/// [
Expand All @@ -130,13 +191,6 @@ extension MessageGenerator {
/// ```
public struct DefaultMessageGenerator: MessageGenerator {
public init() {}

public func generate(message: Chat.Message) -> Message {
[
"role": message.role.rawValue,
"content": message.content,
]
}
}

/// Implementation of ``MessageGenerator`` that produces a
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLMCommon/ChatSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,7 @@ public final class ChatSession {
{
for toolCall in pendingToolCalls {
let toolResult = try await toolDispatch(toolCall)
messages.append(.tool(toolResult))
messages.append(.tool(toolResult, id: toolCall.id))
}
continue restart
}
Expand Down
22 changes: 16 additions & 6 deletions Libraries/MLXLMCommon/Tool/Parsers/JSONToolCallParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,15 @@ public struct JSONToolCallParser: ToolCallParser, Sendable {

guard
let data = jsonStr.data(using: .utf8),
let normalizedData = normalizedToolCallData(from: data),
let function = try? JSONDecoder().decode(ToolCall.Function.self, from: normalizedData)
let toolCall = parseToolCall(from: data)
else { return nil }

// If tool schemas are provided, only accept calls to declared tools.
if let tools, !tools.isEmpty {
var isDeclaredTool = false
for tool in tools {
let functionSpec = tool["function"] as? [String: any Sendable]
if functionSpec?["name"] as? String == function.name {
if functionSpec?["name"] as? String == toolCall.function.name {
isDeclaredTool = true
break
}
Expand All @@ -51,15 +50,21 @@ public struct JSONToolCallParser: ToolCallParser, Sendable {
}
}

return ToolCall(function: function)
return toolCall
}

private func normalizedToolCallData(from data: Data) -> Data? {
private func parseToolCall(from data: Data) -> ToolCall? {
guard var jsonObject = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else {
return nil
}

var id = jsonObject["id"] as? String
if let functionObject = jsonObject["function"] as? [String: Any] {
id = id ?? functionObject["id"] as? String
jsonObject = functionObject
Comment thread
aleroot marked this conversation as resolved.
Resolved
}

if let stringifiedArguments = jsonObject["arguments"] as? String {
guard
let argumentsData = stringifiedArguments.data(using: .utf8),
Expand All @@ -69,6 +74,11 @@ public struct JSONToolCallParser: ToolCallParser, Sendable {
jsonObject["arguments"] = argumentsObject
}

return try? JSONSerialization.data(withJSONObject: jsonObject)
guard
let normalizedData = try? JSONSerialization.data(withJSONObject: jsonObject),
let function = try? JSONDecoder().decode(ToolCall.Function.self, from: normalizedData)
else { return nil }

return ToolCall(function: function, id: id)
}
}
7 changes: 4 additions & 3 deletions Libraries/MLXLMCommon/Tool/Parsers/Llama3ToolCallParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public struct Llama3ToolCallParser: ToolCallParser, Sendable {
public init() {}

private struct LlamaFunction: Codable {
let id: String?
let name: String
let parameters: [String: JSONValue]?
let arguments: [String: JSONValue]?
Expand All @@ -37,7 +38,7 @@ public struct Llama3ToolCallParser: ToolCallParser, Sendable {
name: llamaFunc.name,
arguments: args
)
return ToolCall(function: function)
return ToolCall(function: function, id: llamaFunc.id)
}

// Fallback to Pythonic format
Expand Down Expand Up @@ -67,7 +68,7 @@ public struct Llama3ToolCallParser: ToolCallParser, Sendable {
name: llamaFunc.name,
arguments: args
)
return ToolCall(function: function)
return ToolCall(function: function, id: llamaFunc.id)
}
}

Expand All @@ -78,7 +79,7 @@ public struct Llama3ToolCallParser: ToolCallParser, Sendable {
name: llamaFunc.name,
arguments: args
)
return [ToolCall(function: function)]
return [ToolCall(function: function, id: llamaFunc.id)]
}

// Try Pythonic list like [func1(args), func2(args)] or single func1(args)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@ public struct MistralToolCallParser: ToolCallParser, Sendable {
.trimmingCharacters(in: .whitespacesAndNewlines)
let argsPart = String(text[argsRange.upperBound...])
.trimmingCharacters(in: .whitespacesAndNewlines)
var callID: String?

// Handle optional [CALL_ID] between name and [ARGS]
if let callIdRange = namePart.range(of: "[CALL_ID]") {
let parsedCallID = String(namePart[callIdRange.upperBound...])
.trimmingCharacters(in: .whitespacesAndNewlines)
callID = parsedCallID.isEmpty ? nil : parsedCallID
namePart = String(namePart[..<callIdRange.lowerBound])
.trimmingCharacters(in: .whitespacesAndNewlines)
}
Expand All @@ -57,7 +61,8 @@ public struct MistralToolCallParser: ToolCallParser, Sendable {
}

return ToolCall(
function: ToolCall.Function(name: namePart, arguments: argsDict)
function: ToolCall.Function(name: namePart, arguments: argsDict),
id: callID
)
}
}
10 changes: 9 additions & 1 deletion Libraries/MLXLMCommon/Tool/ToolCall.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,21 @@ public struct ToolCall: Hashable, Codable, Sendable {
self.name = name
self.arguments = arguments.mapValues { JSONValue.from($0) }
}

var argumentsObject: [String: any Sendable] {
arguments.mapValues { $0.sendableValue }
}
}

/// The function to be called
public let function: Function

public init(function: Function) {
/// Optional id used to correlate a tool call with its tool result.
public let id: String?

public init(function: Function, id: String? = nil) {
self.function = function
self.id = id
}
}

Expand Down
12 changes: 12 additions & 0 deletions Libraries/MLXLMCommon/Tool/ToolCallFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,18 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable {
}
}

/// Generate an ID compatible with this tool-call syntax.
func generateToolCallID() -> String {
let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "")

switch self {
case .mistral:
return String(uuid.prefix(9))
default:
return "call_" + uuid.lowercased()
}
}

/// Infer the tool call format based on model type from config.json.
///
/// This method maps known model types to their corresponding tool call formats,
Expand Down
Loading
Loading