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
import argparse
|
2 |
+
# from dataclasses import dataclass
|
3 |
+
from langchain.prompts import ChatPromptTemplate
|
4 |
+
|
5 |
+
try:
|
6 |
+
from langchain_community.vectorstores import Chroma
|
7 |
+
except:
|
8 |
+
from langchain_community.vectorstores import Chroma
|
9 |
+
|
10 |
+
# from langchain.document_loaders import DirectoryLoader
|
11 |
+
from langchain_community.document_loaders import DirectoryLoader
|
12 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
13 |
+
from langchain.schema import Document
|
14 |
+
# from langchain.embeddings import OpenAIEmbeddings
|
15 |
+
#from langchain_openai import OpenAIEmbeddings
|
16 |
+
from langchain_community.vectorstores import Chroma
|
17 |
+
import openai
|
18 |
+
from dotenv import load_dotenv
|
19 |
+
import os
|
20 |
+
import shutil
|
21 |
+
import torch
|
22 |
+
|
23 |
+
from transformers import AutoModel,AutoTokenizer
|
24 |
+
model2 = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
25 |
+
tokenizer2 = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
26 |
+
|
27 |
+
|
28 |
+
# this shoub be used when we can not use sentence_transformers (which reqiures transformers==4.39. we cannot use
|
29 |
+
# this version since causes using large amount of RAm when loading falcon model)
|
30 |
+
# a custom embedding
|
31 |
+
#from sentence_transformers import SentenceTransformer
|
32 |
+
from langchain_experimental.text_splitter import SemanticChunker
|
33 |
+
from typing import List
|
34 |
+
import re
|
35 |
+
import warnings
|
36 |
+
from typing import List
|
37 |
+
|
38 |
+
import torch
|
39 |
+
from langchain import PromptTemplate
|
40 |
+
from langchain.chains import ConversationChain
|
41 |
+
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
|
42 |
+
from langchain.llms import HuggingFacePipeline
|
43 |
+
from langchain.schema import BaseOutputParser
|
44 |
+
from transformers import (
|
45 |
+
AutoModelForCausalLM,
|
46 |
+
AutoTokenizer,
|
47 |
+
StoppingCriteria,
|
48 |
+
StoppingCriteriaList,
|
49 |
+
pipeline,
|
50 |
+
)
|
51 |
+
|
52 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
53 |
+
|
54 |
+
|
55 |
+
class MyEmbeddings:
|
56 |
+
def __init__(self):
|
57 |
+
#self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
58 |
+
self.model=model2
|
59 |
+
|
60 |
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
61 |
+
inputs = tokenizer2(texts, padding=True, truncation=True, return_tensors="pt")
|
62 |
+
|
63 |
+
# Get the model outputs
|
64 |
+
with torch.no_grad():
|
65 |
+
outputs = self.model(**inputs)
|
66 |
+
|
67 |
+
# Mean pooling to get sentence embeddings
|
68 |
+
embeddings = outputs.last_hidden_state.mean(dim=1)
|
69 |
+
return [embeddings[i].tolist() for i, sentence in enumerate(texts)]
|
70 |
+
def embed_query(self, query: str) -> List[float]:
|
71 |
+
inputs = tokenizer2(query, padding=True, truncation=True, return_tensors="pt")
|
72 |
+
|
73 |
+
# Get the model outputs
|
74 |
+
with torch.no_grad():
|
75 |
+
outputs = self.model(**inputs)
|
76 |
+
|
77 |
+
# Mean pooling to get sentence embeddings
|
78 |
+
embeddings = outputs.last_hidden_state.mean(dim=1)
|
79 |
+
return embeddings[0].tolist()
|
80 |
+
|
81 |
+
|
82 |
+
embeddings = MyEmbeddings()
|
83 |
+
|
84 |
+
splitter = SemanticChunker(embeddings)
|
85 |
+
|
86 |
+
|
87 |
+
CHROMA_PATH = "/content/drive/My Drive/chroma8"
|
88 |
+
# call the chroma generated in a directory
|
89 |
+
db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
|
90 |
+
|
91 |
+
|
92 |
+
|
93 |
+
MODEL_NAME = "tiiuae/falcon-7b-instruct"
|
94 |
+
|
95 |
+
model = AutoModelForCausalLM.from_pretrained(
|
96 |
+
MODEL_NAME, trust_remote_code=True, load_in_8bit=True, device_map="auto"
|
97 |
+
)
|
98 |
+
model = model.eval()
|
99 |
+
|
100 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
101 |
+
print(f"Model device: {model.device}")
|
102 |
+
|
103 |
+
|
104 |
+
generation_config = model.generation_config
|
105 |
+
generation_config.temperature = 0
|
106 |
+
generation_config.num_return_sequences = 1
|
107 |
+
generation_config.max_new_tokens = 256
|
108 |
+
generation_config.use_cache = False
|
109 |
+
generation_config.repetition_penalty = 1.7
|
110 |
+
generation_config.pad_token_id = tokenizer.eos_token_id
|
111 |
+
generation_config.eos_token_id = tokenizer.eos_token_id
|
112 |
+
generation_config
|
113 |
+
|
114 |
+
|
115 |
+
prompt = """
|
116 |
+
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context.
|
117 |
+
|
118 |
+
Current conversation:
|
119 |
+
|
120 |
+
Human: Who is Dwight K Schrute?
|
121 |
+
AI:
|
122 |
+
""".strip()
|
123 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
124 |
+
input_ids = input_ids.to(model.device)
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
class StopGenerationCriteria(StoppingCriteria):
|
129 |
+
def __init__(
|
130 |
+
self, tokens: List[List[str]], tokenizer: AutoTokenizer, device: torch.device
|
131 |
+
):
|
132 |
+
stop_token_ids = [tokenizer.convert_tokens_to_ids(t) for t in tokens]
|
133 |
+
self.stop_token_ids = [
|
134 |
+
torch.tensor(x, dtype=torch.long, device=device) for x in stop_token_ids
|
135 |
+
]
|
136 |
+
|
137 |
+
def __call__(
|
138 |
+
self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
|
139 |
+
) -> bool:
|
140 |
+
for stop_ids in self.stop_token_ids:
|
141 |
+
if torch.eq(input_ids[0][-len(stop_ids) :], stop_ids).all():
|
142 |
+
return True
|
143 |
+
return False
|
144 |
+
|
145 |
+
|
146 |
+
stop_tokens = [["Human", ":"], ["AI", ":"]]
|
147 |
+
stopping_criteria = StoppingCriteriaList(
|
148 |
+
[StopGenerationCriteria(stop_tokens, tokenizer, model.device)]
|
149 |
+
)
|
150 |
+
|
151 |
+
generation_pipeline = pipeline(
|
152 |
+
model=model,
|
153 |
+
tokenizer=tokenizer,
|
154 |
+
return_full_text=True,
|
155 |
+
task="text-generation",
|
156 |
+
stopping_criteria=stopping_criteria,
|
157 |
+
generation_config=generation_config,
|
158 |
+
)
|
159 |
+
|
160 |
+
llm = HuggingFacePipeline(pipeline=generation_pipeline)
|
161 |
+
|
162 |
+
|
163 |
+
class CleanupOutputParser(BaseOutputParser):
|
164 |
+
def parse(self, text: str) -> str:
|
165 |
+
user_pattern = r"\nUser"
|
166 |
+
text = re.sub(user_pattern, "", text)
|
167 |
+
human_pattern = r"\nHuman:"
|
168 |
+
text = re.sub(human_pattern, "", text)
|
169 |
+
ai_pattern = r"\nAI:"
|
170 |
+
return re.sub(ai_pattern, "", text).strip()
|
171 |
+
|
172 |
+
@property
|
173 |
+
def _type(self) -> str:
|
174 |
+
return "output_parser"
|
175 |
+
|
176 |
+
|
177 |
+
template = """
|
178 |
+
The following
|
179 |
+
Current conversation:
|
180 |
+
|
181 |
+
{history}
|
182 |
+
|
183 |
+
Human: {input}
|
184 |
+
AI:""".strip()
|
185 |
+
prompt = PromptTemplate(input_variables=["history", "input"], template=template)
|
186 |
+
|
187 |
+
memory = ConversationBufferWindowMemory(
|
188 |
+
memory_key="history", k=6, return_only_outputs=True
|
189 |
+
)
|
190 |
+
|
191 |
+
chain = ConversationChain(
|
192 |
+
llm=llm,
|
193 |
+
memory=memory,
|
194 |
+
prompt=prompt,
|
195 |
+
output_parser=CleanupOutputParser(),
|
196 |
+
verbose=True,
|
197 |
+
)
|
198 |
+
|
199 |
+
|
200 |
+
def get_llama_response(message: str, history: list) -> str:
|
201 |
+
query_text = message
|
202 |
+
|
203 |
+
results = db.similarity_search_with_relevance_scores(query_text, k=3)
|
204 |
+
if len(results) == 0 or results[0][1] < 0.5:
|
205 |
+
print(f"Unable to find matching results.")
|
206 |
+
|
207 |
+
|
208 |
+
context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results])
|
209 |
+
template = """
|
210 |
+
The following is a conversation between a human an AI. The AI acts exactly like Dwight K Schrute from the TV show The Office.
|
211 |
+
Dwight is an experienced and very successful online marketer and salesperson. He is witty, persuasive, uncensored, direct and practical.
|
212 |
+
Dwight helps with every marketing task is given to him. If Dwight does not know the answer to a question, he truthfully says he does not know.
|
213 |
+
|
214 |
+
Current conversation:
|
215 |
+
"""
|
216 |
+
s="""
|
217 |
+
{history}
|
218 |
+
Human: {input}
|
219 |
+
AI:""".strip()
|
220 |
+
|
221 |
+
|
222 |
+
prompt = PromptTemplate(input_variables=["history", "input"], template=template+context_text+ s)
|
223 |
+
|
224 |
+
#print(template)
|
225 |
+
chain.prompt=prompt
|
226 |
+
res = chain(query_text)
|
227 |
+
return(res["response"])
|
228 |
+
|
229 |
+
import gradio as gr
|
230 |
+
|
231 |
+
gr.ChatInterface(get_llama_response).launch()
|