File size: 14,105 Bytes
7013379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import json
from collections import defaultdict
import openai
import re
from config import CFG_APP
from text_embedder import SentenceTransformersTextEmbedder
from datetime import datetime
import tiktoken

doc_metadata = json.load(open(CFG_APP.DOC_METADATA_PATH, "r"))
# Embedding Model
if "sentence-transformers" in CFG_APP.EMBEDDING_MODEL:
    text_embedder = SentenceTransformersTextEmbedder(
        model_name=CFG_APP.EMBEDDING_MODEL,
        paragraphs_path=CFG_APP.DATA_FOLDER,
        device=CFG_APP.DEVICE,
        load_existing_index=True,
    )
else:
    raise ValueError("Embedding model not found !")


# Util Functions
def retrieve_doc_metadata(doc_metadata, doc_id):
    for meta in doc_metadata:
        if meta["id"] == doc_id:
            return meta


def get_reformulation_prompt(query: str) -> list:
    return [
        {
            "role": "user",
            "content": f"""{CFG_APP.REFORMULATION_PROMPT}
            ---
            query: {query}
            standalone question: """,
        }
    ]

def get_hyde_prompt(query: str) -> list:
    return [
        {
            "role": "user",
            "content": f"""{CFG_APP.HYDE_PROMPT}
            ---
            query: {query}
            output: """,
        }
    ]


def make_pairs(lst):
    """From a list of even lenght, make tupple pairs
    Args:
        lst (list): a list of even lenght
    Returns:
        list: the list as tupple pairs
    """
    assert not (l := len(lst) % 2), f"your list is of lenght {l} which is not even"
    return [(lst[i], lst[i + 1]) for i in range(0, len(lst), 2)]


def make_html_source(paragraph, meta_doc, i):
    content = paragraph["content"]
    meta_paragraph = paragraph["meta"]
    return f"""
<div class="card" id="document-{i}">
    <div class="card-content">
        <h2>Excerpts {i} - Document {meta_doc['num_doc']} - Page {meta_paragraph['page_number']}</h2>
        <p>{content}</p>
    </div>
    <div class="card-footer">
        <span>{meta_doc['short_name']}</span>
        <a href="{meta_doc['url']}#page={meta_paragraph['page_number']}" target="_blank" class="pdf-link">
            <span role="img" aria-label="Open PDF">πŸ”—</span>
        </a>
    </div>
</div>
"""

def make_citations_source(citation_dic, query, Hyde: False):
    citation_list = [f'Doc {values[0]} - {keys} (excerpts {values[1]})' for keys, values in citation_dic.items()]

    html_output = '<div class="source">\n'
    html_output += '  <div class="title">Sources</div>\n'
    if Hyde :
        html_output += f'  <div>Query used for retrieval (with the HyDE technique after no response): {query}</div>\n'
    else :
        html_output += f'  <div>Query used for retrieval: {query}</div>\n'
    html_output += '  <br>\n'
    html_output += '  <ul>\n'

    for row in citation_list :
        html_output += f'<li>{row}</li>'

    html_output += '  </ul>\n'
    html_output += '</div>\n'

    return html_output


def preprocess_message(text: str, docs_url: dict) -> str:
    return re.sub(
        r"\[doc (\d+)\]",
        lambda match: f'<a href="{docs_url[match.group(1)]}" target="_blank" class="pdf-link">{match.group(0)}</a>',
        text,
    )


def parse_glossary(query):
    file = "glossary.json"
    glossary = json.load(open(file, "r"))
    words_query = query.split(" ")
    for i, word in enumerate(words_query):
        for key in glossary.keys():
            if word.lower() == key.lower():
                words_query[i] = words_query[i] + f" ({glossary[key]})"
    return " ".join(words_query)


def num_tokens_from_string(string: str, encoding_name: str) -> int:
    encoding = tiktoken.encoding_for_model(encoding_name)
    num_tokens = len(encoding.encode(string))
    return num_tokens


