File size: 16,590 Bytes
498db6b
 
 
 
 
 
 
 
 
 
 
 
 
3ca15d8
498db6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ca15d8
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
TODO: add a boolean to switch llms
"""


import json
import string
import openai

import wikipedia
from langchain.text_splitter import CharacterTextSplitter
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from src.domain.block import Block
from src.llm.llms import openai_llm
from src.tools.wiki import Wiki


# async def get_wikilist_open_source(task: {}) -> str:
#     """
#     get the titles of wiki pages interesting for solving the given task
#     """

#     template = ("<s>[INST] Your task consists in finding the list of wikipedia page titles which provide useful content "
#                 "    for a paragraph whose description is delimited by triple backticks.\n"
#                 "    Make sure that you provide no more than 10 elements and that the list is actually finished."
#                 "    Format your response as a valid JSON list of strings separated by commas.[/INST]</s>"
#                 "    Description: ```{description}```")

#     prompt = PromptTemplate(template=template, input_variables=['description'])
#     llm_chain = LLMChain(llm=opensource_llm, prompt=prompt)
#     response = llm_chain.run({'description': task['description']})
#     llm_list = response.choices[0].message.content
#     try:
#         wikilist = json.loads(llm_list)
#     except:
#         print("json loads failed with" + llm_list)
#         wikilist = list(llm_list.split(','))

#     expanded_wikilist = []

#     expand_factor = 2

#     for wikipage in wikilist:
#         expanded_wikilist += wikipedia.search(wikipage, expand_factor)

#     wikilist = list(set(expanded_wikilist))

#     return wikilist



async def get_wikilist(task: {}) -> str:
    """
    get the titles of wiki pages interesting for solving the given task
    """

    llm = openai_llm
    template = (f"\n"
                f"    Your task consists in finding the list of wikipedia page titles which provide useful content "
                f"    for a paragraph whose description is delimited by triple backticks: ```{task['description']}```\n"
                f"    "
                f"    Make sure that you provide no more than 10 elements and that the list is actually finished."
                f"    Format your response as a valid JSON list of strings separated by commas.\n"
                f"  \n"
                f"    ")

    #wikilist = LLMChain(llm=openai_llm, prompt=prompt).run()
    llm_list = llm.invoke(template)
    try:
        wikilist = json.loads(llm_list)
    except:
        print("json loads failed with" + llm_list)
        wikilist = list(llm_list.split(','))

    expanded_wikilist = []

    expand_factor = 2

    for wikipage in wikilist:
        expanded_wikilist += wikipedia.search(wikipage, expand_factor)

    wikilist = list(set(expanded_wikilist))

    return wikilist


def extract_list(llm_list: str):

    def filter_(el: str):
        resp = 2 < len(el)
        usable_length = len([c for c in el if c in string.ascii_letters])
        resp = resp and len(el)*3/4 < usable_length
        return resp

    try:
        wikilist = llm_list[1:-1].split('"')
        wikilist = [el for el in wikilist if filter_(el)]
        print(wikilist)
    except:
        wikilist = []
        print('issues with the wikilist')
    return wikilist


# def get_public_paragraph_open_source(task: {}) -> str:
#     """returns the task directly performed by chat GPT"""

#     template = ("<s>[INST] Your task consists in generating a paragraph whose description is delimited by triple "
#                 "backticks.\n"
#                 "    The paragraph belongs at the top level of the hierarchy to a document"
#                 "    whose doc_description is delimited by triple backticks.\n"
#                 "    Make sure that the paragraph relates the top level of the document\n"
#                 "    The paragraph belongs to a higher paragraph in the hierarchy whose description (above) is delimited by "
#                 "    triple backticks."
#                 "    Make sure that the paragraph relates with the paragraph in the hierarchy of the document\n"
#                 "    The paragraphs comes after previous paragraphs whose description (before) is delimited by triple "
#                 "    backticks.\n"
#                 "    Make sure that the paragraph relates with previous paragraph without any repetition\n"
#                 "    The paragraphs comes before next paragraphs whose description (after) is delimited by triple backticks.\n"
#                 "    Make sure that the paragraph prepares the transition to the next paragraph without any "
#                 "    repetition. [/INST]</s>"
#                 "    Description: ```{description}```"
#                 "    Doc description: ```{doc_description}```"
#                 "    Above: ```{above}```"
#                 "    Before: ```{before}```"
#                 "    After: ```{after}```"
#                 )
    
