forked from abetlen/llama-cpp-python
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathllama_chat_format.py
More file actions
3573 lines (3266 loc) · 148 KB
/
Copy pathllama_chat_format.py
File metadata and controls
3573 lines (3266 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import dataclasses
import datetime
import json
import os
import random
import string
import sys
from typing import (
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Tuple,
Union,
Protocol,
cast,
)
import jinja2
from jinja2.ext import Extension
from jinja2.sandbox import ImmutableSandboxedEnvironment
import numpy as np
import numpy.typing as npt
import llama_cpp.llama as llama_core
import llama_cpp.llama_types as llama_types
import llama_cpp.llama_grammar as llama_grammar
from ._logger import logger
from ._utils import suppress_stdout_stderr, Singleton
### Common Chat Templates and Special Tokens ###
# Source: https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B/blob/main/tokenizer_config.json
CHATML_CHAT_TEMPLATE = "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
CHATML_BOS_TOKEN = "<s>"
CHATML_EOS_TOKEN = "<|im_end|>"
# Source: https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/blob/main/tokenizer_config.json
MISTRAL_INSTRUCT_CHAT_TEMPLATE = "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token + ' ' }}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}"
MISTRAL_INSTRUCT_BOS_TOKEN = "<s>"
MISTRAL_INSTRUCT_EOS_TOKEN = "</s>"
# Source: https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1/blob/main/tokenizer_config.json
MIXTRAL_INSTRUCT_CHAT_TEMPLATE = "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}"
# Source: https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct/blob/main/tokenizer_config.json
LLAMA3_INSTRUCT_CHAT_TEMPLATE = "{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}{% endif %}"
# Source: https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E-Instruct/blob/main/tokenizer_config.json
LLAMA4_INSTRUCT_BOS_TOKEN = "<|begin_of_text|>"
LLAMA4_INSTRUCT_EOS_TOKEN = "<|eot|>"
LLAMA4_INSTRUCT_CHAT_TEMPLATE = "{% if custom_tools is defined %}\n {% set tools = custom_tools %}\n{% endif %}\n{% if not tools_in_user_message is defined %}\n {% set tools_in_user_message = true %}\n{% endif %}\n{% if not date_string is defined %}\n {% if strftime_now is defined %}\n {% set date_string = strftime_now(\"%d %b %Y\") %}\n {% else %}\n {% set date_string = \"26 Jul 2024\" %}\n {% endif %}\n{% endif %}\n{% if not tools is defined %}\n {% set tools = none %}\n{% endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{% if messages[0]['role'] == 'system' %} \n {% if messages[0]['content'] is string %}\n {% set system_message = messages[0]['content']|trim %}\n {% else %}\n {#- FIXME: The processor requires an array, always. #}\n {% set system_message = messages[0]['content'][0]['text']|trim %}\n {% endif %}\n {% set messages = messages[1:] %}\n {% set user_supplied_system_message = true %}\n{% else %}\n {% set system_message = \"\" %}\n {% set user_supplied_system_message = false %}\n{% endif %}\n\n{#- System message if the user supplied one #}\n{% if user_supplied_system_message %}\n {{ \"<|header_start|>system<|header_end|>\\n\\n\" }}\n {% if tools is not none %}\n {{ \"Environment: ipython\\n\" }}\n {% endif %}\n {% if tools is not none and not tools_in_user_message %}\n {{ \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{ 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{ \"Do not use variables.\\n\\n\" }}\n {% for t in tools %}\n {{ t | tojson(indent=4) }}\n {{ \"\\n\\n\" }}\n {% endfor %}\n {% endif %}\n {{ system_message }}\n {{ \"<|eot|>\" }}\n{% endif %}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{% if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {% if messages | length != 0 %}\n {% set first_user_message = messages[0]['content']|trim %}\n {% set messages = messages[1:] %}\n {% else %}\n {{ raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{% endif %}\n {{ '<|header_start|>user<|header_end|>\\n\\n' -}}\n {{ \"Given the following functions, please respond with a JSON for a function call \" }}\n {{ \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{ 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{ \"Do not use variables.\\n\\n\" }}\n {% for t in tools %}\n {{ t | tojson(indent=4) }}\n {{ \"\\n\\n\" }}\n {% endfor %}\n {{ first_user_message + \"<|eot|>\"}}\n{% endif %}\n\n{% for message in messages %}\n {% if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{ '<|header_start|>' + message['role'] + '<|header_end|>\\n\\n' }}\n {% if message['content'] is string %}\n {{ message['content'] }}\n {% else %}\n {% for content in message['content'] %}\n {% if content['type'] == 'image' %}\n {{ '<|image|>' }}\n {% elif content['type'] == 'text' %}\n {{ content['text'] }}\n {% endif %}\n {% endfor %}\n {% endif %}\n {{ \"<|eot|>\" }}\n {% elif 'tool_calls' in message and message.tool_calls|length > 0 %}\n {{ '<|header_start|>assistant<|header_end|>\\n\\n' -}}\n {{ '<|python_start|>' }}\n {% if message['content'] is string %}\n {{ message['content'] }}\n {% else %}\n {% for content in message['content'] %}\n {% if content['type'] == 'image' %}\n {{ '<|image|>' }}\n {% elif content['type'] == 'text' %}\n {{ content['text'] }}\n {% endif %}\n {% endfor %}\n {% endif %}\n {{ '<|python_end|>' }}\n {% for tool_call in message.tool_calls %}\n {{ '{\"name\": \"' + tool_call.function.name + '\", ' }}\n {{ '\"parameters\": ' }}\n {{ tool_call.function.arguments | tojson }}\n {{ \"}\" }}\n {% endfor %}\n {{ \"<|eot|>\" }}\n {% elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{ \"<|header_start|>ipython<|header_end|>\\n\\n\" }}\n {% if message.content is mapping or message.content is iterable %}\n {{ message.content | tojson }}\n {% else %}\n {{ message.content }}\n {% endif %}\n {{ \"<|eot|>\" }}\n {% endif %}\n{% endfor %}\n{% if add_generation_prompt %}\n {{ '<|header_start|>assistant<|header_end|>\\n\\n' }}\n{% endif %}\n"
# Source: https://huggingface.co/openai/gpt-oss-20b/blob/main/tokenizer_config.json
GPT_OSS_BOS_TOKEN = "<|startoftext|>"
GPT_OSS_EOS_TOKEN = "<|return|>"
GPT_OSS_PAD_TOKEN = "<|endoftext|>"
### Chat Completion Handler ###
class LlamaChatCompletionHandler(Protocol):
"""Base Protocol for a llama chat completion handler.
Very generic protocol that can be used to implement any chat format.
The only hard requirement is that it must return a ChatCompletion when
stream=False and an iterator of ChatCompletionChunks when stream=True."""
def __call__(
self,
*,
# llama.cpp instance
llama: llama_core.Llama,
# openai api parameters
messages: List[llama_types.ChatCompletionRequestMessage],
functions: Optional[List[llama_types.ChatCompletionFunction]] = None,
function_call: Optional[llama_types.ChatCompletionRequestFunctionCall] = None,
tools: Optional[List[llama_types.ChatCompletionTool]] = None,
tool_choice: Optional[llama_types.ChatCompletionToolChoiceOption] = None,
temperature: float = 0.2,
top_p: float = 0.95,
top_k: int = 40,
top_n_sigma: float = -1.00,
stream: bool = False,
stop: Optional[Union[str, List[str]]] = [],
seed: Optional[int] = None,
response_format: Optional[
llama_types.ChatCompletionRequestResponseFormat
] = None,
max_tokens: Optional[int] = None,
present_penalty: float = 0.0,
frequency_penalty: float = 0.0,
repeat_penalty: float = 1.1,
model: Optional[str] = None,
logit_bias: Optional[Dict[str, float]] = None,
# llama.cpp parameters
min_p: float = 0.05,
typical_p: float = 1.0,
mirostat_mode: int = 0,
mirostat_tau: float = 5.0,
mirostat_eta: float = 0.1,
xtc_threshold: float = 0.1,
xtc_probability: float = 0.0,
dry_multiplier: float = 0.0,
dry_base: float = 1.75,
dry_allowed_length: int = 2,
dry_penalty_last_n:int = 0,
dry_seq_breakers: list[str] = ["\n", ":", "\"", "*"],
adaptive_target : float = -1.0,
adaptive_decay : float = 0.9,
use_infill: bool = False,
logits_processor: Optional[llama_core.LogitsProcessorList] = None,
grammar: Optional[llama_grammar.LlamaGrammar] = None,
logprobs: Optional[bool] = None,
top_logprobs: Optional[int] = None,
assistant_prefill: bool = False,
# Reasoning Budget Params
#
# Generic first-reasoning-block budget control. These parameters are
# passed through to llama.create_completion() without model-specific
# inference or template guessing.
reasoning_budget: int = -1,
reasoning_start: str = "<think>",
reasoning_end: str = "</think>",
reasoning_budget_message: Optional[str] = None,
reasoning_start_in_prompt: bool = False,
reasoning_start_max_tokens: Optional[int] = 32,
**kwargs, # type: ignore
) -> Union[
llama_types.CreateChatCompletionResponse,
Iterator[llama_types.CreateChatCompletionStreamResponse],
]: ...
class LlamaChatCompletionHandlerNotFoundException(Exception):
pass
class LlamaChatCompletionHandlerRegistry(Singleton):
_chat_handlers: Dict[str, LlamaChatCompletionHandler] = {}
def register_chat_completion_handler(
self,
name: str,
chat_handler: LlamaChatCompletionHandler,
overwrite: bool = False,
):
if not overwrite and name in self._chat_handlers:
raise ValueError(
f"Formatter with name '{name}' is already registered. Use `overwrite=True` to overwrite it."
)
self._chat_handlers[name] = chat_handler
def unregister_chat_handler(self, name: str):
if name in self._chat_handlers:
del self._chat_handlers[name]
else:
raise ValueError(f"No formatter registered under the name '{name}'.")
def get_chat_completion_handler_by_name(
self, name: str
) -> LlamaChatCompletionHandler:
try:
chat_handler = self._chat_handlers[name]
return chat_handler
except KeyError:
raise LlamaChatCompletionHandlerNotFoundException(
f"Invalid chat handler: {name} (valid formats: {list(self._chat_handlers.keys())})"
)
def get_chat_completion_handler(name: str) -> LlamaChatCompletionHandler:
return LlamaChatCompletionHandlerRegistry().get_chat_completion_handler_by_name(
name
)
def register_chat_completion_handler(name: str):
def decorator(f: LlamaChatCompletionHandler):
LlamaChatCompletionHandlerRegistry().register_chat_completion_handler(name, f)
return f
return decorator
### Chat Formatter ###
@dataclasses.dataclass
class ChatFormatterResponse:
"""Dataclass that stores completion parameters for a given chat format and
create_chat_completion request.
prompt contains the formatted prompt generated from the chat format and messages.
stop contains the stop token or list of stop tokens to use for the chat format."""
prompt: str
stop: Optional[Union[str, List[str]]] = None
stopping_criteria: Optional[llama_core.StoppingCriteriaList] = None
added_special: bool = False
class ChatFormatter(Protocol):
"""Base Protocol for a chat formatter. A chat formatter is a function that
takes a list of messages and returns a chat format response which can be used
to generate a completion. The response can also include a stop token or list
of stop tokens to use for the completion."""
def __call__(
self,
*,
messages: List[llama_types.ChatCompletionRequestMessage],
**kwargs: Any,
) -> ChatFormatterResponse: ...
class Jinja2ChatFormatter(ChatFormatter):
class IgnoreGenerationTags(Extension):
"""Render HuggingFace `{% generation %}` blocks without tracking.
HuggingFace chat templates may wrap assistant text with:
{% generation %}
...
{% endgeneration %}
Transformers uses this tag to compute assistant-token masks. In
llama-cpp-python chat formatting we only need the final rendered prompt,
so this extension simply removes the tag pair and renders the inner
content as normal Jinja template content.
This keeps compatibility with HF templates while avoiding the overhead
of span tracking.
More information see:
https://github.com/huggingface/transformers/blob/39603d0e5cdb6f00e8d473d7fcbb01032d709181/src/transformers/utils/chat_template_utils.py#L425
"""
tags = {"generation"}
def parse(self, parser: jinja2.parser.Parser):
# Consume the opening `{% generation %}` token.
lineno = next(parser.stream).lineno
# Parse and return the block body until `{% endgeneration %}`.
# Returning the body directly makes the tag a transparent wrapper.
body = parser.parse_statements(
("name:endgeneration",),
drop_needle=True,
)
# Preserve line numbers for better template error messages.
for node in body:
node.set_lineno(lineno)
return body
def __init__(
self,
template: str,
eos_token: str,
bos_token: str,
add_generation_prompt: bool = True,
stop_token_ids: Optional[List[int]] = None,
special_tokens_map: Optional[Dict[str, str]] = None,
):
"""Format chat messages with a HuggingFace-style Jinja2 chat template.
Args:
template:
Raw HuggingFace chat template string.
eos_token:
Text form of the model EOS token.
bos_token:
Text form of the model BOS token.
add_generation_prompt:
Whether to ask the template to append the assistant generation
prefix. This mirrors Transformers' `add_generation_prompt`.
stop_token_ids:
Optional token ids that should stop generation when they appear
as the last generated token. This is llama-cpp-python specific.
special_tokens_map:
Optional tokenizer special-token map. Some HF templates may
reference extra variables such as `pad_token`, `unk_token`,
`sep_token`, or model-specific special tokens.
"""
self.template = template
self.eos_token = eos_token
self.bos_token = bos_token
self.add_generation_prompt = add_generation_prompt
self.special_tokens_map = special_tokens_map or {}
self.stop_token_ids = (
{int(token_id) for token_id in stop_token_ids}
if stop_token_ids is not None
else None
)
environment = ImmutableSandboxedEnvironment(
loader=jinja2.BaseLoader(),
trim_blocks=True,
lstrip_blocks=True,
# Keep this aligned with Transformers' chat-template Jinja setup:
# - IgnoreGenerationTags supports `{% generation %}` blocks.
# - loopcontrols supports `{% break %}` and `{% continue %}`.
extensions=[
Jinja2ChatFormatter.IgnoreGenerationTags,
jinja2.ext.loopcontrols,
],
)
# Match Transformers' chat-template JSON behavior.
# Jinja's default `tojson` escapes HTML characters, which is not what
# plain-text chat templates usually expect.
environment.filters["tojson"] = self.tojson
# Register these as globals once instead of passing them on every render.
environment.globals["raise_exception"] = self.raise_exception
environment.globals["strftime_now"] = self.strftime_now
self._environment = environment
self._template = environment.from_string(self.template)
# Precompute static stop fields once. This avoids rebuilding closures and
# StoppingCriteriaList objects for every chat completion request.
self._stop = [self.eos_token] if self.eos_token else []
self._stopping_criteria = self._build_stopping_criteria()
@staticmethod
def raise_exception(message: str):
"""Raise a Jinja template error from inside a chat template."""
raise jinja2.exceptions.TemplateError(message)
@staticmethod
def strftime_now(format_string: str = "%Y-%m-%d %H:%M:%S") -> str:
"""Return the current local time formatted with `datetime.strftime`."""
return datetime.datetime.now().strftime(format_string)
@staticmethod
def tojson(
x: Any,
ensure_ascii: bool = False,
indent: Optional[int] = None,
separators: Optional[Tuple[str, str]] = None,
sort_keys: bool = False,
) -> str:
"""Serialize an object to JSON for chat-template rendering.
This intentionally bypasses Jinja's built-in `tojson` filter because
the built-in filter escapes HTML-sensitive characters. HuggingFace chat
templates expect plain JSON text instead.
"""
return json.dumps(
x,
ensure_ascii=ensure_ascii,
indent=indent,
separators=separators,
sort_keys=sort_keys,
)
def _build_stopping_criteria(self):
"""Create stopping criteria once during initialization."""
if self.stop_token_ids is None:
return None
stop_token_ids = self.stop_token_ids
def stop_on_last_token(
tokens: npt.NDArray[np.intc],
logits: npt.NDArray[np.single],
) -> bool:
# Defensive guard: generation normally calls this with at least one
# token, but the callback should never crash on empty input.
return len(tokens) > 0 and int(tokens[-1]) in stop_token_ids
return llama_core.StoppingCriteriaList([stop_on_last_token])
def __call__(
self,
*,
messages: List[llama_types.ChatCompletionRequestMessage],
functions: Optional[List[llama_types.ChatCompletionFunction]] = None,
function_call: Optional[llama_types.ChatCompletionRequestFunctionCall] = None,
tools: Optional[List[llama_types.ChatCompletionTool]] = None,
tool_choice: Optional[llama_types.ChatCompletionToolChoiceOption] = None,
documents: Optional[List[Dict[str, Any]]] = None,
**kwargs: Any,
) -> ChatFormatterResponse:
"""Render OpenAI-style chat messages into a model prompt.
The method builds the variable context expected by HuggingFace-style
Jinja chat templates and renders the final prompt string used by
llama-cpp-python.
Template variables provided by default:
messages:
The chat history to render. Each item is expected to be an
OpenAI-style message dictionary, usually containing at least
`role` and `content`.
eos_token:
The model's end-of-sequence token string.
bos_token:
The model's beginning-of-sequence token string.
add_generation_prompt:
Whether the template should append the assistant generation
prefix. This mirrors Transformers' `add_generation_prompt`.
functions:
Legacy OpenAI-compatible function definitions, if provided.
function_call:
Legacy OpenAI-compatible function-call selection, if provided.
tools:
OpenAI/HuggingFace-compatible tool definitions, if provided.
This formatter expects tools to already be normalized into
JSON-schema-like dictionaries. It does not auto-convert Python
callables into JSON schemas like Transformers can.
tool_choice:
Optional tool-choice instruction, such as `"auto"`, `"none"`,
or a specific tool/function selection object.
documents:
Optional RAG/document context. Some HF chat templates reference
this variable when rendering retrieval-augmented prompts.
**kwargs:
Extra model-specific or template-specific variables. These are
merged into the template context last, so they can intentionally
override the defaults above when needed.
Additional variables:
Values from `special_tokens_map` are also exposed to the template,
such as `pad_token`, `unk_token`, `sep_token`, or custom
model-specific special tokens. Core variables like `messages`,
`eos_token`, and `bos_token` override `special_tokens_map` entries
by default.
Returns:
ChatFormatterResponse:
Contains the rendered prompt, text stop sequences, optional
token-id stopping criteria, and `added_special=True` because the
chat template is responsible for adding model special tokens.
Raises:
jinja2.exceptions.TemplateError:
If the template calls `raise_exception(...)` or Jinja rendering
fails.
"""
template_kwargs: Dict[str, Any] = {}
# Make extra tokenizer special tokens available to templates, e.g.
# `pad_token`, `unk_token`, `sep_token`, or model-specific tokens.
template_kwargs.update(self.special_tokens_map)
# Explicit core variables should override values from special_tokens_map.
template_kwargs.update(
{
"messages": messages,
"eos_token": self.eos_token,
"bos_token": self.bos_token,
"add_generation_prompt": self.add_generation_prompt,
"functions": functions,
"function_call": function_call,
"tools": tools,
"tool_choice": tool_choice,
"documents": documents,
}
)
# Let caller-provided kwargs extend the template context.
# If a caller intentionally passes a same-name key, it will override the
# defaults above. This is useful for model-specific template variables.
template_kwargs.update(kwargs)
prompt = self._template.render(**template_kwargs)
return ChatFormatterResponse(
prompt=prompt,
stop=self._stop,
stopping_criteria=self._stopping_criteria,
added_special=True,
)
def to_chat_handler(self) -> LlamaChatCompletionHandler:
return chat_formatter_to_chat_completion_handler(self)
def _convert_text_completion_logprobs_to_chat(
logprobs: Optional[llama_types.CompletionLogprobs],
) -> llama_types.ChatCompletionLogprobs:
if logprobs is None:
return None
return {
"content": [
{
"token": token,
"bytes": None,
"logprob": logprob,
"top_logprobs": [
{
"token": top_token,
"logprob": top_logprob,
"bytes": None,
}
for top_token, top_logprob in top_logprobs.items()
],
} for (token, logprob, top_logprobs) in zip(logprobs["tokens"], logprobs["token_logprobs"], logprobs["top_logprobs"])
],
"refusal": None,
}
def _convert_text_completion_to_chat(
completion: llama_types.Completion,
) -> llama_types.ChatCompletion:
assert "usage" in completion
return {
"id": "chat" + completion["id"],
"object": "chat.completion",
"created": completion["created"],
"model": completion["model"],
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": completion["choices"][0]["text"],
},
"logprobs": _convert_text_completion_logprobs_to_chat(completion["choices"][0]["logprobs"]),
"finish_reason": completion["choices"][0]["finish_reason"],
}
],
"usage": completion["usage"],
}
def _convert_text_completion_chunks_to_chat(
chunks: Iterator[llama_types.CreateCompletionStreamResponse],
) -> Iterator[llama_types.ChatCompletionChunk]:
for i, chunk in enumerate(chunks):
if i == 0:
yield {
"id": "chat" + chunk["id"],
"model": chunk["model"],
"created": chunk["created"],
"object": "chat.completion.chunk",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
},
"logprobs": None,
"finish_reason": None,
}
],
}
yield {
"id": "chat" + chunk["id"],
"model": chunk["model"],
"created": chunk["created"],
"object": "chat.completion.chunk",
"choices": [
{
"index": 0,
"delta": (
{
"content": chunk["choices"][0]["text"],
}
if chunk["choices"][0]["finish_reason"] is None
else {}
),
"logprobs": _convert_text_completion_logprobs_to_chat(chunk["choices"][0]["logprobs"]),
"finish_reason": chunk["choices"][0]["finish_reason"],
}
],
}
def _convert_completion_to_chat(
completion_or_chunks: Union[
llama_types.CreateCompletionResponse,
Iterator[llama_types.CreateCompletionStreamResponse],
],
stream: bool = False,
) -> Union[
llama_types.CreateChatCompletionResponse, Iterator[llama_types.ChatCompletionChunk]
]:
if stream:
chunks: Iterator[llama_types.CreateCompletionStreamResponse] = completion_or_chunks # type: ignore
return _convert_text_completion_chunks_to_chat(chunks)
else:
completion: llama_types.Completion = completion_or_chunks # type: ignore
return _convert_text_completion_to_chat(completion)
def _convert_completion_to_chat_function(
tool_name: str,
completion_or_chunks: Union[
llama_types.CreateCompletionResponse,
Iterator[llama_types.CreateCompletionStreamResponse],
],
stream: bool,
):
if not stream:
completion: llama_types.CreateCompletionResponse = completion_or_chunks # type: ignore
assert "usage" in completion
tool_id = "call_" + "_0_" + tool_name + "_" + completion["id"]
# TODO: Fix for legacy function calls
chat_completion: llama_types.CreateChatCompletionResponse = {
"id": "chat" + completion["id"],
"object": "chat.completion",
"created": completion["created"],
"model": completion["model"],
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": None,
"function_call": {
"name": tool_name,
"arguments": completion["choices"][0]["text"],
},
"tool_calls": [
{
"id": tool_id,
"type": "function",
"function": {
"name": tool_name,
"arguments": completion["choices"][0]["text"],
},
}
],
},
"logprobs": _convert_text_completion_logprobs_to_chat(completion["choices"][0]["logprobs"]),
"finish_reason": "tool_calls",
}
],
"usage": completion["usage"],
}
return chat_completion
else:
chunks: Iterator[llama_types.CreateCompletionStreamResponse] = completion_or_chunks # type: ignore
def _stream_response_to_function_stream(
chunks: Iterator[llama_types.CreateCompletionStreamResponse],
) -> Iterator[llama_types.CreateChatCompletionStreamResponse]:
# blank first message
first = True
id_ = None
created = None
model = None
tool_id = None
for chunk in chunks:
if first:
id_ = "chat" + chunk["id"]
created = chunk["created"]
model = chunk["model"]
tool_id = "call_" + "_0_" + tool_name + "_" + chunk["id"]
yield {
"id": id_,
"object": "chat.completion.chunk",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"finish_reason": None,
"logprobs": None,
"delta": {
"role": "assistant",
"content": None,
"function_call": None,
"tool_calls": None,
},
}
],
}
yield {
"id": "chat" + chunk["id"],
"object": "chat.completion.chunk",
"created": chunk["created"],
"model": chunk["model"],
"choices": [
{
"index": 0,
"finish_reason": None,
"logprobs": _convert_text_completion_logprobs_to_chat(chunk["choices"][0]["logprobs"]),
"delta": {
"role": None,
"content": None,
"function_call": {
"name": tool_name,
"arguments": chunk["choices"][0]["text"],
},
"tool_calls": [
{
"index": 0,
"id": tool_id,
"type": "function",
"function": {
"name": tool_name,
"arguments": chunk["choices"][0][
"text"
],
},
}
],
},
}
],
}
first = False
continue
assert tool_id is not None
yield {
"id": "chat" + chunk["id"],
"object": "chat.completion.chunk",
"created": chunk["created"],
"model": chunk["model"],
"choices": [
{
"index": 0,
"finish_reason": None,
"logprobs": _convert_text_completion_logprobs_to_chat(chunk["choices"][0]["logprobs"]),
"delta": {
"role": None,
"content": None,
"function_call": {
"name": tool_name,
"arguments": chunk["choices"][0]["text"],
},
"tool_calls": [
{
"index": 0,
"id": tool_id,
"type": "function",
"function": {
"name": tool_name,
"arguments": chunk["choices"][0]["text"],
},
}
],
},
}
],
}
if id_ is not None and created is not None and model is not None:
yield {
"id": id_,
"object": "chat.completion.chunk",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"finish_reason": "tool_calls",
"logprobs": None,
"delta": {
"role": None,
"content": None,
"function_call": None,
"tool_calls": None,
},
}
],
}
return _stream_response_to_function_stream(chunks)
def chat_formatter_to_chat_completion_handler(
chat_formatter: ChatFormatter,
) -> LlamaChatCompletionHandler:
def chat_completion_handler(
*,
llama: llama_core.Llama,
messages: List[llama_types.ChatCompletionRequestMessage],
functions: Optional[List[llama_types.ChatCompletionFunction]] = None,
function_call: Optional[llama_types.ChatCompletionRequestFunctionCall] = None,
tools: Optional[List[llama_types.ChatCompletionTool]] = None,
tool_choice: Optional[llama_types.ChatCompletionToolChoiceOption] = None,
temperature: float = 0.2,
top_p: float = 0.95,
top_k: int = 40,
min_p: float = 0.05,
typical_p: float = 1.0,
stream: bool = False,
stop: Optional[Union[str, List[str]]] = [],
seed: Optional[int] = None,
response_format: Optional[
llama_types.ChatCompletionRequestResponseFormat
] = None,
max_tokens: Optional[int] = None,
present_penalty: float = 0.0,
frequency_penalty: float = 0.0,
repeat_penalty: float = 1.1,
top_n_sigma: float = -1.00,
mirostat_mode: int = 0,
mirostat_tau: float = 5.0,
mirostat_eta: float = 0.1,
xtc_threshold: float = 0.1,
xtc_probability: float = 0.0,
dry_multiplier: float = 0.0,
dry_base: float = 1.75,
dry_allowed_length: int = 2,
dry_penalty_last_n:int = 0,
dry_seq_breakers: list[str] = ["\n", ":", "\"", "*"],
adaptive_target : float = -1.0,
adaptive_decay : float = 0.9,
use_infill: bool = False,
model: Optional[str] = None,
logits_processor: Optional[llama_core.LogitsProcessorList] = None,
grammar: Optional[llama_grammar.LlamaGrammar] = None,
logit_bias: Optional[Dict[str, float]] = None,
logprobs: Optional[bool] = None,
top_logprobs: Optional[int] = None,
assistant_prefill: bool = False,
# Reasoning Budget Params
#
# Generic first-reasoning-block budget control. These parameters are
# passed through to llama.create_completion() without model-specific
# inference or template guessing.
reasoning_budget: int = -1,
reasoning_start: str = "<think>",
reasoning_end: str = "</think>",
reasoning_budget_message: Optional[str] = None,
reasoning_start_in_prompt: bool = False,
reasoning_start_max_tokens: Optional[int] = 32,
**kwargs, # type: ignore
) -> Union[
llama_types.CreateChatCompletionResponse,
Iterator[llama_types.CreateChatCompletionStreamResponse],
]:
# JIT Interception for Assistant Prefill (Continue Generation)
partial_assistant_text = ""
if assistant_prefill:
if not messages:
if llama.verbose:
print("Llama.create_chat_completion: Warning! 'assistant_prefill=True' but messages list is empty. Ignoring prefill.", file=sys.stderr)
elif messages[-1].get("role") != "assistant":
if llama.verbose:
print(f"Llama.create_chat_completion: Warning! 'assistant_prefill=True' but last message role is '{messages[-1].get('role')}'. Expected 'assistant'. Ignoring prefill.", file=sys.stderr)
else:
# Safe to prefill: pop the last message without mutating the user's original list
messages = messages.copy()
partial_message = messages.pop()
partial_assistant_text = partial_message.get("content", "") or ""
if not partial_assistant_text and llama.verbose:
print("Llama.create_chat_completion: Warning! 'assistant_prefill=True' but the assistant message has no content.", file=sys.stderr)
result = chat_formatter(
messages=messages,
functions=functions,
function_call=function_call,
tools=tools,
tool_choice=tool_choice,
)
# Seamlessly append the partial assistant text to the standard generated Jinja template
if partial_assistant_text:
result.prompt += partial_assistant_text
prompt = llama.tokenize(
result.prompt.encode("utf-8"),
add_bos=not result.added_special,
special=True,
)
if result.stop is not None:
stop = [] if stop is None else [stop] if isinstance(stop, str) else stop
rstop = result.stop if isinstance(result.stop, list) else [result.stop]
stop = stop + rstop
stopping_criteria = None
if result.stopping_criteria is not None:
stopping_criteria = result.stopping_criteria
if response_format is not None and response_format["type"] == "json_object":
grammar = _grammar_for_response_format(
response_format, verbose=llama.verbose
)
# Convert legacy functions to tools
if functions is not None:
tools = [
{
"type": "function",
"function": function,
}
for function in functions
]
# Convert legacy function_call to tool_choice
if function_call is not None:
if isinstance(function_call, str) and (
function_call == "none" or function_call == "auto"
):
tool_choice = function_call
if isinstance(function_call, dict) and "name" in function_call:
tool_choice = {
"type": "function",
"function": {
"name": function_call["name"],
},
}
tool = None
if (
tool_choice is not None
and isinstance(tool_choice, dict)
and tools is not None
):
name = tool_choice["function"]["name"]
tool = next((t for t in tools if t["function"]["name"] == name), None)
if tool is None:
raise ValueError(f"Tool choice '{name}' not found in tools.")
schema = tool["function"]["parameters"]
try:
# create grammar from json schema
grammar = llama_grammar.LlamaGrammar.from_json_schema(
json.dumps(schema), verbose=llama.verbose
)
except Exception as e:
if llama.verbose:
print(str(e), file=sys.stderr)
grammar = llama_grammar.LlamaGrammar.from_string(
llama_grammar.JSON_GBNF, verbose=llama.verbose
)
completion_or_chunks = llama.create_completion(
prompt=prompt,
temperature=temperature,
top_p=top_p,
top_k=top_k,
min_p=min_p,
typical_p=typical_p,
logprobs=top_logprobs if logprobs else None,
stream=stream,
stop=stop,
seed=seed,
max_tokens=max_tokens,
present_penalty=present_penalty,
frequency_penalty=frequency_penalty,
repeat_penalty=repeat_penalty,
top_n_sigma=top_n_sigma,
mirostat_mode=mirostat_mode,
mirostat_tau=mirostat_tau,
mirostat_eta=mirostat_eta,
xtc_threshold=xtc_threshold,
xtc_probability=xtc_probability,
dry_multiplier=dry_multiplier,
dry_base=dry_base,
dry_allowed_length=dry_allowed_length,
dry_penalty_last_n=dry_penalty_last_n,
dry_seq_breakers=dry_seq_breakers,
adaptive_target=adaptive_target,
adaptive_decay=adaptive_decay,
use_infill=use_infill,
model=model,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
grammar=grammar,
logit_bias=logit_bias,
reasoning_budget=reasoning_budget,
reasoning_start=reasoning_start,
reasoning_end=reasoning_end,
reasoning_budget_message=reasoning_budget_message,
reasoning_start_in_prompt=reasoning_start_in_prompt,
reasoning_start_max_tokens=reasoning_start_max_tokens,
)
if tool is not None:
tool_name = tool["function"]["name"]
return _convert_completion_to_chat_function(
tool_name, completion_or_chunks, stream
)
return _convert_completion_to_chat(completion_or_chunks, stream=stream)
return chat_completion_handler
def hf_autotokenizer_to_chat_formatter(
pretrained_model_name_or_path: Union[str, os.PathLike[str]]
) -> ChatFormatter:
# https://huggingface.co/docs/transformers/main/chat_templating