%- 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:
{%- 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 %}
{%- 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".
{%- 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 [])
"// 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) %}
"# 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!")
"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"
{%- 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 -%}
%- 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 -%}
%- 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 -%}
%- 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 -%}
"<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"
"<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 -%}
%- 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 -%}
"<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"
%- 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 -%}
%- if pipeline.stages is {% defined -%}{%- for stage in pipeline.{% stages -%}"<stage name=\""stage.get(name, )"\" type=\""stage.get(type, transform)"\"/>"{%- endfor -%}{%- endif -%}
%- 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 -%}
%- 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 -%}
%- 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 -%}
%- 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"
%- 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"
%- 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 -%}
%- 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 -%}
%- 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"
"<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 -%}
"<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"
"<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"
%- 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"
"<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"
%- 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"
%- 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 -%}
%- 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"
%- 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