Skip to content

Conversation

mayani-nv
Copy link
Collaborator

@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 a "json" response format with schema validation in chat completions.
  • Bug Fixes
    • Improved error handling for missing schema when using the "json" response format.
  • Tests
    • Introduced new integration and unit tests to verify JSON schema validation in chat completions.
    • Updated test configurations to include the new JSON schema validation test.

noiji and others added 9 commits July 15, 2025 18:57
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
Signed-off-by: noiji <[email protected]>
adding the changes to support the json_schema as one of the supported type

Signed-off-by: mayani-nv <[email protected]>
adding flags related to the lora_request else it will give 400 request code 

Signed-off-by: mayani-nv <[email protected]>
Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

"""

Walkthrough

Support for a new "json" response format type was added to the OpenAI protocol implementation, requiring a schema for guided decoding. Corresponding test coverage was created, including a new integration test and a test list update to run this scenario. A comprehensive unit test validates multi-turn chat completion with JSON schema enforcement.

Changes

File(s) Change Summary
tensorrt_llm/serve/openai_protocol.py Added "json" type to ResponseFormat, required schema for this type, updated logic and docstrings.
tests/unittest/llmapi/apps/_test_openai_chat_json.py New test module for chat completions with JSON schema validation, including fixtures and main test.
tests/integration/defs/test_e2e.py Added test function to run the new OpenAI chat JSON schema example.
tests/integration/test_lists/test-db/l0_a10.yml Added new test case to the test list for single A10 GPU scenario.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Model

    Client->>Server: Send chat completion request with response_format={"type": "json", "schema": {...}}
    Server->>Server: Validate presence of schema for "json" type
    Server->>Model: Generate response with guided decoding (using schema)
    Model-->>Server: Return JSON response
    Server-->>Client: Return structured JSON response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Suggested reviewers

  • pcastonguay

Poem

In bytes and lines, a schema appears,
JSON dreams for LLMs, allaying our fears.
New tests now run, with structure in sight,
Ensuring responses are valid and right.
Rabbits rejoice, with data so neat—
Structured replies make this update sweet! 🐇
"""

Note

⚡️ Unit Test Generation - Beta

CodeRabbit's unit test generation is now available in Beta! Automatically generate comprehensive unit tests for your code changes, ensuring better test coverage and catching edge cases you might miss. Our AI analyzes your code structure and creates tests that follow best practices and your project's testing patterns. Learn more here, or just try it under ✨ Finishing Touches.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 46da1dd and cbb407e.

📒 Files selected for processing (1)
  • tensorrt_llm/serve/openai_protocol.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/serve/openai_protocol.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 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 generate unit tests to generate unit tests for 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
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: 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 <[email protected]>
@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 <[email protected]>
@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

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

Signed-off-by: mayani-nv <[email protected]>
Adding the unit test for the json_schema support in xgrammar

Signed-off-by: mayani-nv <[email protected]>
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: 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
Collaborator 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

