File size: 5,332 Bytes
ec7d831
4cfde22
ec7d831
 
 
 
 
 
4cfde22
ec7d831
261e4f0
ec7d831
ee5803c
 
ec7d831
 
 
 
 
6888520
ec7d831
 
 
 
 
 
 
 
 
 
 
 
 
6888520
ec7d831
 
 
 
6888520
ec7d831
6888520
ec7d831
 
 
 
 
 
37a12f4
6888520
ec7d831
 
 
 
 
6888520
ec7d831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6888520
ec7d831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6888520
ec7d831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b25dddd
ec7d831
 
bd77084
ec7d831
 
 
 
 
 
b25dddd
ec7d831
 
 
 
 
b25dddd
ec7d831
 
 
 
 
4cfde22
 
ec7d831
 
 
 
 
 
 
37a12f4
 
ec7d831
 
 
bd77084
37a12f4
ec7d831
37a12f4
ec7d831
37a12f4
 
 
 
ec7d831
 
37a12f4
4cfde22
ec7d831
 
 
37a12f4
 
ec7d831
 
 
 
37a12f4
 
 
4cfde22
409e026
ec7d831
 
409e026
ee5803c
ec7d831
37a12f4
 
ec7d831
 
 
 
37a12f4
 
4cfde22
ec7d831
4cfde22
ec7d831
4cfde22
ec7d831
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import gradio as gr
import os
from langchain_community.vectorstores import FAISS
from langchain_together import TogetherEmbeddings, Together
from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser
from langchain.memory import ConversationBufferMemory
from typing import List, Tuple
import re

TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')


class ChatBot:
    def __init__(self):
        self.embeddings = TogetherEmbeddings(
            model="togethercomputer/m2-bert-80M-32k-retrieval",
            together_api_key=TOGETHER_API_KEY
        )













        
        self.vectorstore = FAISS.load_local(
            ".",
            embeddings=self.embeddings,
            allow_dangerous_deserialization=True  
        )
        self.retriever = self.vectorstore.as_retriever()
        
        self.model = Together(
            model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
            temperature=0.4,
            max_tokens=256,
            top_k=30,
            together_api_key=TOGETHER_API_KEY
        )
        
        self.memory = ConversationBufferMemory(
            return_messages=True,
            memory_key="chat_history",
            output_key="answer"
        )
        
        self.template = """Quyidagi ko'rsatmalarga qat'iy rioya qiling:



1. Faqat o'zbek tilida javob bering
2. Faqat berilgan ma'lumotlar asosida javob bering
3. Agar savol tushunarsiz bo'lsa yoki ma'lumot bo'lmasa, "Kechirasiz, bu haqida ma'lumotga ega emasman" deb javob bering
4. O'zingizdan savol bermang
5. Javobni takrorlamang
6. Salomlashish uchun "Assalomu alaykum" yoki "Vaalaykum assalom" dan foydalaning

Kontekst: {context}
Suhbat Tarixi: {chat_history}
Savol: {question}

Javob:"""



























        self.prompt = ChatPromptTemplate.from_template(self.template)
        
        self.chain = (
            {
                "context": self.retriever,
                "chat_history": lambda x: self.get_chat_history(),
                "question": RunnablePassthrough()
            }
            | self.prompt
            | self.model
            | StrOutputParser()





















        )

    def get_chat_history(self) -> str:
        messages = self.memory.load_memory_variables({})["chat_history"]
        return "\n".join([f"{m.type}: {m.content}" for m in messages])
    
    def process_response(self, response: str) -> str:
        unwanted_tags = ["[INST]", "[/INST]", "<s>", "</s>"]
        for tag in unwanted_tags:
            response = response.replace(tag, "")
        
        response = re.sub(r"```.*?```", "", response, flags=re.DOTALL)
        response = re.sub(r"print\(.*?\)", "", response)
        response = re.sub(r'\s+', ' ', response)
    
        return response.strip()

    def chat(self, message: str, history: List[Tuple[str, str]]) -> str:


























        try:


            
            if message == "__init__":
                return "Assalomu alaykum. Sizga qanday yordam bera olaman?"
                
            self.memory.chat_memory.add_user_message(message)
            response = self.chain.invoke(message)
            clean_response = self.process_response(response)
            
            if not clean_response or len(clean_response.split()) < 3:
                clean_response = "Kechirasiz, savolingizni tushunolmadim. Iltimos, batafsilroq savol bering."
            
            self.memory.chat_memory.add_ai_message(clean_response)
            return clean_response
        except Exception as e:
            return f"Xatolik yuz berdi: {str(e)}"

    def reset_chat(self) -> List[Tuple[str, str]]:
        self.memory.clear()
        return []

def create_demo() -> gr.Interface:
    chatbot = ChatBot()






    
    with gr.Blocks() as demo:
        gr.Markdown("""# RAG Chatbot
        Beeline Uzbekistanning jismoniy shaxslar uchun tariflari haqida ma'lumotlar beruvchi bot""")
        
        
        chatbot_interface = gr.Chatbot(
            height=600,
            show_copy_button=True,

        )
        
        with gr.Row():
            msg = gr.Textbox(
                show_label=False,
                placeholder="Xabaringizni shu yerda yozing",
                container=False
            )
            submit = gr.Button("Xabarni yuborish", variant="primary")
        
        clear = gr.Button("Yangi suhbat")
        
        def respond(message, chat_history):
            message = message.strip()
            if not message:
                return "", chat_history
            
            bot_message = chatbot.chat(message, chat_history)
            chat_history.append((message, bot_message))
            return "", chat_history
        
        def init_chat():
            
            initial_greeting = chatbot.chat("__init__", [])
            return [("", initial_greeting)]
        

        submit.click(respond, [msg, chatbot_interface], [msg, chatbot_interface])
        msg.submit(respond, [msg, chatbot_interface], [msg, chatbot_interface])
        clear.click(init_chat, None, chatbot_interface)
        
        
        demo.load(init_chat, None, chatbot_interface)
    
    return demo


demo = create_demo()

if __name__ == "__main__":
    demo.launch()