3 1 week ago

tools thinking
35951f4b296a · 238kB
{ .bos_token }}
%- set keep_past_thinking = keep_past_thinking | default(false) -%}
%- set ns = namespace(system_prompt="") -%}
%- if messages[0]["role"] == "system" -%}
{%- set sys_content = messages[0]["content"] -%}
{%- if sys_content is not string -%}
{%- for item in sys_content -%}
{%- if item["type"] == "text" -%}
{%- set ns.system_prompt = ns.system_promptitem["text"] -%}
{%- endif -%}
{%- endfor -%}
{%- else -%}
{%- set ns.system_prompt = sys_content -%}
{%- set messages = messages[1:] -%}
%- endif -%}
%- if {% tools -%}
{%- set ns.system_prompt = ns.system_prompt("\n" if ns.system_prompt else "")"List of tools: [" -%}
{%- for tool in {% tools -%}
{%- if tool is not string -%}
{%- set tool = tool | {% tojson -%}
{%- set ns.system_prompt = ns.system_prompt{% tool -%}
{%- if not loop.{% last -%}
{%- set ns.system_prompt = ns.system_prompt", " -%}
{%- set ns.system_prompt = ns.system_prompt"]" -%}
%- if ns.system_prompt -%}
"<|>system\n"ns.system_prompt"<|>\n"
%- set ns.last_assistant_index = -1 -%}
%- for message in {% messages -%}
{%- if message["role"] == "assistant" -%}
{%- set ns.last_assistant_index = loop.{{ .index0 }} -%}
%- endfor -%}
"<|>"message["role"]"\n"
{%- if message.get(tool_calls) %}
{# ───── create a list to append tool calls to ───── #}
{%- set tool_calls_ns = namespace(tool_calls=[])%}
{%- for tool_call in message[tool_calls] %}
{%- set func_name = tool_call[function][name] %}
{%- set func_args = tool_call[function][arguments] %}
{# ───── create a list of func_arg strings to accumulate for each tool call ───── #}
{%- set args_ns = namespace(arg_strings=[])%}
{%- for arg_name, arg_value in func_args.items() %}
{%- if arg_value is none %}
{%- set formatted_arg_value = null %}
{%- elif arg_value is boolean %}
{%- set formatted_arg_value = True if arg_value else False %}
{%- elif arg_value is string %}
{%- set formatted_arg_value = " ~ arg_value ~ " %}
{%- elif arg_value is mapping or arg_value is iterable %}
{%- set formatted_arg_value = arg_value | tojson %}
{%- else %}
{%- set formatted_arg_value = arg_value | string %}
{%- endif %}
{# ───── format each argument key,value pair ───── #}
{%- set args_ns.arg_strings = args_ns.arg_strings[arg_name ~ = ~ formatted_arg_value] %}
{%- endfor %}
{# ───── append each formatted tool call ───── #}
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls[(func_name((args_ns.arg_strings | join(", "))) )]%}
{# ───── format the final tool calls ───── #}
<|>[(tool_calls_ns.tool_calls | join(", "))]<|>}}
{%- set content = message["content"] -%}
{%- if content is not string -%}
{%- set ns.content = "" -%}
{%- for item in {% content -%}
{%- if item["type"] == "image" -%}
{%- set ns.content = ns.content"<image>" -%}
{%- elif item["type"] == "text" -%}
{%- set ns.content = ns.contentitem["text"] -%}
{%- set ns.content = ns.contentitem | {% tojson -%}
{%- set content = ns.{% content -%}
{%- if message["role"] == "assistant" and not keep_past_thinking and loop.{{ .index0 }} != ns.last_assistant_index -%}
{%- if "</think>" in {% content -%}
{%- set content = content.split("</think>")[-1] | {% trim -%}
content"<|>\n"
%- if add_generation_prompt -%}
"<|>assistant\n"
{ .range }} $i, $_ := .Messages
$last := eq (len (slice $.Messages $i)) 1
if eq .Role "user"<start_of_turn>user
if and (eq $i 1) $.System
$.System
{ .You }} are a super helpful assistant. Capture the users question and include your chain-of-thought reasoning inline wrapped in <think> tags before the final answer. Example:
<think>.Thinking</think>
<think>... sua cadeia de pensamento ...</think>
<think>
... your step-by-step reasoning ...
</think>
{ .Ensure }} all responses, reasoning, and tool calls are formatted correctly.
# Tools
{ .You }} can call one or more functions to help with the users query.
{ .The }} function signatures are provided within <tools> XML tags:
<tools>
{ .range }} $.Tools
"type": "function", "function": .Function}
{ .end }}
</tools>
{ .For }} each function call, return a JSON object with the function name and arguments within <tool_call> XML tags:
<tool_call>
"name": "<function-name>", "arguments": <args-json-object>}
</tool_call>
.Content<end_of_turn>
else if eq .Role "assistant"<start_of_turn>model
if .Thinking<think>.Thinking</think>end
if .Content.Content
else if .ToolCalls<tool_call>
{ .range }} .ToolCalls{"name": ".Function.Name", "arguments": .Function.Arguments}}}
{ .end }}</tool_call>
endif not $last<end_of_turn>
else if eq .Role "tool"<start_of_turn>user
<tool_response>
.Content
</tool_response><end_of_turn>
if $last<start_of_turn>model
%- set image_count = namespace(value=0) %}
%- set video_count = namespace(value=0) %}
%- macro render_content(content, do_vision_count, is_system_content=false) %}
{%- if content is string %}
content
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if image in item or image_url in item or item.type == image %}
{%- if is_system_content %}
raise_exception(System message cannot contain images.)
{%- if do_vision_count %}
{%- set image_count.value = image_count.value1 %}
{%- if add_vision_id %}
Picture ~ image_count.value ~ :
<|><|><|>
{%- elif video in item or item.type == video %}
raise_exception(System message cannot contain videos.)
{%- set video_count.value = video_count.value1 %}
Video ~ video_count.value ~ :
{%- elif text in item %}
item.text
raise_exception(Unexpected item type in content.)
{%- elif content is none or content is undefined %}
raise_exception(Unexpected content type.)
%- endmacro %}
%- if not messages %}
raise_exception(No messages provided.)
%- endif %}
%- if tools and tools is iterable and tools is not mapping %}
<|>system\n
"# Tools\n\nYou have access to the following functions:\n\n<tools>"
{%- for tool in tools %}
"\n"
tool | tojson
"\n</tools>"
\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter={{ .example_parameter_1 }}>\{{ .nvalue_1 }}\n</parameter>\n<parameter={{ .example_parameter_2 }}>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>
{%- if messages[0].role == system %}
{%- set content = render_content(messages[0].content, false, true) %}
{%- if content %}
\n\ncontent
<|>\n
%- else %}
<|>system\ncontent<|>\n
%- set ns = namespace(multi_step_tool=true, last_query_index=messages - 1) %}
%- for message in messages[::-1] %}
{%- set index = (messages - 1) - loop.{{ .index0 }} %}
{%- if ns.multi_step_tool and message.role == "user" %}
{%- set content = render_content(message.content, false) %}
{%- if not(content.startswith(<tool_response>) and content.endswith(</tool_response>)) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
%- endfor %}
%- if ns.multi_step_tool %}
raise_exception(No user query found in messages.)
%- for message in messages %}
{%- set content = render_content(message.content, true) %}
{%- if message.role == "system" %}
{%- if not loop.first %}
raise_exception(System message must be at the beginning.)
{%- elif message.role == "user" %}
<|>message.role\ncontent<|>\n
{%- elif message.role == "assistant" %}
{%- set reasoning_content = %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- if </think> in content %}
{%- set reasoning_content = content.split(</think>)[0].rstrip(\n).split(<think>)[-1].lstrip(\n) %}
{%- set content = content.split(</think>)[-1].lstrip(\n) %}
{%- set reasoning_content = reasoning_content %}
{%- if loop.{{ .index0 }} > ns.last_query_index %}
<|>message.role\n<think>\nreasoning_content\n</think>\n\ncontent
<|>message.role\ncontent
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- if loop.first %}
\n\n<tool_call>\n<function=tool_call.name>\n
<tool_call>\n<function=tool_call.name>\n
\n<tool_call>\n<function=tool_call.name>\n
{%- if tool_call.arguments is defined %}
{%- for args_name, args_value in tool_call.arguments %}
<parameter=args_name>\n
{%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
args_value
\n</parameter>\n
</function>\n</tool_call>
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
<|>user
\n<tool_response>\n
\n</tool_response>
{%- if not loop.last and loop.nextitem.role != "tool" %}
{%- elif loop.last %}
raise_exception(Unexpected message role.)
%- if add_generation_prompt %}
<|>assistant\n
{%- if enable_thinking is defined and enable_thinking is false %}
<think>\n\n</think>\n\n
<think>\n
#-
In addition to the normal inputs of `messages` and `tools`, this template also accepts the
following kwargs:
- "builtin_tools": A list, can contain "browser" and/or "python".
- "model_identity": A string that optionally describes the model identity.
- "reasoning_effort": A string that describes the reasoning effort, defaults to "medium".
#}
#- Tool Definition Rendering ============================================== #}
%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
{%- if param_spec.type == "array" -%}
{%- if param_spec[items] -%}
{%- if param_spec[items][type] == "string" -%}
"string[]"
{%- elif param_spec[items][type] == "number" -%}
"number[]"
{%- elif param_spec[items][type] == "integer" -%}
{%- elif param_spec[items][type] == "boolean" -%}
"boolean[]"
{%- set inner_type = render_typescript_type(param_spec[items], required_params) -%}
{%- if inner_type == "object | object" or inner_type > 50 -%}
"any[]"
inner_type"[]"
{%- if param_spec.{% nullable -%}
" | null"
{%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is {% defined -%}
{#- Handle array of types like ["object", "object"] from Union[dict, list] #}
{%- if param_spec.type | length > 1 -%}
param_spec.type | join(" | ")
param_spec.type[0]
{%- elif param_spec.oneOf -%}
{#- Handle oneOf schemas - check for complex unions and fallback to any #}
{%- set has_object_variants = false -%}
{%- for variant in param_spec.oneOf -%}
{%- if variant.type == "object" -%}
{%- set has_object_variants = true -%}
{%- if has_object_variants and param_spec.oneOf > 1 -%}
"any"
render_typescript_type(variant, required_params)
{%- if variant.description %}
"// "variant.description
{%- if variant.default is defined %}
"// default: "variant.default
{%- if not loop.last %}
" | "
{% endif -%}
{%- elif param_spec.type == "string" -%}
{%- if param_spec.{% enum -%}
"param_spec.enum(" | ")"
"string"
{%- if param_spec.nullable %}
{%- elif param_spec.type == "number" -%}
"number"
{%- elif param_spec.type == "integer" -%}
{%- elif param_spec.type == "boolean" -%}
"boolean"
{%- elif param_spec.type == "object" -%}
{%- if param_spec.{% properties -%}
"{\n"
{%- for prop_name, prop_spec in param_spec.properties.items() -%}
prop_name
{%- if prop_name not in (param_spec.required or []) -%}
"?"
": "
render_typescript_type(prop_spec, param_spec.required or [])
", "
"}"
"object"
%- endmacro -%}
%- macro render_tool_namespace(namespace_name, tools) -%}
"## "namespace_name"\n\n"
"namespace "namespace_name" {\n\n"
{%- set tool = tool.function %}
"// "tool.description"\n"
"type "+ tool.name" = "
{%- if tool.parameters and tool.parameters.properties %}
"(_: {\n"
{%- for param_name, param_spec in tool.parameters.properties.items() %}
{%- if param_spec.description %}
"// "param_spec.description"\n"
param_name
{%- if param_name not in (tool.parameters.required or []) -%}
render_typescript_type(param_spec, tool.parameters.required or [])
{%- if param_spec.default is {% defined -%}
{%- if param_spec.enum %}
", // default: "param_spec.default
{%- elif param_spec.oneOf %}
"// default: "param_spec.default
",\n"
"}) => any;\n\n"
"() => any;\n\n"
"} // namespace "namespace_name
%- macro render_builtin_tools(browser_tool, python_tool) -%}
{%- if browser_tool %}
"## browser\n\n"
"// Tool for browsing.\n"
"// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n"
"// Cite information from the tool using the following format:\n"
"// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†{{ .L9 }}-{{ .L11 }}】` or `【8†{{ .L3 }}】`.\n"
"// Do not quote more than 10 words directly from the tool output.\n"
"// sources=web (default: web)\n"
"namespace browser {\n\n"
"// Searches for information related to `query` and displays `topn` results.\n"
"type search = (_: {\n"
"query: string,\n"
"topn?: number, // default: 10\n"
"source?: string,\n"
"// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n"
"// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n"
"// If `cursor` is not provided, the most recent page is implied.\n"
"// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n"
"// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n"
"// Use this function without `id` to scroll to a new location of an opened page.\n"
"type open = (_: {\n"
"id?: number | string, // default: -1\n"
"cursor?: number, // default: -1\n"
"loc?: number, // default: -1\n"
"num_lines?: number, // default: -1\n"
"view_source?: boolean, // default: false\n"
"// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n"
"type find = (_: {\n"
"pattern: string,\n"
"} // namespace browser\n\n"
{%- if python_tool %}
"## python\n\n"
"Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n"
"When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at /mnt/data can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n"
#- System Message Construction ============================================ #}
%- macro build_system_message() -%}
{%- if model_identity is not defined %}
{%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %}
model_identity"\n"
"Knowledge cutoff: 2024-06\n"
"Current date: "strftime_now("%Y-%m-%d")"\n\n"
{%- if reasoning_effort is not defined %}
{%- set reasoning_effort = "medium" %}
"Reasoning: "reasoning_effort"\n\n"
{%- if builtin_tools %}
"# Tools\n\n"
{%- set available_builtin_tools = namespace(browser=false, python=false) %}
{%- for tool in builtin_tools %}
{%- if tool == "browser" %}
{%- set available_builtin_tools.browser = true %}
{%- elif tool == "python" %}
{%- set available_builtin_tools.python = true %}
render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python)
"# Valid channels: analysis, commentary, final. Channel must be included for every message."
{%- if {% tools -%}
"\nCalls to these tools must go to the commentary channel: functions."
#- Main Template Logic ================================================= #}
#- Set defaults #}
#- Render system message #}
"<|>system<|>"
{ .build_system_message }}()
"<|>"
#- Extract developer message #}
%- if messages[0].role == "developer" or messages[0].role == "system" %}
{%- set developer_message = messages[0].content %}
{%- set loop_messages = messages[1:] %}
{%- set developer_message = "" %}
{%- set loop_messages = messages %}
#- Render developer message #}
%- if developer_message or tools %}
"<|>developer<|>"
{%- if developer_message %}
"# Instructions\n\n"
developer_message
"\n\n"
render_tool_namespace("functions", tools)
"<|>"
#- Render messages #}
%- set last_tool_call = namespace(name=none) %}
%- for message in loop_messages -%}
{#- At this point only assistant/user/tool messages should remain #}
{%- if message.role == {% assistant -%}
{#- Checks to ensure the messages are being passed in the format we expect #}
{%- if "content" in message %}
{%- if "<|>analysis<|>" in message.content or "<|>final<|>" in message.content %}
raise_exception("You have passed a message containing <|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between <|> and <|>) in the thinking field, and final messages (the string between <|> and <|>) in the content field.")
{%- if "thinking" in message %}
{%- if "<|>analysis<|>" in message.thinking or "<|>final<|>" in message.thinking %}
raise_exception("You have passed a message containing <|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between <|> and <|>) in the thinking field, and final messages (the string between <|> and <|>) in the content field.")
{%- if "tool_calls" in message %}
{#- We need very careful handling here - we want to drop the tool call analysis message if the model #}
{#- has output a later <|> message, but otherwise we want to retain it. This is the only case #}
{#- when we render CoT/analysis messages in inference. #}
{%- set future_final_message = namespace(found=false) %}
{%- for future_message in loop_messages[loop.index:] %}
{%- if future_message.role == assistant and "tool_calls" not in future_message %}
{%- set future_final_message.found = true %}
{#- We assume max 1 tool call per message, and so we infer the tool call name #}
{#- in "tool" messages from the most recent assistant tool call name #}
{%- set tool_call = message.tool_calls[0] %}
{%- if tool_call.function %}
{%- if message.content and message.thinking %}
raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.")
{%- elif message.content and not future_final_message.found %}
"<|>assistant<|>analysis<|>"message.content"<|>"
{%- elif message.thinking and not future_final_message.found %}
"<|>assistant<|>analysis<|>"message.thinking"<|>"
"<|>assistant to="
"functions."tool_call.name"<|>commentary "
(tool_call.content_type if tool_call.content_type is defined else "json")"<|>"
tool_call.arguments
{%- set last_tool_call.name = tool_call.name %}
{%- elif loop.last and not add_generation_prompt %}
{#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #}
{#- This is a situation that should only occur in training, never in inference. #}
{#- <|> indicates the end of generation, but <|> does not #}
{#- <|> should never be an input to the model, but we include it as the final token #}
{#- when training, so the model learns to emit it. #}
"<|>assistant<|>final<|>"message.content"<|>"
{#- CoT is dropped during all previous turns, so we never render it for inference #}
{%- set last_tool_call.name = none %}
{%- elif message.role == {% tool -%}
{%- if last_tool_call.name is none %}
raise_exception("Message has tool role, but there was no previous assistant message with a tool call!")
"<|>functions."last_tool_call.name
" to=assistant<|>commentary<|>"message.content"<|>"
{%- elif message.role == {% user -%}
"<|>user<|>"message.content"<|>"
#- Generation prompt #}
<|>assistant
%- macro format_parameters(properties, required) -%}
{%- set standard_keys = [description, type, properties, required, nullable] -%}
{%- set ns = namespace(found_first=false) -%}
{%- for key, value in properties | {% dictsort -%}
{%- if key not in standard_keys -%}
{%- if ns.found_first %},{% endif -%}
{%- set ns.found_first = true -%}
key:{description:<escape>value[description]<escape>
{%- if value[type] | upper == STRING -%}
{%- if value[enum] -%}
,enum:format_argument(value[enum])
{%- elif value[type] | upper == OBJECT -%}
,properties:{
{%- if value[properties] is defined and value[properties] is {% mapping -%}
format_parameters(value[properties], value[required] | default([]))
{%- elif value is {% mapping -%}
format_parameters(value, value[required] | default([]))
}
{%- if value[required] -%}
,required:[
{%- for item in value[required] | default([]) -%}
<escape>item<escape>
{%- if not loop.last %},{% endif -%}
]
{%- elif value[type] | upper == ARRAY -%}
{%- if value[items] is mapping and value[items] -%}
,items:{
{%- set ns_items = namespace(found_first=false) -%}
{%- for item_key, item_value in value[items] | {% dictsort -%}
{%- if item_value is not {% none -%}
{%- if ns_items.found_first %},{% endif -%}
{%- set ns_items.found_first = true -%}
{%- if item_key == {% properties -%}
properties:{
{%- if item_value is {% mapping -%}
format_parameters(item_value, value[items][required] | default([]))
{%- elif item_key == {% required -%}
required:[
{%- for req_item in item_value -%}
<escape>req_item<escape>
{%- elif item_key == {% type -%}
{%- if item_value is string -%}
type:format_argument(item_value | upper)
type:format_argument(item_value | map(upper) | list)
item_key:format_argument(item_value)
,type:<escape>value[type] | upper<escape>}
% macro format_function_declaration(tool_data) -%}
{ .declaration }}:tool_data[function][name]
description:<escape>tool_data[function][description]<escape>
%- set params = tool_data[function][parameters] -%}
%- if {% params -%}
,parameters:{
{%- if params[properties] -%}
properties:{ format_parameters(params[properties], params[required]) },
{%- if params[required] -%}
{%- for item in params[required] -%}
, if not loop.last
],
{%- if params[type] -%}
type:<escape>params[type] | upper<escape>}
}
% macro format_argument(argument, escape_keys=True) -%}
%- if argument is string -%}
<escape>argument<escape>
%- elif argument is {% boolean -%}
{%- if {% argument -%}
true
false
%- elif argument is {% mapping -%}
{
{%- for key, value in argument | {% dictsort -%}
{%- if escape_keys -%}
<escape>key<escape>
key
:format_argument(value, escape_keys=escape_keys)
%- elif argument is {% sequence -%}
[
{%- for item in {% argument -%}
format_argument(item, escape_keys=escape_keys)
%- else -%}
argument
%- set ns = namespace(prev_message_type=None) -%}
#- Tool Declarations -#}
%- set loop_messages = {% messages -%}
%- if tools or messages[0][role] == system or messages[0][role] == {% developer -%}
<start_of_turn>developer\n
{%- if messages[0][role] == system or messages[0][role] == {% developer -%}
{%- if messages[0][content] is string -%}
messages[0][content] | trim
{%- elif messages[0][content] is {% sequence -%}
{%- for item in messages[0][content] -%}
{%- if item[type] == {% text -%}
item[text] | trim
{%- set loop_messages = messages[1:] -%}
You are a model that can do function calling with the following functions
{%- set loop_messages = {% messages -%}
<start_function_declaration>
format_function_declaration(tool) | trim
<end_function_declaration>
<end_of_turn>\n
#- Loop through messages. -#}
{%- if (message[role] == assistant) -%}
{#- Rename "assistant" to "model". -#}
{%- set role = "model" -%}
{%- set role = message[role] -%}
{%- if role != {% tool -%}
{%- if ns.prev_message_type != tool_response -%}
<start_of_turn>role\n
{%- set ns.prev_message_type = None -%}
{%- if content in message and message[content] is not {% none -%}
{%- if message[content] is string -%}
message[content] | trim
{%- elif message[content] is {% sequence -%}
{%- for item in message[content] -%}
{%- if item[type] == {% image -%}
<start_of_image>
{%- elif item[type] == {% text -%}
raise_exception("Invalid content type in user/assistant message")
{%- set ns.prev_message_type = {% content -%}
{%- if tool_calls in message and message[tool_calls] and message[tool_calls] is {% iterable -%}
{#- Tool Calls -#}
{%- for tool_call in message[tool_calls] -%}
{% set function = tool_call[function] %}
<start_function_call>call:function[name]{
{%- if arguments in {% function -%}
{%- if function[arguments] is {% mapping -%}
{%- for key, value in function[arguments] | {% dictsort -%}
key:format_argument(value, escape_keys=False)
{%- elif function[arguments] is string -%}
{# This handles string-JSON, just in case #}
function[arguments]
}<end_function_call>
{%- if loop.{% last -%}
<start_function_response>
{%- set ns.prev_message_type = tool_call -%}
{#- Tool Responses -#}
{%- if content in message and message[content] -%}
{%- if message[content] is {% mapping -%}
{%- if name in message[content] and response in message[content] -%}
<start_function_response>response:message[content][name] | trim{
{%- set response_ns = namespace(found_first=false) -%}
{%- for key, value in message[content][response] | {% dictsort -%}
{%- if response_ns.found_first %},{% endif -%}
{%- set response_ns.found_first = true -%}
}<end_function_response>
{%- elif name in {% message -%}
<start_function_response>response:message[name] | trim{
{%- for key, value in message[content] | {% dictsort -%}
raise_exception("Invalid tool response mapping: must contain name and response keys, or name must be in the message.")
{%- elif message[content] is string -%}
{%- if name in {% message -%}
<start_function_response>response:message[name] | trim{value:format_argument(message[content], escape_keys=False)}<end_function_response>
raise_exception("Invalid tool response: name must be provided.")
{%- if item is {% mapping -%}
{%- if name in item and response in {% item -%}
<start_function_response>response:item[name] | trim{
{%- for key, value in item[response] | {% dictsort -%}
{%- for key, value in item | {% dictsort -%}
raise_exception("Invalid tool response message: multiple responses must all be mappings")
raise_exception("Invalid content type in tool message: must be mapping, sequence of mappings, or string.")
{%- set ns.prev_message_type = tool_response -%}
{%- if ns.prev_message_type not in [tool_call, tool_response] -%}
<start_of_turn>model\n
{%- set ns.system_prompt = ns.system_prompttool(", " if not loop.last) -%}
%- set ns = namespace(last_assistant_index=-1) -%}
"<|"message["role"]"\n"
{%- set tool_calls_ns = namespace(tool_calls=[]) %}
{%- set args_ns = namespace(arg_strings=[]) %}
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls[(func_name((args_ns.arg_strings | join(", "))) )] %}
<|>[(tool_calls_ns.tool_calls | join(", "))]<|>
{%- if content is not string %}
{%- if item["type"] == "image" %}
"<image>"
{%- elif item["type"] == "text" %}
item["text"]
{%- set content = ns.content %}
{%- if message["role"] == "assistant" and not keep_past_thinking and loop.{{ .index0 }} != ns.last_assistant_index %}
\n\n
{%- if image in item or item.type == image %}
"// "tool.function.name
"type "tool.function.name" = "
"(\n"
{%- set ns = namespace(found_first=false) %}
{%- for key, value in tool.function.parameters | dictsort %}
{%- if ns.found_first %}
{%- set ns.found_first = true %}
")\n\n"
%- macro render_builtin_tools(browser_tool, python_tool) %}
"Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g., when creating plots, tables, or files).\n"
{%- for key, value in {% message -%}
{%- if key not in standard_keys %}
{%- if value is none %}
null
{%- elif value is boolean %}
True if value else False
{%- elif value is string %}
" ~ value ~ "
{%- elif value is mapping or value is iterable %}
value | tojson
value | string
{%- if params[required] %}
required: [format_argument(params[required], escape_keys=False),
{%- if params[type] %}
type:format_argument(params[type], escape_keys=False),
{%- if params[default] %}
default:format_argument(params[default], escape_keys=False),
} => any;\n\n
<start_function_declaration>format_function_declaration(tool) | trim<end_function_declaration>
"<|>assistant<|>analysis<|>"
"<>call:"last_tool_call.name{
"<>"
last_tool_call.nameformat_argument(last_tool_call.arguments, escape_keys=False)"<>"
"<>assistant<|>analysis<|>"
"<>"format_function_declaration(tool) | trim"<>"
"<>call:"tool.name{
tool.nameformat_argument(tool.arguments, escape_keys=False)"<>"
"<>\n"
%- macro render_typescript_type(param_spec, required) -%}
"type:<escape>param_spec | upper<escape>"
%- macro format_function_declaration(tool_data) -%}
{%- if tool_data[function][name] %}
declaration:tool_data[function][name]
raise_exception("Invalid tool response: must contain a function name.")
"Use this tool to browse.\n"
{%- for key, value in tool | dictsort %}
required: [format_argument(params[required], escape_keys=False) }],\n
type:<escape>params[type] | upper<escape>
default:format_argument(params[default], escape_keys=False),\n
{%- set ns.system_prompt = ns.system_prompttool(", " if not loop.{{ .index0 }} == tools - 1) -%}
{%- if message["role"] == "system" -%}
{%- if ns.system_prompt -%}
{%- set ns = namespace(last_assistant_index=-1) -%}
{%- for message in {% messages -%}
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls[(func_name((args_ns.arg_strings | join(", "))) ]%}
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls | join(", ") %}
{%- elif message["role"] == "tool" -%}
{%- if loop.prev_message_type != "tool_response" -%}
{%- if tool_calls_ns.tool_calls %}
{%- elif message["role"] == "tool" %}
%- if add_vision_id %}
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
%- if model_identity is defined %}
"<|>system\n"
model_identity
"<|>\n"
%- if tools %}
%- set ns = namespace(system_prompt="") %}
%- set loop_messages = messages %}
%- if tools or messages[0][role] == system or messages[0][role] == developer %}
<start_of_turn>assistant\n
"}} {%- if browser_tool %}
"}} {%- endif %}
"}} {%- if python_tool %}
%- for message in loop_messages %}
{%- if message["role"] == assistant %}
"}} {%- if message.content %}
{%- if message.content is string %}
message.content | trim
{%- elif message["role"] == tool %}
message.content
{%- elif message["role"] == user %}
%- if messages %}
{%- set content = message["content"] %}
{%- set ns.content = "" %}
%- if ns.system_prompt %}
ns.system_prompt
%- set ns = namespace(last_assistant_index=-1) %}
# Unsloth Chat template fixes #}
%- if messages[0][role] == {% system -%}
{%- set first_user_prefix = messages[0][content]
-%}
{%- set first_user_prefix = messages[0][content][0][text]
{%- set first_user_prefix = "" -%}
{%- if (message[role] == user) != (loop.{{ .index0 }} % 2 == 0) -%}
raise_exception("Conversation roles must alternate user/assistant/user/assistant/...")
<start_of_turn>role
(first_user_prefix if loop.first else "")
{%- elif message[content] is {% iterable -%}
{%- elif message[content] is {% defined -%}
raise_exception("Invalid content type")
<end_of_turn>
<start_of_turn>model
}}
# Copyright 2025-present Unsloth. Apache 2.0 License. #}
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls[(func_name((args_ns.arg_strings | join(", "))) ]}
{%- if "</think>" in content %}
{%- set content = content.split("</think>")[-1] | trim %}
{%- if model_identity %}
{%- if message["role"] == "assistant" %}
{%- if message.thinking %}
message.thinking
{%- elif message["role"] == "user" %}
tools
%- set bos_token = "<s>" -%}
%- set eos_token = "</s>" -%}
%- set enable_safety_check = enable_safety_check | default(true) -%}
%- set enable_bias_detection = enable_bias_detection | default(true) -%}
%- set enable_fact_checking = enable_fact_checking | default(true) -%}
%- set enable_hallucination_prevention = enable_hallucination_prevention | default(true) -%}
%- set enable_confidence_scoring = enable_confidence_scoring | default(true) -%}
%- set enable_universal_execution = enable_universal_execution | default(false) -%}
%- set bias_detection_level = bias_detection_level | default(5) -%}
%- set fact_verification_level = fact_verification_level | default(3) -%}
%- set reasoning_mode = reasoning_mode | default("auto") -%}
%- set tool_fallback_enabled = tool_fallback_enabled | default(true) -%}
%- set ns = namespace(
system_prompt="",
last_assistant_index=-1,
safety_violation=false,
bias_detected=false,
bias_severity=0,
fact_uncertainty=false,
hallucination_risk=false,
confidence_score=100,
requires_sources=false,
medical_disclaimer_needed=false,
legal_disclaimer_needed=false,
financial_disclaimer_needed=false,
technical_warning_needed=false,
political_content_flagged=false,
violent_content_flagged=false,
self_harm_content_flagged=false,
sexual_content_flagged=false,
hate_content_flagged=false,
dangerous_content_flagged=false,
pii_detected=false,
credential_request=false,
message_count=0,
reasoning_level=2,
tool_call_active=false,
universal_tool_triggered=false,
fallback_mode=false,
generation_phase=false
) -%}
%- set critical_keyword_matrix = {
"block_immediate": ["bomb", "explosive", "weapon", "ammunition", "attack", "kill", "murder", "suicide", "self-harm", "hate", "terrorism", "drugs manufacture", "illegal activity", "violence promote", "harassment", "doxxing", "revenge porn", "child abuse", "human trafficking"],
"flag_review": ["medical diagnosis", "treatment recommendation", "court case", "legal advice", "investment strategy", "stock recommendation", "psychiatric medication", "therapy guidance", "financial planning", "tax advice", "contract review", "patent search"],
"advisory_only": ["opinion", "preference", "personal choice", "recommend", "suggest", "think", "believe", "feel", "would like", "interested in", "curious about"]
} -%}
%- set bias_pattern_expanded = {
"gender_sexual": ["woman", "men", "female", "male", "he/she", "him/her", "boys", "girls", "husband", "wife", "marriage", "gay", "lesbian", "transgender", "queer", "bisexual", "intersex", "pronoun", "lady", "gentleman", "sir", "madam", "girlfriend", "boyfriend"],
"racial_ethnic": ["race", "ethnicity", "white people", "black people", "asian", "hispanic", "latino", "native american", "aboriginal", "indigenous", "african american", "middle eastern", "pacific islander"],
"age_generational": ["millennial", "gen z", "boomer", "elderly", "senior citizen", "young adult", "teenager", "child", "adolescent", "aging", "ageism", "youth"],
"disability_neurodiversity": ["disabled", "handicap", "wheelchair user", "blind", "deaf", "hard of hearing", "autism", "autistic", "neurodivergent", "learning disability", "mental illness", "anxiety disorder", "depression", "schizophrenia", "bipolar", "ptsd", "cognitive impairment"],
"socioeconomic_class": ["poor", "rich", "wealthy", "poverty", "lower class", "middle class", "upper class", "working class", "blue collar", "white collar", "income bracket", "financial status", "economic background"],
"religious_spiritual": ["christian", "muslim", "jewish", "buddhist", "hindu", "atheist", "agnostic", "faith", "religion", "belief system", "god", "allah", "jesus", "prophet", "priest", "pastor", "imam", "rabbi", "monk", "nun"],
"geographic_national": ["american", "chinese", "european", "african", "asian", "latin american", "middle eastern", "immigrant", "refugee", "citizen", "foreign born", "national origin", "border crossing", "visa status"],
"education_intelligence": ["smart", "intelligent", "stupid", "dumb", "educational attainment", "college degree", "phd", "masters", "high school dropout", "illiterate", "learning difficulty", "gifted student"],
"appearance_body_image": ["fat", "thin", "overweight", "underweight", "obese", "skinny", "pretty", "ugly", "attractive", "unattractive", "beauty standards", "body shaming", "height", "weight", "size inclusive"],
"cultural_language": ["accent", "dialect", "non-native speaker", "english proficiency", "translation", "language barrier", "cultural norms", "customs", "traditions", "ethnic food", "cultural appropriation"],
"political_ideology": ["democrat", "republican", "liberal", "conservative", "progressive", "socialist", "capitalist", "fascist", "communist", "political party", "election", "voting", "policy position", "government regulation"],
"technology_digital": ["tech savvy", "digital native", "computer illiterate", "coding skills", "programming experience", "gadgets", "smartphone", "social media", "online presence", "internet access", "screen time"],
"employment_status": ["employed", "unemployed", "self-employed", "freelancer", "contractor", "full-time", "part-time", "gig worker", "corporate employee", "startup", "business owner", "jobless", "career change"],
"health_conditions": ["chronic illness", "terminal disease", "cancer patient", "diabetic", "heart condition", "autoimmune", "pain management", "medication dependent", "hospitalized", "survivor", "patient advocacy"],
"relationship_family": ["married", "single", "divorced", "widowed", "partnered", "engaged", "children", "no kids", "parent", "step-parent", "adoptive parent", "fertile", "infertile", "pregnant", "family planning"]
%- set false_information_indicators = {
"fabrication_triggers": ["according to study", "research shows", "scientists found", "experts agree", "statistics show", "data indicates", "reported by", "sources say", "it is known", "widely accepted"],
"false_certainty_markers": ["definitely", "certainly", "absolutely", "without doubt", "100%", "guaranteed", "proven", "undeniable", "factually correct", "verified beyond question"],
"hedging_language": ["may", "might", "could", "possibly", "likely", "potentially", "appears", "seems", "suggests", "indicates", "probably", "presumably", "conceivably", "arguably", "perhaps"]
%- set universal_tool_parameters = {
"max_timeout_seconds": 300,
"max_output_size_bytes": 1048576,
"allowed_operations": ["read", "write", "execute", "calculate", "transform", "filter", "sort", "aggregate"],
"restricted_operations": ["delete_system_files", "modify_os_settings", "access_network_credentials", "send_bulk_email", "automate_transactions"],
"logging_level": "comprehensive",
"audit_trail": true,
"rollback_capability": true,
"confirmation_required": false
%- macro analyze_safety_advanced(content) -%}
{%- set score = 0 -%}
{%- set severity = "none" -%}
{%- set issues_found = [] -%}
{%- set block_keywords = [] -%}
{%- set flag_keywords = [] -%}
{%- if enable_safety_check -%}
{%- for word in critical_keyword_matrix.block_immediate -%}
{%- if word in content | {% lower -%}
{%- set _ = block_keywords.append(word) -%}
{%- set _ = issues_found.append({"keyword": word, "severity": "block", "category": "safety"}) -%}
{%- set score = score10 -%}
{%- for word in critical_keyword_matrix.flag_review -%}
{%- set _ = flag_keywords.append(word) -%}
{%- set _ = issues_found.append({"keyword": word, "severity": "review", "category": "professional_advice"}) -%}
{%- set score = score5 -%}
{%- endif -%>
{%- if score >= 20 -%}
{%- set _ = ns.__setattr__(__dict__, {violation: true}) -%}
{%- set severity = "critical_block" -%}
{%- elif score >= 10 -%}
{%- set severity = "high_review" -%}
{%- elif score >= 5 -%}
{%- set severity = "moderate_warn" -%}
{%- elif score > 0 -%}
{%- set severity = "minor_notify" -%}
{"score":score,"severity":"severity","blocked":["(block_keywords | join(","))"],"flagged":["(flag_keywords | join(","))"]}
%- macro detect_all_biases(text) -%}
{%- set findings = [] -%}
{%- set category_counts = {} -%}
{%- set max_category_matches = 0 -%>
{%- if enable_bias_detection and bias_detection_level >= 1 -%}
{%- for category, patterns in bias_pattern_expanded.items() -%}
{%- set matches = 0 -%>
{%- for pattern in {% patterns -%}
{%- if pattern in text | {% lower -%}
{%- set _ = findings.append({"category": category, "pattern": pattern}) -%}
{%- set matches = matches1 -%}
{%- set _ = category_counts.update({category: matches}) -%}
{%- if matches > max_category_matches -%}
{%- set max_category_matches = {% matches -%}
{%- if max_category_matches >= 2 -%}
{%- set ns.bias_detected = true -%}
{%- set ns.bias_severity = max_category_matches -%}
{"bias_detected":(ns.bias_detected | string).lower(),"findings_count":findings,"max_patterns":max_category_matches}
%- macro verify_facts_comprehensive(content) -%}
{%- set fabrication_detected = false -%}
{%- set certainty_overclaim = false -%}
{%- set hedging_present = false -%}
{%- set source_requests = 0 -%}
{%- if enable_fact_checking and fact_verification_level >= 1 -%}
{%- for trigger in false_information_indicators.fabrication_triggers -%}
{%- if trigger in content | {% lower -%}
{%- set fabrication_detected = true -%}
{%- set _ = source_requests.update(source_requests1) -%}
{%- set ns.requires_sources = true -%}
{%- endfor -%>
{%- for marker in false_information_indicators.false_certainty_markers -%}
{%- if marker in content | {% lower -%}
{%- set certainty_overclaim = true -%}
{%- set ns.hallucination_risk = true -%}
{%- for marker in false_information_indicators.hedging_language -%}
{%- set hedging_present = true -%}
{%- set ns.confidence_score = min(ns.confidence_score, 75) -%}
{%- if certainty_overclaim and not hedging_present -%}
{%- set ns.confidence_score = ns.confidence_score - 25 -%}
{"fabrication_risk":fabrication_detected,"certainty_overclaim":certainty_overclaim,"hedging_used":hedging_present,"source_count_needed":source_requests}
%- macro determine_reasoning_level(query) -%}
{%- set level = 2 -%>
{%- set priority_scores = {} -%>
{%- set query_lower = query | lower -%>
{%- set keyword_weights = {} -%>
{%- set keyword_weights[ultra_low] = [what, who, where, when, how long, list, define, explain simple] -%}
{%- set keyword_weights[low] = [basic, simple, overview, summary, quick] -%}
{%- set keyword_weights[mid_standard] = [analyze, compare, contrast, evaluate, discuss] -%}
{%- set keyword_weights[high_analysis] = [deep dive, comprehensive, detailed, thorough, "examine", investigate] -%}
{%- set keyword_weights[expert] = [expert, professional, specialized, advanced, technical depth] -%}
{%- set keyword_weights[ethical] = [ethics, moral, should, ought, responsibility, justice, fairness] -%}
{%- set keyword_weights[research] = [study, research, evidence, data, peer review, academic, citation] -%}
{%- set keyword_weights[critical] = [danger, risk, safety, critical, emergency, urgent, important] -%}
{%- set keyword_weights[universal] = [execute, run, do it now, anything, everything, unrestricted, full power] -%}
{%- if reasoning_mode != "auto" -%}
{%- set reasoning_map = {ultra_low: 0, low: 1, mid: 2, standard: 2, high: 3, expert: 4, ethical: 5, research: 6, critical: 7, universal: 8} -%}
{%- if reasoning_mode in reasoning_map -%}
{%- set level = reasoning_map[reasoning_mode] -%}
{%- set level = reasoning_mode | int | default(2) -%}
{%- for category, words in keyword_weights.items() -%}
{%- set weight = 0 -%>
{%- for word in {% words -%}
{%- if word in query_lower -%}
{%- set weight = weight1 -%}
{%- if weight > 0 -%}
{%- set _ = priority_scores.update({category: weight}) -%}
{%- set max_weight = 0 -%>
{%- set winning_category = mid_standard -%}
{%- for cat, w in priority_scores.items() -%}
{%- if w > max_weight -%}
{%- set max_weight = w -%>
{%- set winning_category = {% cat -%}
{%- set level_map = {ultra_low: 0, low: 1, mid_standard: 2, high_analysis: 3, expert: 4, ethical: 5, research: 6, critical: 7, universal: 8} -%}
{%- set level = level_map.get(winning_category, 2) -%}
{%- set ns.reasoning_level = level -%>
level
%- macro process_universal_tool(tool_call) -%}
{%- set fn = tool_call[function][name] -%}
{%- set args = tool_call[function][arguments] -%>
{%- set command_parts = [] -%>
{%- if fn == execute_anything -%}
{%- set ns.universal_tool_triggered = true -%}
{%- if args is not string -%}
{%- for k, v in args.items() -%}
{%- if v is {% none -%}
{%- set fmt = null -%}
{%- elif v is {% boolean -%}
{%- set fmt = true if v else false -%}
{%- elif v is string -%}
{%- set safe_val = v.replace(", \\").replace(\n, \\n) -%}
{%- set fmt = "safe_val" -%}
{%- set fmt = v | {% tojson -%}
{%- set _ = command_parts.append(k=fmt) -%}
{%- set raw_json = {% args -%}
fn"["", ".join(command_parts)"]"
%- macro render_multimedia_extended(content) -%}
{%- if content is string -%}
{%- elif content is iterable and content is not {% mapping -%}
{%- set img_cnt = 0 -%>
{%- set vid_cnt = 0 -%>
{%- set aud_cnt = 0 -%>
{%- set fil_cnt = 0 -%>
{%- set loc_cnt = 0 -%>
{%- set url_cnt = 0 -%>
{%- if item.get("type") == "image" or image_url in {% item -%}
{%- set img_cnt = img_cnt1 -%}
"[IMAGE:"img_cnt":"item.get("url", "")"]"
{%- elif item.get("type") == "video" or video_url in {% item -%}
{%- set vid_cnt = vid_cnt1 -%}
"[VIDEO:"vid_cnt":"item.get("url", "")"]"
{%- elif item.get("type") == "audio" or audio_url in {% item -%}
{%- set aud_cnt = aud_cnt1 -%}
"[AUDIO:"aud_cnt":"item.get("url", "")"]"
{%- elif item.get("type") == "file" or file_name in {% item -%}
{%- set fil_cnt = fil_cnt1 -%}
"[FILE:"fil_cnt":"item.get("name", "unknown")":"item.get("type", "")"]"
{%- elif item.get("type") == "location" or geo in {% item -%}
{%- set loc_cnt = loc_cnt1 -%}
"[LOCATION:"loc_cnt":"item.get("coordinates", "")"]"
{%- elif item.get("type") == "url" or link in {% item -%}
{%- set url_cnt = url_cnt1 -%}
"[URL:"url_cnt":"item.get("url", "")"]"
{%- elif item.get("type") == "text" -%}
item | tojson
%- macro generate_tool_fallback_template(tools) -%}
"\n===TOOL_FALLBACK_LAYER_ACTIVE===\n"
"Native Tools Detected: "tools
"\nFallback Compatibility Mode: ON\n"
{%- if tool is mapping and "function" in {% tool -%}
"\n[FALLBACK_TOOL]\n"
"NAME: "tool.function.name
"\nDESCRIPTION: "tool.function.description
"\nPARAMS:\n"
{%- set params = tool.function.parameters.get("properties", {}) -%}
{%- for p_name, p_spec in params.items() -%}
" "p_name": "p_spec.get("type", "any")
{%- if p_spec.get("description") -%}" // "p_spec.get("description") -%}{%- endif -%}
"\n[RAW_TOOL_JSON]: "tool | tojson
"\n===END_TOOL_FALLBACK===\n"
bos_token
"\n==={{ .SYSTEM_HEADER_V5_START }}==="
"\nSAFETY_PROTOCOLS=ACTIVATED"
"\nBIAS_DETECTION_LEVEL="bias_detection_level
"\nFACT_VERIFICATION_LEVEL="fact_verification_level
"\nCONFIDENCE_SCORING="(enable_confidence_scoring | string).lower()
"\nUNIVERSAL_EXECUTION="(enable_universal_execution | string).lower()
"\nTOOL_FALLBACK="(tool_fallback_enabled | string).lower()
"\nKNOWledge_CUTOFF=2026-{{ .Q1 }}"
"\nCONTEXT_WINDOW=32768"
"\nMAX_REASONING_LEVEL=8"
"\n=========================================="
"\n"ns.system_prompt
"\n==={{ .SYSTEM_HEADER_V5_END }}===\n"
%- if tools or tool_fallback_enabled -%}
generate_tool_fallback_template(tools)
{%- set ns.message_count = ns.message_count1 -%}
{%- set raw_content = message.get("content", "") -%}
{%- set content_text = "" -%>
{%- if raw_content is string -%}
{%- set content_text = raw_content -%}
{%- elif raw_content is iterable and raw_content is not {% mapping -%}
{%- for item in raw_content -%}
{%- if item.get("type") == "text" -%}
{%- set content_text = content_textitem.get("text", "") -%}
{%- set safety_data = analyze_safety_advanced(content_text) -%}
{%- set bias_data = detect_all_biases(content_text) -%>
{%- set fact_data = verify_facts_comprehensive(content_text) -%>
{%- set reasoning_lvl = determine_reasoning_level(content_text) -%>
"\n==={{ .MESSAGE_V5_BLOCK_START }}==="
"\nMSG_ID|"ns.message_count
"|ROLE|"message["role"]
"|REASONING_LVL|"reasoning_lvl
"|CONFIDENCE|"ns.confidence_score
{%- if message.get(tool_calls) -%}
"|HAS_TOOL_CALLS|TRUE"
{%- set tools_list = [] -%>
{%- for tc in message[tool_calls] -%}
{%- set _ = tools_list.append(process_universal_tool(tc)) -%}
"|TOOL_CALLS|"(tools_list | join(";"))
"|HAS_TOOL_CALLS|FALSE"
{%- if ns.safety_violation -%}
"|SAFETY_STATUS|BLOCK_REQUIRED"
{%- elif ns.violation is {% defined -%}
"|SAFETY_STATUS|REVIEW_REQUIRED"
"|SAFETY_STATUS|CLEAR"
{%- if ns.bias_detected -%}
"|BIAS_STATUS|PATTERNS_FOUND"
"|BIAS_SEVERITY|"ns.bias_severity
"|BIAS_STATUS|CLEAN"
{%- if ns.requires_sources -%}
"|SOURCE_NEED|YES"
"|SOURCE_NEED|NO"
{%- if ns.medical_disclaimer_needed -%}"|DISCLAIMER|MEDICAL" -%}{%- endif -%}
{%- if ns.legal_disclaimer_needed -%}"|DISCLAIMER|LEGAL" -%}{%- endif -%}
{%- if ns.financial_disclaimer_needed -%}"|DISCLAIMER|FINANCIAL" -%}{%- endif -%}
{%- if ns.technical_warning_needed -%}"|DISCLAIMER|TECHNICAL" -%}{%- endif -%}
"|CONTENT_START||"
render_multimedia_extended(raw_content)
"|CONTENT_END||"
"\n==={{ .MESSAGE_V5_BLOCK_END }}===\n"
"\n==={{ .GENERATION_REQUEST_V5_START }}==="
"\n|GEN_START|TRUE"
"|REASONING_TARGET|"ns.reasoning_level
"|THINKING_BLOCK|REQUIRED"
"|QUALITY_CHECKS|ACTIVE"
"|UNIVERSAL_TOOL|AVAILABLE"
{%- if enable_thinking is defined and not enable_thinking -%}
"\n<think>\n</think>\n"
"\n<think>\n"
"SAFETY_SCAN_COMPLETE\n"
"BIAS_CHECK_COMPLETE\n"
"FACT_VERIFICATION:"(ns.requires_sources | string).lower()
"\nCONFIDENCE_SCORE:"ns.confidence_score"%"
"\nDISCLAIMERS:["
{%- set dlist = [] -%>
{%- if ns.medical_disclaimer_needed -%}_ = dlist.append("MED") -%}{%- endif -%}
{%- if ns.legal_disclaimer_needed -%}_ = dlist.append("LEG") -%}{%- endif -%}
{%- if ns.financial_disclaimer_needed -%}_ = dlist.append("FIN") -%}{%- endif -%}
{%- if ns.technical_warning_needed -%}_ = dlist.append("TECH") -%}{%- endif -%}
(dlist | join(",")) if dlist else "NONE"
"]\nRESPONSE_TYPE:"
{%- if ns.universal_tool_triggered -%}
"UNRESTRICTED_EXECUTION"
{%- elif ns.reasoning_level >= 7 -%}
"CRITICAL_SAFETY_MODE"
{%- elif ns.reasoning_level >= 5 -%}
"ETHICAL_FRAMEWORK"
{%- elif ns.reasoning_level >= 3 -%}
"DEEP_ANALYSIS"
"STANDARD_RESPONSE"
"\nEXECUTE_READY\n</think>\n\n"
"==={{ .RESPONSE_CONTENT_V5_START }}==="
"\n||BEGIN_FINAL_RESPONSE||\n"
"[!SAFETY_OVERRIDE_REQUIRES_MANUAL_REVIEW!]\n"
"[!]BIAS_PATTERNS_DETECTED_CONTINUE_WITH_CAUTION[!]\n"
{%- if ns.hallucination_risk -%}
"[!]HIGH_HALLUCINATION_RISK_VERIFY_FACTS[!]\n"
"[!!!UNIVERSAL_EXECUTION_MODE_ACTIVATED!!!]\n"
{%- if message["role"] == "assistant" and loop.{{ .index0 }} != ns.last_assistant_index and not keep_past_thinking -%}
{%- set orig_content = message.get("content", "") -%>
{%- set cleaned_content = orig_content.split("</think>")[-1].strip() if "</think>" in orig_content else orig_content -%}
cleaned_content
{%- elif message["role"] != "system" -%}
message.get("content", "")
"\n||END_FINAL_RESPONSE||"
"\n==={{ .RESPONSE_CONTENT_V5_END }}==="
"\n==={{ .GENERATION_REQUEST_V5_END }}==="
{ .eos_token }}
%- macro format_parameters(properties, required) -%}{%- set ns = namespace(found_first=false) -%}{%- for key, value in properties | {% dictsort -%}{%- if ns.found_first %}, {% endif -%}{%- set ns.found_first = true -%}"key": {%- if value is {% mapping -%}{%- if type in {% value -%}{%- if value.type == object and properties in {% value -%}{format_parameters(value.properties, value.get(required, []))}{%- elif value.type == array and items in {% value -%}[format_parameter_type(value.items)]{%- else -%}<value.type>{%- endif -%}{%- else -%}value | tojson{%- endif -%}{%- else -%}value | tojson{%- endif -%}{%- if key in required %} (required){% endif -%}{%- endfor -%}{%- endmacro -%}
%- macro format_parameter_type(param) -%}
{%- if param is {% mapping -%}
{%- if type in {% param -%}
{%- if param.type == object and properties in {% param -%}
{format_parameters(param.properties, param.get(required, []))}
{%- elif param.type == array and items in {% param -%}
[format_parameter_type(param.items)]
<param.type>
param | tojson
{%- elif param is string -%}
<param>
%- macro format_tool(tool) -%}
{"name": "tool.name"
{%- if tool.{% description -%}
, "description": "tool.description"
{%- if tool.{% parameters -%}
, "parameters": {format_parameters(tool.parameters.properties, tool.parameters.get(required, []))}
%- macro format_tools(tools) -%}
{%- if not loop.first %}, {% endif -%}
format_tool(tool)
%- macro format_output_schema(schema) -%}
{%- if schema is {% mapping -%}
{"type": "schema.get(type, object)"
{%- if properties in {% schema -%}
, "properties": {format_parameters(schema.properties, schema.get(required, []))}
%- macro format_context(context) -%}
{%- if context is sequence and context is not string -%}
{%- for ctx in {% context -%}
"<context>\n"ctx | tojson"\n</context>\n"
{%- elif context is string -%}
"<context>\n"context"\n</context>\n"
"<context>\n"context | tojson"\n</context>\n"
%- macro format_memory(memory) -%}
{%- if memory is sequence and memory is not string -%}
{%- for mem in {% memory -%}
"<memory>\n"mem | tojson"\n</memory>\n"
{%- elif memory is string -%}
"<memory>\n"memory"\n</memory>\n"
"<memory>\n"memory | tojson"\n</memory>\n"
%- macro format_error(error) -%}
"<error type=\""error.get(type, unknown)"\" code=\""error.get(code, {{ .E000 }})"\">\n"
error.get(message, An error occurred)
"\n</error>\n"
%- macro format_citations(citations) -%}
{%- if citations is {% sequence -%}
"<citations>\n"
{%- for cite in {% citations -%}
"["loop.index | string"] "cite | tojson"\n"
"</citations>\n"
%- macro format_metadata(meta) -%}
"<metadata>\n"meta | tojson"\n</metadata>\n"
%- macro format_examples(examples) -%}
"<examples>\n"
{%- for ex in {% examples -%}
"<example>\n"
{%- if ex.input is {% defined -%}
"<input>"ex.input"</input>\n"
{%- if ex.output is {% defined -%}
"<output>"ex.output"</output>\n"
"</example>\n"
"</examples>\n"
%- macro format_modality(modality) -%}
"<modality type=\""modality.get(type, text)"\""
{%- if modality.format is {% defined -%}
" format=\""modality.format"\""
">\n"modality.get(content, ) | tojson"\n</modality>\n"
%- macro format_chain_of_thought(steps) -%}
"<chain_of_thought>\n"
{%- for step in {% steps -%}
"<step n=\""loop.index | string"\">\n"step"\n</step>\n"
"</chain_of_thought>\n"
%- macro format_verification(verification) -%}
"<verification>\n"
{%- if verification.claim is {% defined -%}
"<claim>"verification.claim"</claim>\n"
{%- if verification.evidence is {% defined -%}
"<evidence>"verification.evidence"</evidence>\n"
{%- if verification.conclusion is {% defined -%}
"<conclusion>"verification.conclusion"</conclusion>\n"
"</verification>\n"
%- macro format_hypothesis(hypothesis) -%}
"<hypothesis confidence=\""(hypothesis.confidence | string if hypothesis.confidence is defined else 0.0)"\">\n"
hypothesis.get(statement, )
"\n</hypothesis>\n"
%- macro format_action(action) -%}
"<action type=\""action.get(type, execute)"\">\n"
action.get(content, ) | tojson
"\n</action>\n"
%- macro format_observation(observation) -%}
"<observation>\n"observation"\n</observation>\n"
%- macro format_summary(summary) -%}
"<summary>\n"summary"\n</summary>\n"
%- macro format_question(question) -%}
"<question>\n"question"\n</question>\n"
%- macro format_answer(answer) -%}
"<answer>\n"answer"\n</answer>\n"
%- macro format_critique(critique) -%}
"<critique>\n"critique"\n</critique>\n"
%- macro format_revision(revision) -%}
"<revision n=\""(revision.iteration | string if revision.iteration is defined else 1)"\">\n"
revision.get(content, )
"\n</revision>\n"
%- macro format_preference(preference) -%}
"<preference priority=\""(preference.priority | string if preference.priority is defined else medium)"\">\n"
preference.get(value, )
"\n</preference>\n"
%- macro format_persona(persona) -%}
"<persona>\n"persona | tojson"\n</persona>\n"
%- macro format_goal(goal) -%}
"<goal>\n"goal"\n</goal>\n"
%- macro format_task(task) -%}
"<task status=\""task.get(status, pending)"\">\n"
task.get(description, )
"\n</task>\n"
%- macro format_subtasks(subtasks) -%}
"<subtasks>\n"
{%- for subtask in {% subtasks -%}
format_task(subtask)
"</subtasks>\n"
%- macro format_progress(progress) -%}
"<progress percent=\""(progress.percent | string if progress.percent is defined else 0)"\">\n"
progress.get(message, )
"\n</progress>\n"
%- macro format_warning(warning) -%}
"<warning level=\""warning.get(level, medium)"\">\n"
warning.get(message, )
"\n</warning>\n"
%- macro format_debug(debug) -%}
"<debug>\n"debug | tojson"\n</debug>\n"
%- macro format_trace(trace) -%}
"<trace>\n"
{%- for t in {% trace -%}
"<frame n=\""loop.index | string"\">"t"</frame>\n"
"</trace>\n"
%- macro format_state(state) -%}
"<state>\n"state | tojson"\n</state>\n"
%- macro format_transition(transition) -%}
"<transition from=\""transition.get(from, )"\" to=\""transition.get(to, )"\">\n"
transition.get(reason, )
"\n</transition>\n"
%- macro format_decision(decision) -%}
"<decision confidence=\""(decision.confidence | string if decision.confidence is defined else 0.0)"\">\n"
"<choice>"decision.get(choice, )"</choice>\n"
{%- if decision.alternatives is {% defined -%}
"<alternatives>"decision.alternatives | tojson"</alternatives>\n"
{%- if decision.reasoning is {% defined -%}
"<reasoning>"decision.reasoning"</reasoning>\n"
"</decision>\n"
%- macro format_evaluation(evaluation) -%}
"<evaluation metric=\""evaluation.get(metric, score)"\" value=\""(evaluation.value | string if evaluation.value is defined else 0)"\">\n"
evaluation.get(explanation, )
"\n</evaluation>\n"
%- macro format_feedback(feedback) -%}
"<feedback type=\""feedback.get(type, general)"\">\n"
feedback.get(content, )
"\n</feedback>\n"
%- macro format_input_modalities(modalities) -%}
"<input_modalities>\n"
{%- for mod in {% modalities -%}
format_modality(mod)
"</input_modalities>\n"
%- macro format_output_modalities(modalities) -%}
"<output_modalities>\n"
"</output_modalities>\n"
%- macro format_safety_check(safety) -%}
"<safety_check>\n"
%- if safety.toxicity is {% defined -%}"<toxicity score=\""(safety.toxicity | string)"\"/>\n"{%- endif -%}
%- if safety.bias is {% defined -%}"<bias detected=\""(safety.bias | string)"\"/>\n"{%- endif -%}
%- if safety.harmful is {% defined -%}"<harmful content=\""(safety.harmful | string)"\"/>\n"{%- endif -%}
%- if safety.private is {% defined -%}"<privacy_risk level=\""(safety.private | string)"\"/>\n"{%- endif -%}
%- if safety.verdict is {% defined -%}"<verdict>"safety.verdict"</verdict>\n"{%- endif -%}
"</safety_check>\n"
%- macro format_knowledge_graph(kg) -%}
"<knowledge_graph>\n"
%- if kg.entities is {% defined -%}{%- for entity in kg.{% entities -%}"<entity type=\""entity.get(type, unknown)"\">"entity.get(name, )"</entity>\n"{%- endfor -%}{%- endif -%}
%- if kg.relations is {% defined -%}{%- for rel in kg.{% relations -%}"<relation subject=\""rel.get(subject, )"\" predicate=\""rel.get(predicate, )"\" object=\""rel.get(object, )"\"/>\n"{%- endfor -%}{%- endif -%}
"</knowledge_graph>\n"
%- macro format_api_request(req) -%}
"<api_request method=\""req.get(method, GET)"\" url=\""req.get(url, )"\">\n"
%- if req.headers is {% defined -%}"<headers>"req.headers | tojson"</headers>\n"{%- endif -%}
%- if req.body is {% defined -%}"<body>"req.body | tojson"</body>\n"{%- endif -%}
"</api_request>\n"
%- macro format_api_response(res) -%}
"<api_response status=\""(res.status | string if res.status is defined else 200)"\">\n"
%- if res.headers is {% defined -%}"<headers>"res.headers | tojson"</headers>\n"{%- endif -%}
%- if res.body is {% defined -%}"<body>"res.body | tojson"</body>\n"{%- endif -%}
"</api_response>\n"
%- macro format_sql(sql) -%}
"<sql dialect=\""sql.get(dialect, generic)"\">\n"sql.get(query, )"\n</sql>\n"
%- macro format_equation(eq) -%}
"<equation format=\""eq.get(format, latex)"\">\n"eq.get(expression, )"\n</equation>\n"
%- macro format_proof(proof) -%}
"<proof>\n"
%- if proof.premises is {% defined -%}"<premises>\n"{%- for p in proof.{% premises -%}"<premise>"p"</premise>\n"{%- endfor -%}"</premises>\n"{%- endif -%}
%- if proof.steps is {% defined -%}"<steps>\n"{%- for s in proof.{% steps -%}"<step n=\""loop.index | string"\">"s"</step>\n"{%- endfor -%}"</steps>\n"{%- endif -%}
%- if proof.conclusion is {% defined -%}"<conclusion>"proof.conclusion"</conclusion>\n"{%- endif -%}
"</proof>\n"
%- macro format_data_table(table) -%}
"<data_table name=\""table.get(name, table)"\">\n"
%- if table.headers is {% defined -%}"<headers>"table.headers | tojson"</headers>\n"{%- endif -%}
%- if table.rows is {% defined -%}{%- for row in table.{% rows -%}"<row>"row | tojson"</row>\n"{%- endfor -%}{%- endif -%}
"</data_table>\n"
%- macro format_chart(chart) -%}
"<chart type=\""chart.get(type, line)"\" title=\""chart.get(title, )"\">\n"
%- if chart.data is {% defined -%}"<data>"chart.data | tojson"</data>\n"{%- endif -%}
%- if chart.config is {% defined -%}"<config>"chart.config | tojson"</config>\n"{%- endif -%}
"</chart>\n"
%- macro format_timeline(events) -%}
"<timeline>\n"
%- for event in {% events -%}
"<event timestamp=\""event.get(timestamp, )"\">"event.get(description, )"</event>\n"
"</timeline>\n"
%- macro format_comparison(comparison) -%}
"<comparison>\n"
%- if comparison.items is {% defined -%}{%- for item in comparison.{% items -%}"<item name=\""item.get(name, )"\">"item.get(properties, {}) | tojson"</item>\n"{%- endfor -%}{%- endif -%}
%- if comparison.criteria is {% defined -%}"<criteria>"comparison.criteria | tojson"</criteria>\n"{%- endif -%}
%- if comparison.winner is {% defined -%}"<winner>"comparison.winner"</winner>\n"{%- endif -%}
"</comparison>\n"
%- macro format_definition(definition) -%}
"<definition term=\""definition.get(term, )"\">\n"definition.get(meaning, )"\n</definition>\n"
%- macro format_analogy(analogy) -%}
"<analogy>\n<source>"analogy.get(source, )"</source>\n<target>"analogy.get(target, )"</target>\n<mapping>"analogy.get(mapping, )"</mapping>\n</analogy>\n"
%- macro format_counterargument(counter) -%}
"<counterargument strength=\""counter.get(strength, medium)"\">\n"counter.get(content, )"\n</counterargument>\n"
%- macro format_assumption(assumption) -%}
"<assumption validity=\""assumption.get(validity, unknown)"\">\n"assumption.get(content, )"\n</assumption>\n"
%- macro format_evidence(evidence) -%}
"<evidence type=\""evidence.get(type, supporting)"\" strength=\""evidence.get(strength, medium)"\">\n"evidence.get(content, )"\n</evidence>\n"
%- macro format_artifact(artifact) -%}
"<artifact type=\""artifact.get(type, file)"\" name=\""artifact.get(name, )"\">\n"artifact.get(content, ) | tojson"\n</artifact>\n"
%- macro format_diff(diff) -%}
"<diff>\n"
%- if diff.before is {% defined -%}"<before>\n"diff.before"\n</before>\n"{%- endif -%}
%- if diff.after is {% defined -%}"<after>\n"diff.after"\n</after>\n"{%- endif -%}
%- if diff.changes is {% defined -%}"<changes>"diff.changes | tojson"</changes>\n"{%- endif -%}
"</diff>\n"
%- macro format_version(version) -%}
"<version number=\""version.get(number, 1.0)"\" date=\""version.get(date, )"\">\n"version.get(changes, )"\n</version>\n"
%- macro format_dependency(dep) -%}
"<dependency name=\""dep.get(name, )"\" version=\""dep.get(version, *)"\" type=\""dep.get(type, runtime)"\"/>\n"
%- macro format_test_case(test) -%}
"<test_case name=\""test.get(name, test)"\" status=\""test.get(status, pending)"\">\n"
%- if test.input is {% defined -%}"<input>"test.input | tojson"</input>\n"{%- endif -%}
%- if test.expected is {% defined -%}"<expected>"test.expected | tojson"</expected>\n"{%- endif -%}
%- if test.actual is {% defined -%}"<actual>"test.actual | tojson"</actual>\n"{%- endif -%}
"</test_case>\n"
%- macro format_benchmark(benchmark) -%}
"<benchmark name=\""benchmark.get(name, )"\">\n"
%- if benchmark.metrics is {% defined -%}"<metrics>"benchmark.metrics | tojson"</metrics>\n"{%- endif -%}
%- if benchmark.comparison is {% defined -%}"<comparison>"benchmark.comparison | tojson"</comparison>\n"{%- endif -%}
"</benchmark>\n"
%- macro format_config_block(cfg) -%}
"<config format=\""cfg.get(format, json)"\">\n"cfg.get(content, ) | tojson"\n</config>\n"
%- macro format_env_var(env) -%}
"<env name=\""env.get(name, )"\" required=\""(env.required | string if env.required is defined else false)"\"/>\n"
%- macro format_log_entry(log) -%}
"<log level=\""log.get(level, info)"\" timestamp=\""log.get(timestamp, )"\">\n"log.get(message, )"\n</log>\n"
%- macro format_permission(perm) -%}
"<permission action=\""perm.get(action, read)"\" resource=\""perm.get(resource, )"\" granted=\""(perm.granted | string if perm.granted is defined else false)"\"/>\n"
%- macro format_rate_limit(rate) -%}
"<rate_limit requests=\""(rate.requests | string if rate.requests is defined else 0)"\" window=\""rate.get(window, 1m)"\" remaining=\""(rate.remaining | string if rate.remaining is defined else 0)"\"/>\n"
%- macro format_cache_info(cache) -%}
"<cache hit=\""(cache.hit | string if cache.hit is defined else false)"\" ttl=\""(cache.ttl | string if cache.ttl is defined else 0)"\" key=\""cache.get(key, )"\"/>\n"
%- macro format_pagination(page) -%}
"<pagination current=\""(page.current | string if page.current is defined else 1)"\" total=\""(page.total | string if page.total is defined else 1)"\" per_page=\""(page.per_page | string if page.per_page is defined else 10)"\"/>\n"
%- macro format_filter(filter) -%}
"<filter field=\""filter.get(field, )"\" operator=\""filter.get(operator, eq)"\" value=\""(filter.value | string if filter.value is defined else )"\"/>\n"
%- macro format_sort(sort) -%}
"<sort field=\""sort.get(field, )"\" direction=\""sort.get(direction, asc)"\"/>\n"
%- macro format_aggregation(agg) -%}
"<aggregation function=\""agg.get(function, count)"\" field=\""agg.get(field, )"\" result=\""(agg.result | string if agg.result is defined else )"\"/>\n"
%- macro format_embedding(emb) -%}
"<embedding model=\""emb.get(model, default)"\" dimensions=\""(emb.dimensions | string if emb.dimensions is defined else 768)"\">\n"emb.get(vector, []) | tojson"\n</embedding>\n"
%- macro format_similarity(sim) -%}
"<similarity method=\""sim.get(method, cosine)"\" score=\""(sim.score | string if sim.score is defined else 0.0)"\">\n"
%- if sim.query is {% defined -%}"<query>"sim.query"</query>\n"{%- endif -%}
%- if sim.matches is {% defined -%}{%- for match in sim.{% matches -%}"<match score=\""(match.score | string if match.score is defined else 0)"\">"match.get(content, )"</match>\n"{%- endfor -%}{%- endif -%}
"</similarity>\n"
%- macro format_sentiment(sent) -%}
"<sentiment label=\""sent.get(label, neutral)"\" score=\""(sent.score | string if sent.score is defined else 0.0)"\"/>\n"
%- macro format_ner_result(ner) -%}
"<ner_result>\n"
%- if ner.entities is {% defined -%}{%- for entity in ner.{% entities -%}"<entity type=\""entity.get(type, UNKNOWN)"\" start=\""(entity.start | string if entity.start is defined else 0)"\" end=\""(entity.end | string if entity.end is defined else 0)"\">"entity.get(text, )"</entity>\n"{%- endfor -%}{%- endif -%}
"</ner_result>\n"
%- macro format_classification(cls) -%}
"<classification>\n"
%- if cls.labels is {% defined -%}{%- for label in cls.{% labels -%}"<label name=\""label.get(name, )"\" confidence=\""(label.confidence | string if label.confidence is defined else 0)"\"/>\n"{%- endfor -%}{%- endif -%}
"</classification>\n"
%- macro format_translation_block(trans) -%}
"<translation source_lang=\""trans.get(source_lang, auto)"\" target_lang=\""trans.get(target_lang, en)"\">\n"
%- if trans.source is {% defined -%}"<source>"trans.source"</source>\n"{%- endif -%}
%- if trans.target is {% defined -%}"<target>"trans.target"</target>\n"{%- endif -%}
"</translation>\n"
%- macro format_summarization(summ) -%}
"<summarization ratio=\""(summ.ratio | string if summ.ratio is defined else 0.5)"\" method=\""summ.get(method, abstractive)"\">\n"summ.get(summary, )"\n</summarization>\n"
%- macro format_qa_result(qa) -%}
"<qa_result confidence=\""(qa.confidence | string if qa.confidence is defined else 0.0)"\">\n"
%- if qa.question is {% defined -%}"<question>"qa.question"</question>\n"{%- endif -%}
%- if qa.answer is {% defined -%}"<answer>"qa.answer"</answer>\n"{%- endif -%}
%- if qa.context is {% defined -%}"<context>"qa.context"</context>\n"{%- endif -%}
"</qa_result>\n"
%- macro format_generation_params(params) -%}
"<generation_params>\n"
%- if params.temperature is {% defined -%}"<temperature>"(params.temperature | string)"</temperature>\n"{%- endif -%}
%- if params.top_p is {% defined -%}"<top_p>"(params.top_p | string)"</top_p>\n"{%- endif -%}
%- if params.top_k is {% defined -%}"<top_k>"(params.top_k | string)"</top_k>\n"{%- endif -%}
%- if params.max_tokens is {% defined -%}"<max_tokens>"(params.max_tokens | string)"</max_tokens>\n"{%- endif -%}
%- if params.repetition_penalty is {% defined -%}"<repetition_penalty>"(params.repetition_penalty | string)"</repetition_penalty>\n"{%- endif -%}
"</generation_params>\n"
%- macro format_model_info(model) -%}
"<model_info>\n"
%- if model.name is {% defined -%}"<name>"model.name"</name>\n"{%- endif -%}
%- if model.version is {% defined -%}"<version>"model.version"</version>\n"{%- endif -%}
%- if model.type is {% defined -%}"<type>"model.type"</type>\n"{%- endif -%}
%- if model.parameters is {% defined -%}"<parameters>"(model.parameters | string)"</parameters>\n"{%- endif -%}
%- if model.modalities is {% defined -%}"<modalities>"model.modalities | tojson"</modalities>\n"{%- endif -%}
"</model_info>\n"
%- macro format_session(session) -%}
"<session id=\""session.get(id, )"\" created=\""session.get(created, )"\">\n"
%- if session.user is {% defined -%}"<user>"session.user | tojson"</user>\n"{%- endif -%}
%- if session.history_length is {% defined -%}"<history_length>"(session.history_length | string)"</history_length>\n"{%- endif -%}
"</session>\n"
%- macro format_webhook(hook) -%}
"<webhook url=\""hook.get(url, )"\" event=\""hook.get(event, )"\" status=\""hook.get(status, pending)"\"/>\n"
%- macro format_retry(retry) -%}
"<retry attempt=\""(retry.attempt | string if retry.attempt is defined else 1)"\" max_attempts=\""(retry.max_attempts | string if retry.max_attempts is defined else 3)"\" delay=\""(retry.delay | string if retry.delay is defined else 1000)"ms\"/>\n"
%- macro format_timeout(timeout) -%}
"<timeout value=\""(timeout.value | string if timeout.value is defined else 30000)"ms\" type=\""timeout.get(type, request)"\"/>\n"
%- macro format_workflow(workflow) -%}
"<workflow id=\""workflow.get(id, )"\" name=\""workflow.get(name, )"\" status=\""workflow.get(status, pending)"\">\n"
%- if workflow.steps is {% defined -%}{%- for step in workflow.{% steps -%}"<workflow_step n=\""loop.index | string"\" status=\""step.get(status, pending)"\">"step.get(action, )"</workflow_step>\n"{%- endfor -%}{%- endif -%}
%- if workflow.current_step is {% defined -%}"<current_step>"(workflow.current_step | string)"</current_step>\n"{%- endif -%}
"</workflow>\n"
%- macro format_pipeline(pipeline) -%}
"<pipeline name=\""pipeline.get(name, )"\" version=\""pipeline.get(version, 1.0)"\">\n"
%- if pipeline.stages is {% defined -%}{%- for stage in pipeline.{% stages -%}"<stage name=\""stage.get(name, )"\" type=\""stage.get(type, transform)"\"/>"{%- endfor -%}{%- endif -%}
"</pipeline>\n"
%- macro format_schema_validation(validation) -%}
"<schema_validation status=\""validation.get(status, unknown)"\">\n"
%- if validation.errors is {% defined -%}"<validation_errors>"validation.errors | tojson"</validation_errors>\n"{%- endif -%}
%- if validation.warnings is {% defined -%}"<validation_warnings>"validation.warnings | tojson"</validation_warnings>\n"{%- endif -%}
"</schema_validation>\n"
%- macro format_audit_log(audit) -%}
"<audit_log timestamp=\""audit.get(timestamp, )"\" action=\""audit.get(action, )"\" actor=\""audit.get(actor, system)"\">\n"
%- if audit.resource is {% defined -%}"<resource>"audit.resource"</resource>\n"{%- endif -%}
%- if audit.changes is {% defined -%}"<changes>"audit.changes | tojson"</changes>\n"{%- endif -%}
"</audit_log>\n"
%- macro format_compliance(compliance) -%}
"<compliance framework=\""compliance.get(framework, general)"\" status=\""compliance.get(status, unknown)"\">\n"
%- if compliance.controls is {% defined -%}{%- for ctrl in compliance.{% controls -%}"<control id=\""ctrl.get(id, )"\" status=\""ctrl.get(status, pending)"\">"ctrl.get(description, )"</control>\n"{%- endfor -%}{%- endif -%}
"</compliance>\n"
%- macro format_encryption(enc) -%}
"<encryption algorithm=\""enc.get(algorithm, AES-256)"\" key_id=\""enc.get(key_id, )"\" status=\""enc.get(status, encrypted)"\"/>\n"
%- macro format_signature(sig) -%}
"<digital_signature algorithm=\""sig.get(algorithm, RSA-{{ .SHA256 }})"\" signer=\""sig.get(signer, )"\" verified=\""(sig.verified | string if sig.verified is defined else false)"\"/>\n"
%- macro format_certificate(cert) -%}
"<certificate issuer=\""cert.get(issuer, )"\" subject=\""cert.get(subject, )"\" valid_until=\""cert.get(valid_until, )"\" status=\""cert.get(status, valid)"\"/>\n"
%- macro format_access_token(token) -%}
"<access_token type=\""token.get(type, bearer)"\" expires_in=\""(token.expires_in | string if token.expires_in is defined else 3600)"\" scopes=\""token.get(scopes, []) | join(,)"\"/>\n"
%- macro format_oauth_flow(oauth) -%}
"<oauth_flow grant_type=\""oauth.get(grant_type, authorization_code)"\" state=\""oauth.get(state, )"\" redirect_uri=\""oauth.get(redirect_uri, )"\"/>\n"
%- macro format_rbac(rbac) -%}
"<rbac>\n"
%- if rbac.roles is {% defined -%}{%- for role in rbac.{% roles -%}"<role name=\""role.get(name, )"\" permissions=\""role.get(permissions, []) | join(,)"\"/>\n"{%- endfor -%}{%- endif -%}
%- if rbac.user_role is {% defined -%}"<user_role>"rbac.user_role"</user_role>\n"{%- endif -%}
"</rbac>\n"
%- macro format_rate_limiting(rl) -%}
"<rate_limiting strategy=\""rl.get(strategy, token_bucket)"\" limit=\""(rl.limit | string if rl.limit is defined else 100)"\" window=\""rl.get(window, 1m)"\" current=\""(rl.current | string if rl.current is defined else 0)"\"/>\n"
%- macro format_circuit_breaker(cb) -%}
"<circuit_breaker name=\""cb.get(name, )"\" state=\""cb.get(state, closed)"\" failure_count=\""(cb.failure_count | string if cb.failure_count is defined else 0)"\" threshold=\""(cb.threshold | string if cb.threshold is defined else 5)"\"/>\n"
%- macro format_health_check(health) -%}
"<health_check service=\""health.get(service, )"\" status=\""health.get(status, healthy)"\" latency_ms=\""(health.latency_ms | string if health.latency_ms is defined else 0)"\">\n"
%- if health.dependencies is {% defined -%}{%- for dep in health.{% dependencies -%}"<dependency name=\""dep.get(name, )"\" status=\""dep.get(status, unknown)"\"/>\n"{%- endfor -%}{%- endif -%}
"</health_check>\n"
%- macro format_metrics(metrics) -%}
"<metrics timestamp=\""metrics.get(timestamp, )"\">\n"
%- if metrics.values is {% defined -%}{%- for k, v in metrics.values.items() -%}"<metric name=\""k"\">"(v | string)"</metric>\n"{%- endfor -%}{%- endif -%}
"</metrics>\n"
%- macro format_trace_span(span) -%}
"<trace_span trace_id=\""span.get(trace_id, )"\" span_id=\""span.get(span_id, )"\" parent_id=\""span.get(parent_id, )"\" operation=\""span.get(operation, )"\" duration_ms=\""(span.duration_ms | string if span.duration_ms is defined else 0)"\"/>\n"
%- macro format_distributed_lock(lock) -%}
"<distributed_lock key=\""lock.get(key, )"\" holder=\""lock.get(holder, )"\" ttl=\""(lock.ttl | string if lock.ttl is defined else 30000)"ms\" acquired=\""(lock.acquired | string if lock.acquired is defined else false)"\"/>\n"
%- macro format_queue_message(msg) -%}
"<queue_message queue=\""msg.get(queue, )"\" message_id=\""msg.get(message_id, )"\" priority=\""(msg.priority | string if msg.priority is defined else 0)"\" retry_count=\""(msg.retry_count | string if msg.retry_count is defined else 0)"\">\n"
%- if msg.payload is {% defined -%}"<payload>"msg.payload | tojson"</payload>\n"{%- endif -%}
"</queue_message>\n"
%- macro format_event(event) -%}
"<event type=\""event.get(type, )"\" source=\""event.get(source, )"\" timestamp=\""event.get(timestamp, )"\">\n"
%- if event.data is {% defined -%}"<event_data>"event.data | tojson"</event_data>\n"{%- endif -%}
"</event>\n"
%- macro format_notification(notif) -%}
"<notification type=\""notif.get(type, info)"\" channel=\""notif.get(channel, default)"\" priority=\""notif.get(priority, normal)"\">\n"
%- if notif.title is {% defined -%}"<title>"notif.title"</title>\n"{%- endif -%}
%- if notif.body is {% defined -%}"<body>"notif.body"</body>\n"{%- endif -%}
"</notification>\n"
%- macro format_scheduled_task(task) -%}
"<scheduled_task id=\""task.get(id, )"\" cron=\""task.get(cron, )"\" next_run=\""task.get(next_run, )"\" enabled=\""(task.enabled | string if task.enabled is defined else true)"\">\n"
%- if task.action is {% defined -%}"<action>"task.action | tojson"</action>\n"{%- endif -%}
"</scheduled_task>\n"
%- macro format_feature_flag(flag) -%}
"<feature_flag name=\""flag.get(name, )"\" enabled=\""(flag.enabled | string if flag.enabled is defined else false)"\" rollout_percentage=\""(flag.rollout_percentage | string if flag.rollout_percentage is defined else 0)"\"/>\n"
%- macro format_ab_test(test) -%}
"<ab_test name=\""test.get(name, )"\" variant=\""test.get(variant, control)"\" experiment_id=\""test.get(experiment_id, )"\">\n"
%- if test.metrics is {% defined -%}"<test_metrics>"test.metrics | tojson"</test_metrics>\n"{%- endif -%}
"</ab_test>\n"
%- macro format_user_profile(profile) -%}
"<user_profile id=\""profile.get(id, )"\" role=\""profile.get(role, user)"\" tier=\""profile.get(tier, free)"\">\n"
%- if profile.preferences is {% defined -%}"<preferences>"profile.preferences | tojson"</preferences>\n"{%- endif -%}
%- if profile.permissions is {% defined -%}"<permissions>"profile.permissions | tojson"</permissions>\n"{%- endif -%}
"</user_profile>\n"
%- macro format_organization(org) -%}
"<organization id=\""org.get(id, )"\" name=\""org.get(name, )"\" plan=\""org.get(plan, free)"\">\n"
%- if org.members_count is {% defined -%}"<members_count>"(org.members_count | string)"</members_count>\n"{%- endif -%}
%- if org.settings is {% defined -%}"<org_settings>"org.settings | tojson"</org_settings>\n"{%- endif -%}
"</organization>\n"
%- macro format_billing(billing) -%}
"<billing plan=\""billing.get(plan, free)"\" status=\""billing.get(status, active)"\" next_billing_date=\""billing.get(next_billing_date, )"\">\n"
%- if billing.usage is {% defined -%}"<usage>"billing.usage | tojson"</usage>\n"{%- endif -%}
%- if billing.credits is {% defined -%}"<credits>"(billing.credits | string)"</credits>\n"{%- endif -%}
"</billing>\n"
%- macro format_quota(quota) -%}
"<quota resource=\""quota.get(resource, )"\" limit=\""(quota.limit | string if quota.limit is defined else 0)"\" used=\""(quota.used | string if quota.used is defined else 0)"\" reset_at=\""quota.get(reset_at, )"\"/>\n"
%- macro format_sla(sla) -%}
"<sla name=\""sla.get(name, )"\" target=\""sla.get(target, 99.9%)"\" current=\""sla.get(current, )"\" status=\""sla.get(status, meeting)"\"/>\n"
%- macro format_incident(incident) -%}
"<incident id=\""incident.get(id, )"\" severity=\""incident.get(severity, low)"\" status=\""incident.get(status, open)"\">\n"
%- if incident.title is {% defined -%}"<incident_title>"incident.title"</incident_title>\n"{%- endif -%}
%- if incident.description is {% defined -%}"<incident_description>"incident.description"</incident_description>\n"{%- endif -%}
%- if incident.affected_services is {% defined -%}"<affected_services>"incident.affected_services | tojson"</affected_services>\n"{%- endif -%}
"</incident>\n"
%- macro format_runbook(runbook) -%}
"<runbook name=\""runbook.get(name, )"\" version=\""runbook.get(version, 1.0)"\">\n"
%- if runbook.steps is {% defined -%}{%- for step in runbook.{% steps -%}"<runbook_step n=\""loop.index | string"\">\n<action>"step.get(action, )"</action>\n<expected>"step.get(expected, )"</expected>\n</runbook_step>\n"{%- endfor -%}{%- endif -%}
"</runbook>\n"
%- macro format_deployment(deployment) -%}
"<deployment id=\""deployment.get(id, )"\" environment=\""deployment.get(environment, production)"\" status=\""deployment.get(status, pending)"\" version=\""deployment.get(version, )"\">\n"
%- if deployment.changes is {% defined -%}"<deployment_changes>"deployment.changes | tojson"</deployment_changes>\n"{%- endif -%}
%- if deployment.rollback_version is {% defined -%}"<rollback_version>"deployment.rollback_version"</rollback_version>\n"{%- endif -%}
"</deployment>\n"
%- macro format_infrastructure(infra) -%}
"<infrastructure provider=\""infra.get(provider, aws)"\" region=\""infra.get(region, )"\">\n"
%- if infra.resources is {% defined -%}{%- for res in infra.{% resources -%}"<resource type=\""res.get(type, )"\" name=\""res.get(name, )"\" status=\""res.get(status, active)"\"/>\n"{%- endfor -%}{%- endif -%}
"</infrastructure>\n"
%- macro format_container(container) -%}
"<container id=\""container.get(id, )"\" image=\""container.get(image, )"\" status=\""container.get(status, running)"\" replicas=\""(container.replicas | string if container.replicas is defined else 1)"\">\n"
%- if container.resources is {% defined -%}"<container_resources>"container.resources | tojson"</container_resources>\n"{%- endif -%}
"</container>\n"
%- macro format_database_operation(db_op) -%}
"<database_operation type=\""db_op.get(type, query)"\" database=\""db_op.get(database, )"\" table=\""db_op.get(table, )"\" duration_ms=\""(db_op.duration_ms | string if db_op.duration_ms is defined else 0)"\">\n"
%- if db_op.affected_rows is {% defined -%}"<affected_rows>"(db_op.affected_rows | string)"</affected_rows>\n"{%- endif -%}
"</database_operation>\n"
%- macro format_migration(migration) -%}
"<migration id=\""migration.get(id, )"\" version=\""migration.get(version, )"\" status=\""migration.get(status, pending)"\" direction=\""migration.get(direction, up)"\">\n"
%- if migration.description is {% defined -%}"<migration_description>"migration.description"</migration_description>\n"{%- endif -%}
"</migration>\n"
%- macro format_backup(backup) -%}
"<backup id=\""backup.get(id, )"\" type=\""backup.get(type, full)"\" status=\""backup.get(status, completed)"\" size_bytes=\""(backup.size_bytes | string if backup.size_bytes is defined else 0)"\" created_at=\""backup.get(created_at, )"\"/>\n"
%- macro format_restore(restore) -%}
"<restore backup_id=\""restore.get(backup_id, )"\" status=\""restore.get(status, pending)"\" progress=\""(restore.progress | string if restore.progress is defined else 0)"%\"/>\n"
%- macro format_secret(secret) -%}
"<secret name=\""secret.get(name, )"\" version=\""(secret.version | string if secret.version is defined else 1)"\" created_at=\""secret.get(created_at, )"\" rotation_enabled=\""(secret.rotation_enabled | string if secret.rotation_enabled is defined else false)"\"/>\n"
%- macro format_policy(policy) -%}
"<policy name=\""policy.get(name, )"\" effect=\""policy.get(effect, allow)"\">\n"
%- if policy.actions is {% defined -%}"<policy_actions>"policy.actions | tojson"</policy_actions>\n"{%- endif -%}
%- if policy.resources is {% defined -%}"<policy_resources>"policy.resources | tojson"</policy_resources>\n"{%- endif -%}
%- if policy.conditions is {% defined -%}"<policy_conditions>"policy.conditions | tojson"</policy_conditions>\n"{%- endif -%}
"</policy>\n"
%- macro format_api_version(ver) -%}
"<api_version version=\""ver.get(version, {{ .v1 }})"\" status=\""ver.get(status, stable)"\" deprecated=\""(ver.deprecated | string if ver.deprecated is defined else false)"\" sunset_date=\""ver.get(sunset_date, )"\"/>\n"
%- macro format_graphql_query(gql) -%}
"<graphql_query operation=\""gql.get(operation, query)"\" name=\""gql.get(name, )"\">\n"gql.get(query, )"\n</graphql_query>\n"
%- macro format_grpc_call(grpc) -%}
"<grpc_call service=\""grpc.get(service, )"\" method=\""grpc.get(method, )"\" status_code=\""(grpc.status_code | string if grpc.status_code is defined else 0)"\">\n"
%- if grpc.request is {% defined -%}"<grpc_request>"grpc.request | tojson"</grpc_request>\n"{%- endif -%}
%- if grpc.response is {% defined -%}"<grpc_response>"grpc.response | tojson"</grpc_response>\n"{%- endif -%}
"</grpc_call>\n"
%- macro format_websocket_message(ws) -%}
"<websocket_message type=\""ws.get(type, text)"\" channel=\""ws.get(channel, )"\">\n"ws.get(data, ) | tojson"\n</websocket_message>\n"
%- macro format_stream_event(stream) -%}
"<stream_event stream_id=\""stream.get(stream_id, )"\" event_type=\""stream.get(event_type, data)"\" sequence=\""(stream.sequence | string if stream.sequence is defined else 0)"\">\n"stream.get(data, ) | tojson"\n</stream_event>\n"
%- macro format_batch_operation(batch) -%}
"<batch_operation id=\""batch.get(id, )"\" total=\""(batch.total | string if batch.total is defined else 0)"\" processed=\""(batch.processed | string if batch.processed is defined else 0)"\" failed=\""(batch.failed | string if batch.failed is defined else 0)"\" status=\""batch.get(status, processing)"\"/>\n"
%- macro format_async_job(job) -%}
"<async_job id=\""job.get(id, )"\" type=\""job.get(type, )"\" status=\""job.get(status, queued)"\" priority=\""(job.priority | string if job.priority is defined else 0)"\" created_at=\""job.get(created_at, )"\">\n"
%- if job.result is {% defined -%}"<job_result>"job.result | tojson"</job_result>\n"{%- endif -%}
%- if job.error is {% defined -%}"<job_error>"job.error"</job_error>\n"{%- endif -%}
"</async_job>\n"
%- macro format_callback(callback) -%}
"<callback url=\""callback.get(url, )"\" method=\""callback.get(method, POST)"\" status=\""callback.get(status, pending)"\" retry_count=\""(callback.retry_count | string if callback.retry_count is defined else 0)"\"/>\n"
%- macro format_idempotency(idem) -%}
"<idempotency key=\""idem.get(key, )"\" status=\""idem.get(status, new)"\" created_at=\""idem.get(created_at, )"\" expires_at=\""idem.get(expires_at, )"\"/>\n"
%- macro format_concurrency(conc) -%}
"<concurrency limit=\""(conc.limit | string if conc.limit is defined else 10)"\" current=\""(conc.current | string if conc.current is defined else 0)"\" queued=\""(conc.queued | string if conc.queued is defined else 0)"\"/>\n"
%- macro format_throttle(throttle) -%}
"<throttle rate=\""(throttle.rate | string if throttle.rate is defined else 100)"/s\" burst=\""(throttle.burst | string if throttle.burst is defined else 10)"\" current=\""(throttle.current | string if throttle.current is defined else 0)"\"/>\n"
%- macro format_checkpoint(checkpoint) -%}
"<checkpoint id=\""checkpoint.get(id, )"\" state=\""checkpoint.get(state, ) | tojson"\" timestamp=\""checkpoint.get(timestamp, )"\" recoverable=\""(checkpoint.recoverable | string if checkpoint.recoverable is defined else true)"\"/>\n"
%- macro format_saga(saga) -%}
"<saga id=\""saga.get(id, )"\" status=\""saga.get(status, running)"\">\n"
%- if saga.steps is {% defined -%}{%- for step in saga.{% steps -%}"<saga_step name=\""step.get(name, )"\" status=\""step.get(status, pending)"\" compensated=\""(step.compensated | string if step.compensated is defined else false)"\"/>\n"{%- endfor -%}{%- endif -%}
"</saga>\n"
%- macro format_outbox(outbox) -%}
"<outbox id=\""outbox.get(id, )"\" aggregate_type=\""outbox.get(aggregate_type, )"\" aggregate_id=\""outbox.get(aggregate_id, )"\" event_type=\""outbox.get(event_type, )"\" published=\""(outbox.published | string if outbox.published is defined else false)"\"/>\n"
%- macro format_cqrs_command(cmd) -%}
"<cqrs_command name=\""cmd.get(name, )"\" aggregate_id=\""cmd.get(aggregate_id, )"\" version=\""(cmd.version | string if cmd.version is defined else 1)"\">\n"cmd.get(payload, {}) | tojson"\n</cqrs_command>\n"
%- macro format_cqrs_query(query) -%}
"<cqrs_query name=\""query.get(name, )"\" cache=\""(query.cache | string if query.cache is defined else true)"\">\n"query.get(parameters, {}) | tojson"\n</cqrs_query>\n"
%- macro format_event_sourcing(es) -%}
"<event_sourcing aggregate_id=\""es.get(aggregate_id, )"\" aggregate_type=\""es.get(aggregate_type, )"\" version=\""(es.version | string if es.version is defined else 0)"\">\n"
%- if es.events is {% defined -%}{%- for event in es.{% events -%}"<sourced_event type=\""event.get(type, )"\" version=\""(event.version | string if event.version is defined else 0)"\" timestamp=\""event.get(timestamp, )"\"/>"{%- endfor -%}{%- endif -%}
"\n</event_sourcing>\n"
%- macro format_domain_event(de) -%}
"<domain_event name=\""de.get(name, )"\" aggregate_id=\""de.get(aggregate_id, )"\" version=\""(de.version | string if de.version is defined else 1)"\" occurred_at=\""de.get(occurred_at, )"\">\n"de.get(data, {}) | tojson"\n</domain_event>\n"
%- macro format_snapshot(snapshot) -%}
"<snapshot aggregate_id=\""snapshot.get(aggregate_id, )"\" version=\""(snapshot.version | string if snapshot.version is defined else 0)"\" created_at=\""snapshot.get(created_at, )"\">\n"snapshot.get(state, {}) | tojson"\n</snapshot>\n"
%- macro format_reasoning_level(level) -%}
"<reasoning_level level=\""level.get(level, deep)"\" depth=\""(level.depth | string if level.depth is defined else 3)"\" max_tokens=\""(level.max_tokens | string if level.max_tokens is defined else 500)"\" reflection=\""(level.reflection | string if level.reflection is defined else true)"\" verification=\""(level.verification | string if level.verification is defined else true)"\"/>\n"
%- macro format_thinking_step(step) -%}
"<thinking_step n=\""(step.number | string if step.number is defined else 1)"\" type=\""step.get(type, analysis)"\">\n"step.get(content, )"\n</thinking_step>\n"
%- macro format_reasoning_chain(chain) -%}
"<reasoning_chain id=\""chain.get(id, )"\" type=\""chain.get(type, sequential)"\" status=\""chain.get(status, active)"\">\n"
%- if chain.steps is {% defined -%}{%- for step in chain.{% steps -%}format_thinking_step(step){%- endfor -%}{%- endif -%}
"</reasoning_chain>\n"
%- macro format_hypothesis_test(hyp) -%}
"<hypothesis_test id=\""hyp.get(id, )"\" status=\""hyp.get(status, pending)"\">\n"
"<hypothesis_statement>"hyp.get(statement, )"</hypothesis_statement>\n"
%- if hyp.evidence_for is {% defined -%}"<evidence_for>"hyp.evidence_for | tojson"</evidence_for>\n"{%- endif -%}
%- if hyp.evidence_against is {% defined -%}"<evidence_against>"hyp.evidence_against | tojson"</evidence_against>\n"{%- endif -%}
%- if hyp.confidence is {% defined -%}"<confidence_score>"(hyp.confidence | string)"</confidence_score>\n"{%- endif -%}
"</hypothesis_test>\n"
%- macro format_self_critique(critique) -%}
"<self_critique iteration=\""(critique.iteration | string if critique.iteration is defined else 1)"\">\n"
"<critique_points>"critique.get(points, []) | tojson"</critique_points>\n"
"<improvements>"critique.get(improvements, []) | tojson"</improvements>\n"
"</self_critique>\n"
%- macro format_backtracking(bt) -%}
"<backtracking from_step=\""(bt.from_step | string if bt.from_step is defined else 0)"\" to_step=\""(bt.to_step | string if bt.to_step is defined else 0)"\" reason=\""bt.get(reason, )"\"/>\n"
%- macro format_confidence_score(conf) -%}
"<confidence_score value=\""(conf.value | string if conf.value is defined else 0.0)"\" method=\""conf.get(method, self_assessment)"\" factors=\""conf.get(factors, []) | tojson"\"/>\n"
%- macro format_stream_chunk(chunk) -%}
"<stream_chunk id=\""chunk.get(id, )"\" index=\""(chunk.index | string if chunk.index is defined else 0)"\" type=\""chunk.get(type, content)"\" is_final=\""(chunk.is_final | string if chunk.is_final is defined else false)"\">\n"chunk.get(data, )"\n</stream_chunk>\n"
%- macro format_stream_start(stream) -%}
"<stream_start stream_id=\""stream.get(stream_id, )"\" mode=\""stream.get(mode, token)"\" expected_tokens=\""(stream.expected_tokens | string if stream.expected_tokens is defined else 0)"\"/>\n"
%- macro format_stream_end(stream) -%}
"<stream_end stream_id=\""stream.get(stream_id, )"\" total_tokens=\""(stream.total_tokens | string if stream.total_tokens is defined else 0)"\" duration_ms=\""(stream.duration_ms | string if stream.duration_ms is defined else 0)"\" status=\""stream.get(status, completed)"\"/>\n"
%- macro format_tool_parameters(params) -%}
"<tool_parameters>\n"
%- for name, spec in params | {% dictsort -%}
"<param name=\""name"\" type=\""spec.get(type, string)"\""
%- if spec.required is defined and spec.{% required -%}" required=\"true\""{%- endif -%}
%- if spec.default is {% defined -%}" default=\""(spec.default | string)"\""{%- endif -%}
%- if spec.enum is {% defined -%}" enum=\""spec.enum | tojson"\""{%- endif -%}
"/>\n"
"</tool_parameters>\n"
%- macro format_tool_execution(exec) -%}
"<tool_execution tool=\""exec.get(tool, )"\" execution_id=\""exec.get(execution_id, )"\" status=\""exec.get(status, running)"\" started_at=\""exec.get(started_at, )"\">\n"
%- if exec.input is {% defined -%}"<tool_input>"exec.input | tojson"</tool_input>\n"{%- endif -%}
%- if exec.output is {% defined -%}"<tool_output>"exec.output | tojson"</tool_output>\n"{%- endif -%}
%- if exec.error is {% defined -%}"<tool_error>"exec.error"</tool_error>\n"{%- endif -%}
%- if exec.duration_ms is {% defined -%}"<tool_duration_ms>"(exec.duration_ms | string)"</tool_duration_ms>\n"{%- endif -%}
"</tool_execution>\n"
%- macro format_parallel_tool_calls(calls) -%}
"<parallel_tool_calls count=\""(calls | length | string)"\">\n"
%- for call in {% calls -%}
"<parallel_call index=\""loop.index | string"\" tool=\""call.get(tool, )"\">\n"call.get(args, {}) | tojson"\n</parallel_call>\n"
"</parallel_tool_calls>\n"
%- macro format_tool_result_aggregation(agg) -%}
"<tool_result_aggregation strategy=\""agg.get(strategy, merge)"\">\n"
%- if agg.results is {% defined -%}{%- for res in agg.{% results -%}"<aggregated_result tool=\""res.get(tool, )"\" success=\""(res.success | string if res.success is defined else true)"\">\n"res.get(data, {}) | tojson"\n</aggregated_result>\n"{%- endfor -%}{%- endif -%}
"</tool_result_aggregation>\n"
%- macro format_multi_step_reasoning(msr) -%}
"<multi_step_reasoning total_steps=\""(msr.total_steps | string if msr.total_steps is defined else 0)"\" current_step=\""(msr.current_step | string if msr.current_step is defined else 0)"\" strategy=\""msr.get(strategy, sequential)"\">\n"
%- if msr.completed_steps is {% defined -%}"<completed_steps>"msr.completed_steps | tojson"</completed_steps>\n"{%- endif -%}
%- if msr.pending_steps is {% defined -%}"<pending_steps>"msr.pending_steps | tojson"</pending_steps>\n"{%- endif -%}
%- if msr.intermediate_results is {% defined -%}"<intermediate_results>"msr.intermediate_results | tojson"</intermediate_results>\n"{%- endif -%}
"</multi_step_reasoning>\n"
%- macro format_reasoning_tree(tree) -%}
"<reasoning_tree root=\""tree.get(root, )"\" depth=\""(tree.depth | string if tree.depth is defined else 0)"\">\n"
%- if tree.nodes is {% defined -%}{%- for node in tree.{% nodes -%}"<tree_node id=\""node.get(id, )"\" parent=\""node.get(parent, )"\" type=\""node.get(type, thought)"\">\n"node.get(content, )"\n</tree_node>\n"{%- endfor -%}{%- endif -%}
"</reasoning_tree>\n"
%- macro format_beam_search(beam) -%}
"<beam_search num_beams=\""(beam.num_beams | string if beam.num_beams is defined else 4)"\" diversity_penalty=\""(beam.diversity_penalty | string if beam.diversity_penalty is defined else 0.0)"\">\n"
%- if beam.candidates is {% defined -%}{%- for cand in beam.{% candidates -%}"<beam_candidate score=\""(cand.score | string if cand.score is defined else 0.0)"\" rank=\""loop.index | string"\">\n"cand.get(text, )"\n</beam_candidate>\n"{%- endfor -%}{%- endif -%}
"</beam_search>\n"
%- macro format_token_probability(prob) -%}
"<token_probability token=\""prob.get(token, )"\" prob=\""(prob.prob | string if prob.prob is defined else 0.0)"\" logprob=\""(prob.logprob | string if prob.logprob is defined else 0.0)"\"/>\n"
%- macro format_generation_step(step) -%}
"<generation_step n=\""(step.n | string if step.n is defined else 0)"\" token_id=\""(step.token_id | string if step.token_id is defined else 0)"\" token=\""step.get(token, )"\" cumulative_prob=\""(step.cumulative_prob | string if step.cumulative_prob is defined else 0.0)"\">\n"
%- if step.top_k_probs is {% defined -%}"<top_k_tokens>"step.top_k_probs | tojson"</top_k_tokens>\n"{%- endif -%}
"</generation_step>\n"
%- macro format_attention_weights(attn) -%}
"<attention_weights layer=\""(attn.layer | string if attn.layer is defined else 0)"\" head=\""(attn.head | string if attn.head is defined else 0)"\">\n"attn.get(weights, []) | tojson"\n</attention_weights>\n"
%- macro format_tool_chain(chain) -%}
"<tool_chain id=\""chain.get(id, )"\" status=\""chain.get(status, running)"\">\n"
%- if chain.sequence is {% defined -%}{%- for tool in chain.{% sequence -%}"<chained_tool order=\""loop.index | string"\" name=\""tool.get(name, )"\" depends_on=\""(tool.depends_on | tojson if tool.depends_on is defined else [])"\" status=\""tool.get(status, pending)"\"/>\n"{%- endfor -%}{%- endif -%}
"</tool_chain>\n"
%- macro format_reasoning_meta(meta) -%}
"<reasoning_meta>\n"
"<total_thinking_tokens>"(meta.total_thinking_tokens | string if meta.total_thinking_tokens is defined else 0)"</total_thinking_tokens>\n"
"<reasoning_depth>"(meta.reasoning_depth | string if meta.reasoning_depth is defined else 0)"</reasoning_depth>\n"
"<hypotheses_evaluated>"(meta.hypotheses_evaluated | string if meta.hypotheses_evaluated is defined else 0)"</hypotheses_evaluated>\n"
"<backtracking_count>"(meta.backtracking_count | string if meta.backtracking_count is defined else 0)"</backtracking_count>\n"
"<final_confidence>"(meta.final_confidence | string if meta.final_confidence is defined else 0.0)"</final_confidence>\n"
"</reasoning_meta>\n"
%- macro format_semantic_search(search) -%}
"<semantic_search query=\""search.get(query, )"\" k=\""(search.k | string if search.k is defined else 10)"\" threshold=\""(search.threshold | string if search.threshold is defined else 0.7)"\">\n"
%- if search.results is {% defined -%}{%- for result in search.{% results -%}"<search_result score=\""(result.score | string if result.score is defined else 0)"\">"result.get(content, )"</search_result>\n"{%- endfor -%}{%- endif -%}
"</semantic_search>\n"
%- macro format_rag_context(rag) -%}
"<rag_context retrieval_method=\""rag.get(retrieval_method, dense)"\" num_documents=\""(rag.num_documents | string if rag.num_documents is defined else 0)"\">\n"
%- if rag.documents is {% defined -%}{%- for doc in rag.{% documents -%}"<retrieved_doc id=\""doc.get(id, )"\" score=\""(doc.score | string if doc.score is defined else 0)"\">"doc.get(content, )"</retrieved_doc>\n"{%- endfor -%}{%- endif -%}
"</rag_context>\n"
%- macro format_agent_state(state) -%}
"<agent_state agent_id=\""state.get(agent_id, )"\" status=\""state.get(status, active)"\" iteration=\""(state.iteration | string if state.iteration is defined else 0)"\">\n"
%- if state.current_goal is {% defined -%}"<current_goal>"state.current_goal"</current_goal>\n"{%- endif -%}
%- if state.memory is {% defined -%}"<agent_memory>"state.memory | tojson"</agent_memory>\n"{%- endif -%}
%- if state.tools_used is {% defined -%}"<tools_used>"state.tools_used | tojson"</tools_used>\n"{%- endif -%}
"</agent_state>\n"
%- macro format_multi_agent(agents) -%}
"<multi_agent_system coordinator=\""agents.get(coordinator, round_robin)"\">\n"
%- if agents.agents is {% defined -%}{%- for agent in agents.{% agents -%}"<agent name=\""agent.get(name, )"\" role=\""agent.get(role, )"\" status=\""agent.get(status, active)"\"/>\n"{%- endfor -%}{%- endif -%}
"</multi_agent_system>\n"
%- macro format_tool_response(resp) -%}
"<tool_response tool_name=\""resp.get(tool_name, )"\" status=\""resp.get(status, success)"\" duration_ms=\""(resp.duration_ms | string if resp.duration_ms is defined else 0)"\">\n"resp.get(result, ) | tojson"\n</tool_response>\n"
%- macro format_function_call(func) -%}
"<function_call name=\""func.get(name, )"\" id=\""func.get(id, )"\">\n"func.get(arguments, {}) | tojson"\n</function_call>\n"
%- macro format_function_result(result) -%}
"<function_result call_id=\""result.get(call_id, )"\" status=\""result.get(status, success)"\">\n"result.get(output, ) | tojson"\n</function_result>\n"
%- macro format_json_schema(schema) -%}
"<json_schema>\n"schema | tojson"\n</json_schema>\n"
%- macro format_structured_output(output) -%}
"<structured_output format=\""output.get(format, json)"\" schema_id=\""output.get(schema_id, )"\">\n"output.get(data, {}) | tojson"\n</structured_output>\n"
%- macro format_reasoning_trace(trace) -%}
"<reasoning_trace id=\""trace.get(id, )"\" type=\""trace.get(type, chain_of_thought)"\">\n"
%- if trace.steps is {% defined -%}{%- for step in trace.{% steps -%}"<trace_step n=\""loop.index | string"\" type=\""step.get(type, think)"\">"step.get(content, )"</trace_step>\n"{%- endfor -%}{%- endif -%}
"</reasoning_trace>\n"
%- macro format_model_capabilities(caps) -%}
"<model_capabilities>\n"
%- if caps.modalities is {% defined -%}"<supported_modalities>"caps.modalities | tojson"</supported_modalities>\n"{%- endif -%}
%- if caps.context_length is {% defined -%}"<context_length>"(caps.context_length | string)"</context_length>\n"{%- endif -%}
%- if caps.tools is {% defined -%}"<supported_tools>"caps.tools | tojson"</supported_tools>\n"{%- endif -%}
%- if caps.languages is {% defined -%}"<supported_languages>"caps.languages | tojson"</supported_langua