Created
November 25, 2025 16:46
-
-
Save jpic/79a906a40f20c25f70c8b8401d56b8bc to your computer and use it in GitHub Desktop.
monkey patch pydantic to skip callbacks for langchain
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
| # your_project/pydantic_patch.py ← Put this file anywhere loaded at startup | |
| from pydantic import BaseModel | |
| from pydantic.json_schema import model_json_schema | |
| from typing import Any | |
| # Save the original method | |
| _original_model_json_schema = BaseModel.model_json_schema | |
| def _patched_model_json_schema( | |
| cls, | |
| by_alias: bool = True, | |
| ref_template: str = "/schemas/{model}.json", | |
| schema_generator: type = None, | |
| mode: str = "validation", | |
| ) -> dict[str, Any]: | |
| """ | |
| Patched model_json_schema that completely skips any field | |
| whose type is AsyncCallbackManagerForToolRun (or similar callback managers). | |
| This is safe because LangChain only uses these fields at runtime, never in prompts. | |
| """ | |
| # Temporarily override __fields__ to exclude callback fields | |
| original_fields = getattr(cls, "__fields__", {}) | |
| filtered_fields = { | |
| name: field | |
| for name, field in original_fields.items() | |
| if "CallbackManager" not in str(field.type_) | |
| and "run_manager" not in name.lower() | |
| } | |
| # Monkey-patch the model's fields just for this call | |
| old_fields = cls.__fields__ if hasattr(cls, "__fields__") else None | |
| cls.__fields__ = filtered_fields | |
| try: | |
| return _original_model_json_schema( | |
| cls, | |
| by_alias=by_alias, | |
| ref_template=ref_template, | |
| schema_generator=schema_generator or cls.model_config.get("json_schema_generator"), | |
| mode=mode, | |
| ) | |
| finally: | |
| # Always restore original fields | |
| if old_fields is not None: | |
| cls.__fields__ = old_fields | |
| # Apply the patch | |
| BaseModel.model_json_schema = classmethod(_patched_model_json_schema) | |
| print("Pydantic v2 patch applied: callback fields (run_manager, callbacks) are now silently excluded from JSON schema") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment