Skip to content

Conversation

@LinPoly
Copy link
Collaborator

@LinPoly LinPoly commented Nov 19, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added --chat_template command-line option to specify custom chat templates when starting the server
    • Chat templates support both file paths and literal strings, with built-in validation and caching
    • Server can now apply templates per-request or use a default template from initialization
  • Tests

    • Added comprehensive unit tests for chat template loading and validation

Description

Test Coverage

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

Signed-off-by: Pengyun Lin <[email protected]>
@LinPoly LinPoly requested review from 2ez4bz and JunyiXu-nv November 19, 2025 07:34
@LinPoly LinPoly self-assigned this Nov 19, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 19, 2025

📝 Walkthrough

Walkthrough

The changes add chat template support to the TensorRT-LLM serve command. A new load_chat_template() utility function with caching is introduced to load templates from file paths or handle literal strings with error detection. The OpenAIServer constructor accepts an optional chat template, loads it via the utility, and uses it as a fallback during chat prompt construction.

Changes

Cohort / File(s) Summary
CLI and launcher wiring
tensorrt_llm/commands/serve.py
Added --chat_template CLI option and propagated chat_template parameter through serve() function signature and launch_server() invocation to pass template to OpenAIServer initialization.
Chat template loading utility
tensorrt_llm/serve/chat_utils.py
Introduced public load_chat_template() function with internal _load_chat_template() implementation featuring caching, path/literal detection, file I/O with error handling, and fallback retry logic for ambiguous inputs.
Server integration
tensorrt_llm/serve/openai_server.py
Extended OpenAIServer.__init__() to accept optional chat_template parameter, stores preloaded template via load_chat_template(), and updated chat prompt construction to use request-level template with server-level template as fallback.
Test coverage
tests/unittest/llmapi/apps/test_chat_utils.py
Added TestLoadChatTemplate suite with five test cases covering file path loading, literal string loading, None input, invalid path error handling, and Jinja-like template detection.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI (serve command)
    participant Launcher as launch_server()
    participant Server as OpenAIServer.__init__()
    participant TemplateLoader as load_chat_template()
    participant Chat as openai_chat()

    CLI->>+Launcher: serve(..., chat_template)
    Launcher->>+Server: OpenAIServer(..., chat_template)
    Server->>+TemplateLoader: load_chat_template(chat_template)
    TemplateLoader-->>-Server: loaded_template: str | None
    Server->>Server: self.chat_template = loaded_template
    Server-->>-Launcher: initialized
    Launcher-->>-CLI: server ready

    Note over Chat: At request time
    Chat->>Chat: use request.chat_template or self.chat_template
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Path/literal detection logic in _load_chat_template() requires careful review—the heuristic for distinguishing file paths from template strings (checking for {}, \n) and the fallback retry behavior warrant attention
  • Caching behavior of _load_chat_template() should be verified to ensure template immutability and cache key correctness
  • Fallback precedence in openai_chat() between request-level and server-level templates needs validation to ensure expected override semantics
  • Test completeness covers main paths but edge cases around concurrent access to cached templates may warrant consideration

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete; it only contains the template structure with placeholders but lacks actual content explaining the issue, solution, test coverage, and implementation details. Fill in the Description, Test Coverage sections with concrete details. Explain what problem this solves, the implementation approach, and list specific tests that validate the changes.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title '[None][feat] Support custom chat template for tool calling' clearly and concisely summarizes the main feature addition: enabling custom chat templates for tool calling functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
tensorrt_llm/commands/serve.py (1)

359-362: Consider enhancing the help text.

The help text for --chat_template could be more descriptive about the expected input format. Consider mentioning that it accepts either:

  • A file path to a Jinja template file
  • A literal Jinja template string

Example enhancement:

 @click.option("--chat_template",
               type=str,
               default=None,
-              help="[Experimental] Specify the chat template.")
+              help="[Experimental] Path to a chat template file or a literal Jinja template string.")
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee941ac and 7d3e575.

