Skip to content

fix: resolve string field annotations of dataclasses in ComponentTool schemas - #13516

Merged
sjrl merged 4 commits into
deepset-ai:mainfrom
tanishqbaweja:fix/component-tool-dataclass-annotations
Nov 13, 2026
Merged

sjrl merged 4 commits into
deepset-ai:mainfrom
tanishqbaweja:fix/component-tool-dataclass-annotations

Conversation

@tanishqbaweja

Copy link
Copy Markdown
Contributor

Related Issues

  • Related to ComponentTool(AnswerJoiner()) raises SchemaGenerationError (unresolved ExtractedAnswer.Span) #12950 (closed as not planned). There, ComponentTool(component=AnswerJoiner()) failed because ExtractedAnswer annotates its offsets as Optional["Span"]. The issue was closed because there is no clear Agent use case for AnswerJoiner, 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.
  • fix: resolve postponed dataclass fields in ComponentTool #13095 took the same approach (resolve the annotations with get_type_hints, break cycles with a ForwardRef) 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 as Annotated and tuple, so recursive dataclasses keep their current schema.
  • This is the dataclass counterpart of fix: resolve postponed annotations when creating a tool from a function #12739, which resolved postponed annotations for function tools.

Proposed Changes:

ComponentTool documents 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:

  1. A quoted forward reference to a dataclass defined later in the module, such as items: list["Item"].
  2. A dataclass in a module that uses from __future__ import annotations, with a field typed as date, an Enum, Optional[...], Literal[...] or another dataclass.
from dataclasses import dataclass

from haystack import component
from haystack.tools import ComponentTool

@dataclass
class Order:
    items: list["Item"]

@dataclass
class Item:
    sku: str

@component
class OrderCounter:
    @component.output_types(count=int)
    def run(self, order: Order) -> dict:
        """
        Count the items of an order.

        :param order: The order.
        """
        return {"count": len(order.items)}

ComponentTool(component=OrderCounter())
# >> SchemaGenerationError: Failed to create JSON schema for the run method of Component 'OrderCounter'
# >> caused by PydanticUserError: `run` is not fully defined; you should define `Item`, then call `run.model_rebuild()`.

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_model passed string field annotations to pydantic.create_model unchanged. It only walked non-string annotations through _resolve_type, so forward references nested in typing constructs (such as Optional["Span"]) stayed unresolved too. Pydantic then looked those names up in the namespace of haystack.tools.parameters_schema_utils, where create_model is called. Builtins and the names this module happens to import (such as Annotated, 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):

  • The field annotations are resolved with typing.get_type_hints(cls, include_extras=True), that is, in the module and class namespace that define the dataclass. include_extras=True keeps Annotated metadata such as Field(min_length=1). If the annotations can't be resolved (for example, a name imported only under TYPE_CHECKING), the annotations are used as written, which is the current behavior. This mirrors _resolve_parameter_types in haystack/core/type_utils.py.
  • Resolved annotations need care for recursive dataclasses: resolving children: list["Node"] to the real class would make _resolve_type recurse forever, and a real class left inside Annotated or tuple would make Pydantic add a second definition of the dataclass. So _dataclass_to_pydantic_model now 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_references turns every reference to one of them into ForwardRef("<name>"), which Pydantic resolves to the model being built. It does this at any depth, in list, Optional and dict as well as in Annotated, tuple or Mapping, which _resolve_type passes 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.
  • The ChatMessage handling in _resolve_type is unchanged, and the existing schema tests for Haystack's dataclasses (Document, ChatMessage, ToolCall, and others) pass unmodified. A ChatMessage field 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?

  • I added tests to test/tools/test_component_tool.py, next to the existing dataclass tests. They use module-level dataclasses with string annotations, which is what from __future__ import annotations turns 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_annotations has fields annotated "Annotated[str, Field(min_length=1)]", "date", an Enum, "Literal['open', 'done']" and "list[Address]". It asserts the full schema (minLength, format: date, the enum under $defs, the $refs). It also checks that invoke() turns the nested dicts into a date, an enum member and Address instances.
    • test_from_component_with_forward_referenced_dataclass uses items: list["OrderItem"], with OrderItem defined after Order, and asserts the schema and invoke().
    • test_from_component_with_recursive_dataclass uses children: list["TreeNode"].
    • test_from_component_with_recursive_dataclass_in_annotated_and_tuple uses a Category dataclass with subcategories: "Annotated[list[Category], Field(max_length=20)]", related: tuple["Category", ...] = () and parent: "Category | None" = None. It asserts the full schema, with a single Category entry under $defs that keeps Haystack's field descriptions, maxItems and the default, and checks invoke().
  • The first two tests fail on main with SchemaGenerationError (you should define date and you should define OrderItem) and pass with the fix. The two recursive tests pass on main too and guard the recursion handling. If the references inside Annotated and tuple aren't replaced, the last test gets two module-qualified definitions of Category, one of them generated by Pydantic without Haystack's field descriptions.
  • I ran pytest -m "not integration" on test/tools, test/components/agents, test/core, and the OpenAI and Azure chat generator tests (test_openai*.py, test_azure*.py), which build ComponentTool schemas. Compared test by test with main, the only difference is the four new passing tests. Two limits of my environment:
    • Four test/core modules that import pandas or pytest-bdd were not collected.
    • test_serialization_security.py::TestModuleAttributeWalkBypass::test_callable_walk_through_reexported_unallowlisted_class_rejected fails on both main and this branch because rich is not installed.
  • I compared the generated tool schemas with main's, as JSON:
    • Every dataclass in haystack.dataclasses (as a parameter, as list[...] 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 that AnswerJoiner and ExtractedAnswer now build. I fixed PYTHONHASHSEED for this, because PromptBuilder orders its inputs by set iteration.
    • 56 dataclass shapes, most of them recursive: references back to the dataclass inside list, Optional, dict, Sequence, Annotated, tuple and Mapping, mutual references and three-cycles, both with quoted annotations and in a from __future__ import annotations module. 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 a Callable field).
  • test/tools passes, 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 in pyproject.toml.
  • I also ran a script that uses a real from __future__ import annotations module with date, Enum, Literal, Optional and nested-dataclass fields. Creating the ComponentTool fails on main and works with the fix, and invoke() returns the converted values. With the fix, ComponentTool(component=AnswerJoiner()) from ComponentTool(AnswerJoiner()) raises SchemaGenerationError (unresolved ExtractedAnswer.Span) #12950 also builds its schema, with Span under $defs.
  • pre-commit run --files passes 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/tools and the schema comparisons.

