Skip to content

Commit 23ecc77

Browse files
Add ChatRole enum for message history role validation (#518)
## Changes for [#484](#484) - Add `ChatRole(str, Enum)` to `schema.py` as the single source of truth for valid roles - Update `ChatMessage.role` to use `ChatRole` with a `field_validator` that coerces valid strings automatically - Align `_validate_roles` in `base_history.py` to derive valid roles from `ChatRole` instead of hardcoded values - Export `ChatRole` from the `message_history` package `__init__.py` - Add unit tests for valid string coercion, direct enum input, deprecated role warning message, invalid role rejection, and string serialization via `to_dict()` <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes the public `ChatMessage.role` type/validation and role filtering behavior, which may affect downstream callers that assume plain strings (especially the legacy `llm` role), though deprecated values are still accepted with warnings. > > **Overview** > Adds a `ChatRole` enum (`user`/`assistant`/`system`/`tool`) as the single source of truth for message roles, and updates `ChatMessage.role` to coerce valid role strings into the enum while emitting `DeprecationWarning`s for legacy/unknown string roles. > > Aligns `BaseMessageHistory._validate_roles` to derive allowed roles from `ChatRole` (warning-but-allow for `llm`), exports `ChatRole` from `message_history.__init__`, and expands unit tests to cover coercion, deprecation warnings, invalid role rejection, and `to_dict()` role serialization. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 94211c8. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent e7301a2 commit 23ecc77

4 files changed

Lines changed: 102 additions & 18 deletions

File tree

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from redisvl.extensions.message_history.base_history import BaseMessageHistory
22
from redisvl.extensions.message_history.message_history import MessageHistory
3+
from redisvl.extensions.message_history.schema import ChatRole
34
from redisvl.extensions.message_history.semantic_history import SemanticMessageHistory
45

5-
__all__ = ["BaseMessageHistory", "MessageHistory", "SemanticMessageHistory"]
6+
__all__ = ["BaseMessageHistory", "MessageHistory", "SemanticMessageHistory", "ChatRole"]

‎redisvl/extensions/message_history/base_history.py‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import warnings
12
from typing import Any, Dict, List, Optional, Union
23

34
from redisvl.extensions.constants import (
@@ -6,7 +7,7 @@
67
ROLE_FIELD_NAME,
78
TOOL_FIELD_NAME,
89
)
9-
from redisvl.extensions.message_history.schema import ChatMessage
10+
from redisvl.extensions.message_history.schema import ChatMessage, ChatRole
1011
from redisvl.utils.utils import create_ulid, deserialize
1112

1213

@@ -113,25 +114,38 @@ def _validate_roles(
113114
if role is None:
114115
return None
115116

116-
valid_roles = {"system", "user", "llm", "tool"}
117+
deprecated_roles = {"llm"}
118+
valid_roles = {r.value for r in ChatRole}
117119

118120
# Handle single role string
119121
if isinstance(role, str):
120-
if role not in valid_roles:
121-
raise ValueError(
122-
f"Invalid role '{role}'. Valid roles are: {valid_roles}"
122+
if role in valid_roles:
123+
return [role]
124+
elif role in deprecated_roles:
125+
warnings.warn(
126+
f"Role '{role}' is a deprecated value. Update to valid roles: {valid_roles}.",
127+
DeprecationWarning,
128+
stacklevel=2,
123129
)
124-
return [role]
130+
return [role]
131+
else:
132+
raise ValueError(f"Invalid role '{role}'. Valid roles: {valid_roles}")
125133

126134
# Handle list of roles
127135
if isinstance(role, list):
128136
if not role: # Empty list
129137
raise ValueError("roles cannot be empty")
130138
for r in role:
131-
if r not in valid_roles:
132-
raise ValueError(
133-
f"Invalid role '{r}'. Valid roles are: {valid_roles}"
139+
if r in valid_roles:
140+
continue
141+
elif r in deprecated_roles:
142+
warnings.warn(
143+
f"Role '{r}' is a deprecated value. Update to valid roles: {valid_roles}.",
144+
DeprecationWarning,
145+
stacklevel=2,
134146
)
147+
else:
148+
raise ValueError(f"Invalid role '{r}'. Valid roles: {valid_roles}")
135149
return role
136150

137151
raise ValueError("role must be a string or list of strings")

‎redisvl/extensions/message_history/schema.py‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from typing import Dict, List, Optional
1+
import warnings
2+
from enum import Enum
3+
from typing import Any, Dict, List, Optional, Union
24
from uuid import uuid4
35

46
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
@@ -18,13 +20,22 @@
1820
from redisvl.utils.utils import current_timestamp
1921

2022

23+
class ChatRole(str, Enum):
24+
"""Enumeration of valid roles for a chat message."""
25+
26+
USER = "user"
27+
ASSISTANT = "assistant"
28+
SYSTEM = "system"
29+
TOOL = "tool"
30+
31+
2132
class ChatMessage(BaseModel):
2233
"""A single chat message exchanged between a user and an LLM."""
2334

2435
entry_id: Optional[str] = Field(default=None)
2536
"""A unique identifier for the message."""
26-
role: str # TODO -- do we enumify this?
27-
"""The role of the message sender (e.g., 'user' or 'llm')."""
37+
role: Union[ChatRole, str] # str allows deprecated values with warning
38+
"""The role of the message sender (e.g. 'user' or 'assistant')."""
2839
content: str
2940
"""The content of the message."""
3041
session_tag: str
@@ -53,6 +64,20 @@ def generate_id(cls, values):
5364
)
5465
return values
5566

67+
@field_validator("role", mode="before")
68+
@classmethod
69+
def coerce_role(cls, v: Any) -> Union[ChatRole, str]:
70+
if isinstance(v, str):
71+
try:
72+
return ChatRole(v)
73+
except ValueError:
74+
warnings.warn(
75+
f"Role '{v}' is a deprecated value. Update to valid roles: {[r.value for r in ChatRole]}.",
76+
DeprecationWarning,
77+
stacklevel=2,
78+
)
79+
return v
80+
5681
def to_dict(self, dtype: Optional[str] = None) -> Dict:
5782
data = self.model_dump(exclude_none=True)
5883

‎tests/unit/test_message_history_schema.py‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pytest
22
from pydantic import ValidationError
33

4-
from redisvl.extensions.message_history.schema import ChatMessage
4+
from redisvl.extensions.message_history.schema import ChatMessage, ChatRole
55
from redisvl.redis.utils import array_to_buffer
66
from redisvl.utils.utils import create_ulid, current_timestamp, serialize
77

@@ -157,19 +157,63 @@ def test_chat_message_missing_fields():
157157
)
158158

159159

160-
def test_chat_message_invalid_role():
160+
@pytest.mark.parametrize(
161+
"deprecated_role", ["potato", "llm", "admin", "", "User", "SYSTEM"]
162+
)
163+
def test_chat_message_deprecated_role(deprecated_role):
164+
"""Deprecated string roles raise a DeprecationWarning but are stored as-is."""
161165
session_tag = create_ulid()
162166
timestamp = current_timestamp()
163167
content = "Hello, world!"
168+
message = None
164169

165-
with pytest.raises(ValidationError):
166-
ChatMessage(
170+
with pytest.warns(DeprecationWarning, match="deprecated value"):
171+
message = ChatMessage(
167172
entry_id=f"{session_tag}:{timestamp}",
168-
role=[1, 2, 3], # Invalid role type
173+
role=deprecated_role,
169174
content=content,
170175
session_tag=session_tag,
171176
timestamp=timestamp,
172177
)
178+
assert message is not None
179+
assert message.role == deprecated_role
180+
181+
182+
@pytest.mark.parametrize(
183+
"role_input, expected",
184+
[
185+
("user", ChatRole.USER),
186+
("assistant", ChatRole.ASSISTANT),
187+
("system", ChatRole.SYSTEM),
188+
("tool", ChatRole.TOOL),
189+
(ChatRole.USER, ChatRole.USER), # enum value passed directly
190+
(ChatRole.ASSISTANT, ChatRole.ASSISTANT),
191+
],
192+
)
193+
def test_chat_message_role_coercion(role_input, expected):
194+
session_tag = create_ulid()
195+
content = "Hello, world!"
196+
message = ChatMessage(role=role_input, content=content, session_tag=session_tag)
197+
assert message.role == expected
198+
assert isinstance(message.role, ChatRole)
199+
200+
201+
@pytest.mark.parametrize("invalid_role", [123, [1, 2, 3]])
202+
def test_chat_message_invalid_role(invalid_role):
203+
session_tag = create_ulid()
204+
content = "Hello, world!"
205+
with pytest.raises(ValidationError):
206+
ChatMessage(role=invalid_role, content=content, session_tag=session_tag)
207+
208+
209+
def test_chat_message_role_serializes_to_string():
210+
session_tag = create_ulid()
211+
role = "user"
212+
content = "Hello, world!"
213+
message = ChatMessage(role=role, content=content, session_tag=session_tag)
214+
data = message.to_dict()
215+
assert data["role"] == "user"
216+
assert isinstance(data["role"], str)
173217

174218

175219
def test_chat_message_unique_ids_for_rapid_creation():

0 commit comments

Comments
 (0)