feat: Enhance structured output for OpenAI-compatible models #3194
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.
Closes #3174
🎯 Summary
This pull request addresses the feature request to improve structured output capabilities for a wider range of Large Language Models, particularly those with OpenAI-compatible APIs. It introduces two key enhancements:
response_format
Validation: The validation for structured output (response_format
) is now bypassed for any model designated asopenai
-compatible (e.g.,openai/qwen-plus
). This allows developers to leverage structured outputs with custom endpoints and third-party models without encounteringValueError
.converter.py
. This significantly reduces application crashes caused by minor LLM formatting errors (e.g., extra text, missing brackets) by intelligently extracting and repairing the JSON object from the raw output.✨ Key Changes
1.
src/crewai/llm.py
_validate_call_params
method has been updated to skip thesupports_response_schema
check when the model's provider isopenai
orNone
(which defaults to an OpenAI-compatible interface).response_format
to the target API endpoint, which is the correct behavior for compatible models.anthropic
,gemini
, etc., remains unchanged, ensuring no existing functionality is broken.2.
src/crewai/utilities/converter.py
handle_partial_json
, has been introduced to act as a "self-healing" mechanism for malformed JSON.convert_to_model
function now follows a more resilient parsing flow:✅ Benefits
output_pydantic
andoutput_json
with any OpenAI-compatible model.