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
9 changes: 8 additions & 1 deletion src/llamafactory/data/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ class Template:
preserve_thinking: bool
mm_plugin: "BasePlugin"

def _format_system_content(self, system: str, tool_text: str) -> str:
if tool_text and self.format_tools.tool_format == "qwen3_5":
tool_text = tool_text.lstrip("\n")
return tool_text + ("\n\n" + system if system else "")

return system + tool_text
Comment on lines +60 to +65

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To ensure robust defensive programming, _format_system_content should handle cases where system might be None (e.g., if self.default_system is not set or is set to None in custom templates). Accepting Optional[str] and defaulting to an empty string prevents potential runtime TypeError during string concatenation.

Suggested change
def _format_system_content(self, system: str, tool_text: str) -> str:
if tool_text and self.format_tools.tool_format == "qwen3_5":
tool_text = tool_text.lstrip("\n")
return tool_text + ("\n\n" + system if system else "")
return system + tool_text
def _format_system_content(self, system: Optional[str], tool_text: str) -> str:
system = system or ""
if tool_text and self.format_tools.tool_format == "qwen3_5":
tool_text = tool_text.lstrip("\n")
return tool_text + ("\n\n" + system if system else "")
return system + tool_text


def encode_oneturn(
self,
tokenizer: "PreTrainedTokenizer",
Expand Down Expand Up @@ -150,7 +157,7 @@ def _encode(
elements += self.format_prefix.apply()
if system or tools:
tool_text = self.format_tools.apply(content=tools)[0] if tools else ""
elements += self.format_system.apply(content=(system + tool_text))
elements += self.format_system.apply(content=self._format_system_content(system, tool_text))

if message["role"] == Role.USER:
elements += self.format_user.apply(content=message["content"], idx=str(i // 2))
Expand Down
21 changes: 21 additions & 0 deletions tests/data/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,27 @@ def test_qwen3_template(cot_messages: bool):
_check_template("Qwen/Qwen3-8B", "qwen3", prompt_str, answer_str, messages=messages)


@pytest.mark.runs_on(["cpu", "mps"])
def test_qwen35_tools_precede_system_content():
tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA3)
template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template="qwen3_5_nothink"))
tools = (
'[{"type":"function","function":{"name":"lookup_quote","description":"Quote lookup.",'
'"parameters":{"type":"object","properties":{},"required":[]}}}]'
)
prompt_ids, _ = template.encode_oneturn(
tokenizer,
[
{"role": "user", "content": "Check the quote."},
{"role": "assistant", "content": "Done."},
],
system="You are a market data assistant.",
tools=tools,
)
prompt_str = tokenizer.decode(prompt_ids)
assert prompt_str.index("# Tools") < prompt_str.index("You are a market data assistant.")


@pytest.mark.runs_on(["cpu", "mps"])
def test_parse_llama3_template():
tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA3)
Expand Down