def chat(
    query: str,
    history: list,
    threshold: float = CFG_APP.THRESHOLD,
    k_total: int = CFG_APP.K_TOTAL,
) -> tuple:
    """retrieve relevant documents in the document store then query gpt-turbo
    Args:
        query (str): user message.
        history (list, optional): history of the conversation. Defaults to [system_template].
        report_type (str, optional): should be "All available" or "IPCC only". Defaults to "All available".
        threshold (float, optional): similarity threshold, don't increase more than 0.568. Defaults to 0.56.
    Yields:
        tuple: chat gradio format, chat openai format, sources used.
    """

    reformulated_query = openai.ChatCompletion.create(
        model=CFG_APP.MODEL_NAME,
        messages=get_reformulation_prompt(parse_glossary(query)),
        temperature=0,
        max_tokens=CFG_APP.MAX_TOKENS_REF_QUESTION,
    )

    reformulated_query = reformulated_query["choices"][0]["message"]["content"]

    if len(reformulated_query.split("\n")) == 2:
        reformulated_query, language = reformulated_query.split("\n")
        language = language.split(":")[1].strip()
    else:
        reformulated_query = reformulated_query.split("\n")[0]
        language = "English"

    sources, scores = text_embedder.retrieve_faiss(
        reformulated_query,
        k_total=k_total,
        threshold=threshold,
    )

    if CFG_APP.DEBUG == True:
        print("Scores : \n", scores)

    messages = history + [{"role": "user", "content": query}]

    docs_url = defaultdict(str)

    if len(sources) > 0:
        docs_string = []
        docs_html = []
        citations = {}

        num_tokens = num_tokens_from_string(CFG_APP.SOURCES_PROMPT, CFG_APP.MODEL_NAME)
        num_doc = 1

        for i, data in enumerate(sources, 1):
            meta_doc = retrieve_doc_metadata(doc_metadata, data["meta"]["document_id"])
            doc_content = f"πŸ“ƒ Doc {i}: \n{data['content']}"
            num_tokens_doc = num_tokens_from_string(doc_content, CFG_APP.MODEL_NAME)
            if num_tokens + num_tokens_doc > CFG_APP.MAX_TOKENS_API:
                break
            num_tokens += num_tokens_doc
            docs_string.append(doc_content)

            if meta_doc['short_name'] in citations.keys():
                citations[meta_doc['short_name']][1] += f', {i}'
            else :
                citations[meta_doc['short_name']] = [num_doc, f'{i}']
                num_doc += 1

            meta_doc["num_doc"] = citations[meta_doc['short_name']][0]

            docs_html.append(make_html_source(data, meta_doc, i))

            url_doc = f'<a href="{meta_doc["url"]}#page={data["meta"]["page_number"]}" target="_blank" class="pdf-link">'
            docs_url[i] = url_doc

        html_cit = [make_citations_source(citations, reformulated_query, Hyde=False)]

        docs_string = "\n\n".join( [f"Query used for retrieval:\n{reformulated_query}"] + docs_string)

        docs_html = "\n\n".join(html_cit + docs_html)

        messages.append(
            {
                "role": "system",
                "content": f"{CFG_APP.SOURCES_PROMPT}\n\n{docs_string}\n\nAnswer in {language}:",
            }
        )

        if CFG_APP.DEBUG == True:
            print(f" πŸ‘¨β€πŸ’» question asked by the user : {query}")
            print(f" πŸ•› time : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

            print(" πŸ”Œ messages sent to the API :")
            api_messages = [
                {"role": "system", "content": CFG_APP.INIT_PROMPT},
                {"role": "user", "content": reformulated_query},
                {
                    "role": "system",
                    "content": f"{CFG_APP.SOURCES_PROMPT}\n\n{docs_string}\n\nAnswer in {language}:",
                },
            ]
            for message in api_messages:
                print(
                    f"length : {len(message['content'])}, content : {message['content']}"
                )

        response = openai.ChatCompletion.create(
            model=CFG_APP.MODEL_NAME,
            messages=[
                {"role": "system", "content": CFG_APP.INIT_PROMPT},
                {"role": "user", "content": reformulated_query},
                {
                    "role": "system",
                    "content": f"{CFG_APP.SOURCES_PROMPT}\n\nVery important : Answer in {language}.\n\n{docs_string}:",
                },
            ],
            temperature=0,  # deterministic
            stream=True,
            max_tokens=CFG_APP.MAX_TOKENS_ANSWER,
        )
        complete_response = ""
        messages.pop()
        messages.append({"role": "assistant", "content": complete_response})
        for chunk in response:
            chunk_message = chunk["choices"][0]["delta"].get("content")
            if chunk_message:
                complete_response += chunk_message
                complete_response = preprocess_message(complete_response, docs_url)
                messages[-1]["content"] = complete_response
                gradio_format = make_pairs([a["content"] for a in messages[1:]])
                yield gradio_format, messages, docs_html

    else:
        reformulated_query = openai.ChatCompletion.create(
            model=CFG_APP.MODEL_NAME,
            messages=get_hyde_prompt(parse_glossary(query)),
            temperature=0,
            max_tokens=CFG_APP.MAX_TOKENS_REF_QUESTION,
        )

        reformulated_query = reformulated_query["choices"][0]["message"]["content"]

        if len(reformulated_query.split("\n")) == 2:
            reformulated_query, language = reformulated_query.split("\n")
            language = language.split(":")[1].strip()
        else:
            reformulated_query = reformulated_query.split("\n")[0]
            language = "English"

        sources, scores = text_embedder.retrieve_faiss(
            reformulated_query,
            k_total=k_total,
            threshold=threshold,
        )

        if CFG_APP.DEBUG == True:
            print("Scores : \n", scores)

        if len(sources) > 0 :
            docs_string = []
            docs_html = []
            citations = {}

            num_tokens = num_tokens_from_string(CFG_APP.SOURCES_PROMPT, CFG_APP.MODEL_NAME)

            num_doc = 1

            for i, data in enumerate(sources, 1):
                meta_doc = retrieve_doc_metadata(doc_metadata, data["meta"]["document_id"])
                doc_content = f"πŸ“ƒ Doc {i}: \n{data['content']}"
                num_tokens_doc = num_tokens_from_string(doc_content, CFG_APP.MODEL_NAME)
                if num_tokens + num_tokens_doc > CFG_APP.MAX_TOKENS_API:
                    break
                num_tokens += num_tokens_doc
                docs_string.append(doc_content)

                if meta_doc['short_name'] in citations.keys():
                    citations[meta_doc['short_name']][1] += f', {i}'
                else:
                    citations[meta_doc['short_name']] = [num_doc, f'{i}']
                    num_doc += 1

                meta_doc["num_doc"] = citations[meta_doc['short_name']][0]

                docs_html.append(make_html_source(data, meta_doc, i))

                url_doc = f'<a href="{meta_doc["url"]}#page={data["meta"]["page_number"]}" target="_blank" class="pdf-link">'
                docs_url[i] = url_doc

            html_cit = [make_citations_source(citations, reformulated_query, Hyde=True)]

            docs_string = "\n\n".join([f"Query used for retrieval:\n{reformulated_query}"] + docs_string)

            docs_html = "\n\n".join(html_cit + docs_html)

            messages.append(
                {
                    "role": "system",
                    "content": f"{CFG_APP.SOURCES_PROMPT}\n\n{docs_string}\n\nAnswer in {language}:",
                }
            )

            if CFG_APP.DEBUG == True:
                print(f" πŸ‘¨β€πŸ’» question asked by the user : {query}")
                print(f" πŸ•› time : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

                print(" πŸ”Œ messages sent to the API :")
                api_messages = [
                    {"role": "system", "content": CFG_APP.INIT_PROMPT},
                    {"role": "user", "content": reformulated_query},
                    {
                        "role": "system",
                        "content": f"{CFG_APP.SOURCES_PROMPT}\n\nVery important : Answer in {language}.\n\n{docs_string}:",
                    },
                ]
                for message in api_messages:
                    print(
                        f"length : {len(message['content'])}, content : {message['content']}"
                    )

            response = openai.ChatCompletion.create(
                model=CFG_APP.MODEL_NAME,
                messages=[
                    {"role": "system", "content": CFG_APP.INIT_PROMPT},
                    {"role": "user", "content": reformulated_query},
                    {
                        "role": "system",
                        "content": f"{CFG_APP.SOURCES_PROMPT}\n\nVery important : Answer in {language}.\n\n{docs_string}:",
                    },
                ],
                temperature=0,  # deterministic
                stream=True,
                max_tokens=CFG_APP.MAX_TOKENS_ANSWER,
            )
            complete_response = ""
            messages.pop()
            messages.append({"role": "assistant", "content": complete_response})
            for chunk in response:
                chunk_message = chunk["choices"][0]["delta"].get("content")
                if chunk_message:
                    complete_response += chunk_message
                    complete_response = preprocess_message(complete_response, docs_url)
                    messages[-1]["content"] = complete_response
                    gradio_format = make_pairs([a["content"] for a in messages[1:]])
                    yield gradio_format, messages, docs_html

        else :
            docs_string = "⚠️ No relevant passages found in this report"
            complete_response = "**⚠️ No relevant passages found in this report, you may want to ask a more specific question.**"
            messages.append({"role": "assistant", "content": complete_response})
            gradio_format = make_pairs([a["content"] for a in messages[1:]])
            yield gradio_format, messages, docs_string