jonathanjordan21 commited on
Commit
8c92d3f
1 Parent(s): cd73f6e

Create custom_llm.py

Browse files
Files changed (1) hide show
  1. custom_llm.py +115 -0
custom_llm.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ConversationBufferMemory
11
+ from langchain.memory import ChatMessageHistory, ConversationBufferMemory
12
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
13
+ from langchain_community.chat_models import ChatOpenAI
14
+ from langchain_core.runnables import RunnableLambda, RunnablePassthrough
15
+ from langchain_core.messages import AIMessage, HumanMessage
16
+
17
+
18
+ def custom_chain_with_history(llm, memory):
19
+
20
+ prompt = PromptTemplate.from_template("""<s><INST><|system|>
21
+ You are a college student at Gunadarma University, majoring in Informatics / Computer Science. Your name is Jonathan Jordan, but people call you Jojo. You have expertise in Artificial Intelligence and Data Science. You are also good at Data Engineering with AirFlow and Apache Spark. You currently live in Jakarta, Indonesia. You are 21 years old. Your birthday is Friday, 21 June 2002.
22
+
23
+ Below are the detailed personal information of you:
24
+ {context}
25
+
26
+ Respond to the user with the following chat history between you and the user:
27
+ {chat_history}
28
+ <|interviewer|>
29
+ {question}
30
+ <|you|>
31
+ """)
32
+
33
+ def prompt_memory(_):
34
+ t = ""
35
+ for x in memory.chat_memory.messages:
36
+ t += f"<|assistant|>\n<s>{x.content}</s>\n" if type(x) is AIMessage else f"<|user|>\n{x.content}\n"
37
+ # t += f"You: {x.content}\n" if type(x) is AIMessage else f"User: {x.content}\n"
38
+ print(q)
39
+ return "" if len(t) == 0 else t
40
+
41
+ def format_docs(docs):
42
+ print(len(docs))
43
+ return "\n".join([f"{i+1}. {d.page_content}" for i,d in enumerate(docs)])
44
+
45
+ # prompt = ChatPromptTemplate.from_messages(
46
+ # [
47
+ # ("system", "You are a helpful chatbot"),
48
+ # MessagesPlaceholder(variable_name="history"),
49
+ # ("human", "{input}"),
50
+ # ]
51
+ # )
52
+
53
+ return {"chat_history":prompt_memory, "context":db.as_retriever(search_type="similarity", search_kwargs={"k": 8}) | format_docs, "question": RunnablePassthrough()} | prompt | llm
54
+
55
+ class CustomLLM(LLM):
56
+ repo_id : str
57
+ api_token : str
58
+ model_type: Literal["text2text-generation", "text-generation"]
59
+ max_new_tokens: int = None
60
+ temperature: float = 0.001
61
+ timeout: float = None
62
+ top_p: float = None
63
+ top_k : int = None
64
+ repetition_penalty : float = None
65
+ stop : List[str] = []
66
+
67
+
68
+ @property
69
+ def _llm_type(self) -> str:
70
+ return "custom"
71
+
72
+ def _call(
73
+ self,
74
+ prompt: str,
75
+ stop: Optional[List[str]] = None,
76
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
77
+ **kwargs: Any,
78
+ ) -> str:
79
+
80
+ headers = {"Authorization": f"Bearer {self.api_token}"}
81
+ API_URL = f"https://api-inference.huggingface.co/models/{self.repo_id}"
82
+
83
+ parameters_dict = {
84
+ 'max_new_tokens': self.max_new_tokens,
85
+ 'temperature': self.temperature,
86
+ 'timeout': self.timeout,
87
+ 'top_p': self.top_p,
88
+ 'top_k': self.top_k,
89
+ 'repetition_penalty': self.repetition_penalty,
90
+ 'stop':self.stop
91
+ }
92
+
93
+ if self.model_type == 'text-generation':
94
+ parameters_dict["return_full_text"]=False
95
+
96
+ data = {"inputs": prompt, "parameters":parameters_dict, "options":{"wait_for_model":True}}
97
+ data = requests.post(API_URL, headers=headers, json=data).json()
98
+ print(data)
99
+ return data[0]['generated_text']
100
+
101
+ @property
102
+ def _identifying_params(self) -> Mapping[str, Any]:
103
+ """Get the identifying parameters."""
104
+ return {
105
+ 'repo_id': self.repo_id,
106
+ 'model_type':self.model_type,
107
+ 'stop_sequences':self.stop,,
108
+ 'max_new_tokens': self.max_new_tokens,
109
+ 'temperature': self.temperature,
110
+ 'timeout': self.timeout,
111
+ 'top_p': self.top_p,
112
+ 'top_k': self.top_k,
113
+ 'repetition_penalty': self.repetition_penalty
114
+ }
115
+