-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathchat_message.py
291 lines (236 loc) · 8.62 KB
/
chat_message.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
#
# SPDX-License-Identifier: Apache-2.0
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Union
class ChatRole(str, Enum):
"""
Enumeration representing the roles within a chat.
"""
#: The user role. A message from the user contains only text.
USER = "user"
#: The system role. A message from the system contains only text.
SYSTEM = "system"
#: The assistant role. A message from the assistant can contain text and Tool calls. It can also store metadata.
ASSISTANT = "assistant"
#: The tool role. A message from a tool contains the result of a Tool invocation.
TOOL = "tool"
@dataclass
class ToolCall:
"""
Represents a Tool call prepared by the model, usually contained in an assistant message.
:param id: The ID of the Tool call.
:param tool_name: The name of the Tool to call.
:param arguments: The arguments to call the Tool with.
"""
tool_name: str
arguments: Dict[str, Any]
id: Optional[str] = None # noqa: A003
@dataclass
class ToolCallResult:
"""
Represents the result of a Tool invocation.
:param result: The result of the Tool invocation.
:param origin: The Tool call that produced this result.
:param error: Whether the Tool invocation resulted in an error.
"""
result: str
origin: ToolCall
error: bool
@dataclass
class TextContent:
"""
The textual content of a chat message.
:param text: The text content of the message.
"""
text: str
ChatMessageContentT = Union[TextContent, ToolCall, ToolCallResult]
@dataclass
class ChatMessage:
"""
Represents a message in a LLM chat conversation.
:param content: The content of the message.
:param role: The role of the entity sending the message.
:param meta: Additional metadata associated with the message.
"""
_role: ChatRole
_content: Sequence[ChatMessageContentT]
_meta: Dict[str, Any] = field(default_factory=dict, hash=False)
def __len__(self):
return len(self._content)
@property
def role(self) -> ChatRole:
"""
Returns the role of the entity sending the message.
"""
return self._role
@property
def meta(self) -> Dict[str, Any]:
"""
Returns the metadata associated with the message.
"""
return self._meta
@property
def texts(self) -> List[str]:
"""
Returns the list of all texts contained in the message.
"""
return [content.text for content in self._content if isinstance(content, TextContent)]
@property
def text(self) -> Optional[str]:
"""
Returns the first text contained in the message.
"""
if texts := self.texts:
return texts[0]
return None
@property
def tool_calls(self) -> List[ToolCall]:
"""
Returns the list of all Tool calls contained in the message.
"""
return [content for content in self._content if isinstance(content, ToolCall)]
@property
def tool_call(self) -> Optional[ToolCall]:
"""
Returns the first Tool call contained in the message.
"""
if tool_calls := self.tool_calls:
return tool_calls[0]
return None
@property
def tool_call_results(self) -> List[ToolCallResult]:
"""
Returns the list of all Tool call results contained in the message.
"""
return [content for content in self._content if isinstance(content, ToolCallResult)]
@property
def tool_call_result(self) -> Optional[ToolCallResult]:
"""
Returns the first Tool call result contained in the message.
"""
if tool_call_results := self.tool_call_results:
return tool_call_results[0]
return None
def is_from(self, role: ChatRole) -> bool:
"""
Check if the message is from a specific role.
:param role: The role to check against.
:returns: True if the message is from the specified role, False otherwise.
"""
return self._role == role
@classmethod
def from_user(
cls,
text: str,
meta: Optional[Dict[str, Any]] = None,
) -> "ChatMessage":
"""
Create a message from the user.
:param text: The text content of the message.
:param meta: Additional metadata associated with the message.
:returns: A new ChatMessage instance.
"""
return cls(_role=ChatRole.USER, _content=[TextContent(text=text)], _meta=meta or {})
@classmethod
def from_system(
cls,
text: str,
meta: Optional[Dict[str, Any]] = None,
) -> "ChatMessage":
"""
Create a message from the system.
:param text: The text content of the message.
:param meta: Additional metadata associated with the message.
:returns: A new ChatMessage instance.
"""
return cls(_role=ChatRole.SYSTEM, _content=[TextContent(text=text)], _meta=meta or {})
@classmethod
def from_assistant(
cls,
text: Optional[str] = None,
tool_calls: Optional[List[ToolCall]] = None,
meta: Optional[Dict[str, Any]] = None,
) -> "ChatMessage":
"""
Create a message from the assistant.
:param text: The text content of the message.
:param tool_calls: The Tool calls to include in the message.
:param meta: Additional metadata associated with the message.
:returns: A new ChatMessage instance.
"""
content: List[ChatMessageContentT] = []
if text is not None:
content.append(TextContent(text=text))
if tool_calls:
content.extend(tool_calls)
return cls(_role=ChatRole.ASSISTANT, _content=content, _meta=meta or {})
@classmethod
def from_tool(
cls,
tool_result: str,
origin: ToolCall,
error: bool = False,
meta: Optional[Dict[str, Any]] = None,
) -> "ChatMessage":
"""
Create a message from a Tool.
:param tool_result: The result of the Tool invocation.
:param origin: The Tool call that produced this result.
:param error: Whether the Tool invocation resulted in an error.
:param meta: Additional metadata associated with the message.
:returns: A new ChatMessage instance.
"""
return cls(
_role=ChatRole.TOOL,
_content=[ToolCallResult(result=tool_result, origin=origin, error=error)],
_meta=meta or {},
)
def to_dict(self) -> Dict[str, Any]:
"""
Converts ChatMessage into a dictionary.
:returns:
Serialized version of the object.
"""
serialized: Dict[str, Any] = {}
serialized["_role"] = self._role.value
serialized["_meta"] = self._meta
content: List[Dict[str, Any]] = []
for part in self._content:
if isinstance(part, TextContent):
content.append({"text": part.text})
elif isinstance(part, ToolCall):
content.append({"tool_call": asdict(part)})
elif isinstance(part, ToolCallResult):
content.append({"tool_call_result": asdict(part)})
else:
raise TypeError(f"Unsupported type in ChatMessage content: `{type(part).__name__}` for `{part}`.")
serialized["_content"] = content
return serialized
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ChatMessage":
"""
Creates a new ChatMessage object from a dictionary.
:param data:
The dictionary to build the ChatMessage object.
:returns:
The created object.
"""
data["_role"] = ChatRole(data["_role"])
content: List[ChatMessageContentT] = []
for part in data["_content"]:
if "text" in part:
content.append(TextContent(text=part["text"]))
elif "tool_call" in part:
content.append(ToolCall(**part["tool_call"]))
elif "tool_call_result" in part:
result = part["tool_call_result"]["result"]
origin = ToolCall(**part["tool_call_result"]["origin"])
error = part["tool_call_result"]["error"]
tcr = ToolCallResult(result=result, origin=origin, error=error)
content.append(tcr)
else:
raise ValueError(f"Unsupported content in serialized ChatMessage: `{part}`")
data["_content"] = content
return cls(**data)