-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
[BUG] Responses : add structured output for sdk #14206
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
Merged
krrishdholakia
merged 8 commits into
BerriAI:main
from
kankute-sameer:litellm_responses_structured_output
Sep 6, 2025
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8e363fe
feat: add structured output for sdk
kankute-sameer 8d67392
Merge branch 'main' into litellm_responses_structured_output
kankute-sameer 94c1b21
Merge branch 'main' into litellm_responses_structured_output
krrishdholakia f7f106f
Move test to test_litellm/ folder
kankute-sameer ad9f54a
Move test to test_litellm/ folder
kankute-sameer 4fefac1
Move test to test_litellm/ folder
kankute-sameer 231d547
Move test to test_litellm/ folder
kankute-sameer 1980960
Merge branch 'main' into litellm_responses_structured_output
krrishdholakia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
161 changes: 161 additions & 0 deletions
161
tests/test_litellm/responses/test_text_format_conversion.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
import json | ||
import os | ||
import sys | ||
|
||
import pytest | ||
from pydantic import BaseModel | ||
|
||
sys.path.insert( | ||
0, os.path.abspath("../../..") | ||
) # Adds the parent directory to the system path | ||
|
||
import litellm | ||
from litellm.types.llms.openai import ( | ||
IncompleteDetails, | ||
ResponseAPIUsage, | ||
ResponsesAPIResponse, | ||
) | ||
|
||
|
||
class TestTextFormatConversion: | ||
"""Test text_format to text parameter conversion for responses API""" | ||
|
||
def get_base_completion_call_args(self): | ||
"""Get base arguments for completion call""" | ||
return { | ||
"model": "gpt-4o", | ||
"api_key": "test-key", | ||
"api_base": "https://api.openai.com/v1", | ||
} | ||
|
||
@pytest.mark.asyncio | ||
async def test_text_format_to_text_conversion(self): | ||
""" | ||
Test that when text_format parameter is passed to litellm.aresponses, | ||
it gets converted to text parameter in the raw API call to OpenAI. | ||
""" | ||
from unittest.mock import AsyncMock, patch | ||
|
||
class TestResponse(BaseModel): | ||
"""Test Pydantic model for structured output""" | ||
|
||
answer: str | ||
confidence: float | ||
|
||
class MockResponse: | ||
"""Mock response class for testing""" | ||
|
||
def __init__(self, json_data, status_code): | ||
self._json_data = json_data | ||
self.status_code = status_code | ||
self.text = json.dumps(json_data) | ||
|
||
def json(self): | ||
return self._json_data | ||
|
||
# Mock response from OpenAI | ||
mock_response = { | ||
"id": "resp_123", | ||
"object": "response", | ||
"created_at": 1741476542, | ||
"status": "completed", | ||
"model": "gpt-4o", | ||
"output": [ | ||
{ | ||
"type": "message", | ||
"id": "msg_123", | ||
"status": "completed", | ||
"role": "assistant", | ||
"content": [ | ||
{ | ||
"type": "output_text", | ||
"text": '{"answer": "Paris", "confidence": 0.95}', | ||
"annotations": [], | ||
} | ||
], | ||
} | ||
], | ||
"parallel_tool_calls": True, | ||
"usage": { | ||
"input_tokens": 10, | ||
"output_tokens": 20, | ||
"total_tokens": 30, | ||
"output_tokens_details": {"reasoning_tokens": 0}, | ||
}, | ||
"text": {"format": {"type": "json_object"}}, | ||
"error": None, | ||
"incomplete_details": None, | ||
"instructions": None, | ||
"metadata": {}, | ||
"temperature": 1.0, | ||
"tool_choice": "auto", | ||
"tools": [], | ||
"top_p": 1.0, | ||
"max_output_tokens": None, | ||
"previous_response_id": None, | ||
"reasoning": {"effort": None, "summary": None}, | ||
"truncation": "disabled", | ||
"user": None, | ||
} | ||
|
||
base_completion_call_args = self.get_base_completion_call_args() | ||
|
||
with patch( | ||
"litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post", | ||
new_callable=AsyncMock, | ||
) as mock_post: | ||
# Configure the mock to return our response | ||
mock_post.return_value = MockResponse(mock_response, 200) | ||
|
||
litellm._turn_on_debug() | ||
litellm.set_verbose = True | ||
|
||
# Call aresponses with text_format parameter | ||
response = await litellm.aresponses( | ||
input="What is the capital of France?", | ||
text_format=TestResponse, | ||
**base_completion_call_args, | ||
) | ||
|
||
# Verify the request was made correctly | ||
mock_post.assert_called_once() | ||
request_body = mock_post.call_args.kwargs["json"] | ||
print("Request body:", json.dumps(request_body, indent=4)) | ||
|
||
# Validate that text_format was converted to text parameter | ||
assert ( | ||
"text" in request_body | ||
), "text parameter should be present in request body" | ||
assert ( | ||
"text_format" not in request_body | ||
), "text_format should not be in request body" | ||
|
||
# Validate the text parameter structure | ||
text_param = request_body["text"] | ||
assert "format" in text_param, "text parameter should have format field" | ||
assert ( | ||
text_param["format"]["type"] == "json_schema" | ||
), "format type should be json_schema" | ||
assert "name" in text_param["format"], "format should have name field" | ||
assert ( | ||
text_param["format"]["name"] == "TestResponse" | ||
), "format name should match Pydantic model name" | ||
assert "schema" in text_param["format"], "format should have schema field" | ||
assert "strict" in text_param["format"], "format should have strict field" | ||
|
||
# Validate the schema structure | ||
schema = text_param["format"]["schema"] | ||
assert schema["type"] == "object", "schema type should be object" | ||
assert "properties" in schema, "schema should have properties" | ||
assert ( | ||
"answer" in schema["properties"] | ||
), "schema should have answer property" | ||
assert ( | ||
"confidence" in schema["properties"] | ||
), "schema should have confidence property" | ||
|
||
# Validate other request parameters | ||
assert request_body["input"] == "What is the capital of France?" | ||
|
||
# Validate the response | ||
print("Response:", json.dumps(response, indent=4, default=str)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Bug: Code Assumes Fixed Dictionary Structure
In
convert_text_format_to_text_param
, the code directly accesses nested keys withinresponse_format
(e.g.,response_format["json_schema"]["name"]
,response_format["type"]
). This assumes a specific structure for the dictionary returned bytype_to_response_format_param
. If the actual structure doesn't match, it will raise aKeyError
.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.
the type_to_response_format_param returns {
"type": "json_schema",
"json_schema": {
"schema": schema,
"name": response_format.name,
"strict": True,
},
}
so keys will be always be there