Core: Fix __add__ for concatting two BaseMessageChunk's (#29531)

Description:

The change allows you to use the overloaded `+` operator correctly when
`+`ing two BaseMessageChunk subclasses. Without this you *must*
instantiate a subclass for it to work.

Which feels... wrong. Base classes should be decoupled from sub classes
and should have in no way a dependency on them.

Issue:

You can't `+` a BaseMessageChunk with a BaseMessageChunk

e.g. this will explode

```py
from langchain_core.outputs import (
    ChatGenerationChunk,
)
from langchain_core.messages import BaseMessageChunk


chunk1 = ChatGenerationChunk(
    message=BaseMessageChunk(
        type="customChunk",
        content="HI",
    ),
)

chunk2 = ChatGenerationChunk(
    message=BaseMessageChunk(
        type="customChunk",
        content="HI",
    ),
)

# this will throw
new_chunk = chunk1 + chunk2
```

In case anyone ran into this issue themselves, it's probably best to use
the AIMessageChunk:

a la 

```py
from langchain_core.outputs import (
    ChatGenerationChunk,
)
from langchain_core.messages import AIMessageChunk


chunk1 = ChatGenerationChunk(
    message=AIMessageChunk(
        content="HI",
    ),
)

chunk2 = ChatGenerationChunk(
    message=AIMessageChunk(
        content="HI",
    ),
)

# No explosion!
new_chunk = chunk1 + chunk2
```

Dependencies:

None!

Twitter handle: 
`aaron_vogler`

Keeping these for later if need be:
```
baskaryan
efriis 
eyurtsev
ccurme 
vbarda
hwchase17
baskaryan
efriis
```

Co-authored-by: Erick Friis <erick@langchain.dev>
This commit is contained in:
Aaron V 2025-02-07 19:43:36 -05:00 committed by GitHub
parent 4fa3ef0d55
commit dcfaae85d2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -198,6 +198,7 @@ class BaseMessageChunk(BaseMessage):
return self.__class__( # type: ignore[call-arg] return self.__class__( # type: ignore[call-arg]
id=self.id, id=self.id,
type=self.type,
content=merge_content(self.content, other.content), content=merge_content(self.content, other.content),
additional_kwargs=merge_dicts( additional_kwargs=merge_dicts(
self.additional_kwargs, other.additional_kwargs self.additional_kwargs, other.additional_kwargs