import os
import json
import re
from sentence_transformers import SentenceTransformer, CrossEncoder
from huggingface_hub import hf_hub_download
import hnswlib
import numpy as np
from typing import Iterator
import gradio as gr
import pandas as pd
import torch
from easyllm.clients import huggingface
from transformers import AutoTokenizer
huggingface.prompt_builder = "llama2"
huggingface.api_key = os.environ["HUGGINGFACE_TOKEN"]
MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = 4000
EMBED_DIM = 1024
K = 10
EF = 100
COSINE_THRESHOLD = 0.7
SEARCH_INDEX = hf_hub_download(repo_id="sayakpaul/diffusers-qa-chatbot-artifacts", filename="search_index.bin", repo_type="dataset")
EMBEDDINGS_FILE = hf_hub_download(repo_id="sayakpaul/diffusers-qa-chatbot-artifacts", filename="embeddings.npy", repo_type="dataset")
DOCUMENT_DATASET = hf_hub_download(repo_id="sayakpaul/diffusers-qa-chatbot-artifacts", filename="chunked_data.parquet", repo_type="dataset")
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
print("Running on device:", torch_device)
print("CPU threads:", torch.get_num_threads())
model_id = "meta-llama/Llama-2-70b-chat-hf"
biencoder = SentenceTransformer("intfloat/e5-large-v2", device=torch_device)
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-12-v2", max_length=512, device=torch_device)
tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=os.environ["HUGGINGFACE_TOKEN"])
def create_qa_prompt(query, relevant_chunks):
stuffed_context = " ".join(relevant_chunks)
return f"""\
Use the following pieces of context given in to answer the question at the end. \
If you don't know the answer, just say that you don't know, don't try to make up an answer. \
Keep the answer short and succinct.
Context: {stuffed_context}
Question: {query}
Helpful Answer: \
"""
def create_condense_question_prompt(question, chat_history):
return f"""\
Given the following conversation and a follow up question, \
rephrase the follow up question to be a standalone question in its original language. \
Output the json object with single field `question` and value being the rephrased standalone question.
Only output json object and nothing else.
Chat History:
{chat_history}
Follow Up Input: {question}
"""
def get_prompt(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> str:
texts = [f"[INST] <[INST] ")
message = message.strip() if do_strip else message
texts.append(f"{message} [/INST]")
return "".join(texts)
def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
prompt = get_prompt(message, chat_history, system_prompt)
input_ids = tokenizer([prompt], return_tensors="np", add_special_tokens=False)["input_ids"]
return input_ids.shape[-1]
# https://www.philschmid.de/llama-2#how-to-prompt-llama-2-chat
def get_completion(
prompt,
system_prompt=None,
model=model_id,
max_new_tokens=1024,
temperature=0.2,
top_p=0.95,
top_k=50,
stream=False,
debug=False,
):
if temperature < 1e-2:
temperature = 1e-2
messages = []
if system_prompt is not None:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
response = huggingface.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature, # this is the degree of randomness of the model's output
max_tokens=max_new_tokens, # this is the number of new tokens being generated
top_p=top_p,
top_k=top_k,
stream=stream,
debug=debug,
)
return response["choices"][0]["message"]["content"] if not stream else response
# load the index for the Diffusers docs
def load_hnsw_index(index_file):
# Load the HNSW index from the specified file
index = hnswlib.Index(space="ip", dim=EMBED_DIM)
index.load_index(index_file)
return index
# create the index for the Diffusers docs from numpy embeddings
# avoid the arch mismatches when creating search index
def create_hnsw_index(embeddings_file, M=16, efC=100):
embeddings = np.load(embeddings_file)
# Create the HNSW index
num_dim = embeddings.shape[1]
ids = np.arange(embeddings.shape[0])
index = hnswlib.Index(space="ip", dim=num_dim)
index.init_index(max_elements=embeddings.shape[0], ef_construction=efC, M=M)
index.add_items(embeddings, ids)
return index
def create_query_embedding(query):
# Encode the query to get its embedding
embedding = biencoder.encode([query], normalize_embeddings=True)[0]
return embedding
def find_nearest_neighbors(query_embedding):
search_index.set_ef(EF)
# Find the k-nearest neighbors for the query embedding
labels, distances = search_index.knn_query(query_embedding, k=K)
labels = [label for label, distance in zip(labels[0], distances[0]) if (1 - distance) >= COSINE_THRESHOLD]
relevant_chunks = data_df.iloc[labels]["chunk_content"].tolist()
return relevant_chunks
def rerank_chunks_with_cross_encoder(query, chunks):
# Create a list of tuples, each containing a query-chunk pair
pairs = [(query, chunk) for chunk in chunks]
# Get scores for each query-chunk pair using the cross encoder
scores = cross_encoder.predict(pairs)
# Sort the chunks based on their scores in descending order
sorted_chunks = [chunk for _, chunk in sorted(zip(scores, chunks), reverse=True)]
return sorted_chunks
def generate_condensed_query(query, history):
chat_history = ""
for turn in history:
chat_history += f"Human: {turn[0]}\n"
chat_history += f"Assistant: {turn[1]}\n"
condense_question_prompt = create_condense_question_prompt(query, chat_history)
condensed_question = json.loads(get_completion(condense_question_prompt, max_new_tokens=64, temperature=0))
return condensed_question["question"]
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.\
"""
MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = 4000
DESCRIPTION = """
# ๐งจ Diffusers Docs QA Chatbot ๐ค
"""
DESCRIPTION += "This application is almost exactly copied from [smangrul/Diffusers-Docs-QA-Chatbot](https://huggingface.co/spaces/smangrul/Diffusers-Docs-QA-Chatbot).\n Related code: [pacman100/DHS-LLM-Workshop](https://github.com/pacman100/DHS-LLM-Workshop/blob/main/6_Module/)."
LICENSE = """