Notes for the reviewer

  • Mutually recursive dataclasses (A <-> B, or A -> B -> C -> A) now work too, because Pydantic also resolves the outermost model under construction by name. Two limits remain. On main, these shapes either fail or already produce the same schema.
    • A dataclass that refers back to two different ancestors at once (X -> Y -> Z, where Z points to both Y and X) still raises 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_type still leaves a dataclass inside Annotated, tuple or Mapping to 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.
  • fix: keep underscore-prefixed parameters in tool schemas #13473 edits the same loop in _dataclass_to_pydantic_model, so whichever of the two PRs lands second needs a small rebase.
  • fix: handle annotated ChatMessage lists in ComponentTool #13311 adds an Annotated branch to _resolve_type that calls _resolve_type(args[0]). The two PRs only conflict in the test imports: parameters_schema_utils.py merges cleanly, so nothing flags that call. Whichever of fix: handle annotated ChatMessage lists in ComponentTool #13311 and this PR lands second needs to pass converting=converting there. Without it, dataclasses that refer to each other only through Annotated fields recurse until RecursionError. A dataclass that refers to itself inside Annotated is not affected, because its references are replaced before _resolve_type descends.
  • One schema changes for dataclasses that already worked on main. A ChatMessage field with a string annotation (for example in a from __future__ import annotations module) used to resolve by accident to Pydantic's own ChatMessage schema, with _role, _content, _name and _meta. It now gets the same schema as a ChatMessage field without a string annotation: role, content, name and meta. invoke() converts a dataclass input that has no from_dict with Pydantic's TypeAdapter, which expects the underscored names for a nested ChatMessage, 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

  • I have read the contributors guidelines and the code of conduct.
  • I have updated the related issue with new insights and changes.
  • I have added unit tests and updated the docstrings.
  • I've used one of the conventional commit types for my PR title: fix:, feat:, build:, chore:, ci:, docs:, style:, refactor:, perf:, test: and added ! in case the PR includes breaking changes.
  • I have documented my code.
  • I have added a release note file, following the contributors guidelines.
  • I have run pre-commit hooks and fixed any issue.

