File size: 18,274 Bytes
c114607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd77360
c114607
 
 
 
 
b68875e
 
0faabd3
b68875e
 
c114607
 
 
 
 
 
 
b68875e
 
 
c114607
 
 
 
 
e7f116b
f787d9d
5540250
f787d9d
c114607
a32a927
e7f116b
 
 
62d92d6
c114607
8474d86
 
c114607
b68875e
 
c114607
 
 
 
e7f116b
d115c77
c114607
fd77360
c114607
b68875e
 
 
 
 
62d92d6
b68875e
 
c114607
 
 
 
 
 
 
b68875e
c114607
 
 
 
 
 
 
 
 
 
62d92d6
c114607
62d92d6
c114607
 
 
b68875e
c114607
b68875e
 
 
c114607
 
b68875e
c114607
b68875e
c114607
b68875e
c114607
70d8061
b68875e
70d8061
c114607
 
 
 
 
 
 
 
 
 
 
70d8061
b68875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62d92d6
b68875e
 
c114607
b68875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70d8061
b68875e
 
 
 
 
 
 
 
 
c114607
 
 
 
fd77360
 
b68875e
061d4c6
 
 
c40a87c
 
 
061d4c6
 
45e5b38
b68875e
 
 
 
 
 
 
 
 
 
 
 
62d92d6
b68875e
 
 
 
 
 
d2c5780
b68875e
d2c5780
 
 
 
b68875e
d2c5780
b68875e
d2c5780
b68875e
d2c5780
b68875e
 
 
c114607
d2c5780
b68875e
c114607
b68875e
 
 
fd77360
b68875e
 
061d4c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd77360
061d4c6
 
b68875e
 
 
 
 
 
 
 
 
 
 
 
 
 
c114607
 
 
 
 
 
 
 
 
 
 
 
 
b68875e
c114607
 
 
 
b68875e
 
 
1f7503e
 
c114607
1f7503e
c114607
1f7503e
 
 
b68875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c114607
 
 
 
b68875e
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
import gradio as gr
import numpy as np
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import LLMChain
from langchain import PromptTemplate
import re
import pandas as pd
from langchain.vectorstores import FAISS
import requests
from typing import List
from langchain.schema import (
    SystemMessage,
    HumanMessage,
    AIMessage
)
import os
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chat_models import ChatOpenAI

from langchain.llms.base import LLM
from typing import Optional, List, Mapping, Any

import ast
from utils import ClaudeLLM, ClaudeLLM2, extract_website_name, remove_numbers

embeddings = HuggingFaceEmbeddings()
db = FAISS.load_local('db_full', embeddings)

mp_docs = {}
llm_4 = ChatOpenAI(
            temperature=0,
            model='gpt-4'
        )
claude = ClaudeLLM()
def add_text(history, text):

    print(history)
    history = history + [(text, None)]

    return history, ""

def retrieve_thoughts(query, ):
  # print(db.similarity_search_with_score(query = query, k = k, fetch_k = k*10))
    docs_with_score = db.similarity_search_with_score(query = query, k = 1500, fetch_k = len(db.index_to_docstore_id.values()))
    df = pd.DataFrame([dict(doc[0])['metadata'] for doc in docs_with_score], )
    df = pd.concat((df, pd.DataFrame([dict(doc[0])['page_content'] for doc in docs_with_score], columns = ['page_content'])), axis = 1)
    df = pd.concat((df, pd.DataFrame([doc[1] for doc in docs_with_score], columns = ['score'])), axis = 1)

  # TO-DO: What if user query doesn't match what we provide as documents
  # df.sort_values("score", inplace = True)
    
    tier_1 = df
    tier_2 = df[((df['score'] < 1) * (df["score"] > 0.8))]

    tier_1
    chunks_1 = tier_1.groupby(['title', 'url', ]).apply(lambda x: "\n...\n".join(x.sort_values('score').iloc[:3].sort_values('id')['page_content'].values)).values
    score = tier_1.groupby(['title', 'url', ]).apply(lambda x: x.sort_values('score').iloc[:3]['score'].mean()).values

    tier_1_adjusted = tier_1.groupby(['title', 'url', ]).first().reset_index()[[ 'title', 'url', 'author']]
    tier_1_adjusted['content'] = chunks_1
    tier_1_adjusted['score'] = score


    chunks_2 = tier_2.groupby(['title', 'url', ]).apply(lambda x: "\n...\n".join(x.sort_values('id')['page_content'].values)).values
    tier_2_adjusted = tier_2.groupby(['title', 'url', ]).first().reset_index()[[ 'title', 'url']]
    tier_2_adjusted['content'] = chunks_2

  # tier_1 = [doc[0]  for doc in docs if ((doc[1] < 1))][:5]
  # tier_2 = [doc[0]  for doc in docs if ((doc[1] > 0.7)*(doc[1] < 1.5))][10:15]
    tier_1_adjusted.sort_values("score", inplace = True)
    tier_1_adjusted['ref'] = range(1, len(tier_1_adjusted) + 1 )

    return {'tier 1':tier_1_adjusted[:min(len(tier_1_adjusted), 100)], 'tier 2': tier_2_adjusted.loc[:5]}

def get_references(query):
  # TO-DO FINSIH UPP.
  thoughts = retrieve_thoughts(query)
  print(thoughts.keys())
  tier_1 = thoughts['tier 1']
  reference = tier_1[['ref', 'url', 'title', 'author']].to_dict('records')
  return reference
def qa_themes(query,):

    docs = ""

    global db
    print(db)

    global mp_docs
    thoughts = retrieve_thoughts(query)
    if not(thoughts):

        if mp_docs:
            thoughts = mp_docs
    else:
        mp_docs = thoughts

    tier_1 = thoughts['tier 1']
    tier_2 = thoughts['tier 2']

    reference = tier_1[['ref', 'url', 'title', 'author']].to_dict('records')

    tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n author: {x.author}\n content: {x.content}", axis = 1).values)
    tier_2 = list(tier_2.apply(lambda x: f"title: {x['title']}\n Content: {x.content}", axis = 1).values)
    print(f"QUERY: {query}\nTIER 1: {tier_1}\nTIER2: {tier_2}")

    # print(f"DOCS RETRIEVED: {mp_docs.values}")
    # Cynthesis Generation


    # Themes
    session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""
    task = """Your primary responsibility is to identify multiple themes from the given articles. For each theme detected, you are to present it under three separate categories:

    1. Theme Title - An easy-to-understand title that encapsulates the core idea of the theme extracted from the article.

    2. Theme Description - An expanded elaboration that explores the theme in detail based on the arguments and points provided in the article.

    3. Quotes related to theme - Locate and provide at least one compelling quote from the article that directly supports or showcases the theme you have identified. This quote should serve as a specific evidence or example from the article text that corresponds directly to the developed theme.
    

    Keep your answer direct and don't include your thoughts. Make sure that the quote used should have a reference [1] related to the article."""


    prompt = PromptTemplate(
            input_variables=["query", "task", "session_prompt", "articles"],
            template="""
            You are a {session_prompt}
            {task}
            query: {query}
            Articles:
            {articles}

            The extracted themes should be written in structured manner, ensuring clarity and meaningful correlation between the themes and the articles. Don't forget to mention the reference in the quote. Avoid including personal opinions or making generalizations that are not explicitly supported by the articles.
            Keep your answer direct and don't include your thoughts.
            """,
        )


    # llm = BardLLM()
    chain = LLMChain(llm=claude, prompt = prompt)

    themes = chain.run(query=query, articles="\n".join(tier_1), session_prompt = session_prompt, task = task)
    return themes

def qa_retrieve(query,):

    docs = ""

    global db
    print(db)

    global mp_docs
    thoughts = retrieve_thoughts(query)
    if not(thoughts):

        if mp_docs:
            thoughts = mp_docs
    else:
        mp_docs = thoughts

    tier_1 = thoughts['tier 1']
    tier_2 = thoughts['tier 2']

    reference = tier_1[['ref', 'url', 'title']].to_dict('records')

    tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n author: {x.author}\n content: {x.content}", axis = 1).values)
    tier_2 = list(tier_2.apply(lambda x: f"title: {x['title']}\n Content: {x.content}", axis = 1).values)
    print(f"QUERY: {query}\nTIER 1: {tier_1}\nTIER2: {tier_2}")

    # print(f"DOCS RETRIEVED: {mp_docs.values}")
    # Cynthesis Generation

    session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""
    # task = """Create a coherent synthesis in which you use references to the id of articles provided and relevant to the query.

    # Follow the example structure:

    # The best wine to pair with steak depends on the cut of steak and the preparation. Here are some general guidelines for pairing wine with steak:
    # - Choose a dry red wine. The rule of thumb is to choose dry red wines
    # -  leaner cuts of meat pair with lighter wines, while richer, fattier cuts pair up with high tannin wines that can cut through the fat [1].
    # - Consider the cut of steak. Lighter red wines tend to go best with the leaner cuts of steak such as filet mignon, while more marbled, higher fat cuts of meat like a rib eye do well when accompanied by more robust red wines [3].
    # - Take into account the preparation. For a spiced steak, go for a wine with lots of fruit to balance out the heat, like an Old Vine Zinfandel. And if you're drowning your steak in a decadent sauce, find a wine with enough body to stand up to it, like a Cabernet Sauvignon [5].
    # - Popular wine choices include Cabernet Sauvignon, Pinot Noir, Zinfandel, Malbec, Syrah, and Merlot [2].
    # Remember, the goal is to choose a wine that complements the cut of steak and not overwhelm or take away from the flavor of the meat [3]."
    # """

    prompt = PromptTemplate(
            input_variables=["query", "session_prompt", "articles"],
            template="""
          You are a {session_prompt}
          Create a coherent well-structured synthesis in which you use references to the id of articles provided and relevant to the query.

              Follow the example structure, references are not provided but are found in the answer:
              User: What are the secondary effects of covid?
              Cynthesis: \nSecondary effects of COVID-19, often referred to as \"Long COVID\", are a significant concern. These effects are not limited to the acute phase of the disease but persist well past the first month, affecting various organ systems and leading to adverse outcomes such as all-cause death and hospitalization [1]. \n\nOne of the most alarming secondary effects is the increased risk of cardiovascular diseases. Studies have shown a 1.6-fold increased risk of stroke and a 2-fold higher risk of acute coronary disease in individuals who had COVID-19 [2][3][8]. These risks were observed even in younger populations, with a mean age of 44, and were prevalent after 30 days post-infection [2][3]. \n\nAnother study found that the adverse outcomes of COVID-19 could persist up to the 2-year mark, with the toll of adverse sequelae being worst during the first year [3]. The study also highlighted that individuals with severe COVID-19, who were hospitalized, were more likely to be afflicted with protracted symptoms and new medical diagnoses [3]. \n\nHowever, it's important to note that the risks associated with Long COVID might be most significant in the first few weeks post-infection and fade away as time goes on [4][9]. For instance, the chance of developing pulmonary embolism was found to be 32 times higher in the first month after testing positive for COVID-19 [4]. \n\nMoreover, the number of excess deaths in the U.S., which would indicate fatal consequences of mild infections at a delay of months or years, dropped to zero in April, about two months after the end of the winter surge, and have stayed relatively low ever since [4]. This suggests that a second wave of deaths—a long-COVID wave—never seems to break [4]. \n\nIn conclusion, while the secondary effects of COVID-19 are significant and can persist for a long time, the most severe risks seem to occur in the first few weeks post-infection and then gradually decrease. However, the full extent of the long-term effects of COVID-19 is still unknown, and further research is needed to fully understand the ways and extent COVID-19 has affected us.",

            query: {query}

            Articles:
            {articles}

            Make sure to quote the article used if the argument corresponds to the query.
            Use careful reasoning and professional writing for the synthesis. No need to mention your interaction with articles.
            Remember not to mention articles used at the beginning of sentences, keep it cohesive and rich in text while referencing as much as possible of sources given.
            """,
        )


    llm = ClaudeLLM2()
    chain = LLMChain(llm=llm, prompt = prompt)

    consensus = chain.run(query=query, articles="\n".join(tier_1), session_prompt = session_prompt,).strip()
    if "In conclusion" in consensus:
      consensus = consensus[:consensus.index('In conclusion')]
        
    consensus = consensus[consensus.index(':')+1:].strip()
    
    intro = qa_intro(query, consensus, tier_1)
    conclusion = qa_conclusion(query, consensus, tier_1)
    cynthesis = intro + "\n\n" + consensus + conclusion
    # for i in range(1, len(tier_1)+1):
    #   response = response.replace(f'[{i}]', f"<span class='text-primary'>[{i}]</span>")


    # json_resp = {'cynthesis': response, 'questions': questions, 'reference': reference}

    return cynthesis
def qa_intro(query, cynthesis, tier_1,):
  

  llm = ClaudeLLM()
  llm_4 = ChatOpenAI(
              temperature=0.5,
              model='gpt-3.5-turbo-16k'
          )

  session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""

  prompt = PromptTemplate(
          input_variables=["query", "articles"],
          template="""
          Give me an introduction to the following topic. Consider this an abstract. And after finishing the introduction, pick one quote from the sources given below.
          this is the desired structure:
          Introduction: Introduction
          Quote: "quote". [1] (Reference)

          Follow the structure given.
          query: {query}
          
          We have the opportunity to give an introduction to this synthesis without repeating information found.
          Pick an opening quote from the sources given below\n
          ---------\n
          {articles}
          ---------\n

          Don't forget that your job is to only provide an introduction, abstract part that introduces the synthesis and then pick one general quote from the sources given. Maintain the desired structure.""",
      )

  # llm = BardLLM()
  chain = LLMChain(llm=llm_4, prompt = prompt)

  intro = chain.run(query=query, articles="\n".join(tier_1[:15]))
  return intro.strip()

