@@ -125,7 +125,8 @@ public protocol Tokenizer {
125
125
chatTemplate: String ? ,
126
126
addGenerationPrompt: Bool ,
127
127
truncation: Bool ,
128
- maxLength: Int ?
128
+ maxLength: Int ? ,
129
+ tools: [ [ String : Any ] ] ?
129
130
) throws -> [ Int ]
130
131
}
131
132
@@ -323,12 +324,35 @@ public class PreTrainedTokenizer: Tokenizer {
323
324
324
325
public func applyChatTemplate(
325
326
messages: [ [ String : String ] ] ,
326
- chatTemplate: String ? ,
327
+ chatTemplate: String ? = nil ,
327
328
addGenerationPrompt: Bool = false ,
328
329
truncation: Bool = false ,
329
- maxLength: Int ?
330
+ maxLength: Int ? = nil ,
331
+ tools: [ [ String : Any ] ] ? = nil
330
332
) throws -> [ Int ] {
331
- let template = try Template ( chatTemplate ?? tokenizerConfig. chatTemplate? . stringValue ?? defaultChatTemplate)
333
+ var chatTemplateFromConfig : String ?
334
+ if let chatTemplateValue = tokenizerConfig. chatTemplate {
335
+ if let chatTemplateStringValue = chatTemplateValue. stringValue {
336
+ chatTemplateFromConfig = chatTemplateStringValue
337
+ } else if let chatTemplateArrayValue = chatTemplateValue. arrayValue {
338
+ // If a list of chat templates is specified, convert them to a dict
339
+ let templateDict = Dictionary < String , String > ( uniqueKeysWithValues: chatTemplateArrayValue. compactMap { template in
340
+ guard let name = template [ dynamicMember: " name " ] ? . stringValue,
341
+ let templateString = template [ dynamicMember: " template " ] ? . stringValue else {
342
+ return nil
343
+ }
344
+ return ( name, templateString)
345
+ } )
346
+ // Choose the appropriate template
347
+ if let tools = tools, !tools. isEmpty, let toolUseTemplate = templateDict [ " tool_use " ] {
348
+ chatTemplateFromConfig = toolUseTemplate
349
+ } else {
350
+ chatTemplateFromConfig = templateDict [ " default " ]
351
+ }
352
+ }
353
+ }
354
+
355
+ let template = try Template ( chatTemplate ?? chatTemplateFromConfig ?? defaultChatTemplate)
332
356
var context : [ String : Any ] = [
333
357
" messages " : messages,
334
358
" add_generation_prompt " : addGenerationPrompt
0 commit comments