File size: 9,835 Bytes
73c9569 c2250b6 568a490 fe42c39 2a84894 e715c6b 1db302e 0246f03 7db9774 b0d53fc 2a84894 b0d53fc f125e9c e715c6b f125e9c 4ccccb3 e715c6b ec8bfb4 e715c6b 357e5f2 e715c6b 3b72fd6 26c448b 78f9bd7 e715c6b 7f50a5f 0bc5b18 b937596 377be67 b0d53fc 78f9bd7 73c9569 377be67 e715c6b 377be67 2a84894 377be67 b0d53fc e715c6b b0d53fc 73c9569 b0d53fc c1ea140 b0d53fc b1318a8 1db302e dd985f2 1db302e 35836e6 1db302e e715c6b 377be67 c494c5e 377be67 2a84894 73c9569 3ae2ed2 73c9569 377be67 e715c6b 377be67 e715c6b 377be67 e9b987a 524eae4 2a84894 e9b987a e715c6b 340946e e715c6b b0d53fc 2a84894 b0d53fc e715c6b 524eae4 e715c6b 2a84894 b0d53fc 18221a4 b0d53fc 377be67 b0d53fc 0b30f86 524eae4 0b30f86 b0d53fc 0b30f86 1db302e b0d53fc 2a84894 b0d53fc 2a84894 b0d53fc 2a84894 0b30f86 0e0a177 7fa1620 987cd0e 1db302e b0d53fc 0b30f86 e715c6b b0d53fc e715c6b 377be67 e715c6b 377be67 73c9569 2a84894 377be67 2a84894 b0d53fc 8a37cce |
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 |
from datasets import load_dataset
from datasets import Dataset
from sentence_transformers import SentenceTransformer
import faiss
import time
#import torch
import pandas as pd
from llama_cpp import Llama
from langchain_community.llms import LlamaCpp
from transformers import AutoTokenizer, GenerationConfig #, AutoModelForCausalLM
#from transformers import AutoModelForCausalLM, AutoModel
from transformers import TextIteratorStreamer
from threading import Thread
from ctransformers import AutoModelForCausalLM, AutoConfig, Config #, AutoTokenizer
from huggingface_hub import Repository, upload_file
import os
HF_TOKEN = os.getenv('HF_Token')
#Log_Path="./Logfolder"
logfile = 'DiabetesChatLog.txt'
historylog = [{
"Prompt": '',
"Output": ''
}]
data = load_dataset("Namitg02/Test", split='train', streaming=False)
#Returns a list of dictionaries, each representing a row in the dataset.
length = len(data)
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
embedding_dim = embedding_model.get_sentence_embedding_dimension()
# Returns dimensions of embedidng
index = faiss.IndexFlatL2(embedding_dim)
data.add_faiss_index("embeddings", custom_index=index)
# adds an index column for the embeddings
print("check1")
#question = "How can I reverse Diabetes?"
SYS_PROMPT = """You are an assistant for answering questions.
You are given the extracted parts of documents and a question. Provide a conversational answer.
If you don't know the answer, just say "I do not know." Don't make up an answer."""
# Provides context of how to answer the question
llm_model = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
# TheBloke/Llama-2-7B-Chat-GGML , TinyLlama/TinyLlama-1.1B-Chat-v1.0 , microsoft/Phi-3-mini-4k-instruct, health360/Healix-1.1B-V1-Chat-dDPO
# TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF and tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf not working, TinyLlama/TinyLlama-1.1B-Chat-v0.6, andrijdavid/TinyLlama-1.1B-Chat-v1.0-GGUF"
tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
#initiate model and tokenizer
generation_config = AutoConfig.from_pretrained(
"TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
max_new_tokens= 300,
# do_sample=True,
# stream = streamer,
top_p=0.95,
temperature=0.4,
stream = True
# eos_token_id=terminators
)
# send additional parameters to model for generation
#model = llama_cpp.Llama(model_path = tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf AutoModelForCausalLM.from_pretrained(llm_model, model_file = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf", model_type="llama", gpu_layers=0, config = generation_config)
model = Llama(
model_path="./tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf",
chat_format="llama-2",
n_gpu_layers = 0,
temperature=0.75,
max_tokens=500,
top_p=0.95,
# callback_manager=callback_manager,
# verbose=True, # Verbose is required to pass to the callback manager
)
def search(query: str, k: int = 2 ):
"""a function that embeds a new query and returns the most probable results"""
embedded_query = embedding_model.encode(query) # create embedding of a new query
scores, retrieved_examples = data.get_nearest_examples( # retrieve results
"embeddings", embedded_query, # compare our new embedded query with the dataset embeddings
k=k # get only top k results
)
return scores, retrieved_examples
# returns scores (List[float]): the retrieval scores from either FAISS (IndexFlatL2 by default) and examples (dict) format
# called by talk function that passes prompt
#print(scores, retrieved_examples)
def format_prompt(prompt,retrieved_documents,k):
"""using the retrieved documents we will prompt the model to generate our responses"""
PROMPT = f"Question:{prompt}\nContext:"
for idx in range(k) :
PROMPT+= f"{retrieved_documents['0'][idx]}\n"
return PROMPT
#def add_history(formatted_prompt, history, memory_limit=3):
# always keep len(history) <= memory_limit
# if len(history) > memory_limit:
# history = history[-memory_limit:]
# if len(history) == 0:
# return PROMPT + f"{formatted_prompt} [/INST]"
#formatted_message = PROMPT + f"{history[0][0]} [/INST] {history[0][1]} </s>"
# Handle conversation history
# for user_msg, model_answer in history[1:]:
# formatted_message += f"<s>[INST] {user_msg} [/INST] {model_answer} </s>"
# # Handle the current message
# formatted_message += f"<s>[INST] {formatted_prompt} [/INST]"
#return formatted_message
# Called by talk function to add retrieved documents to the prompt. Keeps adding text of retrieved documents to string taht are retreived
def talk(prompt, history):
k = 2 # number of retrieved documents
scores , retrieved_documents = search(prompt, k) # get retrival scores and examples in dictionary format based on the prompt passed
print(retrieved_documents.keys())
print("check4")
formatted_prompt = format_prompt(prompt,retrieved_documents,k) # create a new prompt using the retrieved documents
print("check5")
print(retrieved_documents['0'])
print(formatted_prompt)
# formatted_prompt_with_history = add_history(formatted_prompt, history)
# formatted_prompt_with_history = formatted_prompt_with_history[:600] # to avoid memory issue
print(formatted_prompt_with_history)
messages = [{"role":"system","content":SYS_PROMPT},{"role":"user","content":formatted_prompt}]
# binding the system context and new prompt for LLM
# the chat template structure should be based on text generation model format
print("check6")
print(messages)
print("check7")
streamer = TextIteratorStreamer(
tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
)
# stores print-ready text in a queue, to be used by a downstream application as an iterator. removes special tokens in generated text.
# timeout for text queue. tokenizer for decoding tokens
# called by generate_kwargs
terminators = [
tokenizer.eos_token_id, # End-of-Sequence Token that indicates where the model should consider the text sequence to be complete
tokenizer.convert_tokens_to_ids("<|eot_id|>") # Converts a token strings in a single/ sequence of integer id using the vocabulary
]
# indicates the end of a sequence
text = ""
stream = model(messages, max_tokens=1000, stop=["</s>"], stream=True)
for output in stream:
text += output["choices"][0]["text"]
yield text
# model_input = model.create_chat_completion(messages = messages)
# input_ids = tokenizer.apply_chat_template(
# messages,
# add_generation_prompt=True,
# return_tensors="pt"
# )
# preparing tokens for model input
# add_generation_prompt argument tells the template to add tokens that indicate the start of a bot response
# print(input_ids)
# print("check7")
# print(input_ids.dtype)
# generate_kwargs = dict(
# tokens= input_ids) #,
# streamer=streamer,
# do_sample=True,
# eos_token_id=terminators,
# )
# outputs = model.generate(
# )
# print(outputs)
# calling the model to generate response based on message/ input
# do_sample if set to True uses strategies to select the next token from the probability distribution over the entire vocabulary
# temperature controls randomness. more renadomness with higher temperature
# only the tokens comprising the top_p probability mass are considered for responses
# This output is a data structure containing all the information returned by generate(), but that can also be used as tuple or dictionary.
#
# print("check10")
# t = Thread(target=model.generate, kwargs=generate_kwargs)
# to process multiple instances
# t.start()
# print("check11")
# start a thread
# outputs = []
# outputs = model_input
# return outputs
# print(model.tokenize(messages))
# tokens = model.tokenize(messages)
# for token in model.generate(tokens):
# print(model.detokenize([token]))
# input_ids = tokenizer(*messages)
# print(model.generate(tensor([[ 1, 529, 29989, 5205, 29989]])))
# start = time.time()
# NUM_TOKENS=0
# print('-'*4+'Start Generation'+'-'*4)
# for token in model.generate(input_ids):
# print(model.detokenize(input_ids), end='', flush=True)
# NUM_TOKENS+=1
# time_generate = time.time() - start
# print('\n')
# print('-'*4+'End Generation'+'-'*4)
# print(f'Num of generated tokens: {NUM_TOKENS}')
# print(f'Time for complete generation: {time_generate}s')
# print(f'Tokens per secound: {NUM_TOKENS/time_generate}')
# print(f'Time per token: {(time_generate/NUM_TOKENS)*1000}ms')
pd.options.display.max_colwidth = 800
print("check13")
# outputstring = ''.join(outputs)
# global historylog
# historynew = {
# "Prompt": prompt,
# "Output": outputstring
# }
# historylog.append(historynew)
# return historylog
# print(historylog)
TITLE = "AI Copilot for Diabetes Patients"
DESCRIPTION = "I provide answers to concerns related to Diabetes"
import gradio as gr
# Design chatbot
demo = gr.ChatInterface(
fn=talk,
chatbot=gr.Chatbot(
show_label=True,
show_share_button=True,
show_copy_button=True,
likeable=True,
layout="bubble",
bubble_full_width=False,
),
theme="Soft",
examples=[["what is Diabetes? "]],
title=TITLE,
description=DESCRIPTION,
)
# launch chatbot and calls the talk function which in turn calls other functions
print("check14")
#print(historylog)
#memory_panda = pd.DataFrame(historylog)
#Logfile = Dataset.from_pandas(memory_panda)
#Logfile.push_to_hub("Namitg02/Logfile",token = HF_TOKEN)
demo.launch() |