Skip to content

Commit 660b1a4

Browse files
Python: fix(python): preserve Pydantic field descriptions in schemas (#14454)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone 😄
1 parent 9a70006 commit 660b1a4

2 files changed

Lines changed: 36 additions & 6 deletions

File tree

‎python/semantic_kernel/schema/kernel_json_schema_builder.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,19 @@ def build_model_schema(
8989
field_description = None
9090
if hasattr(model, "model_fields") and field_name in model.model_fields:
9191
field_info = model.model_fields[field_name]
92-
if isinstance(field_info.metadata, dict):
93-
field_description = field_info.metadata.get("description")
94-
elif isinstance(field_info.metadata, list) and field_info.metadata:
95-
field_description = field_info.metadata[0]
96-
elif hasattr(field_info, "description"):
97-
field_description = field_info.description
92+
field_description = getattr(field_info, "description", None)
93+
if field_description is None:
94+
metadata = getattr(field_info, "metadata", None)
95+
if isinstance(metadata, dict):
96+
field_description = metadata.get("description")
97+
elif isinstance(metadata, (list, tuple)):
98+
for item in metadata:
99+
if isinstance(item, str):
100+
field_description = item
101+
break
102+
if isinstance(item, dict) and isinstance(item.get("description"), str):
103+
field_description = item["description"]
104+
break
98105
if not cls._is_optional(field_type):
99106
required.append(field_name)
100107
properties[field_name] = cls.build(field_type, field_description, structured_output)

‎python/tests/unit/schema/test_schema_builder.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from unittest.mock import Mock
77

88
import pytest
9+
from pydantic import Field
910

1011
from semantic_kernel.connectors.utils.structured_output_schema import generate_structured_output_response_format_schema
1112
from semantic_kernel.kernel_pydantic import KernelBaseModel
@@ -76,6 +77,14 @@ class PydanticReasoning(KernelBaseModel):
7677
final_answer: str
7778

7879

80+
class PydanticModelWithConstrainedField(KernelBaseModel):
81+
top_p: float = Field(default=0.9, ge=0.0, le=1.0, description="nucleus sampling")
82+
83+
84+
class PydanticModelWithAnnotatedDescription(KernelBaseModel):
85+
name: Annotated[str, "display name"]
86+
87+
7988
class NonPydanticStep:
8089
explanation: str
8190
output: str
@@ -156,6 +165,20 @@ def test_build_model_schema():
156165
assert result == expected_schema
157166

158167

168+
def test_build_model_schema_uses_pydantic_description_with_constraints():
169+
schema = KernelJsonSchemaBuilder.build_model_schema(PydanticModelWithConstrainedField)
170+
171+
assert schema["properties"]["top_p"] == {"type": "number", "description": "nucleus sampling"}
172+
json.dumps(schema)
173+
174+
175+
def test_build_model_schema_uses_annotated_metadata_description():
176+
schema = KernelJsonSchemaBuilder.build_model_schema(PydanticModelWithAnnotatedDescription)
177+
178+
assert schema["properties"]["name"] == {"type": "string", "description": "display name"}
179+
json.dumps(schema)
180+
181+
159182
def test_build_from_type_name():
160183
expected_schema = {"type": "string", "description": "A simple string"}
161184
result = KernelJsonSchemaBuilder.build_from_type_name("str", description="A simple string")

0 commit comments

Comments
 (0)