File size: 13,616 Bytes
a0ad413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using deprecated Together LLM. Please use langchain_together instead.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os \n",
    "from dotenv import load_dotenv\n",
    "\n",
    "from langchain_community.document_loaders.csv_loader import CSVLoader\n",
    "from langchain_community.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores import Vectara\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "\n",
    "try:\n",
    "    from langchain_together import Together\n",
    "except:\n",
    "    print('Using deprecated Together LLM. Please use langchain_together instead.')\n",
    "    from langchain_community.llms import Together\n",
    "\n",
    "MODEL_NAME = \"mistralai/Mixtral-8x7B-Instruct-v0.1\"\n",
    "\n",
    "load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "vectara_customer_id = os.environ['VECTARA_CUSTOMER_ID']\n",
    "vectara_corpus_id = os.environ['VECTARA_CORPUS_ID']\n",
    "vectara_api_key = os.environ['VECTARA_API_KEY']\n",
    "\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"intfloat/multilingual-e5-large\")\n",
    "\n",
    "vectara = Vectara(vectara_customer_id=vectara_customer_id,\n",
    "                      vectara_corpus_id=vectara_corpus_id,\n",
    "                      vectara_api_key=vectara_api_key)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'ChatPromptTemplate' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[2], line 16\u001b[0m\n\u001b[1;32m      1\u001b[0m template \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[1;32m      2\u001b[0m \u001b[38;5;124mpassage: You are a helpful assistant that understands BIM building documents and engineering disciplines, specifically related to \u001b[39m\u001b[38;5;132;01m{discipline}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\n\u001b[1;32m      3\u001b[0m \u001b[38;5;124mpassage: You will analyze two sets of BIM document metadata comprising of filename, description, and discipline. One set of metadata was automatically generated by AI in English, and the other was annotated by a human in German with a letter prefix.\u001b[39m\n\u001b[0;32m   (...)\u001b[0m\n\u001b[1;32m     14\u001b[0m \u001b[38;5;124mquery: \u001b[39m\u001b[38;5;132;01m{question}\u001b[39;00m\n\u001b[1;32m     15\u001b[0m \u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[0;32m---> 16\u001b[0m prompt \u001b[38;5;241m=\u001b[39m \u001b[43mChatPromptTemplate\u001b[49m\u001b[38;5;241m.\u001b[39mfrom_template(template)\n",
      "\u001b[0;31mNameError\u001b[0m: name 'ChatPromptTemplate' is not defined"
     ]
    }
   ],
   "source": [
    "template = \"\"\"\n",
    "passage: You are a helpful assistant that understands BIM building documents and engineering disciplines, specifically related to {discipline}.\n",
    "passage: You will analyze two sets of BIM document metadata comprising of filename, description, and discipline. One set of metadata was automatically generated by AI in English, and the other was annotated by a human in German with a letter prefix.\n",
    "passage: It is expected that several sets of annotated metadata are incorrect. You will translate the annotated metadata into English and determine if the information is contextually similar between each other.\n",
    "passage: If the metadata sets are somewhat similar, you will advise so. If they are too different, you will specify that the annotated metadata is an anomaly. An anomaly is defined as metadata that is significantly different from the automatically generated metadata or does not match the expected format.\n",
    "passage: Here are some examples of correct and incorrect metadata sets:\n",
    "passage: Correct metadata set:\n",
    "passage: Filename: ISB-020-U3-W-H-01-B17012-001-000.pdf, Description: Novocon S demontiert und Stellantriebe montiert, passage: Discipline: H - Heizung\n",
    "passage: Incorrect metadata set:\n",
    "passage: Filename: incorrect_document.pdf\n",
    "passage: Description: This document contains specifications for the plumbing system in the building.\n",
    "passage: Discipline: Electrical\n",
    "passage: {context}\n",
    "query: {question}\n",
    "\"\"\"\n",
    "prompt = ChatPromptTemplate.from_template(template)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever = vectara.as_retriever()\n",
    "\n",
    "model = Together(model=MODEL_NAME,\n",
    "        temperature=0.7,\n",
    "        max_tokens=256,\n",
    "        top_k=50,\n",
    "        together_api_key=os.environ[\"TOGETHER_API_KEY\"]\n",
    "        )\n",
    "\n",
    "chain = (\n",
    "    {\"context\": retriever, \"question\": RunnablePassthrough()}\n",
    "    | prompt\n",
    "    | model\n",
    "    | StrOutputParser()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "example_metadata = {\"filename\":\"BedienungsanleitungFlanschen-Schieber\", \n",
    "                    \"description\":\"User manual for Flanschen-Schieber (Flange valves) PN 16. It includes information about storage, handling, transport, safety instructions, usage, product description, mounting, demounting, and spare parts.\",\n",
    "                    \"discipline\":\"plumbing\"}\n",
    "madeup_meta = {'name':'electrical_doc.pdf',\n",
    "               'description': 'Electrical wiring scheme and specifications for a generator room',\n",
    "               'discipline':'ventilation'}\n",
    "\n",
    "input_query = f'automatically_generated_metadata: {madeup_meta}, annotated_metadata: {example_metadata}'\n",
    "\n",
    "output = chain.invoke(input_query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "example_metadata = {\"filename\":\"BedienungsanleitungFlanschen-Schieber\", \n",
    "                    \"description\":\"User manual for Flanschen-Schieber (Flange valves) PN 16. It includes information about storage, handling, transport, safety instructions, usage, product description, mounting, demounting, and spare parts.\",\n",
    "                    \"discipline\":\"plumbing\"}\n",
    "real_meta = {'name':'ISB-020-U3-W-S-01-B18003-001-020.pdf',\n",
    "               'description': 'Schieber / Hawle / Schieber 4000 + Handrad 7800 DN100 Schutzraum',\n",
    "               'discipline':'S - Sanitaer'}\n",
    "\n",
    "input_query = f'automatically_generated_metadata: {real_meta}, annotated_metadata: {example_metadata}'\n",
    "\n",
    "output = chain.invoke(input_query)\t  \t\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"\\nBased on the provided passage and query, the automatically generated metadata and the annotated metadata are different in terms of filename, description, and discipline. The automatically generated metadata refers to a specific document with the name 'ISB-020-U3-W-S-01-B18003-001-020.pdf', a description 'Schieber / Hawle / Schieber 4000 + Handrad 7800 DN100 Schutzraum', and a discipline 'S - Sanitaer'. On the other hand, the annotated metadata refers to a user manual for Flanschen-Schieber (Flange valves) PN 16 with a filename 'BedienungsanleitungFlanschen-Schieber', a description that includes information about storage, handling, transport, safety instructions, usage, product description, mounting, demounting, and spare parts, and a discipline 'plumbing'. Therefore, the annotated metadata can be considered an anomaly in this case.\""
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "summary_config = {\"is_enabled\": True, \"max_results\": 3, \"response_lang\": \"eng\"}\n",
    "retriever = vectara.as_retriever(\n",
    "    search_kwargs={\"k\": 3, \"summary_config\": summary_config}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_sources(documents):\n",
    "    return documents[:-1]\n",
    "\n",
    "\n",
    "def get_summary(documents):\n",
    "    return documents[-1].page_content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The metadata set provided appears to be related to plumbing, specifically Flanschen-Schieber (Flange valves) PN 16. The description includes details about storage, handling, transport, safety instructions, usage, product description, mounting, demounting, and spare parts. The discipline associated with this metadata is plumbing [3]. The filenames and descriptions of various files related to plumbing and ventilation systems are listed in the search results, indicating a match with the usual schema for such metadata sets [2, 3].'"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query_str = f'Does this metadata set match the usual schema or is it an anomaly? metadata:{example_metadata}'\n",
    "ans = (retriever | get_summary).invoke(query_str)\n",
    "ans \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The metadata set provided with the name \"ISB-020-U3-W-S-01-B18003-001-020.pdf,\" description \"Schieber / Hawle / Schieber 4000 + Handrad 7800 DN100 Schutzraum,\" and discipline \"S - Sanitaer\" matches the usual schema as it follows the pattern of other entries such as \"ISB-020-U3-W-S-01-B17012-011-000\" with a similar structure and discipline [160]. The discipline \"S - Sanitaer\" is consistent with entries like \"ISB-020-U3-W-S-01-B19009-001-020\" that also belong to the Sanitaer discipline [161]. The description detailing specific items like \"Schieber / Hawle / Schieber 4000 + Handrad 7800 DN100 Schutzraum\" aligns with the content found in other entries under the same discipline [162]. The metadata set appears to be in line with the expected schema and does not seem to be an anomaly based on the available search results.'"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query_str = f\"\"\"Does this metadata set match the usual schema or is it an anomaly? metadata:\n",
    "{real_meta}\"\"\"\n",
    "ans = (retriever | get_summary).invoke(query_str)\n",
    "ans \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"The metadata provided for 'electrical_doc.pdf' does not appear to match the usual schema for electrical documents. The discipline specified as 'ventilation' seems to be inconsistent with typical electrical document schemas [3]. The descriptions and names in the search results are more aligned with electrical systems rather than ventilation [10, 12, 13]. This indicates a potential anomaly in the metadata provided, suggesting a deviation from the expected schema for electrical documentation. It would be advisable to review the metadata to ensure accuracy and alignment with the appropriate discipline to avoid any confusion or misinterpretation of the document's content.\""
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query_str = f\"\"\"query: Does this metadata in either english or german set match the usual schema or is it an anomaly? metadata:\n",
    "{madeup_meta}.\"\"\"\n",
    "ans = (retriever | get_summary).invoke(query_str)\n",
    "ans \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}