#     prompt = PromptTemplate(template=template, input_variables=['description', 'doc_description', 'above', 'before', 'after'])
#     llm_chain = LLMChain(llm=opensource_llm, prompt=prompt)
#     response = llm_chain.run({'description': task['description'], 'doc_description': task['doc_description'],
#                               'above': task['above'], 'before': task['before'], 'after': task['after']})
#     p = response.choices[0].message.content
#     return p

def get_public_paragraph(task: {}) -> str:
    """returns the task directly performed by chat GPT"""
    print(task)
    llm = openai_llm
    template = (f"\n"
                f"    Your task consists in generating a paragraph\\n"
                f"    whose description is delimited by triple backticks: ```{task['description']}```\n"
                f"\n"
                f"    The paragraph belongs at the top level of the hierarchy to a document \\n"
                f"    whose description is delimited by triple backticks: ``` {task['doc_description']}```\n"
                f"    Make sure that the paragraph relates the top level of the document\n"
                f"    \n"
                f"    The paragraph belongs to a higher paragraph in the hierarchy \\n"
                f"    whose description is delimited by triple backticks: ``` {task['above']}```\n"
                f"    Make sure that the paragraph relates with the paragraph in the hierarchy of the document\n"
                f"        \n"
                f"    The paragraphs comes after previous paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['before']}```\n"
                f"    Make sure that the paragraph relates with previous paragraph without any repetition\n"
                f"    \n"
                f"    The paragraphs comes before next paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['after']}```\n"
                f"    Make sure that the paragraph prepares the transition to the next paragraph without any repetition\n"
                f"    \n"
                f"  \n"
                f"\n"
                f"    ")

    p = llm.invoke(template)

    return p


def create_index(wikilist: [str]):
    """
    useful for creating the index of wikipages
    """
    fetch = Wiki().fetch

    pages = [(title, fetch(title)) for title in wikilist if type(fetch(title)) != str]
    texts = []
    chunk = 800
    for title, page in pages:
        texts.append(WikiPage(title=title, fulltext=page.page_content))

    doc_splitter = CharacterTextSplitter(
        separator=".",
        chunk_size=chunk,
        chunk_overlap=100,
        length_function=len,
    )

    paragraphs = texts[0].get_paragraphs(chunk=800)

    split_texts = []
    for p in paragraphs:
        split_texts += doc_splitter.split_text(p)

    for split_text in split_texts:
        assert type(split_text) == str
        assert 0 < len(split_text) < 2 * 500

    wiki_index = Chroma.from_texts(split_texts)

    return wiki_index


def get_wiki_paragraph(wiki_index, task: {}) -> str:
    """useful to get a summary in one line from wiki index"""

    task_description = get_public_paragraph(task)
    wiki_paragraphs = semantic_search(wiki_index, task_description)
    text_content = ""
    for p in wiki_paragraphs:
        text_content += p.page_content + "/n/n"

    template = (f"\n"
                f"    Your task consists in generating a paragraph\\n"
                f"    whose description is delimited by triple backticks: ```{task['description']}```\n"
                f"\n"
                f"    The text generation is based in the documents provided in these sections \n"
                f"    delimited by by triple backticks: ``` {text_content}``` \n"
                f"    The paragraph belongs at the top level of the hierarchy to a document \\n"
                f"    whose description is delimited by triple backticks: ``` {task['doc_description']}```\n"
                f"    Make sure that the paragraph relates the top level of the document\n"
                f"    \n"
                f"    The paragraph belongs to a higher paragraph in the hierarchy \\n"
                f"    whose description is delimited by triple backticks: ``` {task['above']}```\n"
                f"    Make sure that the paragraph relates with the paragraph in the hierarchy of the document\n"
                f"        \n"
                f"    The paragraphs comes after previous paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['before']}```\n"
                f"    Make sure that the paragraph relates with previous paragraph without any repetition\n"
                f"    \n"
                f"    The paragraphs comes before next paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['after']}```\n"
                f"    Make sure that the paragraph prepares the transition to the next paragraph without any repetition\n"
                f"    \n"
                f"  \n"
                f"\n"
                f"    ")

    llm = openai_llm
    p = llm(template)

    return p


# def get_private_paragraph_open_source(texts, task: {}) -> str:
#     """useful to get a summary in one line from wiki index"""

#     text_content = ""
#     for t in texts:
#         text_content += t + "/n/n"

