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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
!pip install gradio --quiet
|
| 2 |
+
!pip install xformer --quiet
|
| 3 |
+
!pip install chromadb --quiet
|
| 4 |
+
!pip install langchain --quiet
|
| 5 |
+
!pip install accelerate --quiet
|
| 6 |
+
!pip install transformers --quiet
|
| 7 |
+
!pip install bitsandbytes --quiet
|
| 8 |
+
!pip install unstructured --quiet
|
| 9 |
+
!pip install sentence-transformers --quiet
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
from textwrap import fill
|
| 15 |
+
from IPython.display import Markdown, display
|
| 16 |
+
|
| 17 |
+
from langchain.prompts.chat import (
|
| 18 |
+
ChatPromptTemplate,
|
| 19 |
+
HumanMessagePromptTemplate,
|
| 20 |
+
SystemMessagePromptTemplate,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
from langchain import PromptTemplate
|
| 24 |
+
from langchain import HuggingFacePipeline
|
| 25 |
+
|
| 26 |
+
from langchain.vectorstores import Chroma
|
| 27 |
+
from langchain.schema import AIMessage, HumanMessage
|
| 28 |
+
from langchain.memory import ConversationBufferMemory
|
| 29 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 30 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 31 |
+
from langchain.document_loaders import UnstructuredMarkdownLoader, UnstructuredURLLoader
|
| 32 |
+
from langchain.chains import LLMChain, SimpleSequentialChain, RetrievalQA, ConversationalRetrievalChain
|
| 33 |
+
|
| 34 |
+
from transformers import BitsAndBytesConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, pipeline
|
| 35 |
+
|
| 36 |
+
import warnings
|
| 37 |
+
warnings.filterwarnings('ignore')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.1"
|
| 42 |
+
|
| 43 |
+
quantization_config = BitsAndBytesConfig(
|
| 44 |
+
load_in_4bit=True,
|
| 45 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 46 |
+
bnb_4bit_quant_type="nf4",
|
| 47 |
+
bnb_4bit_use_double_quant=True,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True)
|
| 51 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 52 |
+
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
MODEL_NAME, torch_dtype=torch.float16,
|
| 55 |
+
trust_remote_code=True,
|
| 56 |
+
device_map="auto",
|
| 57 |
+
quantization_config=quantization_config
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
generation_config = GenerationConfig.from_pretrained(MODEL_NAME)
|
| 61 |
+
generation_config.max_new_tokens = 1024
|
| 62 |
+
generation_config.temperature = 0.001
|
| 63 |
+
generation_config.top_p = 0.95
|
| 64 |
+
generation_config.do_sample = True
|
| 65 |
+
generation_config.repetition_penalty = 1.15
|
| 66 |
+
|
| 67 |
+
pipeline = pipeline(
|
| 68 |
+
"text-generation",
|
| 69 |
+
model=model,
|
| 70 |
+
tokenizer=tokenizer,
|
| 71 |
+
return_full_text=True,
|
| 72 |
+
generation_config=generation_config,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
llm = HuggingFacePipeline(
|
| 77 |
+
pipeline=pipeline,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
embeddings = HuggingFaceEmbeddings(
|
| 82 |
+
model_name="thenlper/gte-large",
|
| 83 |
+
model_kwargs={"device": "cuda"},
|
| 84 |
+
encode_kwargs={"normalize_embeddings": True},
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
urls = [
|
| 89 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/telefonica_M.TEF.html ",
|
| 90 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/bbva_M.BBVA.html ",
|
| 91 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/iberdrola_M.IBE.html",
|
| 92 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/santander_M.SAN.html",
|
| 93 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/ferrovial_M.FER.html",
|
| 94 |
+
"https://www.expansion.com/mercados/cotizaciones/valores/enagas_M.ENG.html",
|
| 95 |
+
"https://www.euroland.com/SiteFiles/market/search.asp?GUID=B8D60F4600CAF1479E480C0BA6CE775E&ViewPageNumber=1&ViewAllStockSelected=False&Operation=selection&SortWinLoser=False&SortDirection=&ColumnToSort=&ClickedWinLoser=&ClickedMarkCap=&NameSearch=&UpperLevel=&LowerLevel=&RegionalIndustry=&RegionalListName=&RegionalListID=&RegionalIndexName=&CorporateSites=False&SharesPerPage=50",
|
| 96 |
+
"https://www.expansion.com/mercados/cotizaciones/indices/ibex35_I.IB.html",
|
| 97 |
+
"https://es.investing.com/equities/telefonica-cash-flow",
|
| 98 |
+
"https://es.investing.com/equities/grupo-ferrovial-cash-flow",
|
| 99 |
+
"https://es.investing.com/equities/bbva-cash-flow",
|
| 100 |
+
"https://es.investing.com/equities/banco-santander-cash-flow",
|
| 101 |
+
"https://es.investing.com/equities/iberdrola-cash-flow",
|
| 102 |
+
"https://es.investing.com/equities/enagas-cash-flow",
|
| 103 |
+
"https://es.investing.com/equities/enagas-ratios",
|
| 104 |
+
"https://es.investing.com/equities/telefonica-ratios",
|
| 105 |
+
"https://es.investing.com/equities/grupo-ferrovial-ratios",
|
| 106 |
+
"https://es.investing.com/equities/bbva-ratios",
|
| 107 |
+
"https://es.investing.com/equities/banco-santander-ratios",
|
| 108 |
+
"https://es.investing.com/equities/iberdrola-ratios"
|
| 109 |
+
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
loader = UnstructuredURLLoader(urls=urls)
|
| 113 |
+
documents = loader.load()
|
| 114 |
+
|
| 115 |
+
len(documents)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=64)
|
| 119 |
+
texts_chunks = text_splitter.split_documents(documents)
|
| 120 |
+
|
| 121 |
+
len(texts_chunks)
|
| 122 |
+
# output: 21
|
| 123 |
+
|
| 124 |
+
template = """
|
| 125 |
+
[INST] <>
|
| 126 |
+
Actúa como un bot financiero experto en el análsis de valores cotizados en el IBEX-35
|
| 127 |
+
<>
|
| 128 |
+
|
| 129 |
+
{context}
|
| 130 |
+
|
| 131 |
+
{question} [/INST]
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
|
| 135 |
+
|
| 136 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 137 |
+
llm=llm,
|
| 138 |
+
chain_type="stuff",
|
| 139 |
+
retriever=db.as_retriever(search_kwargs={"k": 2}),
|
| 140 |
+
return_source_documents=True,
|
| 141 |
+
chain_type_kwargs={"prompt": prompt},
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
query = "¿Cuál es el precio de la acción de BBVA hoy?"
|
| 145 |
+
result_ = qa_chain(
|
| 146 |
+
query
|
| 147 |
+
)
|
| 148 |
+
result = result_["result"].strip()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
display(Markdown(f"<b>{query}</b>"))
|
| 152 |
+
display(Markdown(f"<p>{result}</p>"))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
query = "Haz un análisis técnico de BBVA para el año 2022"
|
| 156 |
+
result_ = qa_chain(
|
| 157 |
+
query
|
| 158 |
+
)
|
| 159 |
+
result = result_["result"].strip()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
display(Markdown(f"<b>{query}</b>"))
|
| 163 |
+
display(Markdown(f"<p>{result}</p>"))
|
| 164 |
+
|
| 165 |
+
result_["source_documents"]
|
| 166 |
+
|
| 167 |
+
custom_template = """You are finance AI Assistant Given the
|
| 168 |
+
following conversation and a follow up question, rephrase the follow up question
|
| 169 |
+
to be a standalone question. At the end of standalone question add this
|
| 170 |
+
'Answer the question in English language.' If you do not know the answer reply with 'I am sorry, I dont have enough information'.
|
| 171 |
+
Chat History:
|
| 172 |
+
{chat_history}
|
| 173 |
+
Follow Up Input: {question}
|
| 174 |
+
Standalone question:
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
CUSTOM_QUESTION_PROMPT = PromptTemplate.from_template(custom_template)
|
| 178 |
+
|
| 179 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 180 |
+
|
| 181 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 182 |
+
llm=llm,
|
| 183 |
+
retriever=db.as_retriever(search_kwargs={"k": 2}),
|
| 184 |
+
memory=memory,
|
| 185 |
+
condense_question_prompt=CUSTOM_QUESTION_PROMPT,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
query = "Haz un análisis técnico definiendo todos los ratios de BBVA para el año 2021"
|
| 190 |
+
result_ = qa_chain({"question": query})
|
| 191 |
+
result = result_["answer"].strip()
|
| 192 |
+
|
| 193 |
+
display(Markdown(f"<b>{query}</b>"))
|
| 194 |
+
display(Markdown(f"<p>{result}</p>"))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
query = "¿Cuánto han crecido las ventas de Iberdrola en los últimos cinco años?"
|
| 198 |
+
result_ = qa_chain({"question": query})
|
| 199 |
+
result = result_["answer"].strip()
|
| 200 |
+
|
| 201 |
+
display(Markdown(f"<b>{query}</b>"))
|
| 202 |
+
display(Markdown(f"<p>{result}</p>"))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
query = "¿Cuál es el precio medio de la acción de Iberdrola en 2022?"
|
| 206 |
+
result_ = qa_chain({"question": query})
|
| 207 |
+
result = result_["answer"].strip()
|
| 208 |
+
|
| 209 |
+
display(Markdown(f"<b>{query}</b>"))
|
| 210 |
+
display(Markdown(f"<p>{result}</p>"))
|
| 211 |
+
|
| 212 |
+
def querying(query, history):
|
| 213 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 214 |
+
|
| 215 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 216 |
+
llm=llm,
|
| 217 |
+
retriever=db.as_retriever(search_kwargs={"k": 2}),
|
| 218 |
+
memory=memory,
|
| 219 |
+
condense_question_prompt=CUSTOM_QUESTION_PROMPT,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
result = qa_chain({"question": query})
|
| 223 |
+
return result["answer"].strip()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
iface = gr.ChatInterface(
|
| 227 |
+
fn = querying,
|
| 228 |
+
chatbot=gr.Chatbot(height=600),
|
| 229 |
+
textbox=gr.Textbox(placeholder="¿Cuál es el precio de la acción de BBVA hoy?", container=False, scale=7),
|
| 230 |
+
title="RanitaRené",
|
| 231 |
+
theme="soft",
|
| 232 |
+
examples=["¿Cuál es el precio de la acción de BBVA hoy?",
|
| 233 |
+
"Haz un análisis técnico de BBVA para el año 2022"
|
| 234 |
+
],
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
cache_examples=True,
|
| 238 |
+
retry_btn="Repetir",
|
| 239 |
+
undo_btn="Deshacer",
|
| 240 |
+
clear_btn="Borrar",
|
| 241 |
+
submit_btn="Enviar"
|
| 242 |
+
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
iface.launch(share=True)
|