|
14 | 14 | so it must be a deliberate choice rather than a silent default. |
15 | 15 | """ |
16 | 16 |
|
| 17 | +import json |
17 | 18 | import logging |
18 | 19 | from typing import Any, Optional |
19 | 20 |
|
|
25 | 26 | _DEFAULT_SPECIAL_TOKENS = ["<|im_end|>", "<|endoftext|>", "<|eot_id|>", "<|end|>"] |
26 | 27 |
|
27 | 28 |
|
| 29 | +def _decode_tool_call_arguments(messages: list[dict[str, Any]]) -> None: |
| 30 | + """In-place: parse each tool call's ``function.arguments`` from a JSON string |
| 31 | + into an object. |
| 32 | +
|
| 33 | + OpenAI sends assistant tool-call arguments as a JSON-encoded string, but HF |
| 34 | + chat templates expect a mapping (e.g. Qwen renders ``arguments|items`` into |
| 35 | + ``<parameter=…>`` tags). Without this, a multi-turn tool conversation makes |
| 36 | + the template raise "Can only get item pairs from a mapping". Left as-is if |
| 37 | + the value isn't valid JSON, so a template that wants the raw string still works. |
| 38 | + """ |
| 39 | + for m in messages: |
| 40 | + for tc in m.get("tool_calls") or []: |
| 41 | + fn = tc.get("function") |
| 42 | + if not isinstance(fn, dict): |
| 43 | + continue |
| 44 | + args = fn.get("arguments") |
| 45 | + if isinstance(args, str): |
| 46 | + try: |
| 47 | + fn["arguments"] = json.loads(args) |
| 48 | + except (ValueError, TypeError): |
| 49 | + pass |
| 50 | + |
| 51 | + |
28 | 52 | class ChatTemplate: |
29 | 53 | def __init__( |
30 | 54 | self, |
@@ -69,8 +93,10 @@ def render( |
69 | 93 | ) -> str: |
70 | 94 | kwargs = {**self._defaults, **(template_kwargs or {})} |
71 | 95 | if self._hf is not None: |
| 96 | + dumped = [m.model_dump(exclude_none=True) for m in messages] |
| 97 | + _decode_tool_call_arguments(dumped) |
72 | 98 | return self._hf.apply_chat_template( |
73 | | - [m.model_dump(exclude_none=True) for m in messages], |
| 99 | + dumped, |
74 | 100 | tools=tools, |
75 | 101 | add_generation_prompt=True, |
76 | 102 | tokenize=False, |
|
0 commit comments