diff --git a/litellm/llms/anthropic/output_schema.py b/litellm/llms/anthropic/output_schema.py index 15bdceb376b..803e2e4a14d 100644 --- a/litellm/llms/anthropic/output_schema.py +++ b/litellm/llms/anthropic/output_schema.py @@ -191,7 +191,7 @@ def shape_claude_output_schema(schema: Mapping[str, object]) -> dict[str, object """Return a new schema that Claude's structured-output API accepts. Idempotent.""" drops_type: Final = _enum_conflicts_with_declared_type(schema) declared_type: Final = None if drops_type else schema.get("type") - object_fields: Final = _object_fields(declared_type, schema) + object_fields: Final = {} if drops_type else _object_fields(declared_type, schema) unsupported_format: Final = _unsupported_format(schema, declared_type) notes: Final = ( *_constraint_notes(schema), diff --git a/tests/e2e/llm_translation/structured_output.py b/tests/e2e/llm_translation/structured_output.py index 7860f8e4613..99cb222ada6 100644 --- a/tests/e2e/llm_translation/structured_output.py +++ b/tests/e2e/llm_translation/structured_output.py @@ -2,7 +2,7 @@ from __future__ import annotations from typing import Final -from pydantic import BaseModel, ConfigDict, TypeAdapter +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter SENTIMENT_PROMPT: Final = "Classify the sentiment of this review: 'The battery died after two days.'" SENTIMENT_LABELS: Final = frozenset({"positive", "negative", "neutral"}) @@ -35,8 +35,8 @@ class _ConstrainedSentiment(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") sentiment: str - confidence: float - reasons: tuple[str, ...] + confidence: float = Field(ge=0, le=1) + reasons: tuple[str, ...] = Field(max_length=3) def assert_sentiment_json(text: str) -> None: diff --git a/tests/unit/llms/anthropic/test_anthropic_output_schema.py b/tests/unit/llms/anthropic/test_anthropic_output_schema.py index 71e1aa2712c..273f3c4cfd8 100644 --- a/tests/unit/llms/anthropic/test_anthropic_output_schema.py +++ b/tests/unit/llms/anthropic/test_anthropic_output_schema.py @@ -93,3 +93,13 @@ def test_output_format_block_shapes_only_its_schema(): def test_output_format_block_without_schema_is_returned_unchanged(): assert shape_claude_output_format({"type": "json_schema"}) == {"type": "json_schema"} + + +def test_nullable_object_enum_keeps_its_type_dropped_instead_of_forcing_object() -> None: + """``enum: [null]`` on an ``["object", "null"]`` node conflicts with the declared type, so the type + is dropped. Re-adding ``type: object`` would make the node impossible to satisfy.""" + shaped = shape_claude_output_schema( + {"type": ["object", "null"], "properties": {"a": {"type": "string"}}, "enum": [None]} + ) + + assert shaped == {"properties": {"a": {"type": "string"}}, "enum": [None]}