📒 Files selected for processing (4)
  • tensorrt_llm/commands/serve.py (5 hunks)
  • tensorrt_llm/serve/chat_utils.py (2 hunks)
  • tensorrt_llm/serve/openai_server.py (3 hunks)
  • tests/unittest/llmapi/apps/test_chat_utils.py (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: venkywonka
Repo: NVIDIA/TensorRT-LLM PR: 6029
File: .github/pull_request_template.md:45-53
Timestamp: 2025-08-27T17:50:13.264Z
Learning: For PR templates in TensorRT-LLM, avoid suggesting changes that would increase developer overhead, such as converting plain bullets to mandatory checkboxes. The team prefers guidance-style bullets that don't require explicit interaction to reduce friction in the PR creation process.
🧬 Code graph analysis (2)
tests/unittest/llmapi/apps/test_chat_utils.py (1)
tensorrt_llm/serve/chat_utils.py (1)
  • load_chat_template (299-304)
tensorrt_llm/serve/openai_server.py (2)
tensorrt_llm/commands/serve.py (1)
  • serve (363-446)
tensorrt_llm/serve/chat_utils.py (2)
  • load_chat_template (299-304)
  • parse_chat_messages_coroutines (223-249)
🪛 Ruff (0.14.5)
tests/unittest/llmapi/apps/test_chat_utils.py

184-184: Unused noqa directive (non-enabled: E501)

Remove unused noqa directive

(RUF100)

tensorrt_llm/serve/chat_utils.py

272-273: Avoid specifying long messages outside the exception class

(TRY003)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (12)
tests/unittest/llmapi/apps/test_chat_utils.py (3)

1-7: LGTM!

The new imports (os, tempfile, load_chat_template) are appropriate for the test fixture and test cases being added.


189-200: LGTM!

The fixture properly manages the lifecycle of the temporary chat template file, including cleanup in the finally block.


203-230: LGTM!

The test suite provides comprehensive coverage of load_chat_template functionality, including edge cases like None input, invalid paths, and the automatic detection of Jinja-like literal strings.

tensorrt_llm/serve/chat_utils.py (3)

3-4: LGTM!

The added imports (lru_cache and Path) are appropriately used in the new chat template loading functionality.


262-293: Verify the path vs. literal detection heuristic.

The function uses JINJA_CHARS = "{}\n" to distinguish between file paths and literal template strings. This heuristic assumes:

  • Paths won't contain these characters
  • Literal Jinja templates will contain at least one of these characters

This could produce unexpected behavior if:

  • A path contains {, }, or \n (unlikely but possible on some filesystems)
  • A literal template string doesn't contain any of these characters (rare for Jinja templates)

Consider adding a comment explaining this heuristic and its assumptions. Also, the static analysis flags the long error message on lines 286-288 as a style issue (TRY003), but this is minor and can be optionally refactored into a constant or custom exception class.


296-304: LGTM!

The caching strategy using lru_cache on the internal _load_chat_template function is well-designed. This ensures that template files are read only once per unique (chat_template, is_literal) combination, improving performance for repeated calls.

tensorrt_llm/serve/openai_server.py (3)

37-38: LGTM!

The import of load_chat_template is properly added and used in the constructor.


85-93: LGTM!

The constructor properly integrates the chat_template parameter and loads it via the new utility function. The parameter placement at the end maintains backward compatibility.


516-516: LGTM!

The fallback pattern request.chat_template or self.chat_template correctly prioritizes per-request templates while falling back to the server-level default. This provides flexibility for callers.

tensorrt_llm/commands/serve.py (3)

154-154: LGTM!

The chat_template parameter is properly added to the launch_server function signature with an appropriate default value for backward compatibility.


184-185: LGTM!

The chat_template parameter is correctly passed to the OpenAIServer constructor.


375-376: LGTM!

The chat_template parameter is properly wired through from the serve function signature to the launch_server call, completing the end-to-end integration from CLI to server.

Also applies to: 444-446

@LinPoly
Copy link
Collaborator Author

LinPoly commented Nov 19, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25014 [ run ] triggered by Bot. Commit: 7d3e575

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25014 [ run ] completed with state FAILURE. Commit: 7d3e575
/LLM/main/L0_MergeRequest_PR pipeline #18896 completed with status: 'FAILURE'

Copy link
Collaborator

@JunyiXu-nv JunyiXu-nv left a comment

Choose a reason for hiding this comment

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

LGTM

@LinPoly
Copy link
Collaborator Author

LinPoly commented Nov 19, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25052 [ run ] triggered by Bot. Commit: 7d3e575

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25052 [ run ] completed with state SUCCESS. Commit: 7d3e575
/LLM/main/L0_MergeRequest_PR pipeline #18933 completed with status: 'FAILURE'

@click.option("--chat_template",
type=str,
default=None,
help="[Experimental] Specify the chat template.")
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit: maybe "Specify a custom chat template. The default is to use the model's chat template, if present"?

return _load_chat_template(chat_template, is_literal=True)


_cached_load_chat_template = lru_cache(_load_chat_template)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit: why not just do

@lru_cache
def _load_chat_template(...):

above?

def chat_template_path():
"""Return the path to the chat template."""
temp_dir = tempfile.gettempdir()
temp_file_path = os.path.join(temp_dir, "chat_template.jinja")
Copy link
Collaborator

Choose a reason for hiding this comment

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

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.

4 participants