core: add RemoveMessage (#23636)

This change adds a new message type `RemoveMessage`. This will enable
`langgraph` users to manually modify graph state (or have the graph
nodes modify the state) to remove messages by `id`

Examples:

* allow users to delete messages from state by calling

```python
graph.update_state(config, values=[RemoveMessage(id=state.values[-1].id)])
```

* allow nodes to delete messages

```python
graph.add_node("delete_messages", lambda state: [RemoveMessage(id=state[-1].id)])
```
This commit is contained in:
Vadym Barda 2024-06-28 17:40:02 -04:00 committed by GitHub
parent 8fce8c6771
commit e8d77002ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 39 additions and 0 deletions

View File

@ -95,6 +95,13 @@ def test_serializable_mapping() -> None:
"structured",
"StructuredPrompt",
),
# This is not exported from langchain, only langchain_core
("langchain", "schema", "messages", "RemoveMessage"): (
"langchain_core",
"messages",
"modifier",
"RemoveMessage",
),
}
serializable_modules = import_all_modules("langchain")

View File

@ -76,6 +76,12 @@ SERIALIZABLE_MAPPING: Dict[Tuple[str, ...], Tuple[str, ...]] = {
"tool",
"ToolMessage",
),
("langchain", "schema", "messages", "RemoveMessage"): (
"langchain_core",
"messages",
"modifier",
"RemoveMessage",
),
("langchain", "schema", "agent", "AgentAction"): (
"langchain_core",
"agents",

View File

@ -29,6 +29,7 @@ from langchain_core.messages.base import (
from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
from langchain_core.messages.human import HumanMessage, HumanMessageChunk
from langchain_core.messages.modifier import RemoveMessage
from langchain_core.messages.system import SystemMessage, SystemMessageChunk
from langchain_core.messages.tool import (
InvalidToolCall,
@ -70,6 +71,7 @@ __all__ = [
"ToolCallChunk",
"ToolMessage",
"ToolMessageChunk",
"RemoveMessage",
"_message_from_dict",
"convert_to_messages",
"get_buffer_string",

View File

@ -0,0 +1,23 @@
from typing import Any, List, Literal
from langchain_core.messages.base import BaseMessage
class RemoveMessage(BaseMessage):
"""Message responsible for deleting other messages."""
type: Literal["remove"] = "remove"
def __init__(self, id: str, **kwargs: Any) -> None:
if kwargs.pop("content", None):
raise ValueError("RemoveMessage does not support 'content' field.")
return super().__init__("", id=id, **kwargs)
@classmethod
def get_lc_namespace(cls) -> List[str]:
"""Get the namespace of the langchain object."""
return ["langchain", "schema", "messages"]
RemoveMessage.update_forward_refs()

View File

@ -21,6 +21,7 @@ EXPECTED_ALL = [
"ToolCallChunk",
"ToolMessage",
"ToolMessageChunk",
"RemoveMessage",
"convert_to_messages",
"get_buffer_string",
"merge_content",