-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[None][feat] Support custom chat template for tool calling #9297
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: Pengyun Lin <[email protected]>
📝 WalkthroughWalkthroughThe changes add chat template support to the TensorRT-LLM serve command. A new Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
Example instruction:
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. Comment |
There was a problem hiding this 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_templatecould 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
📒 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_templatefunctionality, 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_cacheandPath) 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_cacheon the internal_load_chat_templatefunction 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_templateis properly added and used in the constructor.
85-93: LGTM!The constructor properly integrates the
chat_templateparameter 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_templatecorrectly 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_templateparameter is properly added to thelaunch_serverfunction signature with an appropriate default value for backward compatibility.
184-185: LGTM!The
chat_templateparameter is correctly passed to theOpenAIServerconstructor.
375-376: LGTM!The
chat_templateparameter is properly wired through from theservefunction signature to thelaunch_servercall, completing the end-to-end integration from CLI to server.Also applies to: 444-446
|
/bot run |
|
PR_Github #25014 [ run ] triggered by Bot. Commit: |
|
PR_Github #25014 [ run ] completed with state |
JunyiXu-nv
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
/bot run |
|
PR_Github #25052 [ run ] triggered by Bot. Commit: |
|
PR_Github #25052 [ run ] completed with state |
| @click.option("--chat_template", | ||
| type=str, | ||
| default=None, | ||
| help="[Experimental] Specify the chat template.") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can use pytest's built-in tmp_path fixture: https://docs.pytest.org/en/stable/how-to/tmp_path.html#the-tmp-path-fixture
Summary by CodeRabbit
Release Notes
New Features
--chat_templatecommand-line option to specify custom chat templates when starting the serverTests
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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.