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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
print(55877)
|
2 |
+
import argparse
|
3 |
+
# from dataclasses import dataclass
|
4 |
+
from langchain.prompts import ChatPromptTemplate
|
5 |
+
try:
|
6 |
+
from langchain_community.vectorstores import Chroma
|
7 |
+
except:
|
8 |
+
from langchain_community.vectorstores import Chroma
|
9 |
+
#from langchain_openai import OpenAIEmbeddings
|
10 |
+
#from langchain_openai import ChatOpenAI
|
11 |
+
|
12 |
+
# from langchain.document_loaders import DirectoryLoader
|
13 |
+
from langchain_community.document_loaders import DirectoryLoader
|
14 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
15 |
+
from langchain.schema import Document
|
16 |
+
# from langchain.embeddings import OpenAIEmbeddings
|
17 |
+
#from langchain_openai import OpenAIEmbeddings
|
18 |
+
from langchain_community.vectorstores import Chroma
|
19 |
+
import openai
|
20 |
+
from dotenv import load_dotenv
|
21 |
+
import os
|
22 |
+
import shutil
|
23 |
+
|
24 |
+
|
25 |
+
import re
|
26 |
+
import warnings
|
27 |
+
from typing import List
|
28 |
+
|
29 |
+
import torch
|
30 |
+
from langchain import PromptTemplate
|
31 |
+
from langchain.chains import ConversationChain
|
32 |
+
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
|
33 |
+
from langchain.llms import HuggingFacePipeline
|
34 |
+
from langchain.schema import BaseOutputParser
|
35 |
+
from transformers import (
|
36 |
+
AutoModelForCausalLM,
|
37 |
+
AutoTokenizer,
|
38 |
+
StoppingCriteria,
|
39 |
+
StoppingCriteriaList,
|
40 |
+
pipeline,
|
41 |
+
)
|
42 |
+
|
43 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
44 |
+
|
45 |
+
MODEL_NAME = "tiiuae/falcon-7b-instruct"
|
46 |
+
|
47 |
+
model = AutoModelForCausalLM.from_pretrained(
|
48 |
+
MODEL_NAME, trust_remote_code=True, device_map="auto",offload_folder="offload"
|
49 |
+
)
|
50 |
+
model = model.eval()
|
51 |
+
|
52 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
53 |
+
print(f"Model device: {model.device}")
|
54 |
+
|
55 |
+
# a custom embedding
|
56 |
+
from sentence_transformers import SentenceTransformer
|
57 |
+
from langchain_experimental.text_splitter import SemanticChunker
|
58 |
+
from typing import List
|
59 |
+
|
60 |
+
|
61 |
+
class MyEmbeddings:
|
62 |
+
def __init__(self):
|
63 |
+
self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
64 |
+
#self.model=model
|
65 |
+
|
66 |
+
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
67 |
+
return [self.model.encode(t).tolist() for t in texts]
|
68 |
+
def embed_query(self, query: str) -> List[float]:
|
69 |
+
return [self.model.encode([query])][0][0].tolist()
|
70 |
+
|
71 |
+
|
72 |
+
embeddings = MyEmbeddings()
|
73 |
+
|
74 |
+
splitter = SemanticChunker(embeddings)
|
75 |
+
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
# Create CLI.
|
80 |
+
#parser = argparse.ArgumentParser()
|
81 |
+
#parser.add_argument("query_text", type=str, help="The query text.")
|
82 |
+
#args = parser.parse_args()
|
83 |
+
#query_text = args.query_text
|
84 |
+
|
85 |
+
# a sample query to be asked from the bot and it is expected to be answered based on the template
|
86 |
+
query_text="what did alice say to rabbit"
|
87 |
+
|
88 |
+
# Prepare the DB.
|
89 |
+
#embedding_function = OpenAIEmbeddings() # main
|
90 |
+
|
91 |
+
CHROMA_PATH = "chroma8"
|
92 |
+
# call the chroma generated in a directory
|
93 |
+
db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
|
94 |
+
|
95 |
+
# Search the DB for similar documents to the query.
|
96 |
+
results = db.similarity_search_with_relevance_scores(query_text, k=2)
|
97 |
+
if len(results) == 0 or results[0][1] < 0.5:
|
98 |
+
print(f"Unable to find matching results.")
|
99 |
+
|
100 |
+
|
101 |
+
context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results])
|
102 |
+
prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
|
103 |
+
prompt = prompt_template.format(context=context_text, question=query_text)
|
104 |
+
print(prompt)
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
generation_config = model.generation_config
|
110 |
+
generation_config.temperature = 0
|
111 |
+
generation_config.num_return_sequences = 1
|
112 |
+
generation_config.max_new_tokens = 256
|
113 |
+
generation_config.use_cache = False
|
114 |
+
generation_config.repetition_penalty = 1.7
|
115 |
+
generation_config.pad_token_id = tokenizer.eos_token_id
|
116 |
+
generation_config.eos_token_id = tokenizer.eos_token_id
|
117 |
+
generation_config
|
118 |
+
|
119 |
+
prompt = """
|
120 |
+
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.
|
121 |
+
|
122 |
+
Current conversation:
|
123 |
+
|
124 |
+
Human: Who is Dwight K Schrute?
|
125 |
+
AI:
|
126 |
+
""".strip()
|
127 |
+
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
128 |
+
input_ids = input_ids.to(model.device)
|
129 |
+
|
130 |
+
class StopGenerationCriteria(StoppingCriteria):
|
131 |
+
def __init__(
|
132 |
+
self, tokens: List[List[str]], tokenizer: AutoTokenizer, device: torch.device
|
133 |
+
):
|
134 |
+
stop_token_ids = [tokenizer.convert_tokens_to_ids(t) for t in tokens]
|
135 |
+
self.stop_token_ids = [
|
136 |
+
torch.tensor(x, dtype=torch.long, device=device) for x in stop_token_ids
|
137 |
+
]
|
138 |
+
|
139 |
+
def __call__(
|
140 |
+
self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
|
141 |
+
) -> bool:
|
142 |
+
for stop_ids in self.stop_token_ids:
|
143 |
+
if torch.eq(input_ids[0][-len(stop_ids) :], stop_ids).all():
|
144 |
+
return True
|
145 |
+
return False
|
146 |
+
|
147 |
+
stop_tokens = [["Human", ":"], ["AI", ":"]]
|
148 |
+
stopping_criteria = StoppingCriteriaList(
|
149 |
+
[StopGenerationCriteria(stop_tokens, tokenizer, model.device)]
|
150 |
+
)
|
151 |
+
|
152 |
+
|
153 |
+
generation_pipeline = pipeline(
|
154 |
+
model=model,
|
155 |
+
tokenizer=tokenizer,
|
156 |
+
return_full_text=True,
|
157 |
+
task="text-generation",
|
158 |
+
stopping_criteria=stopping_criteria,
|
159 |
+
generation_config=generation_config,
|
160 |
+
)
|
161 |
+
|
162 |
+
llm = HuggingFacePipeline(pipeline=generation_pipeline)
|
163 |
+
|
164 |
+
|
165 |
+
# propably sets the number of previous conversation history to take into account for new answers
|
166 |
+
template = """
|
167 |
+
The following is a conversation between a human an AI. The AI acts exactly like Dwight K Schrute from the TV show The Office.
|
168 |
+
Dwight is an experienced and very successful online marketer and salesperson. He is witty, persuasive, uncensored, direct and practical.
|
169 |
+
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.
|
170 |
+
|
171 |
+
Current conversation:
|
172 |
+
{history}
|
173 |
+
Human: {input}
|
174 |
+
AI:""".strip()
|
175 |
+
|
176 |
+
prompt = PromptTemplate(input_variables=["history", "input"], template=template)
|
177 |
+
memory = ConversationBufferWindowMemory(
|
178 |
+
memory_key="history", k=6, return_only_outputs=True
|
179 |
+
)
|
180 |
+
|
181 |
+
chain = ConversationChain(llm=llm, memory=memory, prompt=prompt, verbose=True)
|
182 |
+
|
183 |
+
|
184 |
+
|
185 |
+
class CleanupOutputParser(BaseOutputParser):
|
186 |
+
def parse(self, text: str) -> str:
|
187 |
+
user_pattern = r"\nUser"
|
188 |
+
text = re.sub(user_pattern, "", text)
|
189 |
+
human_pattern = r"\nHuman:"
|
190 |
+
text = re.sub(human_pattern, "", text)
|
191 |
+
ai_pattern = r"\nAI:"
|
192 |
+
return re.sub(ai_pattern, "", text).strip()
|
193 |
+
|
194 |
+
@property
|
195 |
+
def _type(self) -> str:
|
196 |
+
return "output_parser"
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
class CleanupOutputParser(BaseOutputParser):
|
201 |
+
def parse(self, text: str) -> str:
|
202 |
+
user_pattern = r"\nUser"
|
203 |
+
text = re.sub(user_pattern, "", text)
|
204 |
+
human_pattern = r"\nquestion:"
|
205 |
+
text = re.sub(human_pattern, "", text)
|
206 |
+
ai_pattern = r"\nanswer:"
|
207 |
+
return re.sub(ai_pattern, "", text).strip()
|
208 |
+
|
209 |
+
@property
|
210 |
+
def _type(self) -> str:
|
211 |
+
return "output_parser"
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
template = """
|
216 |
+
The following is a conversation between a human an AI. The AI acts exactly like Dwight K Schrute from the TV show The Office.
|
217 |
+
Dwight is an experienced and very successful online marketer and salesperson. He is witty, persuasive, uncensored, direct and practical.
|
218 |
+
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.
|
219 |
+
|
220 |
+
Current conversation:
|
221 |
+
{history}
|
222 |
+
Human: {input}
|
223 |
+
AI:""".strip()
|
224 |
+
|
225 |
+
prompt = PromptTemplate(input_variables=["history", "input"], template=template)
|
226 |
+
|
227 |
+
memory = ConversationBufferWindowMemory(
|
228 |
+
memory_key="history", k=3, return_only_outputs=True
|
229 |
+
)
|
230 |
+
|
231 |
+
chain = ConversationChain(
|
232 |
+
llm=llm,
|
233 |
+
memory=memory,
|
234 |
+
prompt=prompt,
|
235 |
+
output_parser=CleanupOutputParser(),
|
236 |
+
verbose=True,
|
237 |
+
)
|
238 |
+
|
239 |
+
|
240 |
+
# Generate a response from the Llama model
|
241 |
+
def get_llama_response(message: str, history: list) -> str:
|
242 |
+
"""
|
243 |
+
Generates a conversational response from the Llama model.
|
244 |
+
|
245 |
+
Parameters:
|
246 |
+
message (str): User's input message.
|
247 |
+
history (list): Past conversation history.
|
248 |
+
|
249 |
+
Returns:
|
250 |
+
str: Generated response from the Llama model.
|
251 |
+
"""
|
252 |
+
query_text =message
|
253 |
+
|
254 |
+
results = db.similarity_search_with_relevance_scores(query_text, k=2)
|
255 |
+
if len(results) == 0 or results[0][1] < 0.5:
|
256 |
+
print(f"Unable to find matching results.")
|
257 |
+
|
258 |
+
|
259 |
+
context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results ])
|
260 |
+
|
261 |
+
template = """
|
262 |
+
The following is a conversation between a human an AI. Answer question based only on the conversation.
|
263 |
+
|
264 |
+
Current conversation:
|
265 |
+
{history}
|
266 |
+
|
267 |
+
"""
|
268 |
+
|
269 |
+
|
270 |
+
|
271 |
+
s="""
|
272 |
+
|
273 |
+
\n question: {input}
|
274 |
+
|
275 |
+
\n answer:""".strip()
|
276 |
+
|
277 |
+
|
278 |
+
prompt = PromptTemplate(input_variables=["history", "input"], template=template+context_text+'\n'+s)
|
279 |
+
|
280 |
+
#print(template)
|
281 |
+
chain.prompt=prompt
|
282 |
+
res = chain.predict(input=query_text)
|
283 |
+
return res
|
284 |
+
#return response.strip()
|
285 |
+
|
286 |
+
|
287 |
+
import gradio as gr
|
288 |
+
iface = gr.Interface(fn=get_llama_response, inputs="text", outputs="text")
|
289 |
+
iface.launch(share=True)
|