Skip to content

Add chat templates for command-a and aya-23-8B models#2731

Merged
NanoCode012 merged 2 commits into
axolotl-ai-cloud:mainfrom
hyeobiiii:feature/add_chat_templates_for_command_a_and_aya
May 28, 2025
Merged

Add chat templates for command-a and aya-23-8B models#2731
NanoCode012 merged 2 commits into
axolotl-ai-cloud:mainfrom
hyeobiiii:feature/add_chat_templates_for_command_a_and_aya

Conversation

@hyeobiiii

@hyeobiiii hyeobiiii commented May 27, 2025

Copy link
Copy Markdown
Contributor

Description

This pull request adds Hugging Face–compatible chat_template entries for the following models:

  • CohereLabs/c4ai-command-a-03-2025
  • aya-23-8B

Motivation and Context

1. c4ai-command-a-03-2025

  • The original tokenizer_config.json for this model defines multiple templates (e.g., "default", "tool_use", "rag") as an array, which is not supported by Hugging Face’s apply_chat_template() method.
  • The template also includes unsupported Jinja2 control structures such as {% break %}, causing runtime failures during prompt formatting.

2. aya-23-8B

  • The existing cohere template in Axolotl is designed for the command-r variant, which differs in prompt structure and token usage.
  • To avoid ambiguity, a dedicated aya template is added to support aya-23-8B and future aya-based variants.

Related Issue

Fixes #2730

How has this been tested?

Instruct tuning was successfully conducted using the added chat_template for both command-a and aya-23-8B models. No formatting errors occurred, and the training proceeded as expected.

Screenshots (if appropriate)

Types of changes

Social Handles (Optional)

Summary by CodeRabbit

  • New Features
    • Introduced four new chat templates: "command_a", "command_a_tool_use", "command_a_rag", and "aya", offering advanced formatting for chat interactions, tool use, and document grounding.
    • Expanded chat template selection options with enhanced support for multi-step reasoning and a new assistant persona ("Aya").

@coderabbitai

coderabbitai Bot commented May 27, 2025

Copy link
Copy Markdown
Contributor

