-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy path_chat_normalize.py
324 lines (255 loc) · 11.4 KB
/
_chat_normalize.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import sys
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Optional, cast
from ._chat_types import ChatMessage
if TYPE_CHECKING:
from anthropic.types import Message as AnthropicMessage
from anthropic.types import MessageStreamEvent
if sys.version_info >= (3, 9):
from google.generativeai.types.generation_types import ( # pyright: ignore[reportMissingTypeStubs]
GenerateContentResponse,
)
else:
class GenerateContentResponse:
text: str
from langchain_core.messages import BaseMessage, BaseMessageChunk
from litellm.types.utils import ( # pyright: ignore[reportMissingTypeStubs]
ModelResponse,
)
from openai.types.chat import ChatCompletion, ChatCompletionChunk
class BaseMessageNormalizer(ABC):
@abstractmethod
def normalize(self, message: Any) -> ChatMessage:
pass
@abstractmethod
def normalize_chunk(self, chunk: Any) -> ChatMessage:
pass
@abstractmethod
def can_normalize(self, message: Any) -> bool:
pass
@abstractmethod
def can_normalize_chunk(self, chunk: Any) -> bool:
pass
class StringNormalizer(BaseMessageNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast(Optional[str], message)
return ChatMessage(content=x or "", role="assistant")
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast(Optional[str], chunk)
return ChatMessage(content=x or "", role="assistant")
def can_normalize(self, message: Any) -> bool:
return isinstance(message, str) or message is None
def can_normalize_chunk(self, chunk: Any) -> bool:
return isinstance(chunk, str) or chunk is None
class DictNormalizer(BaseMessageNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("dict[str, Any]", message)
if "content" not in x:
raise ValueError("Message must have 'content' key")
return ChatMessage(content=x["content"], role=x.get("role", "assistant"))
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("dict[str, Any]", chunk)
if "content" not in x:
raise ValueError("Message must have 'content' key")
return ChatMessage(content=x["content"], role=x.get("role", "assistant"))
def can_normalize(self, message: Any) -> bool:
return isinstance(message, dict)
def can_normalize_chunk(self, chunk: Any) -> bool:
return isinstance(chunk, dict)
class LangChainNormalizer(BaseMessageNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("BaseMessage", message)
if isinstance(x.content, list): # type: ignore
raise ValueError(
"The `message.content` provided seems to represent numerous messages. "
"Consider iterating over `message.content` and calling .append_message() on each iteration."
)
return ChatMessage(content=x.content, role="assistant")
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("BaseMessageChunk", chunk)
if isinstance(x.content, list): # type: ignore
raise ValueError(
"The `message.content` provided seems to represent numerous messages. "
"Consider iterating over `message.content` and calling .append_message() on each iteration."
)
return ChatMessage(content=x.content, role="assistant")
def can_normalize(self, message: Any) -> bool:
try:
from langchain_core.messages import BaseMessage
return isinstance(message, BaseMessage)
except Exception:
return False
def can_normalize_chunk(self, chunk: Any) -> bool:
try:
from langchain_core.messages import BaseMessageChunk
return isinstance(chunk, BaseMessageChunk)
except Exception:
return False
class OpenAINormalizer(StringNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("ChatCompletion", message)
return super().normalize(x.choices[0].message.content)
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("ChatCompletionChunk", chunk)
return super().normalize_chunk(x.choices[0].delta.content)
def can_normalize(self, message: Any) -> bool:
try:
from openai.types.chat import ChatCompletion
return isinstance(message, ChatCompletion)
except Exception:
return False
def can_normalize_chunk(self, chunk: Any) -> bool:
try:
from openai.types.chat import ChatCompletionChunk
return isinstance(chunk, ChatCompletionChunk)
except Exception:
return False
class LiteLlmNormalizer(OpenAINormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("ModelResponse", message)
return super().normalize(x)
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("ModelResponse", chunk)
return super().normalize_chunk(x)
def can_normalize(self, message: Any) -> bool:
try:
from litellm.types.utils import ( # pyright: ignore[reportMissingTypeStubs]
ModelResponse,
)
return isinstance(message, ModelResponse)
except Exception:
return False
def can_normalize_chunk(self, chunk: Any) -> bool:
try:
from litellm.types.utils import ( # pyright: ignore[reportMissingTypeStubs]
ModelResponse,
)
return isinstance(chunk, ModelResponse)
except Exception:
return False
class AnthropicNormalizer(BaseMessageNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("AnthropicMessage", message)
content = x.content[0]
if content.type != "text":
raise ValueError(
f"Anthropic message type {content.type} not supported. "
"Only 'text' type is currently supported"
)
return ChatMessage(content=content.text, role="assistant")
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("MessageStreamEvent", chunk)
content = ""
if x.type == "content_block_delta":
if x.delta.type != "text_delta":
raise ValueError(
f"Anthropic message delta type {x.delta.type} not supported. "
"Only 'text_delta' type is supported"
)
content = x.delta.text
return ChatMessage(content=content, role="assistant")
def can_normalize(self, message: Any) -> bool:
try:
from anthropic.types import Message as AnthropicMessage
return isinstance(message, AnthropicMessage)
except Exception:
return False
def can_normalize_chunk(self, chunk: Any) -> bool:
try:
from anthropic.types import (
RawContentBlockDeltaEvent,
RawContentBlockStartEvent,
RawContentBlockStopEvent,
RawMessageDeltaEvent,
RawMessageStartEvent,
RawMessageStopEvent,
)
# The actual MessageStreamEvent is a generic, so isinstance() can't
# be used to check the type. Instead, we manually construct the relevant
# union of relevant classes...
return (
isinstance(chunk, RawContentBlockDeltaEvent)
or isinstance(chunk, RawContentBlockStartEvent)
or isinstance(chunk, RawContentBlockStopEvent)
or isinstance(chunk, RawMessageDeltaEvent)
or isinstance(chunk, RawMessageStartEvent)
or isinstance(chunk, RawMessageStopEvent)
)
except Exception:
return False
class GoogleNormalizer(BaseMessageNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("GenerateContentResponse", message)
return ChatMessage(content=x.text, role="assistant")
def normalize_chunk(self, chunk: Any) -> ChatMessage:
x = cast("GenerateContentResponse", chunk)
return ChatMessage(content=x.text, role="assistant")
def can_normalize(self, message: Any) -> bool:
try:
import google.generativeai.types.generation_types as gtypes # pyright: ignore[reportMissingTypeStubs, reportMissingImports]
return isinstance(
message,
gtypes.GenerateContentResponse, # pyright: ignore[reportUnknownMemberType]
)
except Exception:
return False
def can_normalize_chunk(self, chunk: Any) -> bool:
return self.can_normalize(chunk)
class OllamaNormalizer(DictNormalizer):
def normalize(self, message: Any) -> ChatMessage:
x = cast("dict[str, Any]", message["message"])
return super().normalize(x)
def normalize_chunk(self, chunk: "dict[str, Any]") -> ChatMessage:
msg = cast("dict[str, Any]", chunk["message"])
return super().normalize_chunk(msg)
def can_normalize(self, message: Any) -> bool:
if not isinstance(message, dict):
return False
if "message" not in message:
return False
return super().can_normalize(message["message"])
def can_normalize_chunk(self, chunk: Any) -> bool:
return self.can_normalize(chunk)
class NormalizerRegistry:
def __init__(self) -> None:
# Order of strategies matters (the 1st one that can normalize the message is used)
# So make sure to put the most specific strategies first
self._strategies: dict[str, BaseMessageNormalizer] = {
"openai": OpenAINormalizer(),
"anthropic": AnthropicNormalizer(),
"google": GoogleNormalizer(),
"langchain": LangChainNormalizer(),
"litellm": LiteLlmNormalizer(),
"ollama": OllamaNormalizer(),
"dict": DictNormalizer(),
"string": StringNormalizer(),
}
def register(
self, provider: str, strategy: BaseMessageNormalizer, force: bool = False
) -> None:
if provider in self._strategies:
if force:
del self._strategies[provider]
else:
raise ValueError(f"Provider {provider} already exists in registry")
# Update the strategies dict such that the new strategy is the first to be considered
self._strategies = {provider: strategy, **self._strategies}
message_normalizer_registry = NormalizerRegistry()
def normalize_message(message: Any) -> ChatMessage:
strategies = message_normalizer_registry._strategies
for strategy in strategies.values():
if strategy.can_normalize(message):
return strategy.normalize(message)
raise ValueError(
f"Could not find a normalizer for message of type {type(message)}: {message}. "
"Consider registering a custom normalizer via shiny.ui._chat_types.registry.register()"
)
def normalize_message_chunk(chunk: Any) -> ChatMessage:
strategies = message_normalizer_registry._strategies
for strategy in strategies.values():
if strategy.can_normalize_chunk(chunk):
return strategy.normalize_chunk(chunk)
raise ValueError(
f"Could not find a normalizer for message chunk of type {type(chunk)}: {chunk}. "
"Consider registering a custom normalizer via shiny.ui._chat_types.registry.register()"
)