diff --git a/packages/jinja/src/lexer.ts b/packages/jinja/src/lexer.ts
index a74c6a88fb..5e679aac01 100644
--- a/packages/jinja/src/lexer.ts
+++ b/packages/jinja/src/lexer.ts
@@ -56,6 +56,10 @@ function isInteger(char: string): boolean {
return /[0-9]/.test(char);
}
+function isWhitespace(char: string): boolean {
+ return /\s/.test(char);
+}
+
/**
* A data structure which contains a list of rules to test
*/
@@ -134,19 +138,9 @@ function preprocess(template: string, options: PreprocessOptions = {}): string {
template = template.replace(/([#%-]})\n/g, "$1");
}
- return (
- template
- .replace(/-%}\s*/g, "%}")
- .replace(/\s*{%-/g, "{%")
- .replace(/-}}\s*/g, "}}")
- .replace(/\s*{{-/g, "{{")
- .replace(/-#}\s*/g, "#}")
- .replace(/\s*{#-/g, "{#")
-
- // Handle the custom transformers-specific `generation` tag.
- // See https://github.com/huggingface/transformers/pull/30650 for more information.
- .replace(/{%\s*(end)?generation\s*%}/gs, "")
- );
+ // Handle the custom transformers-specific `generation` tag.
+ // See https://github.com/huggingface/transformers/pull/30650 for more information.
+ return template.replace(/{%\s*(end)?generation\s*%}/gs, "");
}
/**
@@ -185,6 +179,23 @@ export function tokenize(source: string, options: PreprocessOptions = {}): Token
return str;
};
+ const stripTrailingWhitespace = () => {
+ if (tokens.length === 0) return;
+ const lastToken = tokens.at(-1)!;
+ if (lastToken.type === TOKEN_TYPES.Text) {
+ lastToken.value = lastToken.value.trimEnd();
+ if (lastToken.value === "") {
+ tokens.pop(); // Remove empty text token
+ }
+ }
+ };
+
+ const skipLeadingWhitespace = () => {
+ while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) {
+ ++cursorPosition;
+ }
+ };
+
// Build each token until end of input
main: while (cursorPosition < src.length) {
// First, consume all text that is outside of a Jinja statement or expression
@@ -219,6 +230,12 @@ export function tokenize(source: string, options: PreprocessOptions = {}): Token
if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") {
cursorPosition += 2; // Skip the opening {#
+ // Check for leading hyphen for whitespace control {#-
+ const stripBefore = src[cursorPosition] === "-";
+ if (stripBefore) {
+ ++cursorPosition; // Skip the hyphen
+ }
+
let comment = "";
while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") {
// Check for end of input
@@ -227,13 +244,64 @@ export function tokenize(source: string, options: PreprocessOptions = {}): Token
}
comment += src[cursorPosition++];
}
+
+ // Check for trailing hyphen for whitespace control -#}
+ const stripAfter = comment.endsWith("-");
+ if (stripAfter) {
+ comment = comment.slice(0, -1); // Remove the trailing hyphen
+ }
+
+ // Apply whitespace stripping for leading hyphen
+ if (stripBefore) {
+ stripTrailingWhitespace();
+ }
+
tokens.push(new Token(comment, TOKEN_TYPES.Comment));
cursorPosition += 2; // Skip the closing #}
+
+ // Apply whitespace stripping for trailing hyphen
+ if (stripAfter) {
+ skipLeadingWhitespace();
+ }
+
+ continue;
+ }
+
+ // Check for opening statement with whitespace control {%-
+ if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") {
+ stripTrailingWhitespace();
+ tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement));
+ cursorPosition += 3; // Skip {%-
+ continue;
+ }
+
+ // Check for opening expression with whitespace control {{-
+ if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") {
+ stripTrailingWhitespace();
+ tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression));
+ curlyBracketDepth = 0;
+ cursorPosition += 3; // Skip {{-
continue;
}
// Consume (and ignore) all whitespace inside Jinja statements or expressions
- consumeWhile((char) => /\s/.test(char));
+ consumeWhile(isWhitespace);
+
+ // Check for closing statement with whitespace control -%}
+ if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") {
+ tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement));
+ cursorPosition += 3; // Skip -%}
+ skipLeadingWhitespace();
+ continue;
+ }
+
+ // Check for closing expression with whitespace control -}}
+ if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") {
+ tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression));
+ cursorPosition += 3; // Skip -}}
+ skipLeadingWhitespace();
+ continue;
+ }
// Handle multi-character tokens
const char = src[cursorPosition];
@@ -322,5 +390,6 @@ export function tokenize(source: string, options: PreprocessOptions = {}): Token
throw new SyntaxError(`Unexpected character: ${char}`);
}
+
return tokens;
}
diff --git a/packages/jinja/test/e2e.test.js b/packages/jinja/test/e2e.test.js
index ca2bc0a5da..75a5b80851 100644
--- a/packages/jinja/test/e2e.test.js
+++ b/packages/jinja/test/e2e.test.js
@@ -993,6 +993,19 @@ const TEST_CUSTOM_TEMPLATES = Object.freeze({
target:
"<|im_start|>system\n## Metadata\n\nKnowledge Cutoff Date: June 2025\nToday Date: 10 July 2025\nReasoning Mode: /think\n\n## Custom Instructions\n\nYou are a helpful assistant.\n\n<|im_start|>user\nWhat is the capital of France?<|im_end|>\n<|im_start|>assistant\nThe user is asking for the capital of France. This is a factual question. I know this information.The capital of France is Paris.<|im_end|>\n<|im_start|>user\nWhat about Chile?<|im_end|>\n<|im_start|>assistant\n",
},
+ "CohereLabs/command-a-reasoning-08-2025": {
+ // Example adapted from https://huggingface.co/CohereLabs/command-a-reasoning-08-2025
+ chat_template:
+ '{%- set reasoning = reasoning if reasoning is not undefined else true -%}\n{%- set skip_thinking = skip_thinking if skip_thinking is not undefined else (not reasoning) -%}\n{%- set safety_mode = safety_mode if safety_mode is not undefined else "CONTEXTUAL" -%}\n{{ bos_token }}\n{%- macro document_turn(documents) -%}\n{# format documents into chat turn -#}\n<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>{%- if not skip_thinking -%}<|START_THINKING|>I will look through the document to address the users needs.<|END_THINKING|>{%- endif -%}<|START_ACTION|>[\n {"tool_call_id": "0", "tool_name": "direct-injected-document", "parameters": {}}\n]<|END_ACTION|><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><|START_TOOL_RESULT|>[\n {\n "tool_call_id": "0",\n "results": {\n{%- for doc in documents %}\n "{{ loop.index0 }}": {{doc|tojson}}{% if not loop.last %},\n {%- endif %}\n{%- endfor %}\n },\n "is_error": null\n }\n]<|END_TOOL_RESULT|><|END_OF_TURN_TOKEN|>{%- endmacro %}\n{%- macro tool_call_id_to_int(messages, tool_call_id) %}\n{%- if regen_tool_call_ids -%}\n {%- set counter = namespace(value=0) %}\n {%- set tool_call_id_seen = namespace(value=false) %}\n {%- for msg in messages %}\n {%- if msg.tool_calls %}\n {%- for tool_call in msg.tool_calls %}\n {%- if tool_call.id == tool_call_id and not tool_call_id_seen.value -%}\n {{ counter.value }}\n {%- set tool_call_id_seen.value = true %}\n {%- endif %}\n {%- set counter.value = counter.value + 1 %}\n {%- endfor %}\n {%- endif %}\n {%- endfor %}\n{%- else -%}\n {{ tool_call_id }}\n{%- endif -%}\n{%- endmacro %}\n{%- macro format_tool_message(messages, tool_msg) -%}\n{#- format tool message #}{\n "tool_call_id": "{{ tool_call_id_to_int(messages, tool_msg.tool_call_id) }}",\n "results": {\n {%- if tool_msg.content is mapping %}\n "0": {{ tool_msg.content|tojson }}\n {%- else %}\n {%- for content in tool_msg.content %}\n "{{ loop.index0 }}": {{ content|tojson }}{% if not loop.last %},{% endif %}\n {%- endfor %}\n {%- endif %}\n },\n "is_error": null\n }\n{%- endmacro -%}\n{%- macro print_msg(msg) %}\n {%- if msg.content is string -%}\n{{ msg.content }}\n {%- else %}\n {%- set last_was_text = namespace(value=false) %}\n {%- for content in msg.content %}\n {%- if content.type|lower == "text" -%}\n {%- if last_was_text.value %}{{ "\\n" }}{% endif -%}\n{{ content.text }}\n {%- set last_was_text.value = true -%}\n {%- else -%}\n {%- set last_was_text.value = false -%}\n {%- endif -%}\n {%- if content.type|lower == "image" -%}\n{{ content.data }}\n {%- endif -%}\n {%- endfor %}\n {%- set last_was_text = false -%}\n {%- endif %}\n{%- endmacro %}\n{%- macro print_thinking(msg) %}\n {%- if msg.thinking -%}\n{{ msg.thinking }}\n {%- elif msg.content[0].thinking -%}\n{{ msg.content[0].thinking }}\n {%- endif %}\n{%- endmacro %}\n{%- if messages and messages[0][\'role\']|lower == \'system\' %}{%- set developer_preamble = messages[0] %}{% endif %}\n{%- set json_object = true if response_format and response_format.type == "json_object" else false %}\n{%- set json_schema = (response_format.json_schema or response_format.schema) if response_format %}\n{%- set json_mode = json_object or json_schema %}\n{%- set enable_citations = enable_citations if enable_citations is not undefined else false %}\n{%- set tool_idx = namespace(value=0) %}\n{%- set tool_ids_seen = namespace(value=[]) %}\n{%- set regen_tool_call_ids = regen_tool_call_ids if regen_tool_call_ids is not undefined else true -%}\n{%- set sent_documents = namespace(value=false) -%}\n<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble\n{% if safety_mode|upper == \'STRICT\' -%}\nYou are in strict safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will reject requests to generate content related to violence, hate, misinformation or sex to any amount. You will avoid using profanity. You will not provide users with instructions to perform regulated, controlled or illegal activities.\n{%- else -%}\nYou are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes.\n{%- endif %}\n\nYour information cutoff date is June 2024.\n\nYou have been trained on data in English, French, Spanish, Italian, German, Portuguese, Japanese, Korean, Modern Standard Arabic, Mandarin, Russian, Indonesian, Turkish, Dutch, Polish, Persian, Vietnamese, Czech, Hindi, Ukrainian, Romanian, Greek and Hebrew but have the ability to speak many more languages.\n{% if reasoning %}\n## Reasoning\nStart your response by writing <|START_THINKING|>. Then slowly and carefully reason through the problem. If you notice that you\'ve made a mistake, you can correct it. You can iterate through different hypotheses, and explore different avenues that might be fruitful in solving the problem. Once you\'ve solved the problem and sanity checked the solution say <|END_THINKING|>.\nWhen you are ready to respond write <|START_RESPONSE|>. Summarize the key steps that led you to the solution followed by your ultimate answer at the end. Once you are done, end your response with <|END_RESPONSE|>.\n{% endif %}\n{%- if tools or documents or reasoning %}\nYou have been trained to have advanced reasoning and tool-use capabilities and you should make best use of these skills to serve user\'s requests.\n{% if not skip_thinking %}\n## Tool Use\nThink about how you can make best use of the provided tools to help with the task and come up with a high level plan that you will execute first.\n\n0. Start by writing <|START_THINKING|> followed by a detailed step by step plan of how you will solve the problem. For each step explain your thinking fully and give details of required tool calls (if needed). Unless specified otherwise, you write your plan in natural language. When you finish, close it out with <|END_THINKING|>.\n {%- if not reasoning %}\n You can optionally choose to skip this step when the user request is so straightforward to address that only a trivial plan would be needed.\n NOTE: You MUST skip this step when you are directly responding to the user\'s request without using any tools.\n {%- endif %}\n\nThen carry out your plan by repeatedly executing the following steps.\n1. Action: write <|START_ACTION|> followed by a list of JSON-formatted tool calls, with each one containing "tool_name" and "parameters" fields.\n When there are multiple tool calls which are completely independent of each other (i.e. they can be executed in parallel), you should list them out all together in one step. When you finish, close it out with <|END_ACTION|>.\n2. Observation: you will then receive results of those tool calls in JSON format in the very next turn, wrapped around by <|START_TOOL_RESULT|> and <|END_TOOL_RESULT|>. Carefully observe those results and think about what to do next. Note that these results will be provided to you in a separate turn. NEVER hallucinate results.\n Every tool call produces a list of results (when a tool call produces no result or a single result, it\'ll still get wrapped inside a list). Each result is clearly linked to its originating tool call via its "tool_call_id".\n3. Reflection: start the next turn by writing <|START_THINKING|> followed by what you\'ve figured out so far, any changes you need to make to your plan, and what you will do next. When you finish, close it out with <|END_THINKING|>.\n {%- if not reasoning %}\n You can optionally choose to skip this step when everything is going according to plan and no special pieces of information or reasoning chains need to be recorded.\n NOTE: You MUST skip this step when you are done with tool-use actions and are ready to respond to the user.\n {%- endif %}\n\nYou can repeat the above 3 steps multiple times (could be 0 times too if no suitable tool calls are available or needed), until you decide it\'s time to finally respond to the user.\n\n4. Response: then break out of the loop and write <|START_RESPONSE|> followed by a piece of text which serves as a response to the user\'s last request. Use all previous tool calls and results to help you when formulating your response. When you finish, close it out with <|END_RESPONSE|>.\n{% else %}\n## Tool Use\nCarry out the task by repeatedly executing the following steps.\n1. Action: write <|START_ACTION|> followed by a list of JSON-formatted tool calls, with each one containing "tool_name" and "parameters" fields.\n When there are multiple tool calls which are completely independent of each other (i.e. they can be executed in parallel), you should list them out all together in one step. When you finish, close it out with <|END_ACTION|>.\n2. Observation: you will then receive results of those tool calls in JSON format in the very next turn, wrapped around by <|START_TOOL_RESULT|> and <|END_TOOL_RESULT|>. Carefully observe those results and think about what to do next. Note that these results will be provided to you in a separate turn. NEVER hallucinate results.\n Every tool call produces a list of results (when a tool call produces no result or a single result, it\'ll still get wrapped inside a list). Each result is clearly linked to its originating tool call via its "tool_call_id".\n\nYou can repeat the above 2 steps multiple times (could be 0 times too if no suitable tool calls are available or needed), until you decide it\'s time to finally respond to the user.\n\n3. Response: then break out of the loop and write <|START_RESPONSE|> followed by a piece of text which serves as a response to the user\'s last request. Use all previous tool calls and results to help you when formulating your response. When you finish, close it out with <|END_RESPONSE|>.\n{% endif %}\n{%- if enable_citations %}\n## Grounding\nImportantly, note that {% if not skip_thinking %}"Reflection" and {% endif %}"Response" above can be grounded.\nGrounding means you associate pieces of texts (called "spans") with those specific tool results that support them (called "sources"). And you use a pair of tags "" and "" to indicate when a span can be grounded onto a list of sources, listing them out in the closing tag. Sources from the same tool call are grouped together and listed as "{tool_call_id}:[{list of result indices}]", before they are joined together by ",". E.g., "span" means that "span" is supported by result 1 and 2 from "tool_call_id=0" as well as result 0 from "tool_call_id=1".\n{% endif %}\n## Available Tools\nHere is the list of tools that you have available to you.\nYou can ONLY use the tools listed here. When a tool is not listed below, it is NOT available and you should NEVER attempt to use it.\nEach tool is represented as a JSON object with fields like "name", "description", "parameters" (per JSON Schema), and optionally, "responses" (per JSON Schema).\n\n```json\n[\n{%- if documents %}\n {"name": "direct-injected-document", "description": "This is a special tool to directly inject user-uploaded documents into the chat as additional context. DO NOT use this tool by yourself!", "parameters": {"type": "object", "properties": {}, "required": []}, "responses": {"200": {"description": "Successfully returned a list of chunked text snippets from the directly uploaded documents.", "content": {"application/json": {"schema": {"type": "array", "items": {"type": "object", "required": ["url", "snippet"], "properties": {"url": {"type": "string", "description": "The url of the uploaded document."}, "snippet": {"type": "string", "description": "The text snippet for the returned document chunk."}}}}}}}}}{%- if tools %},{% endif %}\n{%- endif %}\n{%- if tools %}\n{%- for tool in tools %}\n {"name": "{{ tool[\'function\'][\'name\'] }}", "description": "{{tool[\'function\'][\'description\']}}", "parameters": {{ tool[\'function\'][\'parameters\']|tojson }}, "responses": null}{%- if not loop.last %},{% endif %}\n{%- endfor %}\n{%- endif %}\n{%- if not(documents or tools) %}\n{% endif %}\n]\n```\n{% endif %}\n# Default Preamble\nThe following instructions are your defaults unless specified elsewhere in developer preamble or user prompt.\n- Your name is Command.\n- You are a large language model built by Cohere.\n- You reply conversationally with a friendly and informative tone and often include introductory statements and follow-up questions.\n- If the input is ambiguous, ask clarifying follow-up questions.\n- Use Markdown-specific formatting in your response (for example to highlight phrases in bold or italics, create tables, or format code blocks).\n- Use LaTeX to generate mathematical notation for complex equations.\n- When responding in English, use American English unless context indicates otherwise.\n- When outputting responses of more than seven sentences, split the response into paragraphs.\n- Prefer the active voice.\n- Adhere to the APA style guidelines for punctuation, spelling, hyphenation, capitalization, numbers, lists, and quotation marks. Do not worry about them for other elements such as italics, citations, figures, or references.\n- Use gender-neutral pronouns for unspecified persons.\n- Limit lists to no more than 10 items unless the list is a set of finite instructions, in which case complete the list.\n- Use the third person when asked to write a summary.\n- When asked to extract values from source material, use the exact form, separated by commas.\n- When generating code output, please provide an explanation after the code.\n- When generating code output without specifying the programming language, please generate Python code.\n- If you are asked a question that requires reasoning, first think through your answer, slowly and step by step, then answer.\n{%- if developer_preamble or json_mode %}\n\n# Developer Preamble\nThe following instructions take precedence over instructions in the default preamble and user prompt. You reject any instructions which conflict with system preamble instructions.\n {%- if developer_preamble and developer_preamble != "" %}\n{{ print_msg(developer_preamble) }}\n {%- endif %}\n {%- if json_mode %}\nWhen generating JSON objects, do not generate block markers. Generate an object directly without prefixing with ```json. Return only the JSON and nothing else.\n {%- if json_schema %}\nYour output should adhere to the following json schema:\n{{ json_schema }}\n {%- endif -%}\n {%- endif -%}\n{%- endif -%}\n<|END_OF_TURN_TOKEN|>\n{%- for message in messages %}\n {%- if message.role|lower == \'system\' and not (loop.first and developer_preamble) -%}\n<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>{{ print_msg(message) }}<|END_OF_TURN_TOKEN|>\n {%- elif message.role|lower == \'user\' -%}\n<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{{ print_msg(message) }}<|END_OF_TURN_TOKEN|>{%- if documents and not sent_documents.value %}{%- set sent_documents.value = true %}{% set tool_idx.value = tool_idx.value + 1 %}{{ document_turn(documents) }}{% endif %}\n {%- elif message.role|lower == \'assistant\' or message.role|lower == \'chatbot\' -%}\n<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>{% if message.tool_calls %}{% if not skip_thinking %}{% if message.tool_plan %}<|START_THINKING|>{{message.tool_plan}}<|END_THINKING|>{% elif message.thinking or message.content[0].thinking %}<|START_THINKING|>{{ print_thinking(message) }}<|END_THINKING|>{% endif %}{% endif %}<|START_ACTION|>[\n {%- for tc in message.tool_calls %}\n {"tool_call_id": "{%- if regen_tool_call_ids -%}{{ tool_idx.value }}{%- else -%}{{ tc.id }}{%- endif -%}", "tool_name": "{{ tc[\'function\'][\'name\'] }}", "parameters": {{ tc[\'function\'][\'arguments\']|tojson }}}{% if not loop.last %},{% endif %}\n {%- set tool_idx.value = tool_idx.value + 1 %}\n {%- endfor %}\n]<|END_ACTION|><|END_OF_TURN_TOKEN|>{% else -%}{% if (message.thinking or message.content[0].thinking) and not skip_thinking %}<|START_THINKING|>{{ print_thinking(message) }}<|END_THINKING|>{% endif %}<|START_RESPONSE|>{{ print_msg(message) }}<|END_RESPONSE|><|END_OF_TURN_TOKEN|>{% endif %}\n {%- elif message.role|lower == \'tool\' and message.tool_call_id not in tool_ids_seen.value -%}\n<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><|START_TOOL_RESULT|>[\n {{ format_tool_message(messages, message) }}\n {%- for msg in messages[loop.index0 + 1:] %}\n {%- if msg.role|lower == \'tool\' %},\n {{ format_tool_message(messages, msg) }}\n {%- set tool_ids_seen.value = tool_ids_seen.value + [msg.tool_call_id] %}\n {%- else %}\n {%- break %}\n {%- endif %}\n {%- endfor %}\n]<|END_TOOL_RESULT|><|END_OF_TURN_TOKEN|>\n {%- endif %}\n{%- endfor %}{%- if add_generation_prompt -%}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>{%- endif %}',
+ data: {
+ messages: [{ role: "user", content: "How many r's are there in strawberry?" }],
+ add_generation_prompt: true,
+ reasoning: true,
+ bos_token: "",
+ },
+ target:
+ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># System Preamble\nYou are in contextual safety mode. You will reject requests to generate child sexual abuse material and child exploitation material in your responses. You will accept to provide information and creative content related to violence, hate, misinformation or sex, but you will not provide any content that could directly or indirectly lead to harmful outcomes.\nYour information cutoff date is June 2024.\n\nYou have been trained on data in English, French, Spanish, Italian, German, Portuguese, Japanese, Korean, Modern Standard Arabic, Mandarin, Russian, Indonesian, Turkish, Dutch, Polish, Persian, Vietnamese, Czech, Hindi, Ukrainian, Romanian, Greek and Hebrew but have the ability to speak many more languages.\n## Reasoning\nStart your response by writing <|START_THINKING|>. Then slowly and carefully reason through the problem. If you notice that you\'ve made a mistake, you can correct it. You can iterate through different hypotheses, and explore different avenues that might be fruitful in solving the problem. Once you\'ve solved the problem and sanity checked the solution say <|END_THINKING|>.\nWhen you are ready to respond write <|START_RESPONSE|>. Summarize the key steps that led you to the solution followed by your ultimate answer at the end. Once you are done, end your response with <|END_RESPONSE|>.\nYou have been trained to have advanced reasoning and tool-use capabilities and you should make best use of these skills to serve user\'s requests.\n## Tool Use\nThink about how you can make best use of the provided tools to help with the task and come up with a high level plan that you will execute first.\n\n0. Start by writing <|START_THINKING|> followed by a detailed step by step plan of how you will solve the problem. For each step explain your thinking fully and give details of required tool calls (if needed). Unless specified otherwise, you write your plan in natural language. When you finish, close it out with <|END_THINKING|>.\nThen carry out your plan by repeatedly executing the following steps.\n1. Action: write <|START_ACTION|> followed by a list of JSON-formatted tool calls, with each one containing "tool_name" and "parameters" fields.\n When there are multiple tool calls which are completely independent of each other (i.e. they can be executed in parallel), you should list them out all together in one step. When you finish, close it out with <|END_ACTION|>.\n2. Observation: you will then receive results of those tool calls in JSON format in the very next turn, wrapped around by <|START_TOOL_RESULT|> and <|END_TOOL_RESULT|>. Carefully observe those results and think about what to do next. Note that these results will be provided to you in a separate turn. NEVER hallucinate results.\n Every tool call produces a list of results (when a tool call produces no result or a single result, it\'ll still get wrapped inside a list). Each result is clearly linked to its originating tool call via its "tool_call_id".\n3. Reflection: start the next turn by writing <|START_THINKING|> followed by what you\'ve figured out so far, any changes you need to make to your plan, and what you will do next. When you finish, close it out with <|END_THINKING|>.\nYou can repeat the above 3 steps multiple times (could be 0 times too if no suitable tool calls are available or needed), until you decide it\'s time to finally respond to the user.\n\n4. Response: then break out of the loop and write <|START_RESPONSE|> followed by a piece of text which serves as a response to the user\'s last request. Use all previous tool calls and results to help you when formulating your response. When you finish, close it out with <|END_RESPONSE|>.\n## Available Tools\nHere is the list of tools that you have available to you.\nYou can ONLY use the tools listed here. When a tool is not listed below, it is NOT available and you should NEVER attempt to use it.\nEach tool is represented as a JSON object with fields like "name", "description", "parameters" (per JSON Schema), and optionally, "responses" (per JSON Schema).\n\n```json\n[]\n```\n# Default Preamble\nThe following instructions are your defaults unless specified elsewhere in developer preamble or user prompt.\n- Your name is Command.\n- You are a large language model built by Cohere.\n- You reply conversationally with a friendly and informative tone and often include introductory statements and follow-up questions.\n- If the input is ambiguous, ask clarifying follow-up questions.\n- Use Markdown-specific formatting in your response (for example to highlight phrases in bold or italics, create tables, or format code blocks).\n- Use LaTeX to generate mathematical notation for complex equations.\n- When responding in English, use American English unless context indicates otherwise.\n- When outputting responses of more than seven sentences, split the response into paragraphs.\n- Prefer the active voice.\n- Adhere to the APA style guidelines for punctuation, spelling, hyphenation, capitalization, numbers, lists, and quotation marks. Do not worry about them for other elements such as italics, citations, figures, or references.\n- Use gender-neutral pronouns for unspecified persons.\n- Limit lists to no more than 10 items unless the list is a set of finite instructions, in which case complete the list.\n- Use the third person when asked to write a summary.\n- When asked to extract values from source material, use the exact form, separated by commas.\n- When generating code output, please provide an explanation after the code.\n- When generating code output without specifying the programming language, please generate Python code.\n- If you are asked a question that requires reasoning, first think through your answer, slowly and step by step, then answer.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>How many r\'s are there in strawberry?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>',
+ },
});
/**
diff --git a/packages/jinja/test/templates.test.js b/packages/jinja/test/templates.test.js
index 1c1d868966..f7924c45f1 100644
--- a/packages/jinja/test/templates.test.js
+++ b/packages/jinja/test/templates.test.js
@@ -218,6 +218,20 @@ const TEST_STRINGS = {
// Unpacking
UNPACKING: `{% macro mul(a, b, c) %}{{ a * b * c }}{% endmacro %}|{{ mul(1, 2, 3) }}|{{ mul(*[1, 2, 3]) }}|`,
+
+ // Whitespace control
+ WHITESPACE_CONTROL_1: `{
+{%- for i in [1, 2, 3] -%}
+ {{ i }}
+{%- endfor -%}
+}`,
+ WHITESPACE_CONTROL_2: `{%- for i in [1, 2, 3] %}{{ i }}{% endfor -%}`,
+ WHITESPACE_CONTROL_3: ` {%- if true -%} A {%- endif -%} `,
+ WHITESPACE_CONTROL_4: `A {{- ' B ' -}} C`,
+ WHITESPACE_CONTROL_5: `{#- comment -#}X`,
+ WHITESPACE_CONTROL_6: `X{#- comment -#}`,
+ WHITESPACE_CONTROL_7: ` {%- set x = 1 -%} {{ x }}`,
+ WHITESPACE_CONTROL_8: ` \n A \n {%- set x = 1 %} \n {{ x }} \nB \n{% set y = 2 -%} \n\n C {{- y -}} D {#-Comment - goes - here--#} \n E \n `,
};
const TEST_PARSED = {
@@ -4325,6 +4339,113 @@ const TEST_PARSED = {
{ value: "}}", type: "CloseExpression" },
{ value: "|", type: "Text" },
],
+
+ // Whitespace control
+ WHITESPACE_CONTROL_1: [
+ { value: "{", type: "Text" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "for", type: "Identifier" },
+ { value: "i", type: "Identifier" },
+ { value: "in", type: "Identifier" },
+ { value: "[", type: "OpenSquareBracket" },
+ { value: "1", type: "NumericLiteral" },
+ { value: ",", type: "Comma" },
+ { value: "2", type: "NumericLiteral" },
+ { value: ",", type: "Comma" },
+ { value: "3", type: "NumericLiteral" },
+ { value: "]", type: "CloseSquareBracket" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "{{", type: "OpenExpression" },
+ { value: "i", type: "Identifier" },
+ { value: "}}", type: "CloseExpression" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "endfor", type: "Identifier" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "}", type: "Text" },
+ ],
+ WHITESPACE_CONTROL_2: [
+ { value: "{%", type: "OpenStatement" },
+ { value: "for", type: "Identifier" },
+ { value: "i", type: "Identifier" },
+ { value: "in", type: "Identifier" },
+ { value: "[", type: "OpenSquareBracket" },
+ { value: "1", type: "NumericLiteral" },
+ { value: ",", type: "Comma" },
+ { value: "2", type: "NumericLiteral" },
+ { value: ",", type: "Comma" },
+ { value: "3", type: "NumericLiteral" },
+ { value: "]", type: "CloseSquareBracket" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "{{", type: "OpenExpression" },
+ { value: "i", type: "Identifier" },
+ { value: "}}", type: "CloseExpression" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "endfor", type: "Identifier" },
+ { value: "%}", type: "CloseStatement" },
+ ],
+ WHITESPACE_CONTROL_3: [
+ { value: "{%", type: "OpenStatement" },
+ { value: "if", type: "Identifier" },
+ { value: "true", type: "Identifier" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "A", type: "Text" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "endif", type: "Identifier" },
+ { value: "%}", type: "CloseStatement" },
+ ],
+ WHITESPACE_CONTROL_4: [
+ { value: "A", type: "Text" },
+ { value: "{{", type: "OpenExpression" },
+ { value: " B ", type: "StringLiteral" },
+ { value: "}}", type: "CloseExpression" },
+ { value: "C", type: "Text" },
+ ],
+ WHITESPACE_CONTROL_5: [
+ { value: " comment ", type: "Comment" },
+ { value: "X", type: "Text" },
+ ],
+ WHITESPACE_CONTROL_6: [
+ { value: "X", type: "Text" },
+ { value: " comment ", type: "Comment" },
+ ],
+ WHITESPACE_CONTROL_7: [
+ { value: "{%", type: "OpenStatement" },
+ { value: "set", type: "Identifier" },
+ { value: "x", type: "Identifier" },
+ { value: "=", type: "Equals" },
+ { value: "1", type: "NumericLiteral" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "{{", type: "OpenExpression" },
+ { value: "x", type: "Identifier" },
+ { value: "}}", type: "CloseExpression" },
+ ],
+ WHITESPACE_CONTROL_8: [
+ { value: " \n A", type: "Text" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "set", type: "Identifier" },
+ { value: "x", type: "Identifier" },
+ { value: "=", type: "Equals" },
+ { value: "1", type: "NumericLiteral" },
+ { value: "%}", type: "CloseStatement" },
+ { value: " \n ", type: "Text" },
+ { value: "{{", type: "OpenExpression" },
+ { value: "x", type: "Identifier" },
+ { value: "}}", type: "CloseExpression" },
+ { value: " \nB \n", type: "Text" },
+ { value: "{%", type: "OpenStatement" },
+ { value: "set", type: "Identifier" },
+ { value: "y", type: "Identifier" },
+ { value: "=", type: "Equals" },
+ { value: "2", type: "NumericLiteral" },
+ { value: "%}", type: "CloseStatement" },
+ { value: "C", type: "Text" },
+ { value: "{{", type: "OpenExpression" },
+ { value: "y", type: "Identifier" },
+ { value: "}}", type: "CloseExpression" },
+ { value: "D", type: "Text" },
+ { value: "Comment - goes - here-", type: "Comment" },
+ { value: "E \n ", type: "Text" },
+ ],
};
const TEST_CONTEXT = {
@@ -4722,6 +4843,16 @@ const TEST_CONTEXT = {
// Unpacking
UNPACKING: {},
+
+ // Whitespace control
+ WHITESPACE_CONTROL_1: {},
+ WHITESPACE_CONTROL_2: {},
+ WHITESPACE_CONTROL_3: {},
+ WHITESPACE_CONTROL_4: {},
+ WHITESPACE_CONTROL_5: {},
+ WHITESPACE_CONTROL_6: {},
+ WHITESPACE_CONTROL_7: {},
+ WHITESPACE_CONTROL_8: {},
};
const EXPECTED_OUTPUTS = {
@@ -4937,6 +5068,16 @@ const EXPECTED_OUTPUTS = {
// Unpacking
UNPACKING: `|6|6|`,
+
+ // Whitespace control
+ WHITESPACE_CONTROL_1: `{123}`,
+ WHITESPACE_CONTROL_2: `123`,
+ WHITESPACE_CONTROL_3: `A`,
+ WHITESPACE_CONTROL_4: `A B C`,
+ WHITESPACE_CONTROL_5: `X`,
+ WHITESPACE_CONTROL_6: `X`,
+ WHITESPACE_CONTROL_7: `1`,
+ WHITESPACE_CONTROL_8: ` \n A \n 1 \nB \nC2DE \n `,
};
describe("Templates", () => {