Spaces:
Runtime error
Runtime error
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_art = FAISS.load_local('db_art', embeddings) | |
db_yt = FAISS.load_local('db_yt', embeddings) | |
mp_docs = {} | |
llm_4 = ChatOpenAI( | |
temperature=0, | |
model='gpt-4' | |
) | |
claude = ClaudeLLM() | |
claude2 = ClaudeLLM2() | |
def add_text(history, text): | |
print(history) | |
history = history + [(text, None)] | |
return history, "" | |
def retrieve_thoughts(query, media): | |
if media[0] == "Articles": | |
db = db_art | |
else: | |
db = db_yt | |
# 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('id')['page_content'].values)).values | |
print(len(chunks_1[0])) | |
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']] | |
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), 30)], 'tier 2': tier_2_adjusted.loc[:5]} | |
def get_references(query, media): | |
# TO-DO FINSIH UPP. | |
thoughts = retrieve_thoughts(query, media) | |
print(thoughts.keys()) | |
tier_1 = thoughts['tier 1'] | |
reference = tier_1[['ref', 'url', 'title']].to_dict('records') | |
return reference | |
def grab_jsons(query, media = None, tier_1 = None, ): | |
response = "" | |
if tier_1 is None: | |
thoughts = retrieve_thoughts(query, media) | |
tier_1 = thoughts['tier 1'] | |
tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n Content: {x.content}", axis = 1).values) | |
for i in range(3, len(tier_1), 3): | |
portion = tier_1[i - 3 :i] | |
response += '\n' + jsonify_articles(query, portion) | |
return response | |
def jsonify_articles(query, tier_1 = None): | |
if tier_1 is None: | |
thoughts = retrieve_thoughts(query) | |
tier_1 = thoughts['tier 1'] | |
tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n Content: {x.content}", axis = 1).values) | |
# json | |
# { | |
# 'ref': 1, | |
# 'quotes': ['quote_1', 'quote_2', 'quote_3'], | |
# 'summary (optional for now as we already have summaries)': "" | |
# } | |
session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will execute different analysis to the articles provided to you. Stay truthful and if you weren't provided any resources give your oppinion only.""" | |
task = """Your primary responsibility is to identify valuable information from the given articles related to a given query. | |
For each article provided, you are to present it under four separate categories: | |
1. Article Reference - A reference for the article id: int | |
2. Article Title - The title for the article: string | |
3. Article quotes - Numerous Quotes extracted from the article that prove certain point of views in a list format [quote_1, quote_2, quote_3, quote_4, quote_5] | |
4. Article Summary - A summary for the article: string | |
Make sure to include all valuable quotes to be used later on. | |
Keep your answer direct and don't include your thoughts. Make sure that the quote used should have a reference [1] that identifies the source.""" | |
prompt = PromptTemplate( | |
input_variables=["query", "task", "articles"], | |
template=""" | |
{task} | |
The extracted information should correlate to the following query. | |
query: {query} | |
Articles: | |
{articles} | |
The extracted information should be written in structured manner, ensuring clarity and meaningful format for the articles. 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. | |
""", | |
) | |
chain = LLMChain(llm=claude, prompt = prompt) | |
json_articles = chain.run(query=query, articles="\n".join(tier_1), task = task).strip() | |
return json_articles | |
def qa_retrieve(query, media): | |
docs = "" | |
global mp_docs | |
thoughts = retrieve_thoughts(query, media) | |
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"ref: [{int(x['ref'])}]\ntitle: {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) | |
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 you. You will generate a rich synthesis with numerous arguments extracted from the sources given.""" | |
# 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]." | |
# """ | |
articles = grab_jsons(query, tier_1 = tier_1) | |
prompt = PromptTemplate( | |
input_variables=["query", "session_prompt", "articles"], | |
template=""" | |
You are a {session_prompt} | |
Create a rich well-structured synthesis in which you use references to the id of articles provided and relevant to the query. | |
The Synthesis should include at least 500 words englobing all prespectives found in the sources. | |
Follow the example structure: | |
User: What are the secondary effects of covid? | |
Synthesis: \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. Add as many arguments and point of views as possible as long as they have a reference. | |
Keep your answer direct and 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 = BardLLM() | |
chain = LLMChain(llm=claude2, prompt = prompt) | |
consensus = chain.run(query=query, articles=articles, session_prompt = session_prompt,) | |
consensus = consensus[consensus.index(':')+1:].strip() | |
if "In conclusion" in consensus: | |
consensus = consensus[:consensus.index('In conclusion')] | |
intro = qa_intro(query, consensus, articles) | |
conclusion = qa_conclusion(query, consensus, articles) | |
cynthesis = intro + "\n\n" + consensus + "\n\n" + 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, | |
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 an introduction to the following consensus without repeating how it starts. Consider this an abstract. And after finishing the introduction, pick one quote from the sources given below. | |
query: {query} | |
Here's the consensus: {cynthesis} | |
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 without repeating it and then pick one general quote from the sources given.""", | |
) | |
# llm = BardLLM() | |
chain = LLMChain(llm=llm_4, prompt = prompt) | |
intro = chain.run(query=query, articles=tier_1, cynthesis = cynthesis) | |
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=tier_1, cynthesis = cynthesis) | |
return conclusion.strip() | |
def qa_faqs(query, media): | |
thoughts = retrieve_thoughts(query, media) | |
# 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 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) | |
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", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="Cynthesis")) | |
questions = gr.Interface(fn = qa_faqs, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="Related Questions")) | |
#themes = gr.Interface(fn = qa_themes, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], 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", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = "json", label = "Reference") | |
json = gr.Interface(fn = grab_jsons, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="json")) | |
#demo = gr.Parallel(cynthesis, reference) | |
#demo = gr.Parallel(themes, reference) | |
demo = gr.Parallel(json, cynthesis, questions, reference) | |
demo.queue(concurrency_count = 4) | |
demo.launch() | |