Core LlamaCPP#
llm module#
serapeum.llama_cpp.llm
#
LlamaCPP provider — local GGUF inference via llama-cpp-python.
Contains the :class:LlamaCPP class, a concrete
:class:~serapeum.core.llms.LLM implementation that runs quantised GGUF
models on-device using the
llama-cpp-python <https://github.com/abetlen/llama-cpp-python>_ backend.
Key capabilities:
- Model sources: local path, direct URL download, or HuggingFace Hub.
- Prompt formatters: pluggable
messages_to_prompt/completion_to_promptper model family (Llama 2, Llama 3, …). - GPU offloading:
n_gpu_layerscontrols layer offloading via cuBLAS / Metal / Vulkan. - Model caching: a module-level :class:
weakref.WeakValueDictionaryreuses loadedLlamainstances across :class:LlamaCPPobjects with identical model path and kwargs. - Async-safe: :meth:
~LlamaCPP.acompleteoffloads CPU-bound inference to a thread pool so the event loop is never blocked.
See Also
serapeum.llama_cpp.formatters: Ready-made prompt formatters. serapeum.llama_cpp.utils: Internal download helpers.
LlamaCPP
#
Bases: Retry, CompletionToChat, LLM
LlamaCPP LLM — local inference via llama-cpp-python.
Runs GGUF models locally using the llama-cpp-python backend. The model is loaded (or downloaded) once at construction time.
messages_to_prompt and completion_to_prompt are required.
GGUF models each have a specific chat template; using the wrong one
produces garbage output. Pass the formatter that matches the model family
you are loading. Ready-made formatters live in
serapeum.llama_cpp.formatters.
Warning
Construction is blocking. Loading a large GGUF file can take
10-30 seconds. To construct inside an async context without blocking
the event loop wrap the call in asyncio.to_thread::
llm = await asyncio.to_thread(LlamaCPP, model_path="...", ...)
Examples:
- Load a model with Llama 3 formatters and explore the instance
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm_v3 = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> llm_v3.temperature 0.1 >>> llm_v3.max_new_tokens 256 >>> llm_v3.context_window 512 - Load a model with Llama 2 formatters and different settings
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama2 import ( ... messages_to_prompt, ... completion_to_prompt, ... ) >>> llm_v2 = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.5, ... max_new_tokens=128, ... context_window=512, ... messages_to_prompt=messages_to_prompt, ... completion_to_prompt=completion_to_prompt, ... ) >>> llm_v2.temperature 0.5 >>> llm_v2.max_new_tokens 128 >>> LlamaCPP.class_name() 'LlamaCPP'
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
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 | |
metadata
property
#
LLM metadata derived from the loaded model's configuration.
Returns:
| Type | Description |
|---|---|
Metadata
|
class: |
Metadata
|
|
Metadata
|
|
Metadata
|
|
Examples:
- Inspect metadata fields of a loaded model
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> meta = llm.metadata >>> meta.context_window 512 >>> meta.num_output 256 >>> meta.model_name.split(".")[-1] 'gguf'
See Also
class_name: Class identifier used for serialisation.
acomplete(prompt, formatted=False, *, stream=False, **kwargs)
async
#
Async text completion — offloads CPU-bound inference to a thread pool.
Wraps :meth:complete in :func:asyncio.to_thread so that the
llama-cpp-python C-level inference call never blocks the running event
loop. The streaming variant collects all token chunks in the worker
thread and re-yields them as an async generator once all chunks are
ready.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input text to complete. |
required |
formatted
|
bool
|
When |
False
|
stream
|
bool
|
When |
False
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the underlying
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CompletionResponse | CompletionResponseAsyncGen
|
class: |
CompletionResponse | CompletionResponseAsyncGen
|
class: |
|
CompletionResponse | CompletionResponseAsyncGen
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If prompt exceeds :attr: |
Examples:
- Non-streaming async completion — explore the response
>>> import os >>> import asyncio >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> response = asyncio.run(llm.acomplete("Once upon a time")) >>> response.raw["choices"][0]["text"] == response.text True >>> sorted(response.raw.keys()) ['choices', 'created', 'id', 'model', 'object', 'usage'] - Streaming async completion — collect and inspect chunks
>>> import os >>> import asyncio >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> async def _collect(): ... return [c async for c in await llm.acomplete("Once upon", stream=True)] >>> chunks = asyncio.run(_collect()) >>> chunks[-1].text.startswith(chunks[0].delta) True >>> chunks[-1].text != chunks[0].delta True
See Also
complete: Synchronous variant of this method. _complete: Non-streaming implementation called in the thread pool. _stream_complete: Streaming implementation called in the thread pool.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
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 | |
class_name()
classmethod
#
Return the canonical class identifier used in serialisation.
Returns:
| Type | Description |
|---|---|
str
|
The string |
complete(prompt, formatted=False, *, stream=False, **kwargs)
#
Run text completion, optionally streaming token-by-token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input text to complete. |
required |
formatted
|
bool
|
When |
False
|
stream
|
bool
|
When |
False
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to the underlying
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CompletionResponse | CompletionResponseGen
|
class: |
CompletionResponse | CompletionResponseGen
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If prompt exceeds :attr: |
Examples:
- Non-streaming completion — explore the response structure
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> response = llm.complete("Once upon a time") >>> response.raw["choices"][0]["text"] == response.text True >>> sorted(response.raw.keys()) ['choices', 'created', 'id', 'model', 'object', 'usage'] >>> response.raw["usage"]["prompt_tokens"] > 0 True - Streaming completion — iterate over token deltas
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> chunks = list(llm.complete("Once upon a time", stream=True)) >>> chunks[-1].text.startswith(chunks[0].delta) True >>> chunks[-1].text != chunks[0].delta True
See Also
acomplete: Async variant that offloads inference to a thread pool. _complete: Non-streaming implementation. _stream_complete: Streaming implementation.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
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 | |
count_tokens(text)
#
Return the number of tokens text encodes to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to count tokens for. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Integer token count for text. |
Examples:
- count_tokens is consistent with tokenize
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> llm.count_tokens("Hello!") == len(llm.tokenize("Hello!")) True - Longer text yields a higher count
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> short_count = llm.count_tokens("Hi") >>> long_count = llm.count_tokens("Hello, how are you doing today?") >>> long_count > short_count # more text yields a higher count True >>> short_count == len(llm.tokenize("Hi")) # consistent with tokenize True
See Also
tokenize: Returns the full token ID list. _guard_context: Calls this method to check prompt length.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
model_post_init(__context)
#
Resolve the model path, download if needed, then load the model.
Called automatically by Pydantic after __init__. All validation
has already completed before this method runs; it performs only I/O
(path resolution, optional download, GGUF loading).
See Also
_resolve_model_path: Locates or downloads the GGUF file. _load_model: Loads (or retrieves from cache) the Llama instance.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
tokenize(text)
#
Return the token IDs for text using the loaded model's vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to tokenize. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
List of integer token IDs produced by the model's tokenizer. |
Examples:
- Tokenize a short string and explore the token IDs
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> tokens = llm.tokenize("Hello!") >>> tokens[0] 1 >>> all(t >= 0 for t in tokens) True - Longer text produces more tokens
>>> import os >>> from serapeum.llama_cpp import LlamaCPP >>> from serapeum.llama_cpp.formatters.llama3 import ( ... messages_to_prompt_v3_instruct, ... completion_to_prompt_v3_instruct, ... ) >>> llm = LlamaCPP( ... model_path=os.environ["LLAMA_MODEL_PATH"], ... temperature=0.1, ... max_new_tokens=256, ... context_window=512, ... messages_to_prompt=messages_to_prompt_v3_instruct, ... completion_to_prompt=completion_to_prompt_v3_instruct, ... ) >>> short = llm.tokenize("Hi") >>> long = llm.tokenize("Hello, how are you doing today?") >>> short[0] == long[0] # both start with the BOS token True >>> len(long) > len(short) # more text yields more tokens True
See Also
count_tokens: Returns the token count instead of the full list. _guard_context: Uses token count to validate prompt length.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\llm.py
utils module#
serapeum.llama_cpp.utils
#
Internal utilities for downloading GGUF model files.
This module provides two private helpers used by
:class:~serapeum.llama_cpp.LlamaCPP to resolve a model path before loading:
- :func:
_fetch_model_file— streams a GGUF file from an arbitrary URL with progress reporting and automatic cleanup on failure. - :func:
_fetch_model_file_hf— downloads from HuggingFace Hub using thehuggingface_hublibrary (optional dependency).
These functions are internal — they are not part of the public API.
External callers should use :class:~serapeum.llama_cpp.LlamaCPP directly.
See Also
serapeum.llama_cpp.llm: The LlamaCPP class that consumes these helpers.
formatters module#
serapeum.llama_cpp.formatters.llama2
#
Prompt formatters for Llama 2 Chat and Mistral Instruct models.
Implements the [INST] <<SYS>> … <</SYS>> template described in the
official Llama 2 blog post:
https://huggingface.co/blog/llama2#how-to-prompt-llama-2
This format is compatible with:
- Llama 2 Chat (7B, 13B, 70B)
- Mistral Instruct v0.1 / v0.2
- Any other model trained on the Llama 2 Chat template
Typical usage::
from serapeum.llama_cpp.formatters.llama2 import (
messages_to_prompt,
completion_to_prompt,
)
See Also
serapeum.llama_cpp.formatters.llama3: Formatter for Llama 3 Instruct models.
completion_to_prompt(completion, system_prompt=None)
#
Convert a plain-text completion to Llama 2 Chat single-turn prompt format.
Wraps completion in the [INST] <<SYS>> … <</SYS>> … [/INST] envelope
expected by Llama 2 Chat and Mistral Instruct models for single-turn
(non-chat) text completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completion
|
str
|
The user's instruction or question as plain text. |
required |
system_prompt
|
str | None
|
System-level instruction inserted inside
|
None
|
Returns:
| Type | Description |
|---|---|
str
|
Prompt string in Llama 2 |
str
|
format, ready to be passed to a Llama 2 / Mistral GGUF model. |
Examples:
- Build a prompt with a custom system prompt — explore the template structure
>>> from serapeum.llama_cpp.formatters.llama2 import completion_to_prompt >>> prompt = completion_to_prompt("What is 2+2?", system_prompt="Be brief.") >>> prompt[:10] '<s> [INST]' >>> prompt.rstrip()[-7:] '[/INST]' >>> prompt.split("<</SYS>>")[0].split("<<SYS>>")[1].strip() 'Be brief.' >>> prompt.split("<</SYS>>")[1].split("[/INST]")[0].strip() 'What is 2+2?' - Build a prompt with the default system prompt
See Also
messages_to_prompt: Multi-turn chat variant for the same model family. DEFAULT_SYSTEM_PROMPT: Default system instruction used when system_prompt is None.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\formatters\llama2.py
messages_to_prompt(messages, system_prompt=None)
#
Convert a sequence of chat messages to Llama 2 Chat prompt format.
Reference: https://huggingface.co/blog/llama2#how-to-prompt-llama-2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Sequence[Message]
|
Ordered sequence of chat messages. If the first message has
role SYSTEM it is extracted as the system prompt; otherwise
system_prompt (or |
required |
system_prompt
|
str | None
|
Optional system-level instruction. Ignored when the first message already carries role SYSTEM. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Prompt string in Llama 2 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a USER or ASSISTANT message appears in the wrong position in the alternating sequence. |
Examples:
- Single user message with a custom system prompt — explore the structure
>>> from serapeum.llama_cpp.formatters.llama2 import messages_to_prompt >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [Message(role=MessageRole.USER, chunks=[TextChunk(content="Hello!")])] >>> prompt = messages_to_prompt(messages, system_prompt="Be brief.") >>> prompt[:10] '<s> [INST]' >>> prompt.split("<</SYS>>")[0].split("<<SYS>>")[1].strip() 'Be brief.' >>> prompt.split("[/INST]")[0].split("<</SYS>>")[1].strip() 'Hello!' - Multi-turn conversation — each turn is wrapped in [INST]...[/INST]
>>> from serapeum.llama_cpp.formatters.llama2 import messages_to_prompt >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [ ... Message(role=MessageRole.USER, chunks=[TextChunk(content="What is 2+2?")]), ... Message(role=MessageRole.ASSISTANT, chunks=[TextChunk(content="4")]), ... Message(role=MessageRole.USER, chunks=[TextChunk(content="And 3+3?")]), ... ] >>> prompt = messages_to_prompt(messages, system_prompt="Be brief.") >>> prompt.count("[INST]") 2 >>> prompt.count("[/INST]") 2 - Explicit SYSTEM message in the conversation is extracted as system prompt
>>> from serapeum.llama_cpp.formatters.llama2 import messages_to_prompt >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [ ... Message(role=MessageRole.SYSTEM, chunks=[TextChunk(content="You are terse.")]), ... Message(role=MessageRole.USER, chunks=[TextChunk(content="Hi!")]), ... ] >>> prompt = messages_to_prompt(messages) >>> prompt.split("<</SYS>>")[0].split("<<SYS>>")[1].strip() 'You are terse.'
See Also
completion_to_prompt: Single-turn variant for the same model family. DEFAULT_SYSTEM_PROMPT: Default system instruction used when system_prompt is None.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\formatters\llama2.py
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 | |
serapeum.llama_cpp.formatters.llama3
#
Prompt formatters for Llama 3 Instruct models.
Implements the <|start_header_id|>…<|end_header_id|>…<|eot_id|> template
described in the official Meta Llama 3 documentation:
https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/
This format is compatible with:
- Meta-Llama-3-8B-Instruct
- Meta-Llama-3-70B-Instruct
- Any other model trained on the Llama 3 chat template
Note
<|begin_of_text|> is intentionally omitted because llama-cpp-python
adds it automatically when loading the model.
Typical usage::
from serapeum.llama_cpp.formatters.llama3 import (
messages_to_prompt_v3_instruct,
completion_to_prompt_v3_instruct,
)
See Also
serapeum.llama_cpp.formatters.llama2: Formatter for Llama 2 / Mistral models.
completion_to_prompt_v3_instruct(completion, system_prompt=None)
#
Convert a plain-text completion to Llama 3 Instruct single-turn prompt format.
Wraps completion in the <|start_header_id|>user<|end_header_id|> /
<|eot_id|> envelope expected by Llama 3 Instruct models for single-turn
(non-chat) text completion.
Note
<|begin_of_text|> is intentionally omitted; llama-cpp-python adds
it automatically during model loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completion
|
str
|
The user's instruction or question as plain text. |
required |
system_prompt
|
str | None
|
System-level instruction inserted in the system header
block. Defaults to :data: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Prompt string ending with the |
str
|
|
str
|
prompts the model to generate its reply. |
Examples:
- Build a prompt with a custom system prompt — explore the sections
>>> from serapeum.llama_cpp.formatters.llama3 import completion_to_prompt_v3_instruct >>> prompt = completion_to_prompt_v3_instruct("What is 2+2?", "Be brief.") >>> sections = prompt.split("<|eot_id|>") >>> sections[0].split("<|end_header_id|>")[1].strip() 'Be brief.' >>> sections[1].split("<|end_header_id|>")[1].strip() 'What is 2+2?' >>> prompt.strip().endswith("<|end_header_id|>") True - Build a prompt with the default system prompt
See Also
messages_to_prompt_v3_instruct: Multi-turn chat variant for the same model family. DEFAULT_SYSTEM_PROMPT: Default system instruction used when system_prompt is None.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\formatters\llama3.py
messages_to_prompt_v3_instruct(messages, system_prompt=None)
#
Convert a sequence of chat messages to Llama 3 Instruct format.
Reference: https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/
Note: <|begin_of_text|> is not needed as Llama.cpp appears to add it already.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Sequence[Message]
|
Ordered sequence of chat messages. If the first message has
role SYSTEM it is extracted as the system prompt; otherwise
system_prompt (or |
required |
system_prompt
|
str | None
|
Optional system-level instruction. Ignored when the first message already carries role SYSTEM. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Prompt string in Llama 3 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a USER or ASSISTANT message appears in the wrong position in the alternating sequence. |
Examples:
- Single user message with a custom system prompt — explore the structure
>>> from serapeum.llama_cpp.formatters.llama3 import messages_to_prompt_v3_instruct >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [Message(role=MessageRole.USER, chunks=[TextChunk(content="Hello!")])] >>> prompt = messages_to_prompt_v3_instruct(messages, system_prompt="Be brief.") >>> prompt.split("<|eot_id|>")[0].split("<|end_header_id|>")[1].strip() 'Be brief.' >>> prompt.split("<|eot_id|>")[1].split("<|end_header_id|>")[1].strip() 'Hello!' - Multi-turn conversation — prompt ends with the assistant header
>>> from serapeum.llama_cpp.formatters.llama3 import messages_to_prompt_v3_instruct >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [ ... Message(role=MessageRole.USER, chunks=[TextChunk(content="What is 2+2?")]), ... Message(role=MessageRole.ASSISTANT, chunks=[TextChunk(content="4")]), ... Message(role=MessageRole.USER, chunks=[TextChunk(content="And 3+3?")]), ... ] >>> prompt = messages_to_prompt_v3_instruct(messages, system_prompt="Be brief.") >>> prompt.count("<|eot_id|>") 4 >>> prompt.strip().endswith("<|end_header_id|>") True - Explicit SYSTEM message is extracted as system prompt
>>> from serapeum.llama_cpp.formatters.llama3 import messages_to_prompt_v3_instruct >>> from serapeum.core.llms import Message, MessageRole, TextChunk >>> messages = [ ... Message(role=MessageRole.SYSTEM, chunks=[TextChunk(content="You are terse.")]), ... Message(role=MessageRole.USER, chunks=[TextChunk(content="Hi!")]), ... ] >>> prompt = messages_to_prompt_v3_instruct(messages) >>> prompt.split("<|eot_id|>")[0].split("<|end_header_id|>")[1].strip() 'You are terse.'
See Also
completion_to_prompt_v3_instruct: Single-turn variant for the same model family. DEFAULT_SYSTEM_PROMPT: Default system instruction used when system_prompt is None.
Source code in libs\providers\llama-cpp\src\serapeum\llama_cpp\formatters\llama3.py
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 | |