This PR was fully generated with an AI assistant.

… 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
tanishqbaweja requested a review from a team as a code owner November 1, 2026 04:55
@tanishqbaweja
tanishqbaweja requested review from davidsbatista and removed request for a team November 1, 2026 04:55
@vercel

vercel Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

@tanishqbaweja is attempting to deploy a commit to the deepset Team on Vercel.

A member of the Team first needs to authorize it.

@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@HaystackBot

Copy link
Copy Markdown
Contributor

Hi @tanishqbaweja, thanks a lot for your contribution! 🙏

We noticed that the Contributor License Agreement (CLA) check (license/cla) hasn't passed yet, so we've temporarily moved this PR to draft and paused the review assignment.

To get your PR reviewed, please sign the CLA via the link in the license/cla check below (or in the CLA bot comment). As soon as the check turns green, this PR will automatically be marked ready for review again and a reviewer will be re-assigned.

@HaystackBot
HaystackBot removed the request for review from davidsbatista November 5, 2026 08:51
@HaystackBot HaystackBot added the cla-pending PR is in draft until the contributor signs the CLA label Nov 5, 2026
@HaystackBot
HaystackBot marked this pull request as draft November 5, 2026 08:51
@HaystackBot
HaystackBot marked this pull request as ready for review November 5, 2026 09:19
@HaystackBot HaystackBot removed the cla-pending PR is in draft until the contributor signs the CLA label Nov 5, 2026
@HaystackBot

Copy link
Copy Markdown
Contributor

Thanks for signing the CLA, @tanishqbaweja! 🎉 This PR is now ready for review again and the reviewer has been re-assigned.

@davidsbatista

Copy link
Copy Markdown
Contributor

@sjrl can you take a look? It's the schema bug from #12950, but it turns out it hits any user dataclass with string annotations (from future import annotations, forward refs), not just AnswerJoiner.

The fix uses the get_type_hints approach from #12185

@sjrl

sjrl commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

yeah I can take over the review

@sjrl
sjrl requested review from sjrl and removed request for davidsbatista November 11, 2026 15:13
@sjrl sjrl self-assigned this Nov 11, 2026
@github-actions github-actions Bot added the type:documentation Improvements on the docs label Nov 11, 2026
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  haystack/core/pipeline
  pipeline.py
  haystack/document_stores/in_memory
  document_store.py
  haystack/tools
  parameters_schema_utils.py 214-217
  haystack/utils
  jinja2_extensions.py
Project Total  

This report was generated by python-coverage-comment-action

Comment thread test/tools/test_component_tool.py Resolved
Comment thread test/tools/test_component_tool.py Resolved
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.
@tanishqbaweja

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @sjrl. All four points are addressed in 56b8c66:

  • Shortened the _replace_back_references docstring to what the function does. Your suggestion as written fails ruff's D205 check ("1 blank line required between summary line and description") because the summary wraps onto a second line, so the summary is now your sentence up to "their models." and "References are replaced at any depth of the type hint." follows as its own paragraph.
  • Removed test_from_component_with_recursive_dataclass together with TreeNode and TreeCounter.
  • Applied your release note suggestion, so it now ends with "Optional or a nested dataclass. Recursive dataclasses keep working."
  • Cut down the fixtures: items: list["OrderItem"] is now a field of Task, and Order and OrderCounter are gone. Task keeps date and drops the Enum and Literal fields, so Priority is gone too. Category no longer has related, so I renamed test_from_component_with_recursive_dataclass_in_annotated_and_tuple to test_from_component_with_recursive_dataclass_in_annotated.

pytest --cov=haystack -m "not integration" test/tools on Python 3.11: 329 passed, 2 skipped, 12 deselected. With parameters_schema_utils.py reverted to main, test_from_component_with_postponed_dataclass_annotations fails (1 failed, 328 passed), and the Category test still fails when the back-reference rewrite is skipped inside Annotated.

@sjrl sjrl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@sjrl
sjrl merged commit 7db911e into deepset-ai:main Nov 13, 2026
22 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic:tests type:documentation Improvements on the docs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants