|
from datasets import load_dataset |
|
from datasets import Dataset |
|
from langchain.docstore.document import Document as LangchainDocument |
|
from sentence_transformers import SentenceTransformer |
|
import faiss |
|
import pandas as pd |
|
import time |
|
import torch |
|
|
|
from transformers import AutoTokenizer |
|
from transformers import AutoModelForCausalLM |
|
from transformers import TextIteratorStreamer |
|
from threading import Thread |
|
|
|
llm_model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" |
|
tokenizer = AutoTokenizer.from_pretrained(llm_model) |
|
|
|
|
|
dataset = load_dataset("Namitg02/Test", split='train', streaming=False) |
|
|
|
|
|
length = len(dataset) |
|
|
|
embedding_model = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1") |
|
|
|
|
|
df = pd.DataFrame(dataset) |
|
|
|
print(check1) |
|
df['embeddings'] = df['text'].apply(lambda x: embedding_model.encode(x)) |
|
|
|
|
|
print(check1a) |
|
print(df.iloc[[1]]) |
|
dataset = Dataset.from_pandas(df) |
|
print(check1b) |
|
|
|
|
|
|
|
print(dataset[2]) |
|
|
|
embedding_dim = embedding_model.get_sentence_embedding_dimension() |
|
|
|
data = dataset |
|
|
|
|
|
d = 384 |
|
m = 32 |
|
|
|
|
|
|
|
data.add_faiss_index("embeddings") |
|
|
|
|
|
print("check1d") |
|
|
|
|
|
SYS_PROMPT = """You are an assistant for answering questions. |
|
You are given the extracted parts of a long document 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.""" |
|
|
|
|
|
print("check2") |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained(llm_model) |
|
|
|
|
|
terminators = [ |
|
tokenizer.eos_token_id, |
|
tokenizer.convert_tokens_to_ids("<|eot_id|>") |
|
] |
|
|
|
|
|
|
|
def search(query: str, k: int = 3 ): |
|
"""a function that embeds a new query and returns the most probable results""" |
|
embedded_query = embedding_model.encode(query) |
|
scores, retrieved_examples = data.get_nearest_examples( |
|
"embeddings", embedded_query, |
|
k=k |
|
) |
|
return scores, retrieved_examples |
|
|
|
|
|
|
|
|
|
print("check2A") |
|
|
|
|
|
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['text'][idx]}\n" |
|
return PROMPT |
|
|
|
|
|
|
|
print("check3") |
|
|
|
|
|
print("check3A") |
|
|
|
|
|
def talk(prompt,history): |
|
k = 1 |
|
scores , retrieved_documents = search(prompt, k) |
|
formatted_prompt = format_prompt(prompt,retrieved_documents,k) |
|
formatted_prompt = formatted_prompt[:400] |
|
messages = [{"role":"system","content":SYS_PROMPT},{"role":"user","content":formatted_prompt}] |
|
|
|
print("check3B") |
|
input_ids = tokenizer.apply_chat_template( |
|
messages, |
|
add_generation_prompt=True, |
|
return_tensors="pt" |
|
).to(model.device) |
|
|
|
|
|
print("check3C") |
|
outputs = model.generate( |
|
input_ids, |
|
max_new_tokens=300, |
|
eos_token_id=terminators, |
|
do_sample=True, |
|
temperature=0.6, |
|
top_p=0.9, |
|
) |
|
|
|
|
|
|
|
|
|
|
|
print("check3D") |
|
streamer = TextIteratorStreamer( |
|
tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True |
|
) |
|
|
|
|
|
|
|
print("check3E") |
|
generate_kwargs = dict( |
|
input_ids= input_ids, |
|
streamer=streamer, |
|
max_new_tokens= 512, |
|
do_sample=True, |
|
top_p=0.95, |
|
temperature=0.75, |
|
eos_token_id=terminators, |
|
) |
|
|
|
print("check3F") |
|
t = Thread(target=model.generate, kwargs=generate_kwargs) |
|
|
|
t.start() |
|
|
|
print("check3G") |
|
outputs = [] |
|
for text in streamer: |
|
outputs.append(text) |
|
print(outputs) |
|
yield "".join(outputs) |
|
print("check3H") |
|
|
|
|
|
TITLE = "AI Copilot for Diabetes Patients" |
|
|
|
DESCRIPTION = "" |
|
|
|
import gradio as gr |
|
|
|
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, |
|
|
|
) |
|
|
|
print("check3I") |
|
demo.launch(share=True) |