Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

llm_interactive.py 12 KB

You have to be logged in to leave a comment. Sign In
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
325
326
327
328
329
330
331
332
333
334
  1. import logging
  2. import json
  3. import difflib
  4. import re
  5. import os
  6. import requests
  7. import pytesseract
  8. from PIL import Image, ImageOps
  9. from io import BytesIO
  10. from typing import Union, List, Dict, Optional, Any, Tuple
  11. from tenacity import retry, stop_after_attempt, wait_random
  12. from openai import OpenAI, AzureOpenAI
  13. from label_studio_ml.model import LabelStudioMLBase
  14. from label_studio_ml.response import ModelResponse
  15. from label_studio_sdk.label_interface.objects import PredictionValue
  16. from label_studio_sdk.label_interface.object_tags import ImageTag, ParagraphsTag
  17. from label_studio_sdk.label_interface.control_tags import ControlTag, ObjectTag
  18. import dagshub
  19. import mlflow
  20. conda_env = {'channels': ['defaults'],
  21. 'dependencies': [
  22. 'python~=3.10',
  23. 'pip',
  24. {'pip': ['mlflow',
  25. 'openai',
  26. 'tenacity',
  27. 'pillow',
  28. 'requests',
  29. 'pytesseract']}],
  30. 'name': 'env'}
  31. logger = logging.getLogger(__name__)
  32. class LLMInteractive(mlflow.pyfunc.PythonModel):
  33. OPENAI_PROVIDER = os.getenv("OPENAI_PROVIDER", "openai")
  34. OPENAI_KEY = os.getenv('OPENAI_API_KEY')
  35. PROMPT_PREFIX = os.getenv("PROMPT_PREFIX", "prompt")
  36. USE_INTERNAL_PROMPT_TEMPLATE = bool(int(os.getenv("USE_INTERNAL_PROMPT_TEMPLATE", 1)))
  37. # if set, this prompt will be used at the beginning of the session
  38. DEFAULT_PROMPT = os.getenv('DEFAULT_PROMPT')
  39. PROMPT_TEMPLATE = os.getenv("PROMPT_TEMPLATE", '**Source Text**:\n\n"{text}"\n\n**Task Directive**:\n\n"{prompt}"')
  40. PROMPT_TAG = "TextArea"
  41. SUPPORTED_INPUTS = ("Image", "Text", "HyperText", "Paragraphs")
  42. NUM_RESPONSES = int(os.getenv("NUM_RESPONSES", 1))
  43. TEMPERATURE = float(os.getenv("TEMPERATURE", 0.7))
  44. OPENAI_MODEL = os.getenv("OPENAI_MODEL")
  45. AZURE_RESOURCE_ENDPOINT = os.getenv("AZURE_RESOURCE_ENDPOINT", '')
  46. AZURE_DEPLOYMENT_NAME = os.getenv("AZURE_DEPLOYMENT_NAME")
  47. AZURE_API_VERSION = os.getenv("AZURE_API_VERSION", "2023-05-15")
  48. OLLAMA_ENDPOINT = os.getenv("OLLAMA_ENDPOINT")
  49. @retry(wait=wait_random(min=5, max=10), stop=stop_after_attempt(6))
  50. def chat_completion_call(self, messages, params, *args, **kwargs):
  51. """
  52. Request to OpenAI API (OpenAI, Azure)
  53. Args:
  54. messages: list of messages
  55. params: dict with parameters
  56. Example:
  57. ```json
  58. {
  59. "api_key": "YOUR_API_KEY",
  60. "provider": "openai",
  61. "model": "gpt-4",
  62. "num_responses": 1,
  63. "temperature": 0.7
  64. }```
  65. """
  66. provider = params.get("provider", self.OPENAI_PROVIDER)
  67. model = params.get("model", self.OPENAI_MODEL)
  68. if provider == "openai":
  69. client = OpenAI(
  70. api_key=params.get("api_key", self.OPENAI_KEY),
  71. )
  72. if not model:
  73. model = 'gpt-3.5-turbo'
  74. elif provider == "azure":
  75. client = AzureOpenAI(
  76. api_key=params.get("api_key", self.OPENAI_KEY),
  77. api_version=params.get("api_version", self.AZURE_API_VERSION),
  78. azure_endpoint=params.get('resource_endpoint', self.AZURE_RESOURCE_ENDPOINT).rstrip('/'),
  79. azure_deployment=params.get('deployment_name', self.AZURE_DEPLOYMENT_NAME)
  80. )
  81. if not model:
  82. model = 'gpt-35-turbo'
  83. elif provider == "ollama":
  84. client = OpenAI(
  85. base_url=params.get('base_url', self.OLLAMA_ENDPOINT),
  86. # required but ignored
  87. api_key='ollama',
  88. )
  89. else:
  90. raise
  91. request_params = {
  92. "messages": messages,
  93. "model": model,
  94. "n": params.get("num_responses", self.NUM_RESPONSES),
  95. "temperature": params.get("temperature", self.TEMPERATURE)
  96. }
  97. completion = client.chat.completions.create(**request_params)
  98. return completion
  99. def gpt(messages: Union[List[Dict], str], params, *args, **kwargs):
  100. """
  101. """
  102. if isinstance(messages, str):
  103. messages = [{"role": "user", "content": messages}]
  104. logger.debug(f"OpenAI request: {messages}, params={params}")
  105. completion = self.chat_completion_call(messages, params)
  106. logger.debug(f"OpenAI response: {completion}")
  107. response = [choice.message.content for choice in completion.choices]
  108. return response
  109. def setup(self):
  110. if self.DEFAULT_PROMPT and os.path.isfile(self.DEFAULT_PROMPT):
  111. logger.info(f"Reading default prompt from file: {self.DEFAULT_PROMPT}")
  112. with open(self.DEFAULT_PROMPT) as f:
  113. self.DEFAULT_PROMPT = f.read()
  114. def _ocr(self, image_url):
  115. # Open the image containing the text
  116. response = requests.get(image_url)
  117. image = Image.open(BytesIO(response.content))
  118. image = ImageOps.exif_transpose(image)
  119. # Run OCR on the image
  120. text = pytesseract.image_to_string(image)
  121. return text
  122. def _get_text(self, task_data, object_tag):
  123. """
  124. """
  125. data = task_data.get(object_tag.value_name)
  126. if data is None:
  127. return None
  128. if isinstance(object_tag, ImageTag):
  129. return self._ocr(data)
  130. elif isinstance(object_tag, ParagraphsTag):
  131. return json.dumps(data)
  132. else:
  133. return data
  134. def _get_prompts(self, context, prompt_tag) -> List[str]:
  135. """Getting prompt values
  136. """
  137. if context:
  138. # Interactive mode - get prompt from context
  139. result = context.get('result')
  140. for item in result:
  141. if item.get('from_name') == prompt_tag.name:
  142. return item['value']['text']
  143. # Initializing - get existing prompt from storage
  144. elif prompt := self.get(prompt_tag.name):
  145. return [prompt]
  146. # Default prompt
  147. elif self.DEFAULT_PROMPT:
  148. if self.USE_INTERNAL_PROMPT_TEMPLATE:
  149. logger.error('Using both `DEFAULT_PROMPT` and `USE_INTERNAL_PROMPT_TEMPLATE` is not supported. '
  150. 'Please either specify `USE_INTERNAL_PROMPT_TEMPLATE=0` or remove `DEFAULT_PROMPT`. '
  151. 'For now, no prompt will be used.')
  152. return []
  153. return [self.DEFAULT_PROMPT]
  154. return []
  155. def _match_choices(self, response: List[str], original_choices: List[str]) -> List[str]:
  156. # assuming classes are separated by newlines
  157. # TODO: support other guardrails
  158. matched_labels = []
  159. predicted_classes = response[0].splitlines()
  160. for pred in predicted_classes:
  161. scores = list(map(lambda l: difflib.SequenceMatcher(None, pred, l).ratio(), original_choices))
  162. matched_labels.append(original_choices[scores.index(max(scores))])
  163. return matched_labels
  164. def _find_choices_tag(self, object_tag):
  165. """Classification predictor
  166. """
  167. li = self.label_interface
  168. try:
  169. choices_from_name, _, _ = li.get_first_tag_occurence(
  170. 'Choices',
  171. self.SUPPORTED_INPUTS,
  172. to_name_filter=lambda s: s == object_tag.name,
  173. )
  174. return li.get_control(choices_from_name)
  175. except:
  176. return None
  177. def _find_textarea_tag(self, prompt_tag, object_tag):
  178. """Free-form text predictor
  179. """
  180. li = self.label_interface
  181. try:
  182. textarea_from_name, _, _ = li.get_first_tag_occurence(
  183. 'TextArea',
  184. self.SUPPORTED_INPUTS,
  185. name_filter=lambda s: s != prompt_tag.name,
  186. to_name_filter=lambda s: s == object_tag.name,
  187. )
  188. return li.get_control(textarea_from_name)
  189. except:
  190. return None
  191. def _find_prompt_tags(self) -> Tuple[ControlTag, ObjectTag]:
  192. """Find prompting tags in the config
  193. """
  194. li = self.label_interface
  195. prompt_from_name, prompt_to_name, value = li.get_first_tag_occurence(
  196. # prompt tag
  197. self.PROMPT_TAG,
  198. # supported input types
  199. self.SUPPORTED_INPUTS,
  200. # if multiple <TextArea> are presented, use one with prefix specified in PROMPT_PREFIX
  201. name_filter=lambda s: s.startswith(self.PROMPT_PREFIX))
  202. return li.get_control(prompt_from_name), li.get_object(prompt_to_name)
  203. def _validate_tags(self, choices_tag: str, textarea_tag: str) -> None:
  204. if not choices_tag and not textarea_tag:
  205. raise ValueError('No supported tags found: <Choices> or <TextArea>')
  206. def _generate_normalized_prompt(self, text: str, prompt: str, task_data: Dict, labels: Optional[List[str]]) -> str:
  207. """
  208. """
  209. if self.USE_INTERNAL_PROMPT_TEMPLATE:
  210. norm_prompt = self.PROMPT_TEMPLATE.format(text=text, prompt=prompt, labels=labels)
  211. else:
  212. norm_prompt = prompt.format(labels=labels, **task_data)
  213. return norm_prompt
  214. def _generate_response_regions(self, response: List[str], prompt_tag,
  215. choices_tag: ControlTag, textarea_tag: ControlTag, prompts: List[str]) -> List:
  216. """
  217. """
  218. regions = []
  219. if choices_tag and len(response) > 0:
  220. matched_labels = self._match_choices(response, choices_tag.labels)
  221. regions.append(choices_tag.label(matched_labels))
  222. if textarea_tag:
  223. regions.append(textarea_tag.label(text=response))
  224. # not sure why we need this but it was in the original code
  225. regions.append(prompt_tag.label(text=prompts))
  226. return regions
  227. def _predict_single_task(self, task_data: Dict, prompt_tag: Any, object_tag: Any, prompt: str,
  228. choices_tag: ControlTag, textarea_tag: ControlTag, prompts: List[str]) -> Dict:
  229. """
  230. """
  231. text = self._get_text(task_data, object_tag)
  232. # Add {labels} to the prompt if choices tag is present
  233. labels = choices_tag.labels if choices_tag else None
  234. norm_prompt = self._generate_normalized_prompt(text, prompt, task_data, labels=labels)
  235. # run inference
  236. # this are params provided through the web interface
  237. response = self.gpt(norm_prompt, self.extra_params)
  238. regions = self._generate_response_regions(response, prompt_tag, choices_tag, textarea_tag, prompts)
  239. return PredictionValue(result=regions, score=0.1, model_version=str(self.model_version))
  240. def predict(self, tasks: List[Dict], context: Optional[Dict] = None, **kwargs) -> ModelResponse:
  241. """
  242. """
  243. predictions = []
  244. # prompt tag contains the prompt in the config
  245. # object tag contains what we plan to label
  246. prompt_tag, object_tag = self._find_prompt_tags()
  247. prompts = self._get_prompts(context, prompt_tag)
  248. if prompts:
  249. prompt = "\n".join(prompts)
  250. choices_tag = self._find_choices_tag(object_tag)
  251. textarea_tag = self._find_textarea_tag(prompt_tag, object_tag)
  252. self._validate_tags(choices_tag, textarea_tag)
  253. for task in tasks:
  254. # preload all task data fields, they are needed for prompt
  255. task_data = open(task).read()
  256. pred = self._predict_single_task(task_data, prompt_tag, object_tag, prompt,
  257. choices_tag, textarea_tag, prompts)
  258. predictions.append(pred)
  259. return ModelResponse(predictions=predictions)
  260. def _prompt_diff(self, old_prompt, new_prompt):
  261. """
  262. """
  263. old_lines = old_prompt.splitlines()
  264. new_lines = new_prompt.splitlines()
  265. diff = difflib.unified_diff(old_lines, new_lines, lineterm="")
  266. return "\n".join(
  267. line for line in diff if line.startswith(('+',)) and not line.startswith(('+++', '---')))
  268. if __name__ == '__main__':
  269. dagshub.init('autolabelling-models', 'jinensetpal')
  270. model = LLMInteractive()
  271. with mlflow.start_run():
  272. mlflow.pyfunc.log_model(
  273. artifact_path='models',
  274. python_model=model,
  275. conda_env=conda_env,
  276. registered_model_name='llm_interactive')
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...