Skip to content

Conversation

@JunyiXu-nv
Copy link
Collaborator

@JunyiXu-nv JunyiXu-nv commented Dec 12, 2025

Summary by CodeRabbit

  • New Features

    • Introduced Responses API support with comprehensive documentation and examples demonstrating basic chat, streaming responses, multi-turn conversations, JSON mode, and tool calling functionality.
  • Documentation

    • Updated compatibility examples guide with new Responses API section and endpoint references.

✏️ Tip: You can customize this high-level summary in your review settings.

Description

We currently support Responses API for general models (not only gpt-oss) in #9392.

It's time to add documentation and examples about it.

Test Coverage

  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py

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.

Details

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.

@JunyiXu-nv JunyiXu-nv requested a review from a team as a code owner December 12, 2025 07:52
Signed-off-by: Junyi Xu <[email protected]>
@JunyiXu-nv
Copy link
Collaborator Author

/bot run

@JunyiXu-nv JunyiXu-nv requested a review from LinPoly December 12, 2025 07:53
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 12, 2025

📝 Walkthrough

Walkthrough

The pull request introduces support for a new Responses API endpoint by updating documentation and adding comprehensive example implementations. Documentation is reorganized to distinguish between Chat Completions and Responses endpoints, and multiple Python example scripts and shell client examples are provided to demonstrate API usage patterns including basic chat, streaming, multi-turn conversations, JSON mode, and tool calling capabilities.

Changes

Cohort / File(s) Summary
Documentation Updates
docs/source/commands/trtllm-serve/trtllm-serve.rst
Added Responses API to list of supported endpoints and integrated new examples section describing usage via OpenAI Python client and curl alongside Chat API documentation.
Example Documentation Reorganization
examples/serve/compatibility/README.md
Restructured main example index by creating dedicated sections for Chat Completions (/v1/chat/completions) and Responses (/v1/responses) endpoints with updated file paths. Renamed Model Requirements table header and expanded Tool Calling capability models.
Responses API Documentation
examples/serve/compatibility/responses/README.md
New documentation file providing quick start guide, key concept explanations (streaming vs. non-streaming, multi-turn context, tool calling), code snippets, and model requirements for Responses API examples.
Responses API Examples
examples/serve/compatibility/responses/example_01_basic_chat.py, example_02_streaming_chat.py, example_03_multi_turn_conversation.py, example_04_json_mode.py, example_05_tool_calling.py
Five new Python example scripts demonstrating Responses API usage: basic non-streaming requests, streaming responses with event handling, multi-turn conversations with context preservation, JSON schema support, and tool/function calling workflows with error handling.
Simple Client Examples
examples/serve/curl_responses_client.sh, examples/serve/openai_responses_client.py
Two lightweight client examples showing direct Responses API invocation using curl and OpenAI Python library respectively.
Test Coverage Extension
tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
Extended parametrized test to include new openai_responses_client.py and curl_responses_client.sh example scripts alongside existing test entries.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15–20 minutes

  • Multiple homogeneous example files following consistent patterns with minimal logic density
  • Documentation reorganization is straightforward and clearly structured
  • Test additions are minimal parameter additions
  • No complex interdependencies or control flow requiring deep analysis

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding documentation and examples for the Responses API.
Description check ✅ Passed PR description clearly explains the purpose (adding docs and examples for Responses API) and includes test coverage details and completed checklist.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/source/commands/trtllm-serve/trtllm-serve.rst (1)

7-12: Doc correctness: add /v1/responses to the supported endpoints list at the top.
Right now the page says Responses API is supported, but the canonical endpoint list doesn’t include it.

Also applies to: 37-38

🧹 Nitpick comments (4)
examples/serve/compatibility/responses/example_01_basic_chat.py (1)

30-33: Guard against empty /v1/models results.
models.data[0] will throw if the server returns no models; a small check makes the example friendlier.

 models = client.models.list()
-model = models.data[0].id
+if not getattr(models, "data", None):
+    raise RuntimeError("No models returned from server (GET /v1/models).")
+model = models.data[0].id
examples/serve/compatibility/responses/example_05_tool_calling.py (1)

118-125: Avoid blind except Exception in the main flow; handle expected failures + exit non-zero for CI.
Right now tool-call failures can degrade into misleading output.

Also applies to: 128-132

examples/serve/compatibility/responses/example_04_json_mode.py (1)

65-80: Catch specific OpenAI SDK exceptions instead of generic Exception.

The suggested fix in the original review is incorrect—ValueError and TypeError are not raised by the OpenAI SDK. Based on the OpenAI Python SDK documentation, the responses.create() method raises SDK-specific exceptions like BadRequestError (for invalid schema) and APIError (for general API failures).

Recommended fix:

+from openai import APIError, BadRequestError
+
 try:
     # Create chat completion with JSON schema
     response = client.responses.create(
@@ -76,8 +78,9 @@ try:
     print("JSON Response:")
     print(response.output_text)
-except Exception as e:
+except BadRequestError as e:
+    print("JSON schema support requires xgrammar and proper configuration.")
+    print(f"Error: {e}")
+except APIError as e:
     print("JSON schema support requires xgrammar and proper configuration.")
     print(f"Error: {e}")

This aligns with the repo's guideline to limit exception handlers to the smallest set of specific errors.

examples/serve/openai_responses_client.py (1)

1-1: Consider using standard Python comment format.

The ### :title format is unconventional for Python. While not incorrect, a standard comment or module-level docstring would be more idiomatic.

Consider replacing with:

-### :title OpenAI Responses Client
+"""OpenAI Responses Client example."""
📜 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 711016c and 8027e18.

📒 Files selected for processing (11)
  • docs/source/commands/trtllm-serve/trtllm-serve.rst (2 hunks)
  • examples/serve/compatibility/README.md (2 hunks)
  • examples/serve/compatibility/responses/README.md (1 hunks)
  • examples/serve/compatibility/responses/example_01_basic_chat.py (1 hunks)
  • examples/serve/compatibility/responses/example_02_streaming_chat.py (1 hunks)
  • examples/serve/compatibility/responses/example_03_multi_turn_conversation.py (1 hunks)
  • examples/serve/compatibility/responses/example_04_json_mode.py (1 hunks)
  • examples/serve/compatibility/responses/example_05_tool_calling.py (1 hunks)
  • examples/serve/curl_responses_client.sh (1 hunks)
  • examples/serve/openai_responses_client.py (1 hunks)
  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: The code developed for TensorRT-LLM should conform to Python 3.8+
Indent Python code with 4 spaces; do not use tabs
Always maintain the namespace when importing in Python, even if only one class or function from a module is used (e.g., use from package.subpackage import foo and then foo.SomeClass() instead of from package.subpackage.foo import SomeClass)
Python filenames should use snake_case (e.g., some_file.py)
Python class names should use PascalCase (e.g., class SomeClass)
Python function and method names should use snake_case (e.g., def my_awesome_function():)
Python local variable names should use snake_case, with prefix k for variable names that start with a number (e.g., k_99th_percentile = ...)
Python global variables should use upper snake_case with prefix G (e.g., G_MY_GLOBAL = ...)
Python constants should use upper snake_case (e.g., MY_CONSTANT = ...)
Avoid shadowing variables declared in an outer scope in Python
Initialize all externally visible members of a Python class in the constructor
For Python interfaces that may be used outside a file, prefer docstrings over comments
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings for Python classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description (e.g., self.x = 5 followed by """<type>: Description of 'x'""" )
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except clause to the smallest set of specific errors possible instead of catching all exceptions
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible and use the else block to implement the logic

Files:

  • examples/serve/openai_responses_client.py
  • examples/serve/compatibility/responses/example_03_multi_turn_conversation.py
  • examples/serve/compatibility/responses/example_01_basic_chat.py
  • examples/serve/compatibility/responses/example_05_tool_calling.py
  • examples/serve/compatibility/responses/example_04_json_mode.py
  • examples/serve/compatibility/responses/example_02_streaming_chat.py
  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
**/*.{cpp,h,cu,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code files should contain an NVIDIA copyright header that includes the current year at the top

Files:

  • examples/serve/openai_responses_client.py
  • examples/serve/compatibility/responses/example_03_multi_turn_conversation.py
  • examples/serve/compatibility/responses/example_01_basic_chat.py
  • examples/serve/compatibility/responses/example_05_tool_calling.py
  • examples/serve/compatibility/responses/example_04_json_mode.py
  • examples/serve/compatibility/responses/example_02_streaming_chat.py
  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
🧠 Learnings (5)
📚 Learning: 2025-11-27T09:23:18.742Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 9511
File: tests/integration/defs/examples/serve/test_serve.py:136-186
Timestamp: 2025-11-27T09:23:18.742Z
Learning: In TensorRT-LLM testing, when adding test cases based on RCCA commands, the command format should be copied exactly as it appears in the RCCA case, even if it differs from existing tests. For example, some RCCA commands for trtllm-serve may omit the "serve" subcommand while others include it.

Applied to files:

  • docs/source/commands/trtllm-serve/trtllm-serve.rst
  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.

Applied to files:

  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.

Applied to files:

  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
📚 Learning: 2025-08-06T13:58:07.506Z
Learnt from: galagam
Repo: NVIDIA/TensorRT-LLM PR: 6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.

Applied to files:

  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
📚 Learning: 2025-08-29T14:07:45.863Z
Learnt from: EmmaQiaoCh
Repo: NVIDIA/TensorRT-LLM PR: 7370
File: tests/unittest/trt/model_api/test_model_quantization.py:24-27
Timestamp: 2025-08-29T14:07:45.863Z
Learning: In TensorRT-LLM's CI infrastructure, pytest skip markers (pytest.mark.skip) are properly honored even when test files have __main__ blocks that call test functions directly. The testing system correctly skips tests without requiring modifications to the __main__ block execution pattern.

Applied to files:

  • tests/unittest/llmapi/apps/_test_trtllm_serve_example.py
🪛 Ruff (0.14.8)
examples/serve/compatibility/responses/example_03_multi_turn_conversation.py

16-16: Shebang should be at the beginning of the file

(EXE005)

examples/serve/compatibility/responses/example_01_basic_chat.py

16-16: Shebang should be at the beginning of the file

(EXE005)

examples/serve/compatibility/responses/example_05_tool_calling.py

16-16: Shebang should be at the beginning of the file

(EXE005)


87-87: Use of possibly insecure function; consider using ast.literal_eval

(S307)


88-88: Do not catch blind exception: Exception

(BLE001)


128-128: Do not catch blind exception: Exception

(BLE001)

examples/serve/compatibility/responses/example_04_json_mode.py

16-16: Shebang should be at the beginning of the file

(EXE005)


78-78: Do not catch blind exception: Exception

(BLE001)

examples/serve/compatibility/responses/example_02_streaming_chat.py

16-16: Shebang should be at the beginning of the file

(EXE005)

⏰ 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 (9)
examples/serve/compatibility/responses/README.md (1)

1-43: Docs look consistent and easy to follow.
Example list + requirements table align with the scripts added in this PR.

docs/source/commands/trtllm-serve/trtllm-serve.rst (1)

69-86: LGTM: Responses API section + includes are a good addition.
Minor nit: consider rewording to “the Completions API, Chat Completions API, and Responses API” for consistency with endpoint naming.

examples/serve/compatibility/responses/example_05_tool_calling.py (1)

47-65: The tools payload format is correct for the OpenAI Responses API.

The tools definition uses the correct shape: a flat object with type, name, description, and parameters fields. OpenAI Responses API expects each tool as {"type": "function", "name": "...", "description": "...", "parameters": {...}} at the top level, which matches what the code implements. No nested "function" wrapper is required.

examples/serve/compatibility/responses/example_03_multi_turn_conversation.py (1)

54-60: No action required. The code correctly uses previous_response_id as the intended mechanism for TRT-LLM's OpenAI-compatible Responses API to continue conversations without resending full context history. This parameter is explicitly defined in ResponsesRequest (matching OpenAI's API specification), properly handled server-side with conversation store integration, and validated by unit tests.

examples/serve/compatibility/responses/example_02_streaming_chat.py (1)

85-90: Streaming contract verified: responses.create(..., stream=True) correctly yields all documented event types for TRT-LLM.

The code correctly handles all 11 event types emitted by TRT-LLM's /v1/responses streaming endpoint: response.created, response.in_progress, response.output_item.added, response.content_part.added, response.reasoning_text.delta, response.output_text.delta, response.reasoning_text.done, response.output_text.done, response.content_part.done, response.output_item.done, and response.completed. The iteration pattern at lines 97-98 (for event in stream:) is correct for OpenAI SDK compatibility.

Also applies to: 97-98

tests/unittest/llmapi/apps/_test_trtllm_serve_example.py (1)

51-60: LGTM: test coverage updated to include Responses clients.

The new scripts (openai_responses_client.py, curl_responses_client.sh, genai_perf_client.sh) exist and integrate correctly. No changes needed to curl_responses_client.sh—curl automatically disables the progress meter when stdout is piped (as subprocess.PIPE does), so JSON parsing will work as expected without the -s flag.

examples/serve/curl_responses_client.sh (1)

1-9: LGTM!

The script provides a clear, minimal example of calling the Responses API endpoint. The structure is appropriate for a demonstration script.

examples/serve/compatibility/README.md (2)

37-58: LGTM!

The reorganization clearly separates Chat Completions and Responses endpoints with consistent structure and formatting. The new Responses section follows the same pattern as Chat Completions, making the documentation easy to navigate.


84-84: No action needed. The addition of "Kimi K2" to the list of tool-capable models is accurate and well-supported in the codebase. The model has native tool calling support with dedicated implementation in tensorrt_llm/serve/chat_utils.py (including K2-specific tool call ID formatting), comprehensive examples in examples/models/core/kimi_k2/, and integration tests throughout the test suite.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #28012 [ run ] triggered by Bot. Commit: 8027e18

@tensorrt-cicd
Copy link
Collaborator

PR_Github #28012 [ run ] completed with state SUCCESS. Commit: 8027e18
/LLM/main/L0_MergeRequest_PR pipeline #21394 completed with status: 'SUCCESS'

Signed-off-by: Junyi Xu <[email protected]>
@JunyiXu-nv
Copy link
Collaborator Author

/bot reuse-pipeline

@tensorrt-cicd
Copy link
Collaborator

PR_Github #28309 [ reuse-pipeline ] triggered by Bot. Commit: e0655e1

@JunyiXu-nv JunyiXu-nv enabled auto-merge (squash) December 15, 2025 05:43
@tensorrt-cicd
Copy link
Collaborator

PR_Github #28309 [ reuse-pipeline ] completed with state SUCCESS. Commit: e0655e1
Reusing PR_Github #28012 for commit e0655e1

@JunyiXu-nv JunyiXu-nv merged commit af899d2 into NVIDIA:main Dec 15, 2025
5 checks passed
sherry-1001 pushed a commit to sherry-1001/TensorRT-LLM that referenced this pull request Dec 16, 2025
codego7250 pushed a commit to codego7250/TensorRT-LLM that referenced this pull request Dec 19, 2025
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.

3 participants