def qa_conclusion(query, cynthesis, tier_1,):


  llm = ClaudeLLM()
  llm_4 = ChatOpenAI(
              temperature=0,
              model='gpt-3.5-turbo-16k'
          )

  session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""

  prompt = PromptTemplate(
          input_variables=["query", "cynthesis", "articles"],
          template="""
          Give me a final conclusion to the following consensus without repeating how it starts. Consider this an abstract.

          query: {query}
          Here's the consensus: {cynthesis}

          We have the opportunity to give a final conclusion to this synthesis without repeating information found.
          \nHere is also some references used to write the synthesis if you want to include some of them in the final conclusion.
          ---------\n
          {articles}
          ---------\n

          Don't forget that your job is to only provide a conclusion, abstract part that give a closure to the synthesis. Feel free to have an opening question if needed, if not no need to write it.""",
      )


  # llm = BardLLM()
  chain = LLMChain(llm=llm_4, prompt = prompt)

  conclusion = chain.run(query=query, articles="\n".join(tier_1[:15]), cynthesis = cynthesis)
  return conclusion.strip()
    
def qa_faqs(query):

    thoughts = retrieve_thoughts(query)

    # tier_1 = thoughts['tier 1']
    tier_2 = thoughts['tier 2']

    # reference = tier_1[['ref', 'url', 'title']].to_dict('records')

    # tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n Content: {x.content}", axis = 1).values)
    tier_2 = list(tier_2.apply(lambda x: f"title: {x['title']}\n Content: {x.content}", axis = 1).values)
# Generate related questions
    session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""

    prompt_q = PromptTemplate(
            input_variables=[ "session_prompt", "articles"],
            template="""
            You are a {session_prompt}
            Give general/global questions related the following articles:

            Articles:
            {articles}

            Make sure not to ask specific questions, keep them general, short and concise.
            """,
        )

    chain_q = LLMChain(llm=claude, prompt = prompt_q)

    questions = chain_q.run(session_prompt = session_prompt, articles = "\n".join(tier_2), )
    questions = questions[questions.index('1'):]

    questions = [ t.strip() for (i, t) in enumerate(questions.split('\n\n'))  if len(t) > 5][:5]
    
    return "\n\n".join(questions)
# examples = [
#     ["Will Russia win the war in Ukraine?"],

#     ]

# demo = gr.Interface(fn=qa_retrieve, title="cicero-qa-api",
#                      inputs=gr.inputs.Textbox(lines=5, label="what would you like to learn about?"),
#                      outputs="json",examples=examples)

def parallel_greet_claude(batch, ):

    batch = ast.literal_eval(batch)
    query, thoughts = batch['query'], batch['thoughts']
    print(thoughts)
    result = qa_retrieve(query, "claude", thoughts)

    return result

# examples = [
#     ["Will Russia win the war in Ukraine?"],
#     ["Covid Global Impact and what's beyond that"]
#     ]

cynthesis = gr.Interface(fn = qa_retrieve, inputs = "text", outputs = gr.components.Textbox(lines=3, label="Cynthesis"))
questions = gr.Interface(fn = qa_faqs, inputs = "text", outputs = gr.components.Textbox(lines=3, label="Related Questions"))
themes = gr.Interface(fn = qa_themes, inputs = "text", outputs = gr.components.Textbox(lines=3, label="themes"))

# gpt_3 = gr.Interface(fn = parallel_greet_gpt_3, inputs = "text", outputs = gr.components.Textbox(lines=3, label="GPT3.5"))
# gpt_4 = gr.Interface(fn = parallel_greet_gpt_4, inputs = "text", outputs = gr.components.Textbox(lines=3, label="GPT4"))
# claude = gr.Interface(fn = parallel_greet_claude, inputs = "text", outputs = gr.components.Textbox(lines=3, label="Claude"))
reference = gr.Interface(fn = get_references, inputs = "text", outputs = "json", label = "Reference")

demo = gr.Parallel(cynthesis, themes, questions, reference)

# demo = gr.Series(references, cynthesis, themes)

demo.queue(concurrency_count = 4)
demo.launch()