Spaces:
Runtime error
Runtime error
File size: 5,598 Bytes
c53fb3a |
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 |
# !pip -q install git+https://github.com/huggingface/transformers # need to install from github
!pip install -q datasets loralib sentencepiece
!pip -q install bitsandbytes accelerate xformers
!pip -q install langchain
!pip -q install gradio
!pip -q install peft chromadb
!pip -q install unstructured
!pip install -q sentence_transformers
!pip -q install pypdf
from google.colab import drive
drive.mount('/content/drive')
"""## LLaMA2 7B Chat
"""
import torch
from peft import PeftModel, PeftConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline
bnb_config = BitsAndBytesConfig(load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=False)
model_id = "meta-llama/Llama-2-7b-chat-hf"
#daryl149/llama-2-7b-chat-hf
#meta-llama/Llama-2-7b-chat-hf
tokenizer = AutoTokenizer.from_pretrained(model_id,token='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')
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config = bnb_config,device_map={"":0},token='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')
import json
import textwrap
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
def get_prompt(instruction, new_system_prompt=DEFAULT_SYSTEM_PROMPT ):
SYSTEM_PROMPT = B_SYS + new_system_prompt + E_SYS
prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST
return prompt_template
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.document_loaders import PyPDFLoader
loader = PyPDFLoader("/content/drive/MyDrive/Gen AI and LLM/data/data.pdf")
text_splitter = RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size = 800,
chunk_overlap = 50,
length_function = len,
)
pages = loader.load_and_split(text_splitter)
db = Chroma.from_documents(pages, HuggingFaceEmbeddings())
instruction = "Given the context that has been provided. \n {context}, Answer the following question - \n{question}"
system_prompt = """You are an expert in question and answering.
You will be given a context to answer from. Be precise in your answers wherever possible.
In case you are sure you don't know the answer then you say that based on the context you don't know the answer.
In all other instances you provide an answer to the best of your capability. Cite urls when you can access them related to the context."""
get_prompt(instruction, system_prompt)
"""## Setting up with LangChain"""
from langchain import HuggingFacePipeline
from langchain import PromptTemplate, LLMChain
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferWindowMemory
template = get_prompt(instruction, system_prompt)
print(template)
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
memory = ConversationBufferWindowMemory(
memory_key="chat_history", k=5,
return_messages=True
)
retriever = db.as_retriever()
def create_pipeline(max_new_tokens=512):
pipe = pipeline("text-generation",
model=model,
tokenizer = tokenizer,
max_new_tokens = max_new_tokens,
temperature = 0.1)
return pipe
class GunaBot:
def __init__(self, memory, prompt, task:str = "text-generation", retriever = retriever):
self.memory = memory
self.prompt = prompt
self.retriever = retriever
def create_chat_bot(self, max_new_tokens = 512):
hf_pipe = create_pipeline(max_new_tokens)
llm = HuggingFacePipeline(pipeline =hf_pipe)
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=self.retriever,
memory=self.memory,
combine_docs_chain_kwargs={"prompt": self.prompt}
)
return qa
Guna_bot = GunaBot(memory = memory, prompt = prompt)
bot = Guna_bot.create_chat_bot()
import gradio as gr
import random
import time
def clear_llm_memory():
bot.memory.clear()
def update_prompt(sys_prompt):
if sys_prompt == "":
sys_prompt = system_prompt
template = get_prompt(instruction, sys_prompt)
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
bot.combine_docs_chain.llm_chain.prompt = prompt
with gr.Blocks() as demo:
update_sys_prompt = gr.Textbox(label = "Update System Prompt")
chatbot = gr.Chatbot(label="Guna Bot", height = 300)
msg = gr.Textbox(label = "Question")
clear = gr.ClearButton([msg, chatbot])
clear_memory = gr.Button(value = "Clear LLM Memory")
def respond(message, chat_history):
bot_message = bot({"question": message})['answer']
chat_history.append((message, bot_message))
return "", chat_history
msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
clear_memory.click(clear_llm_memory)
update_sys_prompt.submit(update_prompt, inputs=update_sys_prompt)
demo.launch(share=False, debug=True)
|