sinapsis-chatbots-base 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
__init__.py ADDED
File without changes
File without changes
File without changes
@@ -0,0 +1,24 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Literal
3
+
4
+ from pydantic.dataclasses import dataclass
5
+
6
+
7
+ @dataclass
8
+ class LLMChatKeys:
9
+ """
10
+ A class to hold constants for the keys used in chat interactions with an LLM (Large Language Model).
11
+
12
+ These keys represent the standard fields in a chat interaction, such as the role of the participant
13
+ and the content of the message. They are typically used when constructing input messages or
14
+ processing the output from an LLM.
15
+ """
16
+
17
+ role: Literal["role"] = "role"
18
+ content: Literal["content"] = "content"
19
+ choices: Literal["choices"] = "choices"
20
+ message: Literal["message"] = "message"
21
+ llm_responses: Literal["llm_responses"] = "llm_responses"
22
+ system_value: Literal["system"] = "system"
23
+ user_value: Literal["user"] = "user"
24
+ assistant_value: Literal["assistant"] = "assistant"
@@ -0,0 +1,33 @@
1
+ # -*- coding: utf-8 -*-
2
+ """This module provides utilities for cleaning and post-processing text."""
3
+
4
+ import re
5
+
6
+
7
+ def postprocess_text(input_text: str, pattern: str | None = None, keep_before: bool = True) -> str:
8
+ """
9
+ Cleans text by removing or splitting based on structured delimiters using a regex pattern.
10
+
11
+ The default pattern detects:
12
+ - `<| ... |>`: Matches anything inside `<|` and `|>`, often used in AI outputs.
13
+ - `</ ... >`: Matches anything inside `</` and `>`, common in XML-like markup.
14
+
15
+ Parameters:
16
+ - response (str): The input string to be cleaned.
17
+ - pattern (str, optional): A regex pattern to match delimiters. Defaults to handling `<|...|>` and `</...>`.
18
+ - keep_before (bool, optional): If True, returns the portion before the first match;
19
+ if False, returns the portion after the first match.
20
+
21
+ Returns:
22
+ - str: The cleaned response string.
23
+ """
24
+ if pattern is None:
25
+ pattern = r"(<\|.*?\|>|</.*?>)"
26
+
27
+ match = re.search(pattern, input_text)
28
+
29
+ if match:
30
+ split_index = match.start() if keep_before else match.end()
31
+ return input_text[:split_index].strip() if keep_before else input_text[split_index:].strip()
32
+
33
+ return input_text
@@ -0,0 +1,20 @@
1
+ # -*- coding: utf-8 -*-
2
+ import importlib
3
+ from typing import Callable
4
+
5
+ _root_lib_path = "sinapsis_chatbots_base.templates"
6
+
7
+ _template_lookup = {
8
+ "QueryContextualizeFromText": f"{_root_lib_path}.query_contextualize_from_text",
9
+ "QueryContextualizeFromFile": f"{_root_lib_path}.query_contextualize_from_file",
10
+ }
11
+
12
+
13
+ def __getattr__(name: str) -> Callable:
14
+ if name in _template_lookup:
15
+ module = importlib.import_module(_template_lookup[name])
16
+ return getattr(module, name)
17
+ raise AttributeError(f"template `{name}` not found in {_root_lib_path}")
18
+
19
+
20
+ __all__ = list(_template_lookup.keys())
@@ -0,0 +1,275 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import uuid
4
+ from abc import abstractmethod
5
+ from collections import deque
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ from sinapsis_core.data_containers.data_packet import DataContainer, TextPacket
10
+ from sinapsis_core.template_base import (
11
+ Template,
12
+ TemplateAttributes,
13
+ TemplateAttributeType,
14
+ )
15
+
16
+ from sinapsis_chatbots_base.helpers.llm_keys import LLMChatKeys
17
+
18
+
19
+ class LLMTextCompletionAttributes(TemplateAttributes):
20
+ """
21
+ Attributes for BaseLLMTextCompletion.
22
+
23
+ This class defines the attributes required for the LLM-based text completion
24
+ template.
25
+ It includes configuration settings for model context size, role, prompt, and
26
+ chat format.
27
+
28
+ Attributes:
29
+ llm_model_name (str): The name of the LLM model to use.
30
+ n_ctx (int): Maximum context size for the model.
31
+ role (Literal["system", "user", "assistant"]): The role in the conversation,
32
+ such as "system", "user", or
33
+ "assistant". Defaults to "assistant".
34
+ prompt (str): A set of instructions provided to the LLM to guide how to respond.
35
+ The default
36
+ value is an empty string.
37
+ system_prompt (str | None): The prompt that indicates the LLM how to behave
38
+ (e.g. you are an expert on...)
39
+ chat_format (str | None): The format for the chat messages
40
+ (e.g., llama-2, chatml, etc.).
41
+ context_max_len (int): The maximum length for the conversation context.
42
+ The default value is 6.
43
+ pattern (str | None): A regex pattern to match delimiters. The default value is
44
+ `<|...|>` and `</...>`.
45
+ keep_before (bool): If True, returns the portion before the first match;
46
+ if False, returns the portion after the first match.
47
+ """
48
+
49
+ llm_model_name: str
50
+ n_ctx: int = 9000
51
+ role: Literal["system", "user", "assistant"] = "assistant"
52
+ prompt: str = ""
53
+ system_prompt: str | Path | None = None
54
+ chat_format: str = "chatml"
55
+ context_max_len: int = 6
56
+ pattern: str | None = None
57
+ keep_before: bool = True
58
+
59
+
60
+ class LLMTextCompletionBase(Template):
61
+ """
62
+ Base template to get a response message from any LLM.
63
+
64
+ This is a base template class for LLM-based text completion. It is designed to work
65
+ with different LLM models (e.g., Llama, GPT). The base functionality includes
66
+ model initialization, response generation, state resetting, and context management.
67
+ Specific model interactions must be implemented in subclasses.
68
+
69
+ """
70
+
71
+ AttributesBaseModel = LLMTextCompletionAttributes
72
+
73
+ def __init__(self, attributes: TemplateAttributeType) -> None:
74
+ """
75
+ Initializes the base template with the provided attributes and initializes
76
+ the LLM model.
77
+
78
+ Args:
79
+ attributes (TemplateAttributeType): Attributes specific to the LLM model.
80
+ """
81
+ super().__init__(attributes)
82
+
83
+ self.llm = self.init_llm_model()
84
+ self._clear_context()
85
+ self.system_prompt = self._set_system_prompt()
86
+
87
+ def _set_system_prompt(self):
88
+ system_prompt = self.attributes.system_prompt
89
+ if ("/" in system_prompt) or ("\\" in system_prompt) or (system_prompt.endswith(".txt")):
90
+ return Path(system_prompt).read_text()
91
+ else:
92
+ return system_prompt
93
+
94
+ def _set_context(self, conversation_id: str) -> None:
95
+ """
96
+ Sets the context for the specified conversation ID, ensuring that a deque
97
+ for the conversation is available to store conversation history.
98
+
99
+ Args:
100
+ conversation_id (str): The unique identifier for the conversation.
101
+ """
102
+ if conversation_id not in self.context:
103
+ self.context[conversation_id] = deque(maxlen=self.attributes.context_max_len)
104
+
105
+ def _clear_context(self) -> None:
106
+ """
107
+ Clears the context, resetting the stored conversation history for
108
+ all conversations.
109
+ """
110
+ self.context: dict = {}
111
+
112
+ @abstractmethod
113
+ def init_llm_model(self) -> Any:
114
+ """
115
+ Initializes the LLM model. This method must be implemented by subclasses
116
+ to set up the specific model.
117
+
118
+ Returns:
119
+ Llama | Any: The initialized model instance.
120
+ """
121
+ raise NotImplementedError("Must be implemented by the subclass.")
122
+
123
+ @abstractmethod
124
+ def get_response(self, input_message: str | list) -> str | None:
125
+ """
126
+ Generates a response from the model based on the provided text input.
127
+
128
+ Args:
129
+ input_message (str | list): The input text or prompt to which the model
130
+ will respond.
131
+
132
+ Returns:
133
+ str | None: The model's response as a string, or None if no response is
134
+ generated.
135
+
136
+ This method should be implemented by subclasses to handle the specifics of
137
+ response generation for different models.
138
+ """
139
+ raise NotImplementedError("Must be implemented by the subclass.")
140
+
141
+ def reset_llm_state(self) -> None:
142
+ """
143
+ Resets the internal state of the language model, ensuring that no memory,
144
+ context, or cached information from previous interactions persists in the
145
+ current session.
146
+
147
+ This method calls `reset()` on the model to clear its internal state and
148
+ `reset_llm_context()` to reset any additional context management mechanisms.
149
+
150
+
151
+ Subclasses may override this method to implement model-specific reset behaviors
152
+ if needed.
153
+ """
154
+ self.llm.reset()
155
+
156
+ def infer(self, text: str | list) -> str | None:
157
+ """
158
+ Gets a response from the model, handling any errors or issues by resetting
159
+ the model state if necessary.
160
+
161
+ Args:
162
+ text (str): The input text for which the model will generate a response.
163
+
164
+ Returns:
165
+ str | None: The model's response as a string or None if the model fails
166
+ to respond.
167
+ """
168
+ try:
169
+ return self.get_response(text)
170
+ except ValueError:
171
+ self.reset_llm_state()
172
+ return self.get_response(text)
173
+
174
+ def append_to_context(self, conv_id: str, message: dict) -> None:
175
+ """
176
+ Appends a new message to the conversation context for the given `conv_id`.
177
+
178
+ Args:
179
+ conv_id (str): The conversation ID.
180
+ message (dict): The message dictionary with role and content keys. Role can be
181
+ 'system', 'assistant' or 'user'.
182
+ """
183
+ if message:
184
+ self.context[conv_id].append(message)
185
+
186
+ @staticmethod
187
+ def generate_dict_msg(role: str, msg_content: str | None) -> dict:
188
+ """For the provided content, generate a dictionary to be appended as the context
189
+ for the response.
190
+ Args:
191
+ role (str): Role of the message, Can be system, user or assistant
192
+ msg_content (str | None): Content of the message to be passed to the llm.
193
+ Returns:
194
+ The dictionary with the key pair values for role and content.
195
+
196
+ """
197
+ return {LLMChatKeys.role: role, LLMChatKeys.content: msg_content}
198
+
199
+ def get_conv_id_and_content(self, packet: TextPacket) -> tuple[str, str]:
200
+ """For an input packet, return a conversation id and the content of the message.
201
+ If the incoming packet does not have id, generate a new one.
202
+
203
+ Args:
204
+ packet(TextPacket): the incoming packet
205
+ Returns:
206
+ tuple[str, str]: The pair of conversation_id and message
207
+ """
208
+ if packet:
209
+ conv_id = packet.id
210
+ prompt = packet.content
211
+ else:
212
+ conv_id = str(uuid.uuid4())
213
+ prompt = self.attributes.prompt
214
+
215
+ return conv_id, prompt
216
+
217
+ def generate_response(self, container: DataContainer) -> DataContainer:
218
+ """
219
+ Processes a list of `TextPacket` objects, generating a response for each
220
+ text packet.
221
+
222
+ If the packet is empty, it generates a new response based on the prompt.
223
+ Otherwise, it uses the conversation context and appends the response to the
224
+ history.
225
+
226
+ Args:
227
+ container (DataContainer): Container where the incoming message is located and
228
+ where the generated response will be appended.
229
+
230
+ Returns:
231
+ DataContainer: Updated DataContainer with the response from the llm.
232
+ """
233
+
234
+ self.logger.debug("Chatbot in progress")
235
+ responses = []
236
+ for packet in container.texts:
237
+ conv_id, prompt = self.get_conv_id_and_content(packet)
238
+ self._set_context(conv_id)
239
+
240
+ if self.system_prompt:
241
+ system_prompt_msg = self.generate_dict_msg(LLMChatKeys.system_value, self.system_prompt)
242
+ self.append_to_context(conv_id, system_prompt_msg)
243
+
244
+ message = self.generate_dict_msg(LLMChatKeys.user_value, prompt)
245
+ self.append_to_context(conv_id, message)
246
+ response = self.infer(list(self.context[conv_id]))
247
+ response_msg = self.generate_dict_msg(LLMChatKeys.assistant_value, response)
248
+ self.append_to_context(conv_id, response_msg)
249
+ self.logger.debug("End of interaction.")
250
+
251
+ responses.append(TextPacket(source=self.instance_name, content=response, id=conv_id))
252
+ container.texts.extend(responses)
253
+ return container
254
+
255
+ def execute(self, container: DataContainer) -> DataContainer:
256
+ """
257
+ Executes the LLMChatTemplate by processing the input `DataContainer`
258
+ and generating a response.
259
+
260
+ This method is responsible for handling the conversation flow, processing the input,
261
+ and returning a response. It also ensures that the model has a prompt or previous conversation
262
+ to work with.
263
+
264
+ Args:
265
+ container (DataContainer): Input data container containing texts.
266
+
267
+ Returns:
268
+ DataContainer: The output data container with the model's response added to the `texts` attribute.
269
+ """
270
+ if not container.texts and not self.attributes.prompt:
271
+ self.logger.debug("No need to process response.")
272
+ return container
273
+
274
+ container = self.generate_response(container)
275
+ return container
@@ -0,0 +1,103 @@
1
+ # -*- coding: utf-8 -*-
2
+ import abc
3
+ from typing import Any
4
+
5
+ from sinapsis_core.data_containers.data_packet import DataContainer
6
+ from sinapsis_core.template_base import Template, TemplateAttributes
7
+
8
+
9
+ class QueryContextualize(Template, abc.ABC):
10
+ """A base class for contextualizing queries based on certain keywords."""
11
+
12
+ class AttributesBaseModel(TemplateAttributes):
13
+ """Attributes for contextualization.
14
+
15
+ Attributes:
16
+ keywords (list[str]): A list of keywords to be used for retrieving context.
17
+ """
18
+
19
+ keywords: list[str]
20
+
21
+ @abc.abstractmethod
22
+ def retrieve_context(self, keyword: str, context_data: dict | Any) -> str:
23
+ """
24
+ Abstract method to retrieve context related to a given keyword.
25
+
26
+ This method must be implemented by subclasses. The implementation should
27
+ return context information associated with the provided `keyword`.
28
+
29
+ Args:
30
+ keyword (str): The keyword for which context is to be retrieved.
31
+ context_data (dict | Any): The data source (could be a dictionary or any other type)
32
+ from which the context information will be retrieved.
33
+
34
+ Returns:
35
+ str: The context related to the provided keyword.
36
+ The return type should be a string representing the relevant context.
37
+ If no context is found, the method should return an empty string.
38
+ """
39
+
40
+ def load_context(self, container: DataContainer) -> None:
41
+ """
42
+ Loads context into the text packets within the provided `DataContainer`
43
+ based on keywords.
44
+
45
+ This method iterates over the text packets in the container and appends the
46
+ retrieved context for each keyword found in the packet's content. It retrieves
47
+ the context using the `retrieve_context` method and appends it to the text
48
+ packet's content.
49
+
50
+ Args:
51
+ container (DataContainer): A container holding the text packets that
52
+ need contextualization.
53
+
54
+ The method checks each text packet in the container, looks for keywords in the
55
+ packet's content, and appends the corresponding context
56
+ (retrieved via `retrieve_context`) to the content if found.
57
+ """
58
+
59
+ for text_packet in container.texts:
60
+ context: str = ""
61
+ for keyword in self.attributes.keywords:
62
+ if keyword in text_packet.content:
63
+ context += self.add_context_to_content(keyword, container)
64
+
65
+ if context:
66
+ text_packet.content += f" here is the context: {context}"
67
+
68
+ if context:
69
+ text_packet.content += f" here is the context: {context}"
70
+
71
+ @abc.abstractmethod
72
+ def add_context_to_content(self, kwd: str, container: DataContainer) -> str:
73
+ """
74
+ Depending on the keyword, append the additional context to the current one
75
+ Args:
76
+ kwd (str): kwd to be added in the context
77
+ container (DataContainer): Container where additional context comes from
78
+ Returns:
79
+ str : The updated context
80
+ """
81
+
82
+ def execute(self, container: DataContainer) -> DataContainer:
83
+ """
84
+ Executes the contextualization process on the provided DataContainer.
85
+
86
+ Args:
87
+ container (DataContainer): A container holding the texts that need
88
+ contextualization.
89
+
90
+ Returns:
91
+ DataContainer: The updated DataContainer with the added context to its
92
+ texts.
93
+
94
+ This method checks if there are texts to process and then loads context into the
95
+ container
96
+ using the `load_context` method.
97
+ """
98
+ if not container.texts:
99
+ self.logger.info("No query to process.")
100
+ return container
101
+ self.load_context(container)
102
+
103
+ return container
@@ -0,0 +1,88 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Any
3
+
4
+ from sinapsis_core.data_containers.data_packet import DataContainer
5
+
6
+ from sinapsis_chatbots_base.templates.query_contextualize import (
7
+ QueryContextualize,
8
+ )
9
+
10
+
11
+ class QueryContextualizeFromFile(QueryContextualize):
12
+ """A subclass of QueryContextualize that retrieves context from files loaded into
13
+ the `generic_data`
14
+ of a DataContainer.
15
+
16
+ This class overrides the `retrieve_context` method to provide context retrieval
17
+ from data files that have been previously read and stored in the `generic_data`
18
+ attribute of a DataContainer. It checks if the provided keyword matches a key
19
+ in the `generic_keys` attribute and then retrieves the associated context
20
+ (in the form of `page_content`) from the `generic_data`.
21
+
22
+ This subclass is intended for use cases where the context is dynamically loaded
23
+ from external files (using a different template or process) and retrieved
24
+ using keywords found in the content.
25
+
26
+
27
+ """
28
+
29
+ class AttributesBaseModel(QueryContextualize.AttributesBaseModel):
30
+ """This class extends the AttributesBaseModel of the parent
31
+ `QueryContextualize`.
32
+
33
+ Attributes:
34
+ keywords (list[str]): A list of keywords to be used for retrieving context.
35
+ generic_keys (list[str]): A list of keywords that can be used to retrieve
36
+ specific context data from the `generic_data` of the container.
37
+ """
38
+
39
+ generic_keys: list[str]
40
+
41
+ def retrieve_context(self, keyword: str, context_data: dict | Any) -> str:
42
+ """Retrieve the context associated with the given keyword from the provided
43
+ context data.
44
+
45
+ This method first checks if the `keyword` exists in the `generic_keys` attribute
46
+ of the current instance.
47
+ If a match is found, it then looks for the corresponding context data in the
48
+ `context_data` passed to the method. If the `keyword` is found in both
49
+ `generic_keys` and `context_data`, it returns the `page_content`
50
+ associated with that keyword.
51
+
52
+ If no match is found in either `generic_keys` or `context_data`, the method
53
+ returns an empty string.
54
+
55
+ Args:
56
+ keyword (str): The key for which the context value is to be retrieved.
57
+ This should correspond to an entry in the `generic_keys` attribute
58
+ of the current instance or a key in the `context_data`.
59
+ context_data (dict[str, Any]): A dictionary or any data source containing
60
+ additional context data. The data should include relevant content
61
+ associated with the `keyword`, typically in the form of `page_content`.
62
+
63
+ Returns:
64
+ str: The context value (i.e., `page_content`) associated with the `keyword`
65
+ if found in both `generic_keys` and `context_data`; otherwise, an empty
66
+ string if no match is found.
67
+ """
68
+ matching_key = next(
69
+ (key for key in self.attributes.generic_keys if keyword.lower() in key.lower()),
70
+ None,
71
+ )
72
+ if matching_key and matching_key in context_data:
73
+ return context_data[matching_key][0].page_content
74
+ return ""
75
+
76
+ def add_context_to_content(self, kwd: str, container: DataContainer) -> str:
77
+ """
78
+ Depending on the keyword, append the additional context to the current one
79
+ Args:
80
+ kwd (str): kwd to be added in the context
81
+ container (DataContainer): Container where additional context comes from
82
+ Returns:
83
+ str : The updated context
84
+ """
85
+
86
+ context = self.retrieve_context(kwd, container.generic_data) + "\n"
87
+
88
+ return context