encoding_dsv4.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. """
  2. DeepSeek-V4 Text and Vision Encoding
  3. A self-contained implementation for encoding/decoding DeepSeek-V4 chat messages
  4. with tool calling, thinking mode, quick instruction tasks, and image content blocks.
  5. """
  6. from typing import Any, Dict, List, Union, Optional, Tuple
  7. import copy
  8. import json
  9. import re
  10. # ============================================================
  11. # Special Tokens
  12. # ============================================================
  13. bos_token: str = "<|begin▁of▁sentence|>"
  14. eos_token: str = "<|end▁of▁sentence|>"
  15. thinking_start_token: str = "<think>"
  16. thinking_end_token: str = "</think>"
  17. dsml_token: str = "|DSML|"
  18. USER_SP_TOKEN = "<|User|>"
  19. ASSISTANT_SP_TOKEN = "<|Assistant|>"
  20. LATEST_REMINDER_SP_TOKEN = "<|latest_reminder|>"
  21. IMAGE_PLACEHOLDER = "<|deepseek_image|>"
  22. IMAGE_TAG_PATTERN = re.compile(r"<image>(.*?)</image>", re.DOTALL)
  23. # Task special tokens for internal classification tasks
  24. DS_TASK_SP_TOKENS = {
  25. "action": "<|action|>",
  26. "query": "<|query|>",
  27. "authority": "<|authority|>",
  28. "domain": "<|domain|>",
  29. "title": "<|title|>",
  30. "read_url": "<|read_url|>",
  31. }
  32. VALID_TASKS = set(DS_TASK_SP_TOKENS.keys())
  33. # ============================================================
  34. # Templates
  35. # ============================================================
  36. system_msg_template: str = "{content}"
  37. user_msg_template: str = "{content}"
  38. latest_reminder_msg_template: str = "{content}"
  39. assistant_msg_template: str = "{reasoning}{content}{tool_calls}" + eos_token
  40. assistant_msg_wo_eos_template: str = "{reasoning}{content}{tool_calls}"
  41. thinking_template: str = "{reasoning_content}"
  42. response_format_template: str = (
  43. "## Response Format:\n\nYou MUST strictly adhere to the following schema to reply:\n{schema}"
  44. )
  45. tool_call_template: str = (
  46. "<{dsml_token}invoke name=\"{name}\">\n{arguments}\n</{dsml_token}invoke>"
  47. )
  48. tool_calls_template = (
  49. "<{dsml_token}{tc_block_name}>\n{tool_calls}\n</{dsml_token}{tc_block_name}>"
  50. )
  51. tool_calls_block_name: str = "tool_calls"
  52. tool_output_template: str = (
  53. "<tool_result>{content}</tool_result>"
  54. )
  55. # Reasoning effort levels. In thinking mode, the prompt for the selected level is
  56. # prepended at the very beginning of the conversation. `low` is the default and
  57. # adds nothing.
  58. REASONING_EFFORT_PROMPTS: Dict[str, str] = {
  59. "low": "",
  60. "high": (
  61. "Reasoning Effort: Absolute maximum with no shortcuts permitted.\n"
  62. "You MUST be very thorough in your thinking and comprehensively decompose the problem to resolve the root cause, rigorously stress-testing your logic against all potential paths, edge cases, and adversarial scenarios.\n"
  63. "Explicitly write out your entire deliberation process, documenting every intermediate step, considered alternative, and rejected hypothesis to ensure absolutely no assumption is left unchecked.\n\n"
  64. ),
  65. "max": (
  66. "Reasoning Effort: Beyond maximum — exhaustive, relentless, and uncompromising.\n"
  67. "You MUST reason with the utmost depth and rigor, leaving absolutely nothing to chance: exhaustively decompose the problem into its most fundamental components, trace every causal chain to its root, and resolve the underlying cause rather than any surface symptom.\n"
  68. "Do not stop reasoning until you have independently verified the solution from multiple angles and are certain that no assumption remains unchecked and no error remains undiscovered.\n\n"
  69. ),
  70. }
  71. DEFAULT_REASONING_EFFORT = "low"
  72. TOOLS_TEMPLATE = """## Tools
  73. You have access to a set of tools to help answer the user's question. You can invoke tools by writing a "<{dsml_token}tool_calls>" block like the following:
  74. <{dsml_token}tool_calls>
  75. <{dsml_token}invoke name="$TOOL_NAME">
  76. <{dsml_token}parameter name="$PARAMETER_NAME" string="true|false">$PARAMETER_VALUE</{dsml_token}parameter>
  77. ...
  78. </{dsml_token}invoke>
  79. <{dsml_token}invoke name="$TOOL_NAME2">
  80. ...
  81. </{dsml_token}invoke>
  82. </{dsml_token}tool_calls>
  83. String parameters should be specified as is and set `string="true"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string="false"`.
  84. If thinking_mode is enabled (triggered by {thinking_start_token}), you MUST output your complete reasoning inside {thinking_start_token}...{thinking_end_token} BEFORE any tool calls or final response.
  85. Otherwise, output directly after {thinking_end_token} with tool calls or final response.
  86. ### Available Tool Schemas
  87. {tool_schemas}
  88. You MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.
  89. """
  90. # ============================================================
  91. # Utility Functions
  92. # ============================================================
  93. def to_json(value: Any) -> str:
  94. """Serialize a value to JSON string."""
  95. try:
  96. return json.dumps(value, ensure_ascii=False)
  97. except:
  98. return json.dumps(value, ensure_ascii=True)
  99. def tools_from_openai_format(tools):
  100. """Extract function definitions from OpenAI-format tool list."""
  101. return [tool["function"] for tool in tools]
  102. def tool_calls_from_openai_format(tool_calls):
  103. """Convert OpenAI-format tool calls to internal format."""
  104. return [
  105. {
  106. "name": tool_call["function"]["name"],
  107. "arguments": tool_call["function"]["arguments"],
  108. }
  109. for tool_call in tool_calls
  110. ]
  111. def tool_calls_to_openai_format(tool_calls):
  112. """Convert internal tool calls to OpenAI format."""
  113. return [
  114. {
  115. "type": "function",
  116. "function": {
  117. "name": tool_call["name"],
  118. "arguments": tool_call["arguments"],
  119. }
  120. }
  121. for tool_call in tool_calls
  122. ]
  123. def encode_arguments_to_dsml(tool_call: Dict[str, str]) -> str:
  124. """
  125. Encode tool call arguments into DSML parameter format.
  126. Args:
  127. tool_call: Dict with "name" and "arguments" (JSON string) keys.
  128. Returns:
  129. DSML-formatted parameter string.
  130. """
  131. p_dsml_template = '<{dsml_token}parameter name="{key}" string="{is_str}">{value}</{dsml_token}parameter>'
  132. P_dsml_strs = []
  133. try:
  134. arguments = json.loads(tool_call["arguments"])
  135. except Exception as err:
  136. arguments = {"arguments": tool_call["arguments"]}
  137. for k, v in arguments.items():
  138. p_dsml_str = p_dsml_template.format(
  139. dsml_token=dsml_token,
  140. key=k,
  141. is_str="true" if isinstance(v, str) else "false",
  142. value=v if isinstance(v, str) else to_json(v),
  143. )
  144. P_dsml_strs.append(p_dsml_str)
  145. return "\n".join(P_dsml_strs)
  146. def decode_dsml_to_arguments(tool_name: str, tool_args: Dict[str, Tuple[str, str]]) -> Dict[str, str]:
  147. """
  148. Decode DSML parameters back to a tool call dict.
  149. Args:
  150. tool_name: Name of the tool.
  151. tool_args: Dict mapping param_name -> (value, is_string_flag).
  152. Returns:
  153. Dict with "name" and "arguments" (JSON string) keys.
  154. """
  155. def _decode_value(key: str, value: str, string: str):
  156. if string == "true":
  157. value = to_json(value)
  158. return f"{to_json(key)}: {value}"
  159. tool_args_json = "{" + ", ".join([_decode_value(k, v, string=is_str) for k, (v, is_str) in tool_args.items()]) + "}"
  160. return dict(name=tool_name, arguments=tool_args_json)
  161. def render_tools(tools: List[Dict[str, Union[str, Dict[str, Any]]]]) -> str:
  162. """
  163. Render tool schemas into the system prompt format.
  164. Args:
  165. tools: List of tool schema dicts (each with name, description, parameters).
  166. Returns:
  167. Formatted tools section string.
  168. """
  169. tools_json = [to_json(t) for t in tools]
  170. return TOOLS_TEMPLATE.format(
  171. tool_schemas="\n".join(tools_json),
  172. dsml_token=dsml_token,
  173. thinking_start_token=thinking_start_token,
  174. thinking_end_token=thinking_end_token,
  175. )
  176. def find_last_user_index(messages: List[Dict[str, Any]]) -> int:
  177. """Find the index of the last user/developer message."""
  178. last_user_index = -1
  179. for idx in range(len(messages) - 1, -1, -1):
  180. if messages[idx].get("role") in ["user", "developer"]:
  181. last_user_index = idx
  182. break
  183. return last_user_index
  184. # ============================================================
  185. # Message Rendering
  186. # ============================================================
  187. def render_message(index: int, messages: List[Dict[str, Any]], thinking_mode: str, drop_thinking: bool = True, reasoning_effort: Optional[str] = None) -> str:
  188. """
  189. Render a single message at the given index into its encoded string form.
  190. This is the core function that converts each message in the conversation
  191. into the DeepSeek-V4 format.
  192. Args:
  193. index: Index of the message to render.
  194. messages: Full list of messages in the conversation.
  195. thinking_mode: Either "chat" or "thinking".
  196. drop_thinking: Whether to drop reasoning content from earlier turns.
  197. reasoning_effort: Reasoning effort level, one of "low", "high", "max".
  198. None is treated as "low".
  199. Returns:
  200. Encoded string for this message.
  201. """
  202. assert 0 <= index < len(messages)
  203. assert thinking_mode in ["chat", "thinking"], f"Invalid thinking_mode `{thinking_mode}`"
  204. prompt = ""
  205. msg = messages[index]
  206. last_user_idx = find_last_user_index(messages)
  207. role = msg.get("role")
  208. content = msg.get("content")
  209. tools = msg.get("tools")
  210. response_format = msg.get("response_format")
  211. tool_calls = msg.get("tool_calls")
  212. reasoning_content = msg.get("reasoning_content")
  213. wo_eos = msg.get("wo_eos", False)
  214. if tools:
  215. tools = tools_from_openai_format(tools)
  216. if tool_calls:
  217. tool_calls = tool_calls_from_openai_format(tool_calls)
  218. # Reasoning effort prefix (only at index 0 in thinking mode; "low" adds nothing)
  219. reasoning_effort = reasoning_effort or DEFAULT_REASONING_EFFORT
  220. assert reasoning_effort in REASONING_EFFORT_PROMPTS, \
  221. f"Invalid reasoning effort: {reasoning_effort}, expected one of {list(REASONING_EFFORT_PROMPTS)}"
  222. if index == 0 and thinking_mode == "thinking":
  223. prompt += REASONING_EFFORT_PROMPTS[reasoning_effort]
  224. if role == "system":
  225. prompt += system_msg_template.format(content=content or "")
  226. if tools:
  227. prompt += "\n\n" + render_tools(tools)
  228. if response_format:
  229. prompt += "\n\n" + response_format_template.format(schema=to_json(response_format))
  230. elif role == "developer":
  231. assert content, f"Invalid message for role `{role}`: {msg}"
  232. content_developer = USER_SP_TOKEN
  233. content_developer += content
  234. if tools:
  235. content_developer += "\n\n" + render_tools(tools)
  236. if response_format:
  237. content_developer += "\n\n" + response_format_template.format(schema=to_json(response_format))
  238. prompt += user_msg_template.format(content=content_developer)
  239. elif role == "user":
  240. prompt += USER_SP_TOKEN
  241. # Handle content blocks (tool results mixed with text)
  242. content_blocks = msg.get("content_blocks")
  243. if content_blocks:
  244. parts = []
  245. for block in content_blocks:
  246. block_type = block.get("type")
  247. if block_type == "text":
  248. parts.append(block.get("text", ""))
  249. elif block_type == "tool_result":
  250. tool_content = block.get("content", "")
  251. if isinstance(tool_content, list):
  252. text_parts = []
  253. for b in tool_content:
  254. if b.get("type") == "text":
  255. text_parts.append(b.get("text", ""))
  256. else:
  257. text_parts.append(f"[Unsupported {b.get('type')}]")
  258. tool_content = "\n\n".join(text_parts)
  259. parts.append(tool_output_template.format(content=tool_content))
  260. else:
  261. parts.append(f"[Unsupported {block_type}]")
  262. prompt += "\n\n".join(parts)
  263. else:
  264. prompt += content or ""
  265. elif role == "latest_reminder":
  266. prompt += LATEST_REMINDER_SP_TOKEN + latest_reminder_msg_template.format(content=content)
  267. elif role == "tool":
  268. raise NotImplementedError("deepseek_v4 merges tool messages into user; please preprocess with merge_tool_messages()")
  269. elif role == "assistant":
  270. thinking_part = ""
  271. tc_content = ""
  272. if tool_calls:
  273. tc_list = [
  274. tool_call_template.format(
  275. dsml_token=dsml_token,
  276. name=tc.get("name"),
  277. arguments=encode_arguments_to_dsml(tc)
  278. )
  279. for tc in tool_calls
  280. ]
  281. tc_content += '\n\n' + tool_calls_template.format(
  282. dsml_token=dsml_token,
  283. tool_calls="\n".join(tc_list),
  284. tc_block_name=tool_calls_block_name,
  285. )
  286. summary_content = content or ""
  287. rc = reasoning_content or ""
  288. # Check if previous message has a task - if so, this is a task output (no thinking)
  289. prev_has_task = index - 1 >= 0 and messages[index - 1].get("task") is not None
  290. if thinking_mode == "thinking" and not prev_has_task:
  291. if not drop_thinking or index > last_user_idx:
  292. thinking_part = thinking_template.format(reasoning_content=rc) + thinking_end_token
  293. else:
  294. thinking_part = ""
  295. if wo_eos:
  296. prompt += assistant_msg_wo_eos_template.format(
  297. reasoning=thinking_part,
  298. content=summary_content,
  299. tool_calls=tc_content,
  300. )
  301. else:
  302. prompt += assistant_msg_template.format(
  303. reasoning=thinking_part,
  304. content=summary_content,
  305. tool_calls=tc_content,
  306. )
  307. else:
  308. raise NotImplementedError(f"Unknown role: {role}")
  309. # Append transition tokens based on what follows
  310. if index + 1 < len(messages) and messages[index + 1].get("role") not in ["assistant", "latest_reminder"]:
  311. return prompt
  312. task = messages[index].get("task")
  313. if task is not None:
  314. # Task special token for internal classification tasks
  315. assert task in VALID_TASKS, f"Invalid task: '{task}'. Valid tasks are: {list(VALID_TASKS)}"
  316. task_sp_token = DS_TASK_SP_TOKENS[task]
  317. if task != "action":
  318. # Non-action tasks: append task sp token directly after the message
  319. prompt += task_sp_token
  320. else:
  321. # Action task: append Assistant + thinking token + action sp token
  322. prompt += ASSISTANT_SP_TOKEN
  323. prompt += thinking_end_token if thinking_mode != "thinking" else thinking_start_token
  324. prompt += task_sp_token
  325. elif messages[index].get("role") in ["user", "developer"]:
  326. # Normal generation: append Assistant + thinking token
  327. prompt += ASSISTANT_SP_TOKEN
  328. if not drop_thinking and thinking_mode == "thinking":
  329. prompt += thinking_start_token
  330. elif drop_thinking and thinking_mode == "thinking" and index >= last_user_idx:
  331. prompt += thinking_start_token
  332. else:
  333. prompt += thinking_end_token
  334. return prompt
  335. # ============================================================
  336. # Preprocessing
  337. # ============================================================
  338. def merge_tool_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  339. """
  340. Merge tool messages into the preceding user message using content_blocks format.
  341. DeepSeek-V4 does not have a standalone "tool" role; instead, tool results
  342. are encoded as <tool_result> blocks within user messages.
  343. This function converts a standard OpenAI-format conversation (with separate
  344. "tool" role messages) into V4 format where tool results are merged into
  345. user messages.
  346. Args:
  347. messages: List of message dicts in OpenAI format.
  348. Returns:
  349. Processed message list with tool messages merged into user messages.
  350. """
  351. merged: List[Dict[str, Any]] = []
  352. for msg in messages:
  353. msg = copy.deepcopy(msg)
  354. role = msg.get("role")
  355. if role == "tool":
  356. # Convert tool message to a user message with tool_result block
  357. tool_block = {
  358. "type": "tool_result",
  359. "tool_use_id": msg.get("tool_call_id", ""),
  360. "content": msg.get("content", ""),
  361. }
  362. # Merge into previous message if it's already a user (merged tool)
  363. if merged and merged[-1].get("role") == "user" and "content_blocks" in merged[-1]:
  364. merged[-1]["content_blocks"].append(tool_block)
  365. else:
  366. merged.append({
  367. "role": "user",
  368. "content_blocks": [tool_block],
  369. })
  370. elif role == "user":
  371. content_blocks = msg.get("content_blocks")
  372. if content_blocks is None:
  373. content_blocks = [{"type": "text", "text": msg.get("content", "")}]
  374. if merged and merged[-1].get("role") == "user" and "content_blocks" in merged[-1] and merged[-1].get("task") is None:
  375. merged[-1]["content_blocks"].extend(content_blocks)
  376. else:
  377. # Preserve structured content and all message-level metadata.
  378. new_msg = msg
  379. new_msg["content_blocks"] = content_blocks
  380. merged.append(new_msg)
  381. else:
  382. merged.append(msg)
  383. return merged
  384. def sort_tool_results_by_call_order(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  385. """
  386. Sort tool_result blocks within user messages by the order of tool_calls
  387. in the preceding assistant message.
  388. Args:
  389. messages: Preprocessed message list (after merge_tool_messages).
  390. Returns:
  391. Message list with sorted tool result blocks.
  392. """
  393. last_tool_call_order: Dict[str, int] = {}
  394. for msg in messages:
  395. role = msg.get("role")
  396. if role == "assistant" and msg.get("tool_calls"):
  397. last_tool_call_order = {}
  398. for idx, tc in enumerate(msg["tool_calls"]):
  399. tc_id = tc.get("id") or tc.get("function", {}).get("id", "")
  400. if tc_id:
  401. last_tool_call_order[tc_id] = idx
  402. elif role == "user" and msg.get("content_blocks"):
  403. tool_blocks = [b for b in msg["content_blocks"] if b.get("type") == "tool_result"]
  404. if len(tool_blocks) > 1 and last_tool_call_order:
  405. sorted_blocks = sorted(
  406. tool_blocks,
  407. key=lambda b: last_tool_call_order.get(b.get("tool_use_id", ""), 0)
  408. )
  409. sorted_idx = 0
  410. new_blocks = []
  411. for block in msg["content_blocks"]:
  412. if block.get("type") == "tool_result":
  413. new_blocks.append(sorted_blocks[sorted_idx])
  414. sorted_idx += 1
  415. else:
  416. new_blocks.append(block)
  417. msg["content_blocks"] = new_blocks
  418. return messages
  419. # ============================================================
  420. # Main Encoding Function
  421. # ============================================================
  422. def _encode_messages_text(
  423. messages: List[Dict[str, Any]],
  424. thinking_mode: str,
  425. context: Optional[List[Dict[str, Any]]] = None,
  426. drop_thinking: bool = True,
  427. add_default_bos_token: bool = True,
  428. reasoning_effort: Optional[str] = None,
  429. ) -> str:
  430. """
  431. Encode a list of messages into the DeepSeek-V4 prompt format.
  432. This is the main entry point for encoding conversations. It handles:
  433. - BOS token insertion
  434. - Thinking mode with optional reasoning content dropping
  435. - Tool message merging into user messages
  436. - Multi-turn conversation context
  437. Args:
  438. messages: List of message dicts to encode.
  439. thinking_mode: Either "chat" or "thinking".
  440. context: Optional preceding context messages (already encoded prefix).
  441. drop_thinking: If True, drop reasoning_content from earlier assistant turns
  442. (only keep reasoning for messages after the last user message).
  443. add_default_bos_token: Whether to prepend BOS token at conversation start.
  444. reasoning_effort: Reasoning effort level, one of "low", "high", "max".
  445. Only takes effect in thinking mode. None is treated as "low".
  446. Returns:
  447. The encoded prompt string.
  448. """
  449. context = context if context else []
  450. # Preprocess: merge tool messages and sort tool results
  451. messages = merge_tool_messages(messages)
  452. messages = sort_tool_results_by_call_order(context + messages)[len(context):]
  453. if context:
  454. context = merge_tool_messages(context)
  455. context = sort_tool_results_by_call_order(context)
  456. full_messages = context + messages
  457. prompt = bos_token if add_default_bos_token and len(context) == 0 else ""
  458. # Resolve drop_thinking: if any message has tools defined, don't drop thinking
  459. effective_drop_thinking = drop_thinking
  460. if any(m.get("tools") for m in full_messages):
  461. effective_drop_thinking = False
  462. if thinking_mode == "thinking" and effective_drop_thinking:
  463. full_messages = _drop_thinking_messages(full_messages)
  464. # After dropping, recalculate how many messages to render
  465. # (context may have shrunk too)
  466. num_to_render = len(full_messages) - len(_drop_thinking_messages(context))
  467. context_len = len(full_messages) - num_to_render
  468. else:
  469. num_to_render = len(messages)
  470. context_len = len(context)
  471. for idx in range(num_to_render):
  472. prompt += render_message(
  473. idx + context_len,
  474. full_messages,
  475. thinking_mode=thinking_mode,
  476. drop_thinking=effective_drop_thinking,
  477. reasoning_effort=reasoning_effort,
  478. )
  479. return prompt
  480. def _drop_thinking_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  481. """
  482. Drop reasoning_content and non-essential messages before the last user message.
  483. Behavior:
  484. - Messages with role in ["user", "system", "tool", "latest_reminder"] are always kept.
  485. - Messages at or after the last user index are always kept.
  486. - Assistant messages before the last user get reasoning_content removed.
  487. - Developer messages before the last user are dropped entirely.
  488. """
  489. last_user_idx = find_last_user_index(messages)
  490. result = []
  491. keep_roles = {"user", "system", "tool", "latest_reminder", "direct_search_results"}
  492. for idx, msg in enumerate(messages):
  493. role = msg.get("role")
  494. if role in keep_roles or idx >= last_user_idx:
  495. result.append(msg)
  496. elif role == "assistant":
  497. msg = copy.copy(msg)
  498. msg.pop("reasoning_content", None)
  499. result.append(msg)
  500. # developer and other roles before last_user_idx are dropped
  501. return result
  502. # ============================================================
  503. # Vision Message Preprocessing
  504. # ============================================================
  505. def parse_tagged_text(text: str) -> Union[str, List[Dict[str, Any]]]:
  506. """Convert ``<image>path</image>`` text into standard content blocks."""
  507. matches = list(IMAGE_TAG_PATTERN.finditer(text))
  508. remaining = IMAGE_TAG_PATTERN.sub("", text)
  509. if "<image>" in remaining or "</image>" in remaining:
  510. raise ValueError("Malformed <image>path</image> tag")
  511. if not matches:
  512. return text
  513. blocks: List[Dict[str, Any]] = []
  514. cursor = 0
  515. for match in matches:
  516. if match.start() > cursor:
  517. blocks.append({"type": "text", "text": text[cursor:match.start()]})
  518. path = match.group(1)
  519. if not path:
  520. raise ValueError("Image path must not be empty")
  521. blocks.append({
  522. "type": "image_url",
  523. "image_url": {"url": path},
  524. })
  525. cursor = match.end()
  526. if cursor < len(text):
  527. blocks.append({"type": "text", "text": text[cursor:]})
  528. return blocks
  529. def _is_image_block(block: Dict[str, Any]) -> bool:
  530. """Return whether a content block is an OpenAI/Anthropic/internal image."""
  531. return isinstance(block, dict) and block.get("type") in ("image", "image_url")
  532. def _extract_image(block: Dict[str, Any]) -> Dict[str, Any]:
  533. """Normalize a supported image block into an internal image record."""
  534. record: Dict[str, Any] = {"type": "image"}
  535. if block.get("type") == "image_url":
  536. image_url = block.get("image_url")
  537. if isinstance(image_url, str):
  538. record["url"] = image_url
  539. else:
  540. record["url"] = (image_url or {}).get("url", "")
  541. else:
  542. for key in ("source", "url", "data"):
  543. if key in block:
  544. record[key] = block[key]
  545. if not any(record.get(key) for key in ("source", "url", "data")):
  546. raise ValueError("Image block does not contain a valid source")
  547. return record
  548. def _process_image_blocks(
  549. blocks: List[Any], image_placeholder: str = IMAGE_PLACEHOLDER
  550. ) -> Tuple[List[Any], List[Dict[str, Any]]]:
  551. """Replace image blocks and collect their records in one ordered traversal."""
  552. new_blocks: List[Any] = []
  553. images: List[Dict[str, Any]] = []
  554. for block in blocks:
  555. if not isinstance(block, dict):
  556. new_blocks.append(block)
  557. continue
  558. if _is_image_block(block):
  559. new_blocks.append({"type": "text", "text": image_placeholder})
  560. images.append(_extract_image(block))
  561. elif block.get("type") == "tool_result" and isinstance(block.get("content"), list):
  562. block = copy.copy(block)
  563. block["content"], nested_images = _process_image_blocks(
  564. block["content"], image_placeholder)
  565. new_blocks.append(block)
  566. images.extend(nested_images)
  567. elif block.get("type") == "text":
  568. text = block.get("text") or ""
  569. if IMAGE_PLACEHOLDER in text:
  570. raise ValueError(
  571. f"Text block contains image placeholder '{IMAGE_PLACEHOLDER}': "
  572. f"'{text[:100]}'. Images should be separate content blocks."
  573. )
  574. new_blocks.append(block)
  575. else:
  576. new_blocks.append(block)
  577. return new_blocks, images
  578. def _validate_no_image_sp_tokens(msg: Dict[str, Any]) -> None:
  579. """Reject user-supplied image placeholder tokens in textual fields."""
  580. content = msg.get("content")
  581. if isinstance(content, str) and IMAGE_PLACEHOLDER in content:
  582. raise ValueError(
  583. f"Message content contains image special token '{IMAGE_PLACEHOLDER}'. "
  584. "Images should be provided as image content blocks."
  585. )
  586. reasoning_content = msg.get("reasoning_content")
  587. if isinstance(reasoning_content, str) and IMAGE_PLACEHOLDER in reasoning_content:
  588. raise ValueError(
  589. f"reasoning_content contains image special token '{IMAGE_PLACEHOLDER}'"
  590. )
  591. def process_image_messages(
  592. messages: List[Dict[str, Any]],
  593. ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
  594. """Normalize image blocks and return their records in prompt order."""
  595. processed: List[Dict[str, Any]] = []
  596. images: List[Dict[str, Any]] = []
  597. for msg in messages:
  598. msg = copy.deepcopy(msg)
  599. _validate_no_image_sp_tokens(msg)
  600. if isinstance(msg.get("content"), list) and "content_blocks" not in msg:
  601. msg["content_blocks"] = msg.pop("content")
  602. if msg.get("content_blocks"):
  603. msg["content_blocks"], message_images = _process_image_blocks(
  604. msg["content_blocks"])
  605. images.extend(message_images)
  606. if not isinstance(msg.get("content"), str):
  607. texts = [
  608. block.get("text", "")
  609. for block in msg["content_blocks"]
  610. if isinstance(block, dict) and block.get("type") == "text"
  611. ]
  612. msg["content"] = "\n\n".join(texts)
  613. processed.append(msg)
  614. return processed, images
  615. def encode_messages(
  616. messages: List[Dict[str, Any]],
  617. thinking_mode: str,
  618. context: Optional[List[Dict[str, Any]]] = None,
  619. drop_thinking: bool = True,
  620. add_default_bos_token: bool = True,
  621. reasoning_effort: Optional[str] = None,
  622. return_multi_modal_data: bool = False,
  623. ) -> Any:
  624. """Encode text or multimodal messages through one canonical public entrypoint.
  625. Text-only calls preserve the original string-returning API. When
  626. return_multi_modal_data is true, the result is ``(prompt, media_data)``.
  627. """
  628. context = context or []
  629. processed_context, _ = process_image_messages(context) if context else ([], [])
  630. processed_messages, images = process_image_messages(messages)
  631. prompt = _encode_messages_text(
  632. processed_messages,
  633. thinking_mode=thinking_mode,
  634. context=processed_context if processed_context else None,
  635. drop_thinking=drop_thinking,
  636. add_default_bos_token=add_default_bos_token,
  637. reasoning_effort=reasoning_effort,
  638. )
  639. if return_multi_modal_data:
  640. return prompt, {"images": images}
  641. return prompt
  642. def load_cases(input_file: str) -> List[Dict[str, Any]]:
  643. """Load one or more OpenAI-format conversation cases from JSON."""
  644. with open(input_file) as file:
  645. data = json.load(file)
  646. if isinstance(data, dict):
  647. data = [data]
  648. elif data and isinstance(data[0], dict) and "role" in data[0]:
  649. data = [{"messages": data}]
  650. cases = []
  651. for case in data:
  652. messages = copy.deepcopy(case["messages"])
  653. if "tools" in case:
  654. if not messages:
  655. raise ValueError("A case with tools must contain at least one message")
  656. messages[0]["tools"] = case["tools"]
  657. cases.append({
  658. "messages": messages,
  659. "context": case.get("context"),
  660. "thinking_mode": case.get("thinking_mode"),
  661. "reasoning_effort": case.get("reasoning_effort"),
  662. })
  663. return cases
  664. def encode_case(
  665. case: Dict[str, Any], thinking_mode: str
  666. ) -> Tuple[str, List[Dict[str, Any]]]:
  667. """Encode one JSON case and return its current-turn image records."""
  668. prompt, media_data = encode_messages(
  669. case["messages"],
  670. thinking_mode=case.get("thinking_mode") or thinking_mode,
  671. context=case.get("context"),
  672. reasoning_effort=case.get("reasoning_effort"),
  673. return_multi_modal_data=True,
  674. )
  675. return prompt, media_data["images"]
  676. # ============================================================
  677. # Parsing (Decoding model output)
  678. # ============================================================
  679. def _read_until_stop(index: int, text: str, stop: List[str]) -> Tuple[int, str, Optional[str]]:
  680. """
  681. Read text from index until one of the stop strings is found.
  682. Returns:
  683. Tuple of (new_index, content_before_stop, matched_stop_string_or_None).
  684. """
  685. min_pos = len(text)
  686. matched_stop = None
  687. for s in stop:
  688. pos = text.find(s, index)
  689. if pos != -1 and pos < min_pos:
  690. min_pos = pos
  691. matched_stop = s
  692. if matched_stop:
  693. content = text[index:min_pos]
  694. return min_pos + len(matched_stop), content, matched_stop
  695. else:
  696. content = text[index:]
  697. return len(text), content, None
  698. def parse_tool_calls(index: int, text: str) -> Tuple[int, Optional[str], List[Dict[str, str]]]:
  699. """
  700. Parse DSML tool calls from text starting at the given index.
  701. Args:
  702. index: Starting position in text.
  703. text: The full text to parse.
  704. Returns:
  705. Tuple of (new_index, last_stop_token, list_of_tool_call_dicts).
  706. Each tool call dict has "name" and "arguments" keys.
  707. """
  708. tool_calls: List[Dict[str, Any]] = []
  709. stop_token = None
  710. tool_calls_end_token = f"</{dsml_token}{tool_calls_block_name}>"
  711. while index < len(text):
  712. index, _, stop_token = _read_until_stop(index, text, [f"<{dsml_token}invoke", tool_calls_end_token])
  713. if _ != ">\n":
  714. raise ValueError(f"Tool call format error: expected '>\\n' but got '{_}'")
  715. if stop_token == tool_calls_end_token:
  716. break
  717. if stop_token is None:
  718. raise ValueError("Missing special token in tool calls")
  719. index, tool_name_content, stop_token = _read_until_stop(index, text, [f"<{dsml_token}parameter", f"</{dsml_token}invoke"])
  720. p_tool_name = re.findall(r'^\s*name="(.*?)">\n$', tool_name_content, flags=re.DOTALL)
  721. if len(p_tool_name) != 1:
  722. raise ValueError(f"Tool name format error: '{tool_name_content}'")
  723. tool_name = p_tool_name[0]
  724. tool_args: Dict[str, Tuple[str, str]] = {}
  725. while stop_token == f"<{dsml_token}parameter":
  726. index, param_content, stop_token = _read_until_stop(index, text, [f"/{dsml_token}parameter"])
  727. param_kv = re.findall(r'^ name="(.*?)" string="(true|false)">(.*?)<$', param_content, flags=re.DOTALL)
  728. if len(param_kv) != 1:
  729. raise ValueError(f"Parameter format error: '{param_content}'")
  730. param_name, string, param_value = param_kv[0]
  731. if param_name in tool_args:
  732. raise ValueError(f"Duplicate parameter name: '{param_name}'")
  733. tool_args[param_name] = (param_value, string)
  734. index, content, stop_token = _read_until_stop(index, text, [f"<{dsml_token}parameter", f"</{dsml_token}invoke"])
  735. if content != ">\n":
  736. raise ValueError(f"Parameter format error: expected '>\\n' but got '{content}'")
  737. tool_call = decode_dsml_to_arguments(tool_name=tool_name, tool_args=tool_args)
  738. tool_calls.append(tool_call)
  739. return index, stop_token, tool_calls
  740. def parse_message_from_completion_text(text: str, thinking_mode: str) -> Dict[str, Any]:
  741. """
  742. Parse a model completion text into a structured assistant message.
  743. This function takes the raw text output from the model (a single assistant turn)
  744. and extracts:
  745. - reasoning_content (thinking block)
  746. - content (summary/response)
  747. - tool_calls (if any)
  748. NOTE: This function is designed to parse only correctly formatted strings and
  749. will raise ValueError for malformed output.
  750. Args:
  751. text: The raw completion text (including EOS token).
  752. thinking_mode: Either "chat" or "thinking".
  753. Returns:
  754. Dict with keys: "role", "content", "reasoning_content", "tool_calls".
  755. tool_calls are in OpenAI format.
  756. """
  757. summary_content, reasoning_content, tool_calls = "", "", []
  758. index, stop_token = 0, None
  759. tool_calls_start_token = f"\n\n<{dsml_token}{tool_calls_block_name}"
  760. is_thinking = thinking_mode == "thinking"
  761. is_tool_calling = False
  762. if is_thinking:
  763. index, content_delta, stop_token = _read_until_stop(index, text, [thinking_end_token, tool_calls_start_token])
  764. reasoning_content = content_delta
  765. assert stop_token == thinking_end_token, "Invalid thinking format: missing </think>"
  766. index, content_delta, stop_token = _read_until_stop(index, text, [eos_token, tool_calls_start_token])
  767. summary_content = content_delta
  768. if stop_token == tool_calls_start_token:
  769. is_tool_calling = True
  770. else:
  771. assert stop_token == eos_token, "Invalid format: missing EOS token"
  772. if is_tool_calling:
  773. index, stop_token, tool_calls = parse_tool_calls(index, text)
  774. index, tool_ends_text, stop_token = _read_until_stop(index, text, [eos_token])
  775. assert not tool_ends_text, "Unexpected content after tool calls"
  776. assert len(text) == index and stop_token in [eos_token, None], "Unexpected content at end"
  777. for sp_token in [bos_token, eos_token, thinking_start_token, thinking_end_token, dsml_token]:
  778. assert sp_token not in summary_content and sp_token not in reasoning_content, \
  779. f"Unexpected special token '{sp_token}' in content"
  780. return {
  781. "role": "assistant",
  782. "content": summary_content,
  783. "reasoning_content": reasoning_content,
  784. "tool_calls": tool_calls_to_openai_format(tool_calls)
  785. }