-
Notifications
You must be signed in to change notification settings - Fork 2.4k
fix: Add Pydantic v2 compatibility for OpenAPI/Swagger UI endpoints #3521
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
base: main
Are you sure you want to change the base?
Conversation
…vgScore Metric Co-authored-by: Ankur Sharma <[email protected]> PiperOrigin-RevId: 831413968
This module resolves Swagger UI 500 errors when using Pydantic v2 by: - Patching MCP ClientSession with proper __get_pydantic_core_schema__ method - Removing deprecated __modify_schema__ methods causing conflicts - Adding compatibility for types.GenericAlias (list[str], dict[str, int]) - Patching httpx.Client and httpx.AsyncClient for schema generation - Providing robust OpenAPI generation with recursion protection - Comprehensive fallback schemas for error recovery The robust_openapi_function handles RecursionError, AttributeError, and other Pydantic v2 schema generation issues while maintaining full OpenAPI specification compliance. Fixes Swagger UI functionality for Google ADK with Pydantic v2.
- Import patch_types_for_pydantic_v2 and create_robust_openapi_function - Apply compatibility patches before FastAPI app creation - Replace default OpenAPI generation with robust error-handling version - Add logging for patch application status and OpenAPI integration - Ensures Swagger UI works correctly with Pydantic v2 by handling: * MCP ClientSession schema generation issues * types.GenericAlias compatibility problems * httpx.Client schema generation errors * Recursion errors in complex model schemas This integration enables Swagger UI functionality while maintaining backward compatibility and providing comprehensive error handling.
- Add test_pydantic_v2_compatibility.py with full test coverage - Test successful schema generation and fallback scenarios - Test patch application success and failure cases - Test robust OpenAPI function with various error conditions: * RecursionError handling with recursion limit management * Generic exception handling with fallback schema * AttributeError handling for missing openapi method * Successful schema preservation - Test logging behavior for different error types - Test httpx Client patching functionality - Follow ADK testing patterns with proper Google license header - Use pytest parametrization and mocking best practices - Clean logging without emoji characters for professional output Ensures reliability and maintainability of Pydantic v2 compatibility fixes with comprehensive error handling validation.
Summary of ChangesHello @mmphego, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request addresses critical Pydantic v2 compatibility issues that were causing internal server errors and preventing the proper display of OpenAPI/Swagger UI documentation in the ADK API server. It introduces a new utility module that patches problematic types and provides a resilient OpenAPI schema generation mechanism. Additionally, it enhances the Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
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.
Code Review
This pull request introduces a compatibility layer for Pydantic v2 to resolve issues with OpenAPI/Swagger UI generation. The core of the fix is in the new pydantic_v2_compatibility.py module, which patches incompatible types and provides a robust fallback mechanism for OpenAPI schema generation. This is a solid approach to ensure the service remains functional even when schema generation fails.
My review has identified several critical issues in the new test suite (test_pydantic_v2_compatibility.py) that need to be addressed. The tests are currently broken due to incorrect imports, flawed mocking, and assertions that don't match the implementation. I've also found a bug in the patching logic for types.GenericAlias. Please see my detailed comments.
Additionally, this PR includes a significant feature addition for ToolTrajectoryCriterion which seems out of scope for a bug fix. While the feature itself is well-implemented, it's generally better to separate new features from bug fixes into different pull requests to simplify review and maintain a clean commit history.
- Fix critical bug in GenericAlias handler calling (handler is callable, not object with generate_schema method) - Completely rewrite test_pydantic_v2_compatibility.py to address all PR feedback: - Remove invalid imports of nested functions (__get_pydantic_core_schema__) - Fix assertion mismatches (OpenAPI version 3.1.0, correct API title) - Restructure tests to validate patching mechanism itself - Fix handler mocking to treat handlers as callables - Add comprehensive behavior tests with proper classmethod calling - All 17 tests now pass with full coverage of patching scenarios - Address types.GenericAlias immutability issues in tests - Improve error handling and fallback validation
8730501 to
890129f
Compare
|
Thanks a lot for the fix. Just tested on my machine - works again! |
Hopefully, we will not need a patch in the next release 😄 |
|
Can this be merged sooner? |
|
Hi @mmphego , Thank you for your contribution! |
…ython 3.9-3.13 - Reformat with pyink and sorted imports with isort
Hi @ryanaiagent, addressed py3.9 compartibility, isort and formatting issues. |
Please ensure you have read the contribution guide before creating a pull request.
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
2. Or, if no issue exists, describe the change:
Problem:
The Swagger UI documentation endpoint (
/docs) returns 500 Internal Server Error when using Pydantic v2 due to multiple compatibility issues:PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'httpx.Client'>)__modify_schema__methods cause conflicts with Pydantic v2types.GenericAlias(e.g.,list[str],dict[str, int]) not handled properlySolution:
This PR implements a comprehensive Pydantic v2 compatibility layer that:
__get_pydantic_core_schema__methods__modify_schema__) that conflict with v2The solution is non-invasive and applies patches during application startup before FastAPI initialization.
Testing Plan
Unit Tests:
Unit Test Results:
Manual End-to-End (E2E) Tests:
Test Environment:
Test Steps:
uv run adk api_server --port 8000http://localhost:8000/docshttp://localhost:8000/openapi.jsonBefore Fix:
After Fix:
Swagger UI now loads successfully with full API documentation, interactive endpoint testing, and proper schema generation.
Checklist
Additional context
Implementation Details:
Files Changed:
src/google/adk/utils/pydantic_v2_compatibility.py- New compatibility module (390 lines)src/google/adk/cli/adk_web_server.py- Integration of patches into web server startuptests/unittests/utils/test_pydantic_v2_compatibility.py- Comprehensive unit tests (229 lines)Key Features:
Compatibility:
list[str],dict[str, int]generic syntaxThis fix enables reliable Swagger UI functionality for all Google ADK users, resolving the widespread documentation access issues reported across multiple GitHub issues.