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
14 changes: 10 additions & 4 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1986,8 +1986,8 @@ private struct TextToolTokenLoopHandler: TokenLoopHandler {
}
}

// Check if we have a complete tool call.
if let toolCall = toolCallProcessor.toolCalls.popLast() {
// Emit all complete tool calls in parse order.
for toolCall in toolCallProcessor.drainToolCalls() {
if case .terminated = emit(.toolCall(toolCall)) {
return false
}
Expand All @@ -2007,9 +2007,15 @@ private struct TextToolTokenLoopHandler: TokenLoopHandler {
mutating func onGenerationEnd(
emit: (sending Generation) -> AsyncStream<Generation>.Continuation.YieldResult
) {
toolCallProcessor.processEOS()
if let bufferedText = toolCallProcessor.processEOS(returnBufferedText: true),
!bufferedText.isEmpty
{
if case .terminated = emit(.chunk(bufferedText)) {
return
}
}

for toolCall in toolCallProcessor.toolCalls {
for toolCall in toolCallProcessor.drainToolCalls() {
if case .terminated = emit(.toolCall(toolCall)) {
break
}
Expand Down
16 changes: 16 additions & 0 deletions Libraries/MLXLMCommon/Tool/Parsers/JSONToolCallParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ public struct JSONToolCallParser: ToolCallParser, Sendable {
let function = try? JSONDecoder().decode(ToolCall.Function.self, from: normalizedData)
else { return nil }

// If tool schemas are provided, only accept calls to declared tools.
Comment thread
aleroot marked this conversation as resolved.
Resolved
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 {
isDeclaredTool = true
break
}
}

guard isDeclaredTool else {
return nil
}
}

return ToolCall(function: function)
}

Expand Down
Loading
Loading