Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- fix(chat_format): keep the text of list-typed message content in the built-in chat formats by @sohailshk in #2448
- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
34 changes: 22 additions & 12 deletions llama_cpp/llama_chat_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -872,13 +872,28 @@ def guess_chat_format_from_gguf_metadata(metadata: Dict[str, str]) -> Optional[s
# TODO: Replace these with jinja2 templates


def _content_text(content: Any) -> Optional[str]:
"""Return the text of message content, joining the text parts of a list."""
if isinstance(content, str):
return content
if isinstance(content, list):
texts = [
part.get("text") or ""
for part in content
if isinstance(part, dict) and part.get("type") == "text"
]
if texts:
return "".join(texts)
return None


def _get_system_message(
messages: List[llama_types.ChatCompletionRequestMessage],
) -> str:
"""Get the first system message."""
for message in messages:
if message["role"] == "system":
return message["content"] or ""
return _content_text(message["content"]) or ""
return ""


Expand All @@ -891,9 +906,7 @@ def _map_roles(
for message in messages:
role = message["role"]
if role in role_map:
content: str | None = (
message["content"] if isinstance(message["content"], str) else None
)
content: str | None = _content_text(message["content"])
output.append((role_map[role], content))
return output

Expand Down Expand Up @@ -1364,14 +1377,11 @@ def format_mistral_instruct(
stop = eos
prompt = ""
for message in messages:
if (
message["role"] == "user"
and message["content"] is not None
and isinstance(message["content"], str)
):
prompt += "[INST] " + message["content"]
elif message["role"] == "assistant" and message["content"] is not None:
prompt += " [/INST]" + message["content"] + eos
content = _content_text(message["content"])
if message["role"] == "user" and content is not None:
prompt += "[INST] " + content
elif message["role"] == "assistant" and content is not None:
prompt += " [/INST]" + content + eos
prompt += " [/INST]"
return ChatFormatterResponse(prompt=prompt, stop=stop)

Expand Down
37 changes: 37 additions & 0 deletions tests/test_llama_chat_format.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json

import jinja2
import pytest

from llama_cpp import (
ChatCompletionRequestUserMessage,
Expand Down Expand Up @@ -37,6 +38,42 @@ def test_mistral_instruct():
assert prompt == reference


@pytest.mark.parametrize(
"formatter",
[
llama_chat_format.format_llama2,
llama_chat_format.format_llama3,
llama_chat_format.format_chatml,
llama_chat_format.format_zephyr,
llama_chat_format.format_mistral_instruct,
llama_chat_format.format_gemma,
],
)
def test_chat_formatters_keep_text_of_content_parts(formatter):
text_messages = [
{"role": "system", "content": "Be brief."},
{"role": "user", "content": "Hello there"},
{"role": "assistant", "content": "Hi"},
{"role": "user", "content": "Bye"},
]
part_messages = [
{"role": "system", "content": [{"type": "text", "text": "Be brief."}]},
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64,"}},
{"type": "text", "text": "Hello "},
{"type": "text", "text": "there"},
],
},
{"role": "assistant", "content": [{"type": "text", "text": "Hi"}]},
{"role": "user", "content": [{"type": "text", "text": "Bye"}]},
]
prompt = formatter(messages=part_messages).prompt
assert "Hello there" in prompt
assert prompt == formatter(messages=text_messages).prompt


mistral_7b_tokenizer_config = """{
"add_bos_token": true,
"add_eos_token": false,
Expand Down