"""

Walkthrough

Four new chat templates—command_a, command_a_tool_use, command_a_rag, and aya—were added to the chat templates dictionary, each supporting advanced Jinja2-based formatting for multi-step tool use, document grounding, and assistant personas. Corresponding enum members were introduced to the ChatTemplate enum, enabling their selection and usage within the codebase.

Changes

Files / Paths Change Summary
src/axolotl/utils/chat_templates.py Added four new Jinja2 chat templates: command_a, command_a_tool_use, command_a_rag, and aya
src/axolotl/utils/schemas/enums.py Added corresponding enum members to ChatTemplate: command_a, command_a_tool_use, command_a_rag, and aya

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ChatTemplateSelector
    participant TemplateEngine

    User->>ChatTemplateSelector: Selects template (e.g., "command_a")
    ChatTemplateSelector->>TemplateEngine: Loads selected template
    TemplateEngine->>User: Formats chat messages using the template
Loading

Assessment against linked issues

Objective Addressed Explanation
Add Hugging Face–compatible chat templates for command-a and aya-23-8B models (#2730)
Ensure templates are selectable via enum and integrated into Axolotl pipeline (#2730)

Poem

In the warren, new templates appear,
For Command-A and Aya, let’s all cheer!
Enum and macros, so clever and neat,
Now Axolotl’s chat is truly complete.
🐇✨
With prompts that can reason, reflect, and relay,
The future of chatting is hopping this way!
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a0b96b and 1796cd8.

📒 Files selected for processing (1)
  • src/axolotl/utils/chat_templates.py (1 hunks)
🔇 Additional comments (3)
src/axolotl/utils/chat_templates.py (3)

43-43: Verify template complexity and performance implications

The command_a template is extremely complex with multiple macros, conditional logic, and nested loops. This complexity may impact:

  • Template rendering performance
  • Debugging and troubleshooting
  • Future maintenance

Please verify:

  1. Performance benchmarks for template rendering with typical message volumes
  2. Error handling for malformed inputs or edge cases
  3. Documentation for the complex multi-step tool use workflow

Consider breaking down this monolithic template into smaller, focused components if performance or maintainability becomes an issue.


46-46: LGTM: Clean and focused template implementation

The aya template is well-structured with clear logic for alternating user/assistant roles and proper system message handling. The implementation is concise while supporting the necessary features for the Aya model.


43-46: Request clarification on template modifications mentioned in PR comments

According to the PR objectives, a reviewer noted specific changes beyond loop removal:

  • Change from {{ tool_msg.content|tojson }} to {{ tool_msg.content }}
  • Change from {{ tool['function']['parameters']|tojson }} to {{ tool['function']['parameters']['properties']|tojson }}

Could you clarify the purpose and impact of these modifications? The removal of |tojson filters could affect:

  • JSON serialization of content
  • Data type handling and validation
  • Compatibility with downstream processing

Understanding these changes would help ensure they don't introduce data formatting issues or breaking changes.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/axolotl/utils/schemas/enums.py (1)

46-49: Enum list is drifting away from any ordering – consider sorting or grouping new members

The new members are appended at the bottom of an already long list. Although there’s no functional impact, a predictable ordering (e.g., alphabetical or grouped by vendor) makes future scanning / merge-conflict resolution easier.

-    command_a = "command_a"  # pylint: disable=invalid-name
-    command_a_tool_use = "command_a_tool_use"  # pylint: disable=invalid-name
-    command_a_rag = "command_a_rag"  # pylint: disable=invalid-name
-    aya = "aya"  # pylint: disable=invalid-name
+#   --- Cohere / Command family ---
+    command_a = "command_a"  # pylint: disable=invalid-name
+    command_a_tool_use = "command_a_tool_use"  # pylint: disable=invalid-name
+    command_a_rag = "command_a_rag"  # pylint: disable=invalid-name
+
+#   --- Aya family ---
+    aya = "aya"  # pylint: disable=invalid-name

(Keeping a small comment divider or alphabetical sort would be equally fine.)

src/axolotl/utils/chat_templates.py (2)

43-43: Very large multi-line string literals may hurt readability & tooling

command_a’s template is ~600 lines long and lives inline inside the Python source.
Consider relocating monster templates to external *.j2 or *.json.j2 files (then Path.read_text()), leaving only a concise registration call here. Benefits:

• diff-friendly reviews (you rarely need to re-scroll the full constant)
• syntax highlighting & linting for Jinja in editors
• dramatically smaller Python module load time


46-46: aya template is added, but not referenced in docs or CLI help

Developers may not discover the new template without explicit mention. Please update:

• README / documentation tables
--chat_template CLI flag description (if any autocompletion list exists)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a8af60 and 9a0b96b.

📒 Files selected for processing (2)
  • src/axolotl/utils/chat_templates.py (1 hunks)
  • src/axolotl/utils/schemas/enums.py (1 hunks)
🔇 Additional comments (2)
src/axolotl/utils/chat_templates.py (2)

45-45: command_a_rag sets tools = [] but keeps full tool instructions

command_a_rag initialises tools = [], yet the System Preamble still talks about “provided tools” and prints the tool list block.
If tools is guaranteed empty this wording is confusing. Either:

  1. Remove the tool-use section for RAG-only mode, or
  2. Accept a tools argument and let callers pass an empty list (no template change).

43-46: Sync between enum and template map successfully achieved – good job

All four keys (command_a, command_a_tool_use, command_a_rag, aya) match the new ChatTemplate enum members, preventing runtime look-ups from failing.

Comment thread src/axolotl/utils/chat_templates.py Outdated
"pixtral": '{%- if messages[0]["role"] == "system" %}\n {%- set system_message = messages[0]["content"] %}\n {%- set loop_messages = messages[1:] %}\n{%- else %}\n {%- set loop_messages = messages %}\n{%- endif %}\n\n{{- bos_token }}\n{%- for message in loop_messages %}\n {%- if (message[\'role\'] == \'user\') != (loop.index0 % 2 == 0) %}\n {{- raise_exception(\'After the optional system message, conversation roles must alternate user/assistant/user/assistant/...\') }}\n {%- endif %}\n {%- if message["role"] == "user" %}\n {%- if loop.last and system_message is defined %}\n {{- "[INST]" + system_message + "\n\n" }}\n {%- else %}\n {{- "[INST]" }}\n {%- endif %}\n {%- if message["content"] is not string %}\n {%- for chunk in message["content"] %}\n {%- if chunk["type"] == "text" %}\n {{- chunk["text"] }}\n {%- elif chunk["type"] == "image" %}\n {{- "[IMG]" }}\n {%- else %}\n {{- raise_exception("Unrecognized content type!") }}\n {%- endif %}\n {%- endfor %}\n {%- else %}\n {{- message["content"] }}\n {%- endif %}\n {{- "[/INST]" }}\n {%- elif message["role"] == "assistant" %}\n {%- if message["content"] is not string %}\n {%- for chunk in message["content"] %}\n {%- if chunk["type"] == "text" %}\n {{- chunk["text"] }}\n {%- elif chunk["type"] == "image" %}\n {{- "[IMG]" }}\n {%- else %}\n {{- raise_exception("Unrecognized content type!") }}\n{%- endif %}\n{%- endfor %}\n{{- eos_token }}\n{%- else %}\n{{- message["content"] + eos_token }}\n{%- endif %}\n {%- else %}\n {{- raise_exception("Only user and assistant roles are supported, with the exception of an initial optional system message!") }}\n {%- endif %}\n{%- endfor %}',
"qwen2_vl": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
"command_a": "{{ bos_token }}{% if documents %}\n{% set tools = [] %}\n{%- macro document_turn(documents) -%}\n{# format documents into chat turn #}\n<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_THINKING|>I will look through the document to address the users needs.<|END_THINKING|><|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 },\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{%- 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{%- endmacro %}\n{%- macro format_tool_message(messages, tool_msg) -%}\n{# format tool message #}\n {\n \"tool_call_id\": \"{{ tool_call_id_to_int(messages, tool_msg.tool_call_id) }}\",\n \"results\": {\n \"0\": {\"text\": \"{{ tool_msg.content }}\"}\n },\n \"is_error\": null\n }\n{%- endmacro -%}\n{%- if messages and messages[0]['role']|lower == 'system' %}{%- set developer_preamble = messages[0]['content'] %}{% endif %}\n{%- set tool_idx = namespace(value=0) %}\n{%- set tool_ids_seen = namespace(value=[]) %}\n{%- set sent_documents = namespace(value=false) %}\n<|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.\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 tools or documents %}\n\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\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 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\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 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\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{% if enable_citations %}\n\n## Grounding\nImportantly, note that \"Reflection\" and \"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 \"<co>\" and \"</co>\" 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., \"<co>span</co: 0:[1,2],1:[0]>\" 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\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\n{% endif %}\n{% for tool in tools %}\n {\"name\": \"{{ tool['function']['name'] }}\", \"description\": \"{{tool['function']['description']}}\", \"parameters\": {{ tool['function']['parameters']['properties']|tojson }}, \"responses\": null}{%- if not loop.last %},{% endif %}\n\n{% endfor %}\n]\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 %}\n\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{{ developer_preamble }}\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|>{{ message.content }}<|END_OF_TURN_TOKEN|>\n {%- elif message.role|lower == 'user' %}\n<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{{ message.content }}<|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 %}<|START_THINKING|>{{message.tool_plan}}<|END_THINKING|><|START_ACTION|>[\n {% for tc in message.tool_calls %}\n {\"tool_call_id\": \"{{ tool_idx.value }}\", \"tool_name\": \"{{ tc['function']['name'] }}\", \"parameters\": {{ tc['function']['arguments']|tojson }}}{% if not loop.last %},{% endif %}\n\n {% set tool_idx.value = tool_idx.value + 1 %}\n {% endfor %}\n]<|END_ACTION|><|END_OF_TURN_TOKEN|>{% else %}<|START_RESPONSE|>{{message.content}}<|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{%- set stopped = false %}\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 not stopped and 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 {%- set stopped = true %}\n {%- endif %}\n {%- endfor %}\n \n]<|END_TOOL_RESULT|><|END_OF_TURN_TOKEN|>\n {%- endif %}\n{%- endfor %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>\n{%- else -%}\n{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}\n {%- set system_message = messages[0]['content'] %}{% elif false == true %}\n {%- set loop_messages = messages %}{% set system_message = '' %}\n{%- else %}\n {%- set loop_messages = messages %}\n {%- set system_message = false %}\n{%- endif %}\n{%- if system_message != false -%}\n {{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + system_message + '<|END_OF_TURN_TOKEN|>' }}\n{%- else -%}\n {{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><|END_OF_TURN_TOKEN|>' }}\n{%- endif %}\n{%- for message in loop_messages %}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}\n {%- endif -%}\n {%- set content = message['content'] -%}\n {%- if message['role'] == 'user' -%}\n {{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}\n {%- elif message['role'] == 'assistant' -%}\n {{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>' + content.strip() + '<|END_RESPONSE|><|END_OF_TURN_TOKEN|>' }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt -%}\n {{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_RESPONSE|>' }}\n{%- endif %}\n{% endif %}",
"command_a_tool_use": "{{ bos_token }}{%- macro document_turn(documents) -%}\n{# format documents into chat turn #}\n<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|><|START_THINKING|>I will look through the document to address the users needs.<|END_THINKING|><|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 },\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{%- 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{%- endmacro %}\n{%- macro format_tool_message(messages, tool_msg) -%}\n{# format tool message #}\n {\n \\\"tool_call_id\\\": \\\"{{ tool_call_id_to_int(messages, tool_msg.tool_call_id) }}\\\",\n \\\"results\\\": {\n \\\"0\\\": {{ tool_msg.content|tojson }}\n },\n \\\"is_error\\\": null\n }\n{%- endmacro -%}\n{%- if messages and messages[0]['role']|lower == 'system' %}{%- set developer_preamble = messages[0]['content'] %}{% endif %}\n{%- set tool_idx = namespace(value=0) %}\n{%- set tool_ids_seen = namespace(value=[]) %}\n{%- set sent_documents = namespace(value=false) %}\n<|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.\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 tools or documents %}\n\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\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 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\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 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\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{% if enable_citations %}\n\n## Grounding\nImportantly, note that \\\"Reflection\\\" and \\\"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 \\\"<co>\\\" and \\\"</co>\\\" 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., \\\"<co>span</co: 0:[1,2],1:[0]>\\\" 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\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\n{% endif %}\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\n{% endfor %}\n]\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 %}\n\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{{ developer_preamble }}\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|>{{ message.content }}<|END_OF_TURN_TOKEN|>\n {%- elif message.role|lower == 'user' %}\n<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{{ message.content }}<|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 %}<|START_THINKING|>{{message.tool_plan}}<|END_THINKING|><|START_ACTION|>[\n {% for tc in message.tool_calls %}\n {\\\"tool_call_id\\\": \\\"{{ tool_idx.value }}\\\", \\\"tool_name\\\": \\\"{{ tc['function']['name'] }}\\\", \\\"parameters\\\": {{ tc['function']['arguments']|tojson }}}{% if not loop.last %},{% endif %}\n\n {% set tool_idx.value = tool_idx.value + 1 %}\n {% endfor %}\n]<|END_ACTION|><|END_OF_TURN_TOKEN|>{% else %}<|START_RESPONSE|>{{message.content}}<|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 {%- set stopped = false %}\n {%- for msg in messages[loop.index0 + 1:] %}\n {%- if not stopped and 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 {%- set stopped = true %}\n {%- endif %}\n {%- endfor %}\n\n]<|END_TOOL_RESULT|><|END_OF_TURN_TOKEN|>\n {%- endif %}\n{%- endfor %}<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Escape-heavy template duplicates lot of text – factor out common base

command_a_tool_use is almost a byte-for-byte copy of command_a with JSON escaped.
A single “base” template plus a helper such as json.dumps(template) or a small Jinja filter would prevent divergence and shrink maintenance surface.

🤖 Prompt for AI Agents
In src/axolotl/utils/chat_templates.py at line 44, the command_a_tool_use
template is a nearly exact copy of command_a but with heavy JSON escaping,
causing duplication and maintenance challenges. Refactor by extracting the
common base template shared by both into a single macro or variable. Then create
a helper function or Jinja filter that applies JSON escaping or formatting as
needed, and have command_a_tool_use render the base template through this helper
instead of duplicating the entire content. This will reduce redundancy and
simplify future updates.

@NanoCode012

Copy link
Copy Markdown
Collaborator

Thanks for the PR and testing out the templates.

Just a quick look, there's also a few other changes noticed from the original (beside the for loop):

  • {{ tool_msg.content|tojson }} -> {{ tool_msg.content }}
  • {{ tool['function']['parameters']|tojson }} -> {{ tool['function']['parameters']['properties']|tojson }}

Could you please explain these change and any others that you may have made as well?

@hyeobiiii

Copy link
Copy Markdown
Contributor Author

@NanoCode012

I realized that some unintended changes were mixed into the previous commit by mistake during the process. I've corrected it now — apologies for any confusion caused.
I’ve also updated the commit to only modify the for loop as intended.

@NanoCode012 NanoCode012 merged commit 4a80d30 into axolotl-ai-cloud:main May 28, 2025
1 check passed
@hyeobiiii hyeobiiii deleted the feature/add_chat_templates_for_command_a_and_aya branch May 28, 2025 08:51
@NanoCode012

Copy link
Copy Markdown
Collaborator

Thanks for the fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add chat templates for command-a and aya-23-8B models

2 participants