langchain - ✅(Solved) Fix AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile [4 pull requests, 3 comments, 4 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
langchain-ai/langchain#36312Fetched 2026-04-08 01:40:58
View on GitHub
Comments
3
Participants
4
Timeline
14
Reactions
0
Author
Timeline (top)
cross-referenced ×4labeled ×4commented ×3referenced ×2

While building for nixpkgs, test_summarization_middleware_missing_profile fails with a Pydantic error.

Error Message

________________ test_summarization_middleware_missing_profile _________________ [gw1] darwin -- Python 3.14.3 /nix/store/dfkim8vahgdqhk1lrxz1j4mcighlrk99-python3-3.14.3/bin/python3.14

def test_summarization_middleware_missing_profile() -> None:
    """Ensure automatic profile inference falls back when profiles are unavailable."""

    class ImportErrorProfileModel(BaseChatModel):
        @override
        def _generate(
            self,
            messages: list[BaseMessage],
            stop: list[str] | None = None,
            run_manager: CallbackManagerForLLMRun | None = None,
            **kwargs: Any,
        ) -> ChatResult:
            raise NotImplementedError

        @property
        def _llm_type(self) -> str:
            return "mock"

        # NOTE: Using __getattribute__ because @property cannot override Pydantic fields.
        def __getattribute__(self, name: str) -> Any:
            if name == "profile":
                msg = "Profile not available"
                raise AttributeError(msg)
            return super().__getattribute__(name)

    with pytest.raises(
        ValueError,
        match="Model profile information is required to use fractional token limits",
    ):
        _ = SummarizationMiddleware(
          model=ImportErrorProfileModel(), trigger=("fraction", 0.5), keep=("messages", 1)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^
        )

tests/unit_tests/agents/middleware/implementations/test_summarization.py:420:


/nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/load/serializable.py:118: in init super().init(*args, **kwargs) /nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/language_models/chat_models.py:393: in _set_model_profile if self.profile is None: ^^^^^^^^^^^^


self = ImportErrorProfileModel(), item = 'profile'

def __getattr__(self, item: str) -> Any:
    private_attributes = object.__getattribute__(self, '__private_attributes__')
    if item in private_attributes:
        attribute = private_attributes[item]
        if hasattr(attribute, '__get__'):
            return attribute.__get__(self, type(self))  # type: ignore

        try:
            # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
            return self.__pydantic_private__[item]  # type: ignore
        except KeyError as exc:
            raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
    else:
        # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
        # See `BaseModel.__repr_args__` for more details
        try:
            pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
        except AttributeError:
            pydantic_extra = None

        if pydantic_extra and item in pydantic_extra:
            return pydantic_extra[item]
        else:
            if hasattr(self.__class__, item):
                return super().__getattribute__(item)  # Raises AttributeError if appropriate
            else:
                # this is the current error
              raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')

E AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile'

/nix/store/9izjmjhx5ypi29bbgv04jmmdw9cbwszv-python3.14-pydantic-2.12.5/lib/python3.14/site-packages/pydantic/main.py:1026: AttributeError

Root Cause

NOTE: Using getattribute because @property cannot override Pydantic fields.

        def __getattribute__(self, name: str) -> Any:
            if name == "profile":
                msg = "Profile not available"
                raise AttributeError(msg)
            return super().__getattribute__(name)

Fix Action

Fix / Workaround

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

PR fix notes

PR #1: fix(core): handle AttributeError from getattribute in _set_model_profile

Description (problem / solution / changelog)

Fixes #36312

_set_model_profile and _check_profile_keys accessed self.profile directly, crashing model construction with AttributeError when a subclass overrides __getattribute__ to raise it for profile. Fixed by using getattr(self, profile, None) which catches AttributeError from both __getattr__ and __getattribute__.

Verification: Added regression test test_summarization_middleware_missing_profile_attribute_error reproducing the exact failing scenario. Both new and existing profile tests pass. All 74 core chat_models unit tests pass.

AI assistance was used in diagnosing and implementing this fix.

Changed files

  • libs/core/langchain_core/language_models/chat_models.py (modified, +6/-3)
  • libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py (modified, +40/-0)

PR #36316: AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile #36312

Description (problem / solution / changelog)

Fixes #36312

_set_model_profile and _check_profile_keys in BaseChatModel accessed self.profile directly, causing model construction to crash with AttributeError when a subclass overrides getattribute to raise it for
'profile'. Replaced with getattr(self, "profile", None) which safely catches AttributeError from both getattr and getattribute overrides.

Verification: Added regression test test_summarization_middleware_missing_profile_attribute_error reproducing the exact failing scenario from the bug report. Both new and existing profile
tests pass. All 74 core chat_models/ unit tests pass.

▎ AI assistance was used in diagnosing and implementing this fix.

LinkedIn: https://www.linkedin.com/in/rino-a-12769910a/

Changed files

  • libs/core/langchain_core/language_models/chat_models.py (modified, +6/-3)
  • libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py (modified, +40/-0)

PR #36342: fix(core): handle AttributeError when accessing profile in chat_models

Description (problem / solution / changelog)

Issue

Fixes #36312

When a model class overrides to raise an for the attribute, the and validators would fail during model initialization.

Changes

Modified and in to use to safely access the field, falling back to if is raised.

This ensures that models with custom implementations that raise for can still be instantiated without errors.

Testing

  • Added test script to verify the fix works with a model that raises for
  • All existing tests in pass
  • All existing tests in pass

Changed files

  • libs/core/langchain_core/language_models/chat_models.py (modified, +15/-3)

PR #36379: fix(core): suppress AttributeError from self.profile read in _set_model_profile

Description (problem / solution / changelog)

Problem

_set_model_profile crashes when a subclass overrides __getattribute__ to raise AttributeError for the profile attribute (or when any property/descriptor raises on access).

The current code places contextlib.suppress(Exception) only around the _resolve_model_profile() call, but the triggering line if self.profile is None is outside the suppress block:

# current — crashes before entering suppress
if self.profile is None:
    with contextlib.suppress(Exception):
        self.profile = self._resolve_model_profile()

This causes test_summarization_middleware_missing_profile to fail with:

AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile'

because ImportErrorProfileModel.__getattribute__ raises AttributeError for profile, which is never caught.

Fix

Move the guard inside the suppress block so errors from both reading and resolving the profile are suppressed:

with contextlib.suppress(Exception):
    if self.profile is None:
        self.profile = self._resolve_model_profile()

This does not change any behaviour for the normal case — self.profile is a Pydantic field with a plain None default, so reading it never throws under normal conditions.

Fixes #36312

Test plan

  • test_summarization_middleware_missing_profile in tests/unit_tests/agents/middleware/implementations/test_summarization.py should now pass
  • Existing model profile tests should be unaffected

Changed files

  • libs/core/langchain_core/language_models/chat_models.py (modified, +5/-5)

Code Example

Build langchain @ 1.2.13 with langchain-core 1.2.22

---

________________ test_summarization_middleware_missing_profile _________________
[gw1] darwin -- Python 3.14.3 /nix/store/dfkim8vahgdqhk1lrxz1j4mcighlrk99-python3-3.14.3/bin/python3.14

    def test_summarization_middleware_missing_profile() -> None:
        """Ensure automatic profile inference falls back when profiles are unavailable."""

        class ImportErrorProfileModel(BaseChatModel):
            @override
            def _generate(
                self,
                messages: list[BaseMessage],
                stop: list[str] | None = None,
                run_manager: CallbackManagerForLLMRun | None = None,
                **kwargs: Any,
            ) -> ChatResult:
                raise NotImplementedError

            @property
            def _llm_type(self) -> str:
                return "mock"

            # NOTE: Using __getattribute__ because @property cannot override Pydantic fields.
            def __getattribute__(self, name: str) -> Any:
                if name == "profile":
                    msg = "Profile not available"
                    raise AttributeError(msg)
                return super().__getattribute__(name)

        with pytest.raises(
            ValueError,
            match="Model profile information is required to use fractional token limits",
        ):
            _ = SummarizationMiddleware(
>               model=ImportErrorProfileModel(), trigger=("fraction", 0.5), keep=("messages", 1)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^
            )

tests/unit_tests/agents/middleware/implementations/test_summarization.py:420:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/load/serializable.py:118: in __init__
    super().__init__(*args, **kwargs)
/nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/language_models/chat_models.py:393: in _set_model_profile
    if self.profile is None:
       ^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = ImportErrorProfileModel(), item = 'profile'

    def __getattr__(self, item: str) -> Any:
        private_attributes = object.__getattribute__(self, '__private_attributes__')
        if item in private_attributes:
            attribute = private_attributes[item]
            if hasattr(attribute, '__get__'):
                return attribute.__get__(self, type(self))  # type: ignore

            try:
                # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
                return self.__pydantic_private__[item]  # type: ignore
            except KeyError as exc:
                raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
        else:
            # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
            # See `BaseModel.__repr_args__` for more details
            try:
                pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
            except AttributeError:
                pydantic_extra = None

            if pydantic_extra and item in pydantic_extra:
                return pydantic_extra[item]
            else:
                if hasattr(self.__class__, item):
                    return super().__getattribute__(item)  # Raises AttributeError if appropriate
                else:
                    # this is the current error
>                   raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
E                   AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile'

/nix/store/9izjmjhx5ypi29bbgv04jmmdw9cbwszv-python3.14-pydantic-2.12.5/lib/python3.14/site-packages/pydantic/main.py:1026: AttributeError
RAW_BUFFERClick to expand / collapse

Checked other resources

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

Package (Required)

  • langchain
  • langchain-openai
  • langchain-anthropic
  • langchain-classic
  • langchain-core
  • langchain-model-profiles
  • langchain-tests
  • langchain-text-splitters
  • langchain-chroma
  • langchain-deepseek
  • langchain-exa
  • langchain-fireworks
  • langchain-groq
  • langchain-huggingface
  • langchain-mistralai
  • langchain-nomic
  • langchain-ollama
  • langchain-openrouter
  • langchain-perplexity
  • langchain-qdrant
  • langchain-xai
  • Other / not sure / general

Related Issues / PRs

No response

Reproduction Steps / Example Code (Python)

Build langchain @ 1.2.13 with langchain-core 1.2.22

Error Message and Stack Trace (if applicable)

________________ test_summarization_middleware_missing_profile _________________
[gw1] darwin -- Python 3.14.3 /nix/store/dfkim8vahgdqhk1lrxz1j4mcighlrk99-python3-3.14.3/bin/python3.14

    def test_summarization_middleware_missing_profile() -> None:
        """Ensure automatic profile inference falls back when profiles are unavailable."""

        class ImportErrorProfileModel(BaseChatModel):
            @override
            def _generate(
                self,
                messages: list[BaseMessage],
                stop: list[str] | None = None,
                run_manager: CallbackManagerForLLMRun | None = None,
                **kwargs: Any,
            ) -> ChatResult:
                raise NotImplementedError

            @property
            def _llm_type(self) -> str:
                return "mock"

            # NOTE: Using __getattribute__ because @property cannot override Pydantic fields.
            def __getattribute__(self, name: str) -> Any:
                if name == "profile":
                    msg = "Profile not available"
                    raise AttributeError(msg)
                return super().__getattribute__(name)

        with pytest.raises(
            ValueError,
            match="Model profile information is required to use fractional token limits",
        ):
            _ = SummarizationMiddleware(
>               model=ImportErrorProfileModel(), trigger=("fraction", 0.5), keep=("messages", 1)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^
            )

tests/unit_tests/agents/middleware/implementations/test_summarization.py:420:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/load/serializable.py:118: in __init__
    super().__init__(*args, **kwargs)
/nix/store/dx4ynf6cxw0xsj93lhd1qpa8j7i4harl-python3.14-langchain-core-1.2.22/lib/python3.14/site-packages/langchain_core/language_models/chat_models.py:393: in _set_model_profile
    if self.profile is None:
       ^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = ImportErrorProfileModel(), item = 'profile'

    def __getattr__(self, item: str) -> Any:
        private_attributes = object.__getattribute__(self, '__private_attributes__')
        if item in private_attributes:
            attribute = private_attributes[item]
            if hasattr(attribute, '__get__'):
                return attribute.__get__(self, type(self))  # type: ignore

            try:
                # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
                return self.__pydantic_private__[item]  # type: ignore
            except KeyError as exc:
                raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
        else:
            # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
            # See `BaseModel.__repr_args__` for more details
            try:
                pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
            except AttributeError:
                pydantic_extra = None

            if pydantic_extra and item in pydantic_extra:
                return pydantic_extra[item]
            else:
                if hasattr(self.__class__, item):
                    return super().__getattribute__(item)  # Raises AttributeError if appropriate
                else:
                    # this is the current error
>                   raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
E                   AttributeError: 'ImportErrorProfileModel' object has no attribute 'profile'

/nix/store/9izjmjhx5ypi29bbgv04jmmdw9cbwszv-python3.14-pydantic-2.12.5/lib/python3.14/site-packages/pydantic/main.py:1026: AttributeError

Description

While building for nixpkgs, test_summarization_middleware_missing_profile fails with a Pydantic error.

System Info

langchain @ 1.2.13 langchain-core @ 1.2.22

extent analysis

Fix Plan

To fix the issue, we need to modify the ImportErrorProfileModel class to handle the case where the profile attribute is not available. We can do this by overriding the __getattribute__ method to return a default value or raise a custom error.

Here are the steps:

  • Modify the ImportErrorProfileModel class to override the __getattribute__ method.
  • In the __getattribute__ method, check if the attribute name is profile. If it is, return a default value or raise a custom error.
  • Update the test_summarization_middleware_missing_profile test to expect the custom error.

Code Changes

class ImportErrorProfileModel(BaseChatModel):
    @override
    def _generate(
        self,
        messages: list[BaseMessage],
        stop: list[str] | None = None,
        run_manager: CallbackManagerForLLMRun | None = None,
        **kwargs: Any,
    ) -> ChatResult:
        raise NotImplementedError

    @property
    def _llm_type(self) -> str:
        return "mock"

    def __getattribute__(self, name: str) -> Any:
        if name == "profile":
            # Return a default value or raise a custom error
            raise ValueError("Model profile information is required")
        return super().__getattribute__(name)

Verification

To verify that the fix worked, run the test_summarization_middleware_missing_profile test again. The test should pass, and the custom error should be raised.

Extra Tips

  • Make sure to update the test_summarization_middleware_missing_profile test to expect the custom error.
  • Consider adding additional error handling to the ImportErrorProfileModel class to handle other potential errors.
  • Review the Pydantic documentation to ensure that the __getattribute__ method is being used correctly.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING