Skip to content

[https://nvbugs/5361178][fix]: Json schema support in trtllm-serve using xgrammar #6197

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

mayani-nv
Copy link
Contributor

@mayani-nv mayani-nv commented Jul 18, 2025

Description

The PR will help leverage json_schema support in trtllm-serve. Currently, in order to run this successfuly the sequence of steps is as follows

  1. start the trtllm-serve
trtllm-serve nvidia/Llama-4-Scout-17B-16E-Instruct-FP8 --backend pytorch --tp_size=2 --max_num_tokens=8192 --max_batch_size 64 --kv_cache_free_gpu_memory_fraction 0.95 --extra_llm_api_options extra-llm-api-config.yaml

where the extra-llm-api-config.yaml needs to contain the guided_decoding_backend. Secondly, the disable_overlap_scheduler needs to be True in order for this to work

cat extra-llm-api-config.yaml
kv_cache_config:
  enable_block_reuse: true
enable_chunked_prefill: true
enable_attention_dp: false
disable_overlap_scheduler: true
guided_decoding_backend: xgrammar
cuda_graph_config: {
  max_batch_size: 64,
  padding_enabled: true
  }

Then running the following request

import json
import re
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import List

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-used")

class CapitalInfo(BaseModel):
    name: str = Field(..., pattern=r"^\w+$", description="The name of the capital city")
    population: int = Field(..., description="The population of the capital city")


response = client.chat.completions.create(
    model="nvidia/Llama-4-Scout-17B-16E-Instruct-FP8",
    messages=[
        {
            "role": "user",
            "content": "Please generate the information of the capital of France in the JSON format. ",
        },

    ],
    response_format={
        "type": "json_schema",
        "json_schema": CapitalInfo.model_json_schema(),
    },
    temperature=0.7,
)

message_content = response.choices[0].message.content
# validate the JSON response by the pydantic model
#print('message_content', message_content)
capital_info = CapitalInfo.model_validate_json(message_content)
print(capital_info)

gives the output as name='Paris' population=2148271. On the server side, you can see the logs can be seen as well

[07/18/2025-23:45:14] [TRT-LLM] [RANK 0] [I] Run generation only CUDA graph warmup for batch size=1
INFO:     Started server process [17082]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
[07/18/2025-23:47:59] [TRT-LLM] [RANK 0] [I] --- DEBUG: XGrammarMatcherFactory creating matcher with guide_type: GuideType.JSON_SCHEMA and guide: {"properties": {"name": {"description": "The name of the capital city", "pattern": "^\\w+$", "title": "Name", "type": "string"}, "population": {"description": "The population of the capital city", "title": "Population", "type": "integer"}}, "required": ["name", "population"], "title": "CapitalInfo", "type": "object"}
[07/18/2025-23:48:00] [TRT-LLM] [RANK 0] [I] --- DEBUG: XGrammarMatcher created successfully.
INFO:     127.0.0.1:33454 - "POST /v1/chat/completions HTTP/1.1" 200 OK

Summary by CodeRabbit

  • New Features

    • Added support for specifying response format using a JSON schema in chat completions.
    • Users can now receive structured responses that conform to a provided JSON schema.
  • Tests

    • Introduced new tests to validate chat completion responses against user-defined JSON schemas, ensuring correct structure and content.

adding the changes to support the json_schema as one of the supported type

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
adding flags related to the lora_request else it will give 400 request code 

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
Copy link

coderabbitai bot commented Jul 18, 2025

Walkthrough

Support for a new "json_schema" response format has been added to the OpenAI protocol implementation, including model changes and decoding logic. A comprehensive test module was introduced to validate chat completion responses formatted according to a user-provided JSON schema, ensuring schema compliance and correct API integration.

Changes

File(s) Change Summary
tensorrt_llm/serve/openai_protocol.py Added "json_schema" as an allowed ResponseFormat.type; added json_schema field; updated decoding logic to handle "json_schema"; updated documentation for CompletionRequest.
tests/unittest/llmapi/apps/_test_openai_json_schema.py New test module: fixtures for server/client/model setup; test for chat completion with JSON schema response format; schema validation.

Estimated code review effort

2 (~20 minutes)

Poem

In fields of code where schemas grow,
A rabbit hops where data flows.
With JSON shapes and cities bright,
Paris shines in schema light.
Tests now check what models say—
Hop, hop, hooray for JSON’s way!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 152e2df and 52f833a.

📒 Files selected for processing (2)
  • tensorrt_llm/serve/openai_protocol.py (3 hunks)
  • tensorrt_llm/serve/openai_server.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
tensorrt_llm/serve/openai_server.py

294-294: Local variable lora_request is assigned to but never used

Remove assignment to unused variable lora_request

(F841)

🔇 Additional comments (3)
tensorrt_llm/serve/openai_protocol.py (3)

55-59: LGTM! Clean extension of ResponseFormat for JSON schema support.

The implementation correctly extends the existing response format types to include "json_schema" and adds the appropriate optional field to hold the schema data. The type annotations and field definitions follow the established patterns.


148-149: LGTM! Correct implementation of JSON schema guided decoding.

The conversion logic properly handles the new "json_schema" type by passing the schema data to GuidedDecodingParams(json=response_format.json_schema). This follows the expected pattern and integrates well with the existing guided decoding framework.


211-211: LGTM! Documentation accurately reflects the new capability.

The description correctly includes {'type': 'json_schema'} alongside the existing supported format types, maintaining consistency with the documentation style.

fixing typo with `lora_request`

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
@amukkara amukkara requested review from syuoni and amukkara July 19, 2025 00:26
@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Jul 19, 2025
@amukkara
Copy link
Collaborator

amukkara commented Jul 21, 2025

@mayani-nv #6000 added overlap scheduler support for guided decoding. Would that be sufficient to run json_schema requests with overlap scheduler? if so, can you update this PR's description?

Fixing the `lora_request` typo

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
@amukkara
Copy link
Collaborator

Description

The PR will help leverage json_schema support in trtllm-serve. Currently, in order to run this successfuly the sequence of steps is as follows

  1. start the trtllm-serve
trtllm-serve nvidia/Llama-4-Scout-17B-16E-Instruct-FP8 --backend pytorch --tp_size=2 --max_num_tokens=8192 --max_batch_size 64 --kv_cache_free_gpu_memory_fraction 0.95 --extra_llm_api_options extra-llm-api-config.yaml

where the extra-llm-api-config.yaml needs to contain the guided_decoding_backend. Secondly, the disable_overlap_scheduler needs to be True in order for this to work

cat extra-llm-api-config.yaml
kv_cache_config:
  enable_block_reuse: true
enable_chunked_prefill: true
enable_attention_dp: false
disable_overlap_scheduler: true
guided_decoding_backend: xgrammar
cuda_graph_config: {
  max_batch_size: 64,
  padding_enabled: true
  }

Then running the following request

import json
import re
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import List

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-used")

class CapitalInfo(BaseModel):
    name: str = Field(..., pattern=r"^\w+$", description="The name of the capital city")
    population: int = Field(..., description="The population of the capital city")


response = client.chat.completions.create(
    model="nvidia/Llama-4-Scout-17B-16E-Instruct-FP8",
    messages=[
        {
            "role": "user",
            "content": "Please generate the information of the capital of France in the JSON format. ",
        },

    ],
    response_format={
        "type": "json_schema",
        "json_schema": CapitalInfo.model_json_schema(),
    },
    temperature=0.7,
)

message_content = response.choices[0].message.content
# validate the JSON response by the pydantic model
#print('message_content', message_content)
capital_info = CapitalInfo.model_validate_json(message_content)
print(capital_info)

gives the output as name='Paris' population=2148271. On the server side, you can see the logs can be seen as well

[07/18/2025-23:45:14] [TRT-LLM] [RANK 0] [I] Run generation only CUDA graph warmup for batch size=1
INFO:     Started server process [17082]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://localhost:8000 (Press CTRL+C to quit)
[07/18/2025-23:47:59] [TRT-LLM] [RANK 0] [I] --- DEBUG: XGrammarMatcherFactory creating matcher with guide_type: GuideType.JSON_SCHEMA and guide: {"properties": {"name": {"description": "The name of the capital city", "pattern": "^\\w+$", "title": "Name", "type": "string"}, "population": {"description": "The population of the capital city", "title": "Population", "type": "integer"}}, "required": ["name", "population"], "title": "CapitalInfo", "type": "object"}
[07/18/2025-23:48:00] [TRT-LLM] [RANK 0] [I] --- DEBUG: XGrammarMatcher created successfully.
INFO:     127.0.0.1:33454 - "POST /v1/chat/completions HTTP/1.1" 200 OK

Similarly, structural_tag can also be seen supported by xgrammar

server side logs

s"]},"end":"</function>"}],"triggers":["<function="]}
[07/18/2025-23:57:13] [TRT-LLM] [RANK 0] [I] --- DEBUG: Structural tag parameters: {'type': 'structural_tag', 'structures': [{'begin': '<function=calendar_event>', 'schema': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the event'}, 'date': {'type': 'string', 'description': 'The date of the event'}, 'participants': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['name', 'date', 'participants']}, 'end': '</function>'}], 'triggers': ['<function=']}
[07/18/2025-23:57:13] [TRT-LLM] [RANK 0] [I] --- DEBUG: XGrammarMatcher created successfully.
INFO:     127.0.0.1:42988 - "POST /v1/chat/completions HTTP/1.1" 200 OK

Client side request and response

# request
from openai import OpenAI

# 1. Initialize the client to connect to your local server
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-used")

# 2. Define the JSON schema as a plain dictionary
# This removes the need for pydantic for this simple test.
calendar_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string", "description": "The name of the event"},
        "date": {"type": "string", "description": "The date of the event"},
        "participants": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["name", "date", "participants"],
}

# 3. Define the response_format for structural_tag
# This tells the model to use the specified tags and schema.
response_format = {
    "type": "structural_tag",
    "structures": [{
        "begin": "<function=calendar_event>",
        "end": "</function>",
        "schema": calendar_schema
    }],
    "triggers": ["<function="]
}

# 4. Make the API call with a simplified prompt
response = client.chat.completions.create(
    model="nvidia/Llama-4-Scout-17B-16E-Instruct-FP8",
    messages=[
        {
            "role": "system",
            "content": "You are a data extraction expert. Wrap your JSON output in <function=calendar_event> tags."
        },
        {
            "role": "user", 
            "content": "Alice and Bob are going to a science fair on Friday."
        },
    ],
    response_format=response_format,
    temperature=0.7,
)

# 5. Print the raw output from the model
# For this minimal test, we just want to see if the model respected the structural tags.
print("--- Model Output ---")
print(response.choices[0].message.content) 



# response
--- Model Output ---
<function=calendar_event>{"name": "Science Fair", "date": "Friday", "participants": ["Alice", "Bob"]}</function>

Summary by CodeRabbit

  • New Features

    • Added support for a new response format type, "json_schema", allowing users to specify a JSON schema for output formatting.
    • Updated documentation to reflect the new "json_schema" option in response format choices.
  • Chores

    • Minor internal adjustments to request handling with no visible impact on user experience.

PR description has both json_schema and structural tag example. Since this PR only adds json_schema, can we remove the structural_tag example to keep the description concise? @mayani-nv

structures: Optional[List[StructuralTag]] = None
triggers: Optional[List[str]] = None
json_schema: Optional[Dict[str, Any]] = None
Copy link
Collaborator

Choose a reason for hiding this comment

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

please add a simple test case for json_schema. can be based on the test for structural_tag.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done, please review.

removing the `lora_request` as the latest main branch contains this defined. 

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
Adding the unit test for the json_schema support in xgrammar

Signed-off-by: mayani-nv <67936769+mayani-nv@users.noreply.github.com>
Copy link

@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: 0

🧹 Nitpick comments (2)
tests/unittest/llmapi/apps/_test_openai_json_schema.py (2)

15-17: Fix inconsistent fixture ID.

The fixture ID "TinyLlama-1.1B-Chat" doesn't match the actual model name "llama-3.1-model/Llama-3.1-8B-Instruct". This inconsistency could be confusing.

-@pytest.fixture(scope="module", ids=["TinyLlama-1.1B-Chat"])
+@pytest.fixture(scope="module", ids=["Llama-3.1-8B-Instruct"])

57-67: Consider more inclusive regex pattern for city names.

The regex pattern ^\w+$ for the capital name field might be too restrictive, as it only allows word characters and would reject valid city names with spaces, hyphens, or apostrophes (e.g., "New York", "Saint-Denis").

Consider a more inclusive pattern:

-        name: str = Field(...,
-                          pattern=r"^\w+$",
-                          description="The name of the capital city")
+        name: str = Field(...,
+                          pattern=r"^[\w\s\-'\.]+$",
+                          description="The name of the capital city")

However, since this test specifically asks for Paris (which matches the current pattern), the current implementation works for this test case.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 02e62f2 and 93ba7d5.

📒 Files selected for processing (1)
  • tests/unittest/llmapi/apps/_test_openai_json_schema.py (1 hunks)
🔇 Additional comments (5)
tests/unittest/llmapi/apps/_test_openai_json_schema.py (5)

1-12: LGTM! Well-organized imports and appropriate test configuration.

The imports are logically grouped and the thread leak detection disable is appropriate for OpenAI server integration tests.


20-34: LGTM! Proper resource management and configuration.

The fixture correctly creates a temporary configuration file with appropriate cleanup in the finally block. The xgrammar backend configuration aligns with the JSON schema support requirements.


36-44: LGTM! Clean server setup with proper resource management.

The server fixture correctly configures the RemoteOpenAIServer with the necessary backend and options.


47-54: LGTM! Clean client fixture setup.

Both synchronous and asynchronous client fixtures are properly configured with appropriate scope.


70-103: LGTM! Comprehensive test with good validation.

The test function thoroughly validates both the OpenAI API integration and JSON schema compliance. The assertions cover response structure, content parsing, and expected values.

Consider setting temperature=0.0 for more deterministic results in unit tests, though the current configuration should work fine for the specific prompt used.

@mayani-nv
Copy link
Contributor Author

@mayani-nv #6000 added overlap scheduler support for guided decoding. Would that be sufficient to run json_schema requests with overlap scheduler? if so, can you update this PR's description?

The main commiit fc8b29c4fffbaec7b579ec7ac65ee3170245f8a4 is not supporting guided decoding with overlap scheduler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Community want to contribute PRs initiated from Community
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants