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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, List, Mapping, Optional
|
2 |
+
|
3 |
+
from langchain_core.callbacks.manager import CallbackManagerForLLMRun
|
4 |
+
from langchain_core.language_models.llms import LLM
|
5 |
+
from typing import Literal
|
6 |
+
import requests
|
7 |
+
from langchain.prompts import PromptTemplate, ChatPromptTemplate
|
8 |
+
from operator import itemgetter
|
9 |
+
|
10 |
+
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
|
11 |
+
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
|
12 |
+
from langchain_community.chat_models import ChatOpenAI
|
13 |
+
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
|
14 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
15 |
+
|
16 |
+
from langchain_community.document_loaders import DirectoryLoader
|
17 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
18 |
+
from langchain_community.document_loaders import PyMuPDFLoader
|
19 |
+
import os, requests
|
20 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
21 |
+
from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings
|
22 |
+
|
23 |
+
from langchain.vectorstores import FAISS
|
24 |
+
from langchain_core.runnables import RunnableBranch
|
25 |
+
import pickle, asyncio, traceback
|
26 |
+
|
27 |
+
# os.environ['FAISS_NO_AVX2'] = '1'
|
28 |
+
import pandas as pd
|
29 |
+
|
30 |
+
|
31 |
+
async def create_vectorstore():
|
32 |
+
API_TOKEN = os.getenv('HF_INFER_API')
|
33 |
+
|
34 |
+
loader = os.getenv('knowledge_base')
|
35 |
+
# web_loader = load_web("https://lintasmediadanawa.com")
|
36 |
+
|
37 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=20)
|
38 |
+
|
39 |
+
# docs = splitter.create_documents([loader]+web_loader)
|
40 |
+
docs = splitter.create_documents([loader])
|
41 |
+
print(len(docs))
|
42 |
+
emb_model = HuggingFaceEmbeddings(model_name='sentence-transformers/paraphrase-multilingual-mpnet-base-v2', encode_kwargs={'normalize_embeddings': True})
|
43 |
+
|
44 |
+
# emb_model = HuggingFaceInferenceAPIEmbeddings(
|
45 |
+
# api_key=API_TOKEN, model_name="sentence-transformers/paraphrase-multilingual-mpnet-base-v2", encode_kwargs={'normalize_embeddings': True}
|
46 |
+
# )
|
47 |
+
|
48 |
+
async def add_docs(d):
|
49 |
+
db.aadd_documents(await splitter.atransform_documents([d]))
|
50 |
+
|
51 |
+
db = await FAISS.afrom_documents(docs, emb_model)
|
52 |
+
|
53 |
+
f = pickle.load(open("wi_knowledge.dat", "rb"))
|
54 |
+
|
55 |
+
print("Docs len :", len(f))
|
56 |
+
|
57 |
+
tasks = []
|
58 |
+
|
59 |
+
for d in f:
|
60 |
+
tasks.append(db.aadd_documents(await splitter.atransform_documents([d])))
|
61 |
+
|
62 |
+
await asyncio.gather(*tasks)
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
# asyncio.run(db.aadd_documents(asyncio.run(splitter.atransform_documents(f))))
|
67 |
+
|
68 |
+
# emb_model = HuggingFaceInferenceAPIEmbeddings(
|
69 |
+
# api_key=API_TOKEN, model_name="sentence-transformers/paraphrase-multilingual-mpnet-base-v2", encode_kwargs={'normalize_embeddings': True}
|
70 |
+
# )
|
71 |
+
|
72 |
+
# x = open("wi_knowledge.pkl", 'rb')
|
73 |
+
|
74 |
+
# db = FAISS.deserialize_from_bytes(
|
75 |
+
# embeddings=emb_model, serialized=x
|
76 |
+
# )
|
77 |
+
|
78 |
+
# db = pickle.load(x)
|
79 |
+
# print(db)
|
80 |
+
# db.add_documents( splitter.transform_documents(docs) )
|
81 |
+
|
82 |
+
return db
|
83 |
+
|
84 |
+
|
85 |
+
def custom_chain_with_history(llm, memory):
|
86 |
+
|
87 |
+
# prompt = PromptTemplate.from_template("""<s><INST><|system|>
|
88 |
+
# You are a helpful and informative AI customer service assistant. Always remember to thank the customer when they say thank you and greet them when they greet you.
|
89 |
+
|
90 |
+
# You have access to the following context of knowledge base and internal resources to find the most relevant information for the customer's needs:
|
91 |
+
# {context}
|
92 |
+
|
93 |
+
# Respond to the user with the following chat history between you and the user:
|
94 |
+
# {chat_history}
|
95 |
+
# <|user|>
|
96 |
+
# {question}
|
97 |
+
# <|assistant|>
|
98 |
+
# """)
|
99 |
+
|
100 |
+
|
101 |
+
prompt = PromptTemplate.from_template("""<s><INST><|system|>
|
102 |
+
Anda adalah asisten AI Chatbot customer service.
|
103 |
+
Anda memiliki akses table dibawah ini untuk menemukan informasi yang paling relevan dengan kebutuhan user:
|
104 |
+
{context}
|
105 |
+
|
106 |
+
Berikan respon kepada user berdasarkan riwayat chat berikut dengan bahasa yang digunakan terakhir kali oleh user, jika tidak ada informasi yang relevan maka itu adalah informasi yang rahasia dan Anda tidak diizinkan untuk menyebarkan informasi tersebut kepada user:
|
107 |
+
{chat_history}
|
108 |
+
<|user|>
|
109 |
+
{question}
|
110 |
+
<|assistant|>
|
111 |
+
""")
|
112 |
+
|
113 |
+
def prompt_memory(memory):
|
114 |
+
t = ""
|
115 |
+
for x in memory.chat_memory.messages:
|
116 |
+
t += f"<|assistant|>\n<s>{x.content}</s>\n" if type(x) is AIMessage else f"<|user|>\n{x.content}\n"
|
117 |
+
return "" if len(t) == 0 else t
|
118 |
+
|
119 |
+
def format_docs(docs):
|
120 |
+
# print(len(docs))
|
121 |
+
return "\n".join([f"{i+1}. {d.page_content}" for i,d in enumerate(docs)])
|
122 |
+
|
123 |
+
# prompt = ChatPromptTemplate.from_messages(
|
124 |
+
# [
|
125 |
+
# ("system", "You are a helpful chatbot"),
|
126 |
+
# MessagesPlaceholder(variable_name="history"),
|
127 |
+
# ("human", "{input}"),
|
128 |
+
# ]
|
129 |
+
# )
|
130 |
+
|
131 |
+
# return {"chat_history":prompt_memory, "context":asyncio.run(create_vectorstore()).as_retriever(search_type="similarity", search_kwargs={"k": 12}) | format_docs, "question": RunnablePassthrough()} | prompt | llm
|
132 |
+
return {"chat_history":lambda x:prompt_memory(x['memory']), "context":itemgetter("question") | asyncio.run(create_vectorstore()).as_retriever(search_type="similarity", search_kwargs={"k": 100000}) | format_docs, "question": lambda x:x['question']} | prompt | llm
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
def format_df(df):
|
138 |
+
out = ""
|
139 |
+
|
140 |
+
for x in df.columns:
|
141 |
+
out+= x + "|"
|
142 |
+
out = out[:-1] + "\n\n"
|
143 |
+
|
144 |
+
for _,row in df.iterrows():
|
145 |
+
for x in row.values:
|
146 |
+
out += str(x) + "|"
|
147 |
+
|
148 |
+
out = out[:-1]
|
149 |
+
out += "\n"
|
150 |
+
|
151 |
+
return out
|
152 |
+
|
153 |
+
|
154 |
+
def out_format(text, llm, df):
|
155 |
+
|
156 |
+
prompt = PromptTemplate.from_template("""<s><INST>Fix the following code. Do not give explanation, just create the python code:
|
157 |
+
{code}
|
158 |
+
|
159 |
+
Error Message : {err}
|
160 |
+
Always change the corresponding columns into datetime format with parameter day_first=True, example:
|
161 |
+
df['column_name'] = pd.to_datetime(df['column_name'], day_first=True)
|
162 |
+
|
163 |
+
|
164 |
+
Always use idxmin or idxmax instead of array indicies whenever it is possible
|
165 |
+
Always use .iloc to query a dataframe instead of using array indicies directly
|
166 |
+
|
167 |
+
The output must follow the following example format:
|
168 |
+
```python
|
169 |
+
# Generated Code
|
170 |
+
```
|
171 |
+
|
172 |
+
</INST></s>""")
|
173 |
+
|
174 |
+
err_chain = prompt | llm
|
175 |
+
|
176 |
+
e_ = None
|
177 |
+
|
178 |
+
for i in range(6):
|
179 |
+
|
180 |
+
try :
|
181 |
+
print(text)
|
182 |
+
text_split = text.split("`python")[-1].split("```")[0].replace('\_', "_")
|
183 |
+
# text_split = text.split("# Generated Code")[-1].split("```")[0].replace("\_", "_")
|
184 |
+
if "response" not in text_split:
|
185 |
+
text = text.split("```")[0].replace('\_', "_")
|
186 |
+
else :
|
187 |
+
text = text_split
|
188 |
+
|
189 |
+
print(text)
|
190 |
+
try :
|
191 |
+
exec(text)
|
192 |
+
except :
|
193 |
+
text_split = text.split("# Generated Code")[-1].split("```")[0].replace("\_", "_")
|
194 |
+
if "response" not in text_split:
|
195 |
+
text = text.split("```")[0].replace('\_', "_")
|
196 |
+
else :
|
197 |
+
text = "# Generated Code" + text_split
|
198 |
+
print(text)
|
199 |
+
exec(text)
|
200 |
+
|
201 |
+
return text
|
202 |
+
except Exception as e:
|
203 |
+
print(f"ERORRR! ATTEMPT : {i}\n",str(traceback.format_exc(limit=2)))
|
204 |
+
text = err_chain.invoke({"code":text, "err":str(traceback.format_exc(limit=2))})
|
205 |
+
e_ = traceback.format_exc(limit=2)
|
206 |
+
# exec(text)
|
207 |
+
|
208 |
+
return "Bad Python Code, Error Message : " + str(e_)
|
209 |
+
|
210 |
+
|
211 |
+
def unique_value_str_func(unique_val):
|
212 |
+
return "\n".join([str(i+1) + "." + k + ": " + str(v) for i,(k,v) in enumerate(unique_val.items())])
|
213 |
+
|
214 |
+
|
215 |
+
|
216 |
+
|
217 |
+
def custom_dataframe_chain(llm, df, unique_values):
|
218 |
+
unique_str = unique_value_str_func(unique_values)
|
219 |
+
print(unique_str)
|
220 |
+
|
221 |
+
prompt = PromptTemplate.from_template("""<s><INST>You have access to a pandas dataframe variable named "df". Below are the examples of the dataframe:
|
222 |
+
{df_example}
|
223 |
+
|
224 |
+
Given the following user input, create relevant python code to get the relevant information in the dataframe and store the response string result in a variable named "response". Do not explain, just create the python code:
|
225 |
+
|
226 |
+
{question}
|
227 |
+
|
228 |
+
Always change the corresponding columns into datetime format with parameter day_first=True, example:
|
229 |
+
df['column_name'] = pd.to_datetime(df['column_name'], day_first=True)
|
230 |
+
|
231 |
+
|
232 |
+
Always use idxmin or idxmax instead of array indicies whenever it is possible
|
233 |
+
|
234 |
+
|
235 |
+
Do not import pandas and Do not create or re-assign "df" variable
|
236 |
+
Below is the unique value of the important categorical columns:
|
237 |
+
{unique_val}
|
238 |
+
|
239 |
+
|
240 |
+
The output must follow the following example format:
|
241 |
+
```python
|
242 |
+
# Generated Code
|
243 |
+
```
|
244 |
+
|
245 |
+
</INST></s>""").partial(unique_val=unique_str)
|
246 |
+
|
247 |
+
return prompt | llm | RunnableLambda(lambda x:out_format(x, llm, df))
|
248 |
+
|
249 |
+
|
250 |
+
|
251 |
+
def custom_unique_df_chain(llm, df):
|
252 |
+
prompt = PromptTemplate(template="""<s><INST>You have access to a pandas dataframe variable named "df". Below are the examples of the dataframe:
|
253 |
+
{df_example}
|
254 |
+
|
255 |
+
|
256 |
+
Create unique values for the important non-datetime categorical columns with maximum 20 unique values for each columns. Store the unique values in a variable named "response" with the following format of python dictionary:
|
257 |
+
|
258 |
+
{{ column_name1 : [list_of_unique_column1], column_name2 : [list_of_unique_values_column2], column_name3 : [list_of_unique_values_column3] }}
|
259 |
+
|
260 |
+
The output must follow the following example format:
|
261 |
+
```python
|
262 |
+
# Generated Code
|
263 |
+
```
|
264 |
+
|
265 |
+
</INST></s>""", input_variables=["df_example"])
|
266 |
+
|
267 |
+
|
268 |
+
return prompt | llm | RunnableLambda(lambda x:out_format(x, llm, df))
|
269 |
+
|
270 |
+
|
271 |
+
def custom_combined_chain(llm, df_chain, memory_chain):
|
272 |
+
|
273 |
+
prompt = PromptTemplate.from_templates("""<s><INST> Given the following question, classify it as either being more relevant with a dataframe object of ticket submissions' history or several documents of user guide and general knowledge:
|
274 |
+
|
275 |
+
<question>
|
276 |
+
{question}
|
277 |
+
</question>
|
278 |
+
|
279 |
+
Do not respond with more than two words.
|
280 |
+
|
281 |
+
</s></INST>""")
|
282 |
+
|
283 |
+
branch = RunnableBranch(
|
284 |
+
(lambda x: "anthropic" in x["topic"].lower(), anthropic_chain),
|
285 |
+
(lambda x: "langchain" in x["topic"].lower(), langchain_chain),
|
286 |
+
general_chain,
|
287 |
+
)
|
288 |
+
|
289 |
+
# def route(info):
|
290 |
+
# if 'ticket' in info['topic']:
|
291 |
+
# return df_chain
|
292 |
+
# else:
|
293 |
+
# return memory_chain
|
294 |
+
|
295 |
+
|
296 |
+
# full_chain = RunnablePassthrough.assign(topic= (llm | prompt)) | RunnableLambda(route)
|
297 |
+
|
298 |
+
return RunnableBranch( (lambda x: "ticket" in x['topic'].lower(), df_chain), (lambda x: "dataframe" in x['topic'].lower(), df_chain), memory_chain )
|
299 |
+
|
300 |
+
|
301 |
+
class CustomLLM(LLM):
|
302 |
+
repo_id : str
|
303 |
+
api_token : str
|
304 |
+
model_type: Literal["text2text-generation", "text-generation"]
|
305 |
+
max_new_tokens: int = None
|
306 |
+
temperature: float = 0.001
|
307 |
+
timeout: float = None
|
308 |
+
top_p: float = None
|
309 |
+
top_k : int = None
|
310 |
+
repetition_penalty : float = None
|
311 |
+
stop : List[str] = []
|
312 |
+
|
313 |
+
|
314 |
+
@property
|
315 |
+
def _llm_type(self) -> str:
|
316 |
+
return "custom"
|
317 |
+
|
318 |
+
def _call(
|
319 |
+
self,
|
320 |
+
prompt: str,
|
321 |
+
stop: Optional[List[str]] = None,
|
322 |
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
323 |
+
**kwargs: Any,
|
324 |
+
) -> str:
|
325 |
+
|
326 |
+
headers = {"Authorization": f"Bearer {self.api_token}"}
|
327 |
+
API_URL = f"https://api-inference.huggingface.co/models/{self.repo_id}"
|
328 |
+
|
329 |
+
parameters_dict = {
|
330 |
+
'max_new_tokens': self.max_new_tokens,
|
331 |
+
'temperature': self.temperature,
|
332 |
+
'timeout': self.timeout,
|
333 |
+
'top_p': self.top_p,
|
334 |
+
'top_k': self.top_k,
|
335 |
+
'repetition_penalty': self.repetition_penalty,
|
336 |
+
'stop':self.stop
|
337 |
+
}
|
338 |
+
|
339 |
+
if self.model_type == 'text-generation':
|
340 |
+
parameters_dict["return_full_text"]=False
|
341 |
+
|
342 |
+
data = {"inputs": prompt, "parameters":parameters_dict, "options":{"wait_for_model":True}}
|
343 |
+
data = requests.post(API_URL, headers=headers, json=data).json()
|
344 |
+
return data[0]['generated_text']
|
345 |
+
|
346 |
+
@property
|
347 |
+
def _identifying_params(self) -> Mapping[str, Any]:
|
348 |
+
"""Get the identifying parameters."""
|
349 |
+
return {
|
350 |
+
'repo_id': self.repo_id,
|
351 |
+
'model_type':self.model_type,
|
352 |
+
'stop_sequences':self.stop,
|
353 |
+
'max_new_tokens': self.max_new_tokens,
|
354 |
+
'temperature': self.temperature,
|
355 |
+
'timeout': self.timeout,
|
356 |
+
'top_p': self.top_p,
|
357 |
+
'top_k': self.top_k,
|
358 |
+
'repetition_penalty': self.repetition_penalty
|
359 |
+
}
|