Repository navigation
Conversation
… schemas ComponentTool passed string field annotations of dataclass inputs to Pydantic unchanged and left forward references nested in typing constructs unresolved. Pydantic then looked the names up in the namespace of haystack.tools.parameters_schema_utils, so a forward reference such as `items: list["Item"]`, or a dataclass defined in a module that uses `from __future__ import annotations` with a field typed as date, an Enum, Literal, Optional or another dataclass, made ComponentTool raise SchemaGenerationError. _dataclass_to_pydantic_model now resolves the field annotations with typing.get_type_hints(include_extras=True) and falls back to the annotations as written when they cannot be resolved. The dataclasses whose conversion is in progress are passed down. Wherever a field type refers back to one of them, including inside Annotated, tuple or Mapping, the reference becomes a forward reference to its model, so recursive dataclasses keep their current schema.
|
@tanishqbaweja is attempting to deploy a commit to the deepset Team on Vercel. A member of the Team first needs to authorize it. |
|
Hi @tanishqbaweja, thanks a lot for your contribution! 🙏 We noticed that the Contributor License Agreement (CLA) check ( To get your PR reviewed, please sign the CLA via the link in the |
|
Thanks for signing the CLA, @tanishqbaweja! 🎉 This PR is now ready for review again and the reviewer has been re-assigned. |
|
yeah I can take over the review |
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Fold the forward-referenced `items: list["OrderItem"]` field into Task and drop Order and OrderCounter. Task keeps `date` as its only date, Enum or Literal field, so Priority goes too. Remove the TreeNode test, which the Category test already covers, and drop the `related` field of Category, since its Annotated field already covers the back-reference rewrite. The Category test is renamed to test_from_component_with_recursive_dataclass_in_annotated accordingly. Shorten the _replace_back_references docstring to what the function does and drop the implementation detail from the release note.
|
Thanks for the review, @sjrl. All four points are addressed in 56b8c66:
|
Related Issues
ComponentTool(component=AnswerJoiner())failed becauseExtractedAnswerannotates its offsets asOptional["Span"]. The issue was closed because there is no clear Agent use case forAnswerJoiner, with the note that the schema-generation problem was still useful to have identified. The same bug hits user-defined dataclasses, which is what this PR fixes. As a side effect,AnswerJoiner's schema now builds.get_type_hints, break cycles with aForwardRef) but was closed automatically before any review because its CLA wasn't signed. This PR is an independent implementation. It also falls back to the annotations as written when they can't be resolved, and it replaces references back to a dataclass inside other typing constructs too, such asAnnotatedandtuple, so recursive dataclasses keep their current schema.Proposed Changes:
ComponentTooldocuments dataclass inputs ("Dataclasses (both simple and nested structures)"), but creating the tool fails when a dataclass has string field annotations. Two common patterns hit this:items: list["Item"].from __future__ import annotations, with a field typed asdate, anEnum,Optional[...],Literal[...]or another dataclass.Such a component can't be wrapped as a tool, and so can't be given to an
Agent, unless its parameters schema is written by hand.Cause:
_dataclass_to_pydantic_modelpassed string field annotations topydantic.create_modelunchanged. It only walked non-string annotations through_resolve_type, so forward references nested in typing constructs (such asOptional["Span"]) stayed unresolved too. Pydantic then looked those names up in the namespace ofhaystack.tools.parameters_schema_utils, wherecreate_modelis called. Builtins and the names this module happens to import (such asAnnotated,Any,Union,Sequence,ChatMessage) resolved by accident, and Pydantic resolved a dataclass's reference to itself to the model being built; anything else, including the user's other classes, failed.Fix (in
haystack/tools/parameters_schema_utils.py):typing.get_type_hints(cls, include_extras=True), that is, in the module and class namespace that define the dataclass.include_extras=TruekeepsAnnotatedmetadata such asField(min_length=1). If the annotations can't be resolved (for example, a name imported only underTYPE_CHECKING), the annotations are used as written, which is the current behavior. This mirrors_resolve_parameter_typesinhaystack/core/type_utils.py.children: list["Node"]to the real class would make_resolve_typerecurse forever, and a real class left insideAnnotatedortuplewould make Pydantic add a second definition of the dataclass. So_dataclass_to_pydantic_modelnow passes down an immutable set of the dataclasses whose conversion is in progress (there is no module-level state). Before a field type is resolved, the new private helper_replace_back_referencesturns every reference to one of them intoForwardRef("<name>"), which Pydantic resolves to the model being built. It does this at any depth, inlist,Optionalanddictas well as inAnnotated,tupleorMapping, which_resolve_typepasses to Pydantic unchanged. Type hints without such references are returned as they are. Recursive dataclasses that work on main therefore produce the same schema as before.ChatMessagehandling in_resolve_typeis unchanged, and the existing schema tests for Haystack's dataclasses (Document,ChatMessage,ToolCall, and others) pass unmodified. AChatMessagefield with a string annotation now goes through it as well; see the notes for the reviewer.There are no public API changes.
How did you test it?
test/tools/test_component_tool.py, next to the existing dataclass tests. They use module-level dataclasses with string annotations, which is whatfrom __future__ import annotationsturns every annotation into. This is the same approach as the test in fix: resolve postponed annotations when creating a tool from a function #12739.test_from_component_with_postponed_dataclass_annotationshas fields annotated"Annotated[str, Field(min_length=1)]","date", anEnum,"Literal['open', 'done']"and"list[Address]". It asserts the full schema (minLength,format: date, the enum under$defs, the$refs). It also checks thatinvoke()turns the nested dicts into adate, an enum member andAddressinstances.test_from_component_with_forward_referenced_dataclassusesitems: list["OrderItem"], withOrderItemdefined afterOrder, and asserts the schema andinvoke().test_from_component_with_recursive_dataclassuseschildren: list["TreeNode"].test_from_component_with_recursive_dataclass_in_annotated_and_tupleuses aCategorydataclass withsubcategories: "Annotated[list[Category], Field(max_length=20)]",related: tuple["Category", ...] = ()andparent: "Category | None" = None. It asserts the full schema, with a singleCategoryentry under$defsthat keeps Haystack's field descriptions,maxItemsand the default, and checksinvoke().SchemaGenerationError(you should define dateandyou should define OrderItem) and pass with the fix. The two recursive tests pass on main too and guard the recursion handling. If the references insideAnnotatedandtuplearen't replaced, the last test gets two module-qualified definitions ofCategory, one of them generated by Pydantic without Haystack's field descriptions.pytest -m "not integration"ontest/tools,test/components/agents,test/core, and the OpenAI and Azure chat generator tests (test_openai*.py,test_azure*.py), which buildComponentToolschemas. Compared test by test with main, the only difference is the four new passing tests. Two limits of my environment:test/coremodules that import pandas or pytest-bdd were not collected.test_serialization_security.py::TestModuleAttributeWalkBypass::test_callable_walk_through_reexported_unallowlisted_class_rejectedfails on both main and this branch becauserichis not installed.haystack.dataclasses(as a parameter, aslist[...]and as... | None), every built-in component that can be created with default arguments, and 15 more common components created with simple arguments: the schemas are identical, except thatAnswerJoinerandExtractedAnswernow build. I fixedPYTHONHASHSEEDfor this, becausePromptBuilderorders its inputs by set iteration.list,Optional,dict,Sequence,Annotated,tupleandMapping, mutual references and three-cycles, both with quoted annotations and in afrom __future__ import annotationsmodule. The 31 shapes that build on main give byte-identical schemas with the fix. 23 shapes fail on main and build with the fix, and 2 fail on both (the shape in the first note below, and aCallablefield).test/toolspasses, and both schema comparisons give the same results, on Python 3.11 with pydantic 2.14.2 and with pydantic 2.12.0, the minimum version inpyproject.toml.from __future__ import annotationsmodule withdate,Enum,Literal,Optionaland nested-dataclass fields. Creating theComponentToolfails on main and works with the fix, andinvoke()returns the converted values. With the fix,ComponentTool(component=AnswerJoiner())from ComponentTool(AnswerJoiner()) raises SchemaGenerationError (unresolved ExtractedAnswer.Span) #12950 also builds its schema, withSpanunder$defs.pre-commit run --filespasses on the changed files, and mypy reports no issues for them.I tested on Windows with Python 3.12, plus Python 3.11 for
test/toolsand the schema comparisons.Notes for the reviewer
SchemaGenerationError. Pydantic only sees the model being built and the outermost one. To keep the change small, I didn't add a model registry for this case, but I can add one if you think it's worth it._resolve_typestill leaves a dataclass insideAnnotated,tupleorMappingto Pydantic. So if A reaches B only through such a construct and B refers back to A, the schema builds, but B and a second definition of A come from Pydantic, without Haystack's field descriptions._dataclass_to_pydantic_model, so whichever of the two PRs lands second needs a small rebase.Annotatedbranch to_resolve_typethat calls_resolve_type(args[0]). The two PRs only conflict in the test imports:parameters_schema_utils.pymerges cleanly, so nothing flags that call. Whichever of fix: handle annotated ChatMessage lists in ComponentTool #13311 and this PR lands second needs to passconverting=convertingthere. Without it, dataclasses that refer to each other only throughAnnotatedfields recurse untilRecursionError. A dataclass that refers to itself insideAnnotatedis not affected, because its references are replaced before_resolve_typedescends.ChatMessagefield with a string annotation (for example in afrom __future__ import annotationsmodule) used to resolve by accident to Pydantic's ownChatMessageschema, with_role,_content,_nameand_meta. It now gets the same schema as aChatMessagefield without a string annotation:role,content,nameandmeta.invoke()converts a dataclass input that has nofrom_dictwith Pydantic'sTypeAdapter, which expects the underscored names for a nestedChatMessage, so arguments that follow this schema fail, as they already do on main when the annotation isn't a string. I kept that conversion out of this PR, but I can fix it here or in a follow-up.Checklist
fix:,feat:,build:,chore:,ci:,docs:,style:,refactor:,perf:,test:and added!in case the PR includes breaking changes.This PR was fully generated with an AI assistant.