spark-nlp 5.5.0rc1__py2.py3-none-any.whl → 5.5.1__py2.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.

Potentially problematic release.


This version of spark-nlp might be problematic. Click here for more details.

@@ -0,0 +1,207 @@
1
+ # Copyright 2017-2024 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains classes for the PromptAssembler."""
15
+
16
+ from pyspark import keyword_only
17
+ from pyspark.ml.param import TypeConverters, Params, Param
18
+
19
+ from sparknlp.common import AnnotatorType
20
+ from sparknlp.internal import AnnotatorTransformer
21
+
22
+
23
+ class PromptAssembler(AnnotatorTransformer):
24
+ """Assembles a sequence of messages into a single string using a template. These strings can then
25
+ be used as prompts for large language models.
26
+
27
+ This annotator expects an array of two-tuples as the type of the input column (one array of
28
+ tuples per row). The first element of the tuples should be the role and the second element is
29
+ the text of the message. Possible roles are "system", "user" and "assistant".
30
+
31
+ An assistant header can be added to the end of the generated string by using
32
+ ``setAddAssistant(True)``.
33
+
34
+ At the moment, this annotator uses llama.cpp as a backend to parse and apply the templates.
35
+ llama.cpp uses basic pattern matching to determine the type of the template, then applies a
36
+ basic version of the template to the messages. This means that more advanced templates are not
37
+ supported.
38
+
39
+ For an extended example see the
40
+ `example notebook <https://github.com/JohnSnowLabs/spark-nlp/blob/master/examples/python/llama.cpp/PromptAssember_with_AutoGGUFModel.ipynb>`__.
41
+
42
+ ====================== ======================
43
+ Input Annotation types Output Annotation type
44
+ ====================== ======================
45
+ ``NONE`` ``DOCUMENT``
46
+ ====================== ======================
47
+
48
+ Parameters
49
+ ----------
50
+ inputCol
51
+ Input column name
52
+ outputCol
53
+ Output column name
54
+ chatTemplate
55
+ Template used for the chat
56
+ addAssistant
57
+ Whether to add an assistant header to the end of the generated string
58
+
59
+ Examples
60
+ --------
61
+ >>> from sparknlp.base import *
62
+ >>> messages = [
63
+ ... [
64
+ ... ("system", "You are a helpful assistant."),
65
+ ... ("assistant", "Hello there, how can I help you?"),
66
+ ... ("user", "I need help with organizing my room."),
67
+ ... ]
68
+ ... ]
69
+ >>> df = spark.createDataFrame([messages]).toDF("messages")
70
+ >>> template = (
71
+ ... "{{- bos_token }} {%- if custom_tools is defined %} {%- set tools = custom_tools %} {%- "
72
+ ... "endif %} {%- if not tools_in_user_message is defined %} {%- set tools_in_user_message = true %} {%- "
73
+ ... 'endif %} {%- if not date_string is defined %} {%- set date_string = "26 Jul 2024" %} {%- endif %} '
74
+ ... "{%- if not tools is defined %} {%- set tools = none %} {%- endif %} {#- This block extracts the "
75
+ ... "system message, so we can slot it into the right place. #} {%- if messages[0]['role'] == 'system' %}"
76
+ ... " {%- set system_message = messages[0]['content']|trim %} {%- set messages = messages[1:] %} {%- else"
77
+ ... ' %} {%- set system_message = "" %} {%- endif %} {#- System message + builtin tools #} {{- '
78
+ ... '"<|start_header_id|>system<|end_header_id|>\\n\\n" }} {%- if builtin_tools is defined or tools is '
79
+ ... 'not none %} {{- "Environment: ipython\\n" }} {%- endif %} {%- if builtin_tools is defined %} {{- '
80
+ ... '"Tools: " + builtin_tools | reject(\\'equalto\', \\'code_interpreter\\') | join(", ") + "\\n\\n"}} '
81
+ ... '{%- endif %} {{- "Cutting Knowledge Date: December 2023\\n" }} {{- "Today Date: " + date_string '
82
+ ... '+ "\\n\\n" }} {%- if tools is not none and not tools_in_user_message %} {{- "You have access to '
83
+ ... 'the following functions. To call a function, please respond with JSON for a function call." }} {{- '
84
+ ... '\\'Respond in the format {"name": function name, "parameters": dictionary of argument name and its'
85
+ ... ' value}.\\' }} {{- "Do not use variables.\\n\\n" }} {%- for t in tools %} {{- t | tojson(indent=4) '
86
+ ... '}} {{- "\\n\\n" }} {%- endfor %} {%- endif %} {{- system_message }} {{- "<|eot_id|>" }} {#- '
87
+ ... "Custom tools are passed in a user message with some extra guidance #} {%- if tools_in_user_message "
88
+ ... "and not tools is none %} {#- Extract the first user message so we can plug it in here #} {%- if "
89
+ ... "messages | length != 0 %} {%- set first_user_message = messages[0]['content']|trim %} {%- set "
90
+ ... 'messages = messages[1:] %} {%- else %} {{- raise_exception("Cannot put tools in the first user '
91
+ ... "message when there's no first user message!\\") }} {%- endif %} {{- "
92
+ ... "'<|start_header_id|>user<|end_header_id|>\\n\\n' -}} {{- \\"Given the following functions, please "
93
+ ... 'respond with a JSON for a function call " }} {{- "with its proper arguments that best answers the '
94
+ ... 'given prompt.\\n\\n" }} {{- \\'Respond in the format {"name": function name, "parameters": '
95
+ ... 'dictionary of argument name and its value}.\\' }} {{- "Do not use variables.\\n\\n" }} {%- for t in '
96
+ ... 'tools %} {{- t | tojson(indent=4) }} {{- "\\n\\n" }} {%- endfor %} {{- first_user_message + '
97
+ ... "\\"<|eot_id|>\\"}} {%- endif %} {%- for message in messages %} {%- if not (message.role == 'ipython' "
98
+ ... "or message.role == 'tool' or 'tool_calls' in message) %} {{- '<|start_header_id|>' + message['role']"
99
+ ... " + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }} {%- elif 'tool_calls' in "
100
+ ... 'message %} {%- if not message.tool_calls|length == 1 %} {{- raise_exception("This model only '
101
+ ... 'supports single tool-calls at once!") }} {%- endif %} {%- set tool_call = message.tool_calls[0]'
102
+ ... ".function %} {%- if builtin_tools is defined and tool_call.name in builtin_tools %} {{- "
103
+ ... "'<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}} {{- \\"<|python_tag|>\\" + tool_call.name + "
104
+ ... '".call(" }} {%- for arg_name, arg_val in tool_call.arguments | items %} {{- arg_name + \\'="\\' + '
105
+ ... 'arg_val + \\'"\\' }} {%- if not loop.last %} {{- ", " }} {%- endif %} {%- endfor %} {{- ")" }} {%- '
106
+ ... "else %} {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}} {{- '{\\"name\": \\"' + "
107
+ ... 'tool_call.name + \\'", \\' }} {{- \\'"parameters": \\' }} {{- tool_call.arguments | tojson }} {{- "}" '
108
+ ... "}} {%- endif %} {%- if builtin_tools is defined %} {#- This means we're in ipython mode #} {{- "
109
+ ... '"<|eom_id|>" }} {%- else %} {{- "<|eot_id|>" }} {%- endif %} {%- elif message.role == "tool" '
110
+ ... 'or message.role == "ipython" %} {{- "<|start_header_id|>ipython<|end_header_id|>\\n\\n" }} {%- '
111
+ ... "if message.content is mapping or message.content is iterable %} {{- message.content | tojson }} {%- "
112
+ ... 'else %} {{- message.content }} {%- endif %} {{- "<|eot_id|>" }} {%- endif %} {%- endfor %} {%- if '
113
+ ... "add_generation_prompt %} {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }} {%- endif %} "
114
+ ... )
115
+ >>> prompt_assembler = (
116
+ ... PromptAssembler()
117
+ ... .setInputCol("messages")
118
+ ... .setOutputCol("prompt")
119
+ ... .setChatTemplate(template)
120
+ ... )
121
+ >>> prompt_assembler.transform(df).select("prompt.result").show(truncate=False)
122
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
123
+ |result |
124
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
125
+ |[<|start_header_id|>system<|end_header_id|>\n\nYou are a helpful assistant.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nHello there, how can I help you?<|eot_id|><|start_header_id|>user<|end_header_id|>\n\nI need help with organizing my room.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n]|
126
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
127
+ """
128
+
129
+ outputAnnotatorType = AnnotatorType.DOCUMENT
130
+
131
+ inputCol = Param(
132
+ Params._dummy(),
133
+ "inputCol",
134
+ "input column name",
135
+ typeConverter=TypeConverters.toString,
136
+ )
137
+ outputCol = Param(
138
+ Params._dummy(),
139
+ "outputCol",
140
+ "output column name",
141
+ typeConverter=TypeConverters.toString,
142
+ )
143
+ chatTemplate = Param(
144
+ Params._dummy(),
145
+ "chatTemplate",
146
+ "Template used for the chat",
147
+ typeConverter=TypeConverters.toString,
148
+ )
149
+ addAssistant = Param(
150
+ Params._dummy(),
151
+ "addAssistant",
152
+ "Whether to add an assistant header to the end of the generated string",
153
+ typeConverter=TypeConverters.toBoolean,
154
+ )
155
+ name = "PromptAssembler"
156
+
157
+ @keyword_only
158
+ def __init__(self):
159
+ super(PromptAssembler, self).__init__(
160
+ classname="com.johnsnowlabs.nlp.PromptAssembler"
161
+ )
162
+ self._setDefault(outputCol="prompt", addAssistant=True)
163
+
164
+ @keyword_only
165
+ def setParams(self):
166
+ kwargs = self._input_kwargs
167
+ return self._set(**kwargs)
168
+
169
+ def setInputCol(self, value):
170
+ """Sets input column name.
171
+
172
+ Parameters
173
+ ----------
174
+ value : str
175
+ Name of the input column
176
+ """
177
+ return self._set(inputCol=value)
178
+
179
+ def setOutputCol(self, value):
180
+ """Sets output column name.
181
+
182
+ Parameters
183
+ ----------
184
+ value : str
185
+ Name of the Output Column
186
+ """
187
+ return self._set(outputCol=value)
188
+
189
+ def setChatTemplate(self, value):
190
+ """Sets the chat template.
191
+
192
+ Parameters
193
+ ----------
194
+ value : str
195
+ Template used for the chat
196
+ """
197
+ return self._set(chatTemplate=value)
198
+
199
+ def setAddAssistant(self, value):
200
+ """Sets whether to add an assistant header to the end of the generated string.
201
+
202
+ Parameters
203
+ ----------
204
+ value : bool
205
+ Whether to add an assistant header to the end of the generated string
206
+ """
207
+ return self._set(addAssistant=value)
@@ -113,6 +113,13 @@ class _BertQuestionAnsweringLoader(ExtendedJavaWrapper):
113
113
  jspark,
114
114
  )
115
115
 
116
+ class _BertMultipleChoiceLoader(ExtendedJavaWrapper):
117
+ def __init__(self, path, jspark):
118
+ super(_BertMultipleChoiceLoader, self).__init__(
119
+ "com.johnsnowlabs.nlp.annotators.classifier.dl.BertForMultipleChoice.loadSavedModel",
120
+ path,
121
+ jspark,
122
+ )
116
123
 
117
124
  class _DeBERTaLoader(ExtendedJavaWrapper):
118
125
  def __init__(self, path, jspark):