-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-9860][doc] Add docs and examples for Responses API #9946
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
[TRTLLM-9860][doc] Add docs and examples for Responses API #9946
Conversation
Signed-off-by: Junyi Xu <[email protected]>
Signed-off-by: Junyi Xu <[email protected]>
|
/bot run |
📝 WalkthroughWalkthroughThe 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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~15–20 minutes
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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: 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/responsesto 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/modelsresults.
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].idexamples/serve/compatibility/responses/example_05_tool_calling.py (1)
118-125: Avoid blindexcept Exceptionin 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 genericException.The suggested fix in the original review is incorrect—
ValueErrorandTypeErrorare not raised by the OpenAI SDK. Based on the OpenAI Python SDK documentation, theresponses.create()method raises SDK-specific exceptions likeBadRequestError(for invalid schema) andAPIError(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
### :titleformat 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
📒 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., usefrom package.subpackage import fooand thenfoo.SomeClass()instead offrom 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 prefixkfor variable names that start with a number (e.g.,k_99th_percentile = ...)
Python global variables should use upper snake_case with prefixG(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 = 5followed 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.pyexamples/serve/compatibility/responses/example_03_multi_turn_conversation.pyexamples/serve/compatibility/responses/example_01_basic_chat.pyexamples/serve/compatibility/responses/example_05_tool_calling.pyexamples/serve/compatibility/responses/example_04_json_mode.pyexamples/serve/compatibility/responses/example_02_streaming_chat.pytests/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.pyexamples/serve/compatibility/responses/example_03_multi_turn_conversation.pyexamples/serve/compatibility/responses/example_01_basic_chat.pyexamples/serve/compatibility/responses/example_05_tool_calling.pyexamples/serve/compatibility/responses/example_04_json_mode.pyexamples/serve/compatibility/responses/example_02_streaming_chat.pytests/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.rsttests/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: Thetoolspayload format is correct for the OpenAI Responses API.The tools definition uses the correct shape: a flat object with
type,name,description, andparametersfields. 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 usesprevious_response_idas the intended mechanism for TRT-LLM's OpenAI-compatible Responses API to continue conversations without resending full context history. This parameter is explicitly defined inResponsesRequest(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/responsesstreaming 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, andresponse.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 tocurl_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-sflag.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 intensorrt_llm/serve/chat_utils.py(including K2-specific tool call ID formatting), comprehensive examples inexamples/models/core/kimi_k2/, and integration tests throughout the test suite.
examples/serve/compatibility/responses/example_03_multi_turn_conversation.py
Show resolved
Hide resolved
|
PR_Github #28012 [ run ] triggered by Bot. Commit: |
|
PR_Github #28012 [ run ] completed with state |
Signed-off-by: Junyi Xu <[email protected]>
|
/bot reuse-pipeline |
|
PR_Github #28309 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #28309 [ reuse-pipeline ] completed with state |
Signed-off-by: Junyi Xu <[email protected]>
Signed-off-by: Junyi Xu <[email protected]>
Summary by CodeRabbit
New Features
Documentation
✏️ 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
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 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.