#     template = ("\n"
#                 "    Your task consists in generating a paragraph"
#                 "    whose description is delimited by triple backticks\n"
#                 "    The text generation is based in the documents provided in these sections \n"
#                 "    delimited by by triple backticks (text_content)\n"
#                 "    The paragraph belongs at the top level of the hierarchy to a document"
#                 "    whose description is delimited by triple backticks (doc_decription)\n"
#                 "    Make sure that the paragraph relates the top level of the document\n"
#                 "    \n"
#                 "    The paragraph belongs to a higher paragraph in the hierarchy"
#                 "    whose description is delimited by triple backticks (above)\n"
#                 "    Make sure that the paragraph relates with the paragraph in the hierarchy of the document\n"
#                 "        \n"
#                 "    The paragraphs comes after previous paragraphs"
#                 "    whose description is delimited by triple backticks (before)\n"
#                 "    Make sure that the paragraph relates with previous paragraph without any repetition\n"
#                 "    \n"
#                 "    The paragraphs comes before next paragraphs"
#                 "    whose description is delimited by triple backticks (after)\n"
#                 "    Make sure that the paragraph prepares the transition to the next paragraph without any repetition\n"
#                 "    description: ```{description}```"
#                 "    text_content: ```{text_content}```"
#                 "    doc_description: ```{doc_description}```"
#                 "    above: ```{above}```"
#                 "    before: ```{before}```"
#                 "    after: ```{after}```")

#     prompt = PromptTemplate(template=template, input_variables=['description', 'text_content', 'doc_description', 'above', 'before', 'after'])
#     llm_chain = LLMChain(llm=opensource_llm, prompt=prompt)
#     response = llm_chain.run({'description': task['description'], 'text_content': text_content, 'doc_description': task['doc_description'],
#                                 'above': task['above'], 'before': task['before'], 'after': task['after']})
#     p = response.choices[0].message.content


def get_private_paragraph(texts, task: {}) -> str:
    """useful to get a summary in one line from wiki index"""

    text_content = ""
    for t in texts:
        text_content += t + "/n/n"

    template = (f"\n"
                f"    Your task consists in generating a paragraph\\n"
                f"    whose description is delimited by triple backticks: ```{task['description']}```\n"
                f"\n"
                f"    The text generation is based in the documents provided in these sections \n"
                f"    delimited by by triple backticks: ``` {text_content}``` \n"
                f"    The paragraph belongs at the top level of the hierarchy to a document \\n"
                f"    whose description is delimited by triple backticks: ``` {task['doc_description']}```\n"
                f"    Make sure that the paragraph relates the top level of the document\n"
                f"    \n"
                f"    The paragraph belongs to a higher paragraph in the hierarchy \\n"
                f"    whose description is delimited by triple backticks: ``` {task['above']}```\n"
                f"    Make sure that the paragraph relates with the paragraph in the hierarchy of the document\n"
                f"        \n"
                f"    The paragraphs comes after previous paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['before']}```\n"
                f"    Make sure that the paragraph relates with previous paragraph without any repetition\n"
                f"    \n"
                f"    The paragraphs comes before next paragraphs \\n"
                f"    whose description is delimited by triple backticks: ``` {task['after']}```\n"
                f"    Make sure that the paragraph prepares the transition to the next paragraph without any repetition\n"
                f"    \n"
                f"  \n"
                f"\n"
                f"    ")

    llm = openai_llm
    p = llm.invoke(template)

    return p

def summarize_paragraph_v2(prompt : str, title_doc : str = '', title_para : str = ''):
    max_tokens = 850
    location_of_the_paragraph = prompt.split(" :")[0]
    """summarizes the paragraph"""
    task = (f"Your task consists in summarizing in English the paragraph of the document untitled ```{title_doc}``` located in the ```{location_of_the_paragraph}``` section of the document."
                f"The paragraph title is ```{title_para}```."
                f"Your response shall be concise and shall respect the following format:"
                f"<summary>"
                f"If you see that the summary that you are creating will not respect ```{max_tokens}``` tokens, find a way to make it shorter.")
    generation = openai.chat.completions.create(model="gpt-3.5-turbo-16k", messages=[{"role":"system","content":task},{"role":"user","content":prompt}])
    res = generation.choices[0].message.content
    print("****************")
    print(res)
    print("----")
    return str(res).strip()

def generate_response_to_exigence(exigence : str, titre_exigence : str, content : str):
    """
    Generates a response to an exigence depending on the context of the exigence and the blocks of the document.
    """
    task = (f"Your task consists in generating a response to a requirement in a tender for Orange, a telecommunication operator."
            f"The requirement dealing with {titre_exigence} is expressed below between triple backquotes:"
            f"```{exigence}```"
            f"Your answer should be precise, consistent and as concise as possible with no politeness formulas and strictly be based on the following text delimited by triple backquotes : ```{content}```"
            )
    llm = openai_llm
    generation = llm.invoke(task)
    return generation