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|
+
|
3 |
+
# hf_token
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
load_dotenv()
|
6 |
+
import os
|
7 |
+
hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
8 |
+
|
9 |
+
|
10 |
+
# [์ ํ1] ๊ฑฐ๋๋ชจ๋ธ ๋ญ์ฒด์ธ Custom LLM (HF InferenceClient) - 70B๊ฐ ๋ฌด๋ฃ!!!, openai๋ณด๋ค ์ฑ๋ฅ ์๋จ์ด์ง (์คํธ๋ฆฌ๋ฐ์ ์์ง ์๋จ)
|
11 |
+
# model_name = "tiiuae/falcon-180B-chat"
|
12 |
+
model_name="meta-llama/Llama-2-70b-chat-hf"
|
13 |
+
# model_name="NousResearch/Llama-2-70b-chat-hf"
|
14 |
+
# model_name="meta-llama/Llama-2-13b-chat-hf"
|
15 |
+
# model_name="meta-llama/Llama-2-7b-chat-hf"
|
16 |
+
# model_name = "HuggingFaceH4/zephyr-7b-alpha"
|
17 |
+
|
18 |
+
kwargs = {"max_new_tokens":256, "temperature":0.9, "top_p":0.6, "repetition_penalty":1.3, "do_sample":True}
|
19 |
+
|
20 |
+
# ์ปค์คํ
LLM
|
21 |
+
from pydantic import BaseModel, Field
|
22 |
+
from typing import Any, Optional, Dict, List
|
23 |
+
from huggingface_hub import InferenceClient
|
24 |
+
from langchain.llms.base import LLM
|
25 |
+
|
26 |
+
class CustomInferenceClient(LLM, KwArgsModel):
|
27 |
+
model_name: str
|
28 |
+
inference_client: InferenceClient
|
29 |
+
|
30 |
+
def __init__(self, model_name: str, hf_token: str, kwargs: Optional[Dict[str, Any]] = None):
|
31 |
+
inference_client = InferenceClient(model=model_name, token=hf_token)
|
32 |
+
super().__init__(
|
33 |
+
model_name=model_name,
|
34 |
+
hf_token=hf_token,
|
35 |
+
kwargs=kwargs,
|
36 |
+
inference_client=inference_client # inference_client ์ธ์ ์ถ๊ฐ
|
37 |
+
)
|
38 |
+
|
39 |
+
def _call(
|
40 |
+
self,
|
41 |
+
prompt: str,
|
42 |
+
stop: Optional[List[str]] = None
|
43 |
+
) -> str:
|
44 |
+
if stop is not None:
|
45 |
+
raise ValueError("stop kwargs are not permitted.")
|
46 |
+
# pdb.set_trace()
|
47 |
+
# response_gen = self.__dict__['client'].text_generation(prompt, stream=True, **self.kwargs) # ์ ์ฅ๋ kwargs๋ฅผ ์ฌ์ฉ,
|
48 |
+
response_gen = self.inference_client.text_generation(prompt, **self.kwargs, stream=True)
|
49 |
+
response = ''.join(response_gen) # ์ ๋๋ ์ดํฐ์ ๋ชจ๋ ๊ฐ์ ๋ฌธ์์ด๋ก ์ฐ๊ฒฐ
|
50 |
+
return response
|
51 |
+
|
52 |
+
@property
|
53 |
+
def _llm_type(self) -> str:
|
54 |
+
return "custom"
|
55 |
+
|
56 |
+
@property
|
57 |
+
def _identifying_params(self) -> dict:
|
58 |
+
return {"model_name": self.model_name}
|
59 |
+
|
60 |
+
# ์ฌ์ฉ ์์ :
|
61 |
+
# prompt="How do you make cheese?"
|
62 |
+
# prompt = "Tell me the names of the last 10 U.S. presidents"
|
63 |
+
prompt="Tell me 10 of the world's largest buildings in high order"
|
64 |
+
|
65 |
+
llm = CustomInferenceClient(model_name=model_name, hf_token=hf_token, kwargs=kwargs) # hf_token ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
|
66 |
+
# llm = CustomInferenceClient(model_name=model_name, kwargs=kwargs) # hf_token ์ฌ์ฉํ์ง ์๋ ๊ฒฝ์ฐ
|
67 |
+
|
68 |
+
|
69 |
+
# ์๋ฒ ๋ฉ ๊ฐ์ฒด ์์ฑ
|
70 |
+
from langchain.embeddings import HuggingFaceInstructEmbeddings
|
71 |
+
embeddings = HuggingFaceInstructEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cuda"})
|
72 |
+
|
73 |
+
# ๋ฒกํฐDB ๋ก๋
|
74 |
+
path_work ='.'
|
75 |
+
|
76 |
+
from langchain.vectorstores import Chroma
|
77 |
+
vectordb = Chroma(
|
78 |
+
persist_directory = path_work + '/cromadb_llama2-papers',
|
79 |
+
embedding_function=embeddings)
|
80 |
+
|
81 |
+
retriever = vectordb.as_retriever(search_kwargs={"k": 5})
|
82 |
+
|
83 |
+
# RetrievalQA ์ฒด์ธ ๋ง๋ค๊ธฐ
|
84 |
+
from langchain.chains import RetrievalQA
|
85 |
+
qa_chain = RetrievalQA.from_chain_type(
|
86 |
+
# llm=OpenAI(), # from langchain.llms import OpenAI
|
87 |
+
llm=llm,
|
88 |
+
chain_type="stuff",
|
89 |
+
retriever=retriever,
|
90 |
+
return_source_documents=True,
|
91 |
+
verbose=True,
|
92 |
+
)
|
93 |
+
qa_chain
|
94 |
+
|
95 |
+
# ๊ทธ๋ผ๋์ค
|
96 |
+
import json
|
97 |
+
import os
|
98 |
+
import gradio as gr
|
99 |
+
|
100 |
+
# Stream text
|
101 |
+
def predict(message, chatbot, temperature=0.9, max_new_tokens=512, top_p=0.6, repetition_penalty=1.3,):
|
102 |
+
|
103 |
+
temperature = float(temperature)
|
104 |
+
if temperature < 1e-2: temperature = 1e-2
|
105 |
+
top_p = float(top_p)
|
106 |
+
|
107 |
+
# ํ๋กฌํํธ
|
108 |
+
# system_message = "\nYou are a psychological counselor who gives friendly and professional counseling on the concerns of Korean clients."
|
109 |
+
# input_prompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n "
|
110 |
+
# for interaction in chatbot:
|
111 |
+
# input_prompt = input_prompt + str(interaction[0]) + " [/INST] " + str(interaction[1]) + " </s><s> [INST] "
|
112 |
+
|
113 |
+
# input_prompt = input_prompt + str(message) + " [/INST] "
|
114 |
+
|
115 |
+
|
116 |
+
# conversationalRetrievalChain (ํ์คํ ๋ฆฌ๊ฐ ์ฒด์ธ ๋ด์ฅ ํ๋กฌํํธ์ ์ธํ๋จ)
|
117 |
+
# chat_history = []
|
118 |
+
# for interaction in chatbot:
|
119 |
+
# chat_history = chat_history + [(str(interaction[0]), str(interaction[1]))]
|
120 |
+
# llm_response = qa_chain_conv({"question": message, "chat_history": chat_history})
|
121 |
+
# res_result = llm_response['answer']
|
122 |
+
|
123 |
+
|
124 |
+
# RetrievalQA ์ฒด์ธ (ํ์คํ ๋ฆฌ๊ฐ ์ฒด์ธ ๋ด์ฅ ํ๋กฌํํธ์ ์ธํ ์๋จ)
|
125 |
+
llm_response = qa_chain(message)
|
126 |
+
res_result = llm_response['result']
|
127 |
+
|
128 |
+
# conversationalRetrievalChain, RetrievalQA ์ฒด์ธ ๊ณตํต
|
129 |
+
res_relevant_doc = [source.metadata['source'] for source in llm_response["source_documents"]]
|
130 |
+
response = f"{res_result}" + "\n\n" + "[๋ต๋ณ ๊ทผ๊ฑฐ ์์ค ๋
ผ๋ฌธ (ctrl + click ํ์ธ์!)] :" + "\n" + f" \n {res_relevant_doc}"
|
131 |
+
print("response: =====> \n", response, "\n\n")
|
132 |
+
|
133 |
+
#3) json ํํ๋ก ๋ณํ (api response์ ๊ฐ์ ํํ)
|
134 |
+
import json
|
135 |
+
tokens = response.split('\n')
|
136 |
+
token_list = []
|
137 |
+
for idx, token in enumerate(tokens):
|
138 |
+
token_dict = {"id": idx + 1, "text": token}
|
139 |
+
token_list.append(token_dict)
|
140 |
+
response = {"data": {"token": token_list}}
|
141 |
+
response = json.dumps(response, indent=4)
|
142 |
+
|
143 |
+
'''{'data': {'token': [{'id': 1, 'text': 'Artificial intelligence (AI) refers to...'},
|
144 |
+
{'id': 2, 'text': 'I hope this information helher questions!'}]}}'''
|
145 |
+
|
146 |
+
# ===========================================================================
|
147 |
+
# ์คํธ๋ฆฌ๋ฐ ์์ (partial_message)
|
148 |
+
response = json.loads(response) # {'data': {'token': [{'id': 1, 'text': '๋ต๋ณ์ " ์๋
ํ์ธ์. ์ ๋ ์ก์์ง ๋ฐ์ฌ.....
|
149 |
+
data_dict = response.get('data', {})
|
150 |
+
token_list = data_dict.get('token', [])
|
151 |
+
|
152 |
+
import time
|
153 |
+
partial_message = ""
|
154 |
+
# ํ์ด๋ผ์ดํธ: .iter_lines() ๋์ ์ token_list๋ฅผ ์ง์ ์ํํฉ๋๋ค.
|
155 |
+
for token_entry in token_list:
|
156 |
+
if token_entry: # filter out keep-alive new lines (if any)
|
157 |
+
try:
|
158 |
+
# ํ์ด๋ผ์ดํธ: ์ง์ ์ฌ์ ์์ 'id'์ 'text'๋ฅผ ์ถ์ถํฉ๋๋ค.
|
159 |
+
token_id = token_entry.get('id', None)
|
160 |
+
token_text = token_entry.get('text', None)
|
161 |
+
|
162 |
+
# time.sleep์ผ๋ก ๊ธ์ ์๋ ์กฐ์ ํ๋ฉฐ ๊ธ์ ๋ด๋ณด๋
|
163 |
+
if token_text: # ์ด ๋ถ๋ถ์ ์ํ๋ ๋๋ก ์กฐ์ ํ ์ ์์ต๋๋ค.
|
164 |
+
# partial_message = partial_message + token_text
|
165 |
+
for char in token_text: # ๋ฌธ์ ํ๋์ฉ ์ํ (์ถ๊ฐ๋จ)
|
166 |
+
partial_message += char # partial_message์ ๋ฌธ์ ์ถ๊ฐ (๋ณ๊ฒฝ๋จ)
|
167 |
+
yield partial_message
|
168 |
+
time.sleep(0.01)
|
169 |
+
else:
|
170 |
+
# gr.Warning(f"The key 'text' does not exist or is None in this token entry: {token_entry}")
|
171 |
+
print(f"[[์๋]] ==> The key 'text' does not exist or is None in this token entry: {token_entry}")
|
172 |
+
|
173 |
+
except KeyError as e:
|
174 |
+
gr.Warning(f"KeyError: {e} occurred for token entry: {token_entry}")
|
175 |
+
continue
|
176 |
+
|
177 |
+
# ํ์ดํ/์ค๋ช
/์ง๋ฌธ์์
|
178 |
+
title = "llama-2 ๋ชจ๋ธ ๊ด๋ จ ๋
ผ๋ฌธ QA ์๋น์ค"
|
179 |
+
description = """chat history ์ ์ง ๋ณด๋ค๋ QA์ ์ถฉ์คํ๋๋ก ์ ์๋์์ผ๋ Single turn์ผ๋ก ํ์ฉ์ ํ์ฌ ์ฃผ์ธ์. (chat history ํ์ฉ์ ๋ค๋ฅธ ์ฃผ์ ๋ก ๋ณ๋ ์ ์ ์์ )"""
|
180 |
+
css = """.toast-wrap { display: none !important } """
|
181 |
+
examples=[['Can you tell me about the llama-2 model?'],['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ["tell me about method for human pose estimation based on DNNs"]]
|
182 |
+
|
183 |
+
# ์ข์์
|
184 |
+
import gradio as gr
|
185 |
+
def vote(data: gr.LikeData):
|
186 |
+
if data.liked: print("You upvoted this response: " + data.value)
|
187 |
+
else: print("You downvoted this response: " + data.value)
|
188 |
+
|
189 |
+
# ๊ทธ๋ผ๋์ค (์ธ์ ์กฐ์ )
|
190 |
+
additional_inputs = [
|
191 |
+
# gr.Textbox("", label="Optional system prompt"),
|
192 |
+
gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
|
193 |
+
gr.Slider(label="Max new tokens", value=256, minimum=0, maximum=4096, step=64, interactive=True, info="The maximum numbers of new tokens"),
|
194 |
+
gr.Slider(label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens"),
|
195 |
+
gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens")
|
196 |
+
]
|
197 |
+
|
198 |
+
chatbot_stream = gr.Chatbot(avatar_images=(
|
199 |
+
"https://drive.google.com/uc?id=13rYrN0cH_9tR7GveqO1q2JiyBCqkfCLZ", # https://drive.google.com/uc?id= ๋ค์ ID๊ฐ๋ง (๋ชจ๋ ์ฌ์ฉ์ ์ก์ธ์ค ๊ถํ ํ์ฉ)
|
200 |
+
"https://drive.google.com/uc?id=1tfELAQW_VbPCy6QTRbexRlwAEYo8rSSv"
|
201 |
+
), bubble_full_width = False)
|
202 |
+
|
203 |
+
chat_interface_stream = gr.ChatInterface(predict,
|
204 |
+
title=title,
|
205 |
+
description=description,
|
206 |
+
# textbox=gr.Textbox(lines=5),
|
207 |
+
chatbot=chatbot_stream,
|
208 |
+
css=css,
|
209 |
+
examples=examples,
|
210 |
+
# cache_examples=True,
|
211 |
+
# additional_inputs=additional_inputs,
|
212 |
+
)
|
213 |
+
|
214 |
+
# Gradio Demo
|
215 |
+
with gr.Blocks() as demo:
|
216 |
+
|
217 |
+
with gr.Tab("์คํธ๋ฆฌ๋ฐ"):
|
218 |
+
#gr.ChatInterface(predict, title=title, description=description, css=css, examples=examples, cache_examples=True, additional_inputs=additional_inputs,)
|
219 |
+
chatbot_stream.like(vote, None, None)
|
220 |
+
chat_interface_stream.render()
|
221 |
+
|
222 |
+
|
223 |
+
demo.queue(concurrency_count=75, max_size=100).launch(debug=True)
|
224 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub
|
2 |
+
langchain
|
3 |
+
gradio
|
4 |
+
python-dotenv
|
5 |
+
|
6 |
+
|