@amukkara amukkara requested a review from LinPoly July 22, 2025 18:18
@amukkara amukkara changed the title [https://nvbugs/5361178][fix]: Json schema support in trtllm-serve using xgrammar [nvbugs/5361178] feat: Json schema support in trtllm-serve using xgrammar Jul 22, 2025
@amukkara amukkara changed the title [nvbugs/5361178] feat: Json schema support in trtllm-serve using xgrammar [nvbugs/5361178] feat: json_schema support in trtllm-serve using xgrammar Jul 22, 2025
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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93ba7d5 and 46da1dd.

📒 Files selected for processing (4)
  • tensorrt_llm/serve/openai_protocol.py (3 hunks)
  • tests/integration/defs/test_e2e.py (1 hunks)
  • tests/integration/test_lists/test-db/l0_a10.yml (1 hunks)
  • tests/unittest/llmapi/apps/_test_openai_chat_json.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/integration/test_lists/test-db/l0_a10.yml
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/serve/openai_protocol.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{cpp,h,hpp,cc,cxx,cu,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,h,hpp,cc,cxx,cu,py}: Use only spaces for indentation. Do not use tabs. Indent 4 spaces at a time.
All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • tests/integration/defs/test_e2e.py
  • tests/unittest/llmapi/apps/_test_openai_chat_json.py
**/*.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.
Python filenames should use snake_case (e.g., some_file.py).
Python classes should use PascalCase (e.g., class SomeClass).
Python functions and methods should use snake_case (e.g., def my_awesome_function():).
Python local variables should use snake_case. Prefix k for variable names that start with a number (e.g., k_99th_percentile = ...).
Python global variables should use upper snake_case and 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 interfaces that may be used outside a file, prefer docstrings over comments in Python.
Comments in Python 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.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the docstring for the class.
Avoid using reflection in Python when functionality can be easily achieved without it.
When using try-except blocks in Python, limit the except to the smallest set of errors possible.
When using try-except blocks to handle multiple possible variable types in Python, keep the body of the try as small as possible, using the else block to implement the logic.

Files:

  • tests/integration/defs/test_e2e.py
  • tests/unittest/llmapi/apps/_test_openai_chat_json.py
🧬 Code Graph Analysis (1)
tests/unittest/llmapi/apps/_test_openai_chat_json.py (1)
tests/integration/defs/test_e2e.py (1)
  • temp_extra_llm_api_options_file (670-705)
🪛 Ruff (0.12.2)
tests/unittest/llmapi/apps/_test_openai_chat_json.py

88-88: Undefined name Any

(F821)


103-103: Undefined name json

(F821)


104-104: Undefined name json

(F821)


106-106: Undefined name output_text

(F821)


109-109: Undefined name jsonschema

(F821)


131-131: Undefined name first_message

(F821)

🔇 Additional comments (2)
tests/integration/defs/test_e2e.py (1)

1446-1452: LGTM! The integration test follows established patterns.

The new test function correctly follows the same pattern as other OpenAI test functions in this file and properly integrates the JSON schema test.

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

16-79: Well-structured test fixtures with proper setup and cleanup.

The fixtures are correctly implemented with:

  • Appropriate scoping (module scope for shared resources)
  • Proper cleanup in the temporary file fixture
  • Correct server configuration for JSON schema testing (xgrammar backend, disabled overlap scheduler)
  • Good separation of concerns between different fixture types

Comment on lines +3 to +9
import os
import tempfile

import openai
import pytest
import yaml

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix missing imports that cause undefined name errors.

The static analysis correctly identifies several missing imports that are used later in the code.

Add the missing imports:

 import os
 import tempfile
+import json
+from typing import Any

 import openai
 import pytest
 import yaml
+import jsonschema
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import os
import tempfile
import openai
import pytest
import yaml
import os
import tempfile
import json
from typing import Any
import openai
import pytest
import yaml
import jsonschema
🤖 Prompt for AI Agents
In tests/unittest/llmapi/apps/_test_openai_chat_json.py around lines 3 to 9,
there are missing imports causing undefined name errors. Review the code to
identify all used but not imported modules or functions, then add the necessary
import statements at the top of the file to resolve these errors.

Comment on lines +87 to +111
def _create_and_validate_response(
messages: list[dict[str, Any]]) -> dict[str, any]:
chat_completion = client.chat.completions.create(
model=model_name,
messages=messages,
max_tokens=1000,
temperature=0.0,
response_format={
"type": "json",
"schema": user_profile_schema
},
)
message = chat_completion.choices[0].message
assert message.content is not None

try:
message_json = json.loads(message.content)
except json.JSONDecodeError:
pytest.fail(
f"The output was not a valid JSON string. Output: {output_text}"
)

jsonschema.validate(instance=message_json, schema=user_profile_schema)
return message_json

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variables in the helper function.

The helper function has several undefined variable references that will cause runtime errors.

Apply these fixes:

 def _create_and_validate_response(
-        messages: list[dict[str, Any]]) -> dict[str, any]:
+        messages: list[dict[str, Any]]) -> dict[str, Any]:
     chat_completion = client.chat.completions.create(
         model=model_name,
         messages=messages,
         max_tokens=1000,
         temperature=0.0,
         response_format={
             "type": "json",
             "schema": user_profile_schema
         },
     )
     message = chat_completion.choices[0].message
     assert message.content is not None

     try:
         message_json = json.loads(message.content)
     except json.JSONDecodeError:
         pytest.fail(
-            f"The output was not a valid JSON string. Output: {output_text}"
+            f"The output was not a valid JSON string. Output: {message.content}"
         )

     jsonschema.validate(instance=message_json, schema=user_profile_schema)
     return message_json
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _create_and_validate_response(
messages: list[dict[str, Any]]) -> dict[str, any]:
chat_completion = client.chat.completions.create(
model=model_name,
messages=messages,
max_tokens=1000,
temperature=0.0,
response_format={
"type": "json",
"schema": user_profile_schema
},
)
message = chat_completion.choices[0].message
assert message.content is not None
try:
message_json = json.loads(message.content)
except json.JSONDecodeError:
pytest.fail(
f"The output was not a valid JSON string. Output: {output_text}"
)
jsonschema.validate(instance=message_json, schema=user_profile_schema)
return message_json
def _create_and_validate_response(
messages: list[dict[str, Any]]) -> dict[str, Any]:
chat_completion = client.chat.completions.create(
model=model_name,
messages=messages,
max_tokens=1000,
temperature=0.0,
response_format={
"type": "json",
"schema": user_profile_schema
},
)
message = chat_completion.choices[0].message
assert message.content is not None
try:
message_json = json.loads(message.content)
except json.JSONDecodeError:
pytest.fail(
f"The output was not a valid JSON string. Output: {message.content}"
)
jsonschema.validate(instance=message_json, schema=user_profile_schema)
return message_json
🧰 Tools
🪛 Ruff (0.12.2)

88-88: Undefined name Any

(F821)


103-103: Undefined name json

(F821)


104-104: Undefined name json

(F821)


106-106: Undefined name output_text

(F821)


109-109: Undefined name jsonschema

(F821)

🤖 Prompt for AI Agents
In tests/unittest/llmapi/apps/_test_openai_chat_json.py between lines 87 and
111, the helper function _create_and_validate_response references undefined
variables such as client, model_name, user_profile_schema, json, pytest,
jsonschema, and output_text. To fix this, ensure all these variables and modules
are properly imported or defined in the file. Replace output_text with
message.content in the pytest.fail call to correctly reference the invalid JSON
string. Verify that client and model_name are initialized before this function
is called, and import json, pytest, and jsonschema modules at the top of the
file.

@amukkara
Copy link
Collaborator

Moved to #6321

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.

5 participants