-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-9242][doc] Add examples showcasing openai compatible APIs #9520
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?
[TRTLLM-9242][doc] Add examples showcasing openai compatible APIs #9520
Conversation
Signed-off-by: Junyi Xu <219237550+JunyiXu-nv@users.noreply.github.com>
c300107 to
f934896
Compare
|
/bot run |
📝 WalkthroughWalkthroughThis PR adds documentation and example scripts demonstrating OpenAI API compatibility features for TensorRT-LLM's Chat Completions endpoint, including basic chat, streaming, multi-turn conversations, JSON mode, tool calling, and advanced sampling parameters. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Client
participant Server
rect rgb(200, 220, 255)
Note over User,Server: Non-Streaming / Multi-Turn Pattern
User->>Client: Initialize with base_url, api_key
Client->>Server: GET /v1/models
Server-->>Client: Return model list
Client->>User: Select model
User->>Client: Call chat_completions.create()
Client->>Server: POST /v1/chat/completions
Server-->>Client: Return full response
Client->>User: Display response & usage
end
sequenceDiagram
participant User
participant Client
participant Server
rect rgb(220, 255, 220)
Note over User,Server: Streaming Pattern
User->>Client: Initialize with base_url, api_key
Client->>Server: GET /v1/models
Server-->>Client: Return model list
User->>Client: Call chat_completions.create(stream=True)
Client->>Server: POST /v1/chat/completions (stream=true)
loop Each chunk arrives
Server-->>Client: Streaming chunk
Client->>User: Print token/delta
end
Client->>User: Display final stop_reason
end
sequenceDiagram
participant User
participant Client
participant Server
participant ToolFunction
rect rgb(255, 240, 200)
Note over User,Server: Tool Calling Pattern
User->>Client: Initialize & select model
User->>Client: Call chat_completions.create(tools=[...])
Client->>Server: POST /v1/chat/completions with tools
Server-->>Client: Response with tool_calls
Client->>User: Display tool call details
User->>ToolFunction: Execute tool function locally
ToolFunction-->>User: Return result
User->>Client: Call chat_completions.create(messages=[...tool_result...])
Client->>Server: POST /v1/chat/completions with tool result
Server-->>Client: Final response
Client->>User: Display final response
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 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 |
|
PR_Github #26005 [ run ] triggered by Bot. Commit: |
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: 8
🧹 Nitpick comments (7)
examples/serve/compatibility/chat_completions/example_02_streaming_chat.py (1)
40-61: PotentialNameErrorif stream is empty.The
chunkvariable is used on line 61 after the for loop. If the stream yields no chunks,chunkwould be undefined, causing aNameError. While unlikely in practice, consider guarding against this edge case.current_state = "none" +finish_reason = None for chunk in stream: has_content = hasattr(chunk.choices[0].delta, "content") and chunk.choices[0].delta.content has_reasoning_content = ( hasattr(chunk.choices[0].delta, "reasoning_content") and chunk.choices[0].delta.reasoning_content ) if has_content: if current_state != "content": print("Content: ", end="", flush=True) current_state = "content" print(chunk.choices[0].delta.content, end="", flush=True) if has_reasoning_content: if current_state != "reasoning_content": print("Reasoning: ", end="", flush=True) current_state = "reasoning_content" print(chunk.choices[0].delta.reasoning_content, end="", flush=True) + + if chunk.choices[0].finish_reason: + finish_reason = chunk.choices[0].finish_reason print("\n") -print("Stop reason: ", chunk.choices[0].finish_reason) +print("Stop reason: ", finish_reason)examples/serve/compatibility/chat_completions/example_05_json_mode.py (1)
48-65: Consider narrowing the exception handling scope.The broad
Exceptioncatch (flagged by Ruff BLE001) obscures different failure modes. For an example script, this is acceptable since it provides a clear message about requirements. However, you could improve clarity by catching specific exceptions.+from openai import APIError + try: # Create chat completion with JSON schema response = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": "You are a helpful assistant that outputs JSON."}, {"role": "user", "content": "Give me information about Tokyo."}, ], response_format={"type": "json_schema", "json_schema": schema}, max_tokens=4096, ) print("JSON Response:") result = json.loads(response.choices[0].message.content) print(json.dumps(result, indent=2)) -except Exception as e: +except (APIError, json.JSONDecodeError) as e: print("JSON schema support requires xgrammar and proper configuration.") print(f"Error: {e}")examples/serve/compatibility/chat_completions/example_04_streaming_with_usage.py (2)
15-17: Optionally guard against an empty model list from the server.
models.data[0]on Lines 16–17 will raiseIndexErrorif the server returns no models. In practice this should not happen, but a small guard would make the example more robust and error-message friendly.For example:
-# Get the model name from the server -models = client.models.list() -model = models.data[0].id +# Get the model name from the server +models = client.models.list() +if not models.data: + raise RuntimeError("No models available from the server; please verify trtllm-serve is running with a model.") +model = models.data[0].id
36-66: Guard access tochunk.usagein case no chunks or no usage info are returned.Lines 62–66 assume that:
- At least one chunk was received, and
- The last chunk has a
.usagefield.If the stream fails early or the server doesn’t send usage (misconfig, older server, etc.), this will raise an
AttributeError. You can keep behavior identical for the happy path but add a safe fallback:-chunk = None +chunk = None current_state = "none" for chunk in stream: @@ print() -print( - f"Tokens used: {chunk.usage.total_tokens} " - f"(prompt: {chunk.usage.prompt_tokens}, " - f"completion: {chunk.usage.completion_tokens})" -) +if chunk is not None and getattr(chunk, "usage", None) is not None: + print( + f"Tokens used: {chunk.usage.total_tokens} " + f"(prompt: {chunk.usage.prompt_tokens}, " + f"completion: {chunk.usage.completion_tokens})" + ) +else: + print("Tokens used: (usage information not available)")examples/serve/compatibility/chat_completions/example_06_tool_calling.py (1)
100-105: Narrow or document the broadexcept Exceptionhandler.The
except Exception as e:on Lines 103–105 is intentionally user‑friendly but very broad and suppresses all unexpected errors, which can make debugging harder and conflicts with the guideline of catching the smallest relevant set of exceptions.For an example script, two lightweight options:
- Narrow to the specific client/network exceptions you expect (e.g., connection errors, API errors), or
- Keep the broad handler but re‑raise unknown errors after logging, or at least add a comment/
# noqa: BLE001to acknowledge the trade‑off.For example:
-except Exception as e: - print("Note: Tool calling requires model support (e.g., Llama 3.1+ models)") - print(f"Error: {e}") +except Exception as e: + # Broad catch for demo purposes; in production, catch specific client/network errors instead. + print("Note: Tool calling requires model support (e.g., Llama 3.1+ models)") + print(f"Error: {e}")examples/serve/compatibility/chat_completions/README.md (1)
43-47: Align tool‑calling model examples and clean up wording.The tool‑calling requirements are described slightly differently in a few places:
- Here in the Examples Overview and Model Requirements table you mention “Qwen3, gpt_oss”.
- In
example_06_tool_calling.pyyou mention “Llama 3.1+, Mistral Instruct”.- In the top‑level compatibility README you refer generically to “tool‑capable” models.
To avoid confusing users, consider standardizing the wording across these docs, e.g., something like:
Requires a tool‑capable model (e.g., Qwen3, Llama 3.1+, Mistral Instruct,
gpt_oss).Also, in the Model Requirements table row:
| Tool calling | Compatible model (Qwen3 and gpt_oss.) |you can drop the final period and/or make the phrasing parallel with the JSON mode row, e.g.:
| Tool calling | Compatible model (Qwen3, `gpt_oss`, etc.) |Also applies to: 94-100
examples/serve/compatibility/README.md (1)
12-16: Tighten wording around reasoning/tool‑calling models.The sentence around Lines 12–16 reads a bit awkwardly:
for reasoning model or model with tool calling ability. Specify
--tool_parserand--reasoning_parser, e.g.Consider something like:
For a reasoning model or a model with tool‑calling ability, specify `--tool_parser` and `--reasoning_parser`, for example:This both fixes the grammar and adds the recommended hyphenation.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
examples/serve/compatibility/README.md(1 hunks)examples/serve/compatibility/chat_completions/README.md(1 hunks)examples/serve/compatibility/chat_completions/example_01_basic_chat.py(1 hunks)examples/serve/compatibility/chat_completions/example_02_streaming_chat.py(1 hunks)examples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.py(1 hunks)examples/serve/compatibility/chat_completions/example_04_streaming_with_usage.py(1 hunks)examples/serve/compatibility/chat_completions/example_05_json_mode.py(1 hunks)examples/serve/compatibility/chat_completions/example_06_tool_calling.py(1 hunks)examples/serve/compatibility/chat_completions/example_07_advanced_sampling.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/compatibility/chat_completions/example_02_streaming_chat.pyexamples/serve/compatibility/chat_completions/example_06_tool_calling.pyexamples/serve/compatibility/chat_completions/example_04_streaming_with_usage.pyexamples/serve/compatibility/chat_completions/example_05_json_mode.pyexamples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.pyexamples/serve/compatibility/chat_completions/example_01_basic_chat.pyexamples/serve/compatibility/chat_completions/example_07_advanced_sampling.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/compatibility/chat_completions/example_02_streaming_chat.pyexamples/serve/compatibility/chat_completions/example_06_tool_calling.pyexamples/serve/compatibility/chat_completions/example_04_streaming_with_usage.pyexamples/serve/compatibility/chat_completions/example_05_json_mode.pyexamples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.pyexamples/serve/compatibility/chat_completions/example_01_basic_chat.pyexamples/serve/compatibility/chat_completions/example_07_advanced_sampling.py
🧠 Learnings (3)
📓 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.
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.
📚 Learning: 2025-08-01T15:14:45.673Z
Learnt from: yibinl-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 6506
File: examples/models/core/mixtral/requirements.txt:3-3
Timestamp: 2025-08-01T15:14:45.673Z
Learning: In TensorRT-LLM, examples directory can have different dependency versions than the root requirements.txt file. Version conflicts between root and examples dependencies are acceptable because examples are designed to be standalone and self-contained.
Applied to files:
examples/serve/compatibility/README.md
📚 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:
examples/serve/compatibility/README.md
🧬 Code graph analysis (1)
examples/serve/compatibility/chat_completions/example_02_streaming_chat.py (1)
tensorrt_llm/inputs/multimodal.py (1)
has_content(519-521)
🪛 LanguageTool
examples/serve/compatibility/README.md
[grammar] ~12-~12: Use a hyphen to join words.
Context: ... for reasoning model or model with tool calling ability. Specify --tool_parser...
(QB_NEW_EN_HYPHEN)
🪛 Ruff (0.14.6)
examples/serve/compatibility/chat_completions/example_02_streaming_chat.py
1-1: Shebang is present but file is not executable
(EXE001)
examples/serve/compatibility/chat_completions/example_06_tool_calling.py
1-1: Shebang is present but file is not executable
(EXE001)
103-103: Do not catch blind exception: Exception
(BLE001)
examples/serve/compatibility/chat_completions/example_04_streaming_with_usage.py
1-1: Shebang is present but file is not executable
(EXE001)
examples/serve/compatibility/chat_completions/example_05_json_mode.py
1-1: Shebang is present but file is not executable
(EXE001)
63-63: Do not catch blind exception: Exception
(BLE001)
examples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.py
1-1: Shebang is present but file is not executable
(EXE001)
examples/serve/compatibility/chat_completions/example_01_basic_chat.py
1-1: Shebang is present but file is not executable
(EXE001)
examples/serve/compatibility/chat_completions/example_07_advanced_sampling.py
1-1: Shebang is present but file is not executable
(EXE001)
⏰ 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 (3)
examples/serve/compatibility/chat_completions/example_01_basic_chat.py (1)
7-43: LGTM - Clean example implementation.The example clearly demonstrates the basic chat completion workflow: client initialization, model discovery, request creation, and response handling. The code follows Python conventions and is well-structured for educational purposes.
examples/serve/compatibility/chat_completions/example_07_advanced_sampling.py (1)
38-44: Good demonstration ofextra_bodyfor TensorRT-LLM specific parameters.The use of
extra_bodyto pass TensorRT-LLM specific sampling parameters is the correct pattern for extending the OpenAI client API.examples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.py (1)
24-58: LGTM - Clear multi-turn conversation pattern.The example effectively demonstrates how to maintain conversation context by appending messages to the history. Using
temperature=0for the math questions ensures deterministic outputs, which is appropriate for this demonstration.
examples/serve/compatibility/chat_completions/example_02_streaming_chat.py
Show resolved
Hide resolved
examples/serve/compatibility/chat_completions/example_03_multi_turn_conversation.py
Show resolved
Hide resolved
examples/serve/compatibility/chat_completions/example_04_streaming_with_usage.py
Show resolved
Hide resolved
examples/serve/compatibility/chat_completions/example_06_tool_calling.py
Show resolved
Hide resolved
examples/serve/compatibility/chat_completions/example_06_tool_calling.py
Show resolved
Hide resolved
examples/serve/compatibility/chat_completions/example_07_advanced_sampling.py
Show resolved
Hide resolved
|
PR_Github #26005 [ run ] completed with state |
Signed-off-by: Junyi Xu <219237550+JunyiXu-nv@users.noreply.github.com>
|
/bot reuse-pipeline |
|
PR_Github #26101 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #26101 [ reuse-pipeline ] completed with state |
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.
Description
Added more example codes for users to interact with trtllm-serve by openai sdk.
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.