SUMANA SUMANAKUL (ING) commited on
Commit
1682215
·
1 Parent(s): 2d3755a

modify code

Browse files
Files changed (3) hide show
  1. app.py +251 -139
  2. utils/chat.py +12 -2
  3. utils/chat_prompts.py +156 -26
app.py CHANGED
@@ -6,205 +6,317 @@ import uuid
6
  from utils.chat import ChatLaborLaw
7
 
8
 
9
- def initialize_session():
10
- """
11
- สร้าง session ID ใหม่ และสร้าง instance ใหม่ของ ChatLaborLaw
12
- """
13
  session_id = str(uuid.uuid4())[:8]
14
- chatbot_instance = ChatLaborLaw()
15
- return "", session_id, chatbot_instance, []
16
-
17
- async def chat_function(prompt: str, history_ui: list, chatbot_instance: ChatLaborLaw):
18
- """
19
- จัดการการสนทนา
20
- """
21
- if chatbot_instance is None or not prompt.strip():
22
- return history_ui, chatbot_instance, ""
23
-
24
- response = await chatbot_instance.chat(prompt)
25
- history_ui.append((prompt, response))
26
- return history_ui, chatbot_instance, ""
27
-
28
- def save_feedback(feedback: str, history_ui: list, session_id: str):
29
- """
30
- บันทึก Feedback
31
- """
32
- if not feedback.strip():
33
- return ""
34
- os.makedirs("feedback", exist_ok=True)
35
- filename = f"feedback/feedback_{session_id}.txt"
 
 
 
 
 
36
  with open(filename, "a", encoding="utf-8") as f:
37
  f.write("=== Feedback Received ===\n")
38
  f.write(f"Session ID: {session_id}\n")
39
- f.write(f"Feedback: {feedback}\n\n")
40
  f.write("Chat History:\n")
41
- for user_msg, assistant_msg in history_ui:
42
- f.write(f"User: {user_msg}\n")
43
- f.write(f"Assistant: {assistant_msg}\n")
44
- f.write("-" * 20 + "\n")
45
- f.write("\n==========================\n\n")
46
- gr.Info("ขอบคุณสำหรับข้อเสนอแนะ!")
47
- return ""
48
-
49
- # --------------------------------------------------------------------------
50
- # สร้าง Gradio Interface
51
- # --------------------------------------------------------------------------
52
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
53
  gr.Markdown("# สอบถามเรื่องกฎหมายแรงงาน")
54
 
55
- session_id_state = gr.State()
56
- chatbot_instance_state = gr.State()
57
-
58
- chatbot_interface = gr.Chatbot(
59
- label="ประวัติการสนทนา",
60
- height=550,
61
- # bubble_styling=False,
62
- show_copy_button=True
63
- )
64
- user_input = gr.Textbox(placeholder="พิมพ์คำถามของคุณที่นี่...", label="คำถาม", lines=2)
65
 
66
- with gr.Row():
67
- submit_button = gr.Button("ส่ง", variant="primary", scale=4)
68
- clear_button = gr.Button("เริ่มการสนทนาใหม่", scale=1)
 
 
 
69
 
70
- submit_event = submit_button.click(
 
71
  fn=chat_function,
72
- inputs=[user_input, chatbot_interface, chatbot_instance_state],
73
- outputs=[chatbot_interface, chatbot_instance_state, user_input]
74
  )
 
75
  user_input.submit(
76
  fn=chat_function,
77
- inputs=[user_input, chatbot_interface, chatbot_instance_state],
78
- outputs=[chatbot_interface, chatbot_instance_state, user_input]
79
  )
80
 
 
 
81
  clear_button.click(
82
  fn=initialize_session,
83
  inputs=[],
84
- outputs=[user_input, session_id_state, chatbot_instance_state, chatbot_interface],
85
- queue=False
 
 
 
86
  )
87
 
88
- with gr.Accordion("ส่งข้อเสนอแนะ (Feedback)", open=False):
89
- feedback_input = gr.Textbox(placeholder="ความคิดเห็นของคุณมีความสำคัญต่อการพัฒนาของเรา...", label="Feedback", lines=2, scale=4)
90
- send_feedback_button = gr.Button("ส่ง Feedback")
 
 
91
 
92
  send_feedback_button.click(
93
- fn=save_feedback,
94
- inputs=[feedback_input, chatbot_interface, session_id_state],
95
- outputs=[feedback_input],
96
- queue=False
97
  )
98
 
 
99
  demo.load(
100
  fn=initialize_session,
101
  inputs=[],
102
- outputs=[user_input, session_id_state, chatbot_instance_state, chatbot_interface]
103
  )
104
 
105
- demo.queue().launch()
106
-
107
-
108
- # # Function to initialize a new session and create chatbot instance for that session
109
- # async def initialize_session():
110
- # session_id = str(uuid.uuid4())[:8]
111
- # chatbot = ChatLaborLaw()
112
- # # chatbot = Chat("gemini-2.0-flash")
113
- # history = []
114
- # return "", session_id, chatbot, history
115
-
116
 
117
- # # Function to handle user input and chatbot response
118
- # async def chat_function(prompt, history, session_id, chatbot):
119
- # if chatbot is None:
120
- # return history, "", session_id, chatbot # Skip if chatbot not ready
121
-
122
- # # Append the user's input to the message history
123
- # history.append({"role": "user", "content": prompt})
124
 
125
- # # Get the response from the chatbot
126
- # response = await chatbot.chat(prompt) # ใช้ await ได้แล้ว
127
-
128
- # # Append the assistant's response to the message history
129
- # history.append({"role": "assistant", "content": response})
130
-
131
- # return history, "", session_id, chatbot
132
 
133
 
134
- # # Function to save feedback with chat history
135
- # async def send_feedback(feedback, history, session_id, chatbot):
136
- # os.makedirs("app/feedback", exist_ok=True)
137
- # filename = f"app/feedback/feedback_{session_id}.txt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  # with open(filename, "a", encoding="utf-8") as f:
139
  # f.write("=== Feedback Received ===\n")
140
  # f.write(f"Session ID: {session_id}\n")
141
- # f.write(f"Feedback: {feedback}\n")
142
  # f.write("Chat History:\n")
143
- # for msg in history:
144
- # f.write(f"{msg['role']}: {msg['content']}\n")
145
- # f.write("\n--------------------------\n\n")
146
- # return "" # Clear feedback input
147
-
148
-
149
- # # Create the Gradio interface
 
 
 
 
150
  # with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
151
  # gr.Markdown("# สอบถามเรื่องกฎหมายแรงงาน")
152
 
153
- # # Initialize State
154
- # session_state = gr.State()
155
- # chatbot_instance = gr.State()
156
- # chatbot_history = gr.State([])
157
-
158
- # # Chat UI
159
- # chatbot_interface = gr.Chatbot(type="messages", label="Chat History")
160
- # user_input = gr.Textbox(placeholder="Type your message here...", elem_id="user_input", lines=1)
 
 
161
 
162
- # submit_button = gr.Button("Send")
163
- # clear_button = gr.Button("Delete Chat History")
 
164
 
165
- # # Submit actions
166
- # submit_button.click(
167
  # fn=chat_function,
168
- # inputs=[user_input, chatbot_history, session_state, chatbot_instance],
169
- # outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
170
  # )
171
-
172
  # user_input.submit(
173
  # fn=chat_function,
174
- # inputs=[user_input, chatbot_history, session_state, chatbot_instance],
175
- # outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
176
  # )
177
 
178
- # # # Clear history
179
- # # clear_button.click(lambda: [], outputs=chatbot_interface)
180
  # clear_button.click(
181
  # fn=initialize_session,
182
  # inputs=[],
183
- # outputs=[user_input, session_state, chatbot_instance, chatbot_history]
184
- # ).then(
185
- # fn=lambda: gr.update(value=[]),
186
- # inputs=[],
187
- # outputs=chatbot_interface
188
  # )
189
 
190
-
191
- # # Feedback section
192
- # with gr.Row():
193
- # feedback_input = gr.Textbox(placeholder="Send us feedback...", label="Feedback")
194
- # send_feedback_button = gr.Button("Send Feedback")
195
 
196
  # send_feedback_button.click(
197
- # fn=send_feedback,
198
- # inputs=[feedback_input, chatbot_history, session_state, chatbot_instance],
199
- # outputs=[feedback_input]
 
200
  # )
201
 
202
- # # Initialize session on load
203
  # demo.load(
204
  # fn=initialize_session,
205
  # inputs=[],
206
- # outputs=[user_input, session_state, chatbot_instance, chatbot_history]
207
  # )
208
 
209
- # # Launch
210
- # demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from utils.chat import ChatLaborLaw
7
 
8
 
9
+ # Function to initialize a new session and create chatbot instance for that session
10
+ async def initialize_session():
 
 
11
  session_id = str(uuid.uuid4())[:8]
12
+ chatbot = ChatLaborLaw()
13
+ # chatbot = Chat("gemini-2.0-flash")
14
+ history = []
15
+ return "", session_id, chatbot, history
16
+
17
+
18
+ # Function to handle user input and chatbot response
19
+ async def chat_function(prompt, history, session_id, chatbot):
20
+ if chatbot is None:
21
+ return history, "", session_id, chatbot # Skip if chatbot not ready
22
+
23
+ # Append the user's input to the message history
24
+ history.append({"role": "user", "content": prompt})
25
+
26
+ # Get the response from the chatbot
27
+ response = await chatbot.chat(prompt) # ใช้ await ได้แล้ว
28
+
29
+ # Append the assistant's response to the message history
30
+ history.append({"role": "assistant", "content": response})
31
+
32
+ return history, "", session_id, chatbot
33
+
34
+
35
+ # Function to save feedback with chat history
36
+ async def send_feedback(feedback, history, session_id, chatbot):
37
+ os.makedirs("app/feedback", exist_ok=True)
38
+ filename = f"app/feedback/feedback_{session_id}.txt"
39
  with open(filename, "a", encoding="utf-8") as f:
40
  f.write("=== Feedback Received ===\n")
41
  f.write(f"Session ID: {session_id}\n")
42
+ f.write(f"Feedback: {feedback}\n")
43
  f.write("Chat History:\n")
44
+ for msg in history:
45
+ f.write(f"{msg['role']}: {msg['content']}\n")
46
+ f.write("\n--------------------------\n\n")
47
+ return "" # Clear feedback input
48
+
49
+
50
+ # Create the Gradio interface
 
 
 
 
51
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
52
  gr.Markdown("# สอบถามเรื่องกฎหมายแรงงาน")
53
 
54
+ # Initialize State
55
+ session_state = gr.State()
56
+ chatbot_instance = gr.State()
57
+ chatbot_history = gr.State([])
 
 
 
 
 
 
58
 
59
+ # Chat UI
60
+ chatbot_interface = gr.Chatbot(type="messages", label="Chat History")
61
+ user_input = gr.Textbox(placeholder="Type your message here...", elem_id="user_input", lines=1)
62
+
63
+ submit_button = gr.Button("Send")
64
+ clear_button = gr.Button("Delete Chat History")
65
 
66
+ # Submit actions
67
+ submit_button.click(
68
  fn=chat_function,
69
+ inputs=[user_input, chatbot_history, session_state, chatbot_instance],
70
+ outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
71
  )
72
+
73
  user_input.submit(
74
  fn=chat_function,
75
+ inputs=[user_input, chatbot_history, session_state, chatbot_instance],
76
+ outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
77
  )
78
 
79
+ # # Clear history
80
+ # clear_button.click(lambda: [], outputs=chatbot_interface)
81
  clear_button.click(
82
  fn=initialize_session,
83
  inputs=[],
84
+ outputs=[user_input, session_state, chatbot_instance, chatbot_history]
85
+ ).then(
86
+ fn=lambda: gr.update(value=[]),
87
+ inputs=[],
88
+ outputs=chatbot_interface
89
  )
90
 
91
+
92
+ # Feedback section
93
+ with gr.Row():
94
+ feedback_input = gr.Textbox(placeholder="Send us feedback...", label="Feedback")
95
+ send_feedback_button = gr.Button("Send Feedback")
96
 
97
  send_feedback_button.click(
98
+ fn=send_feedback,
99
+ inputs=[feedback_input, chatbot_history, session_state, chatbot_instance],
100
+ outputs=[feedback_input]
 
101
  )
102
 
103
+ # Initialize session on load
104
  demo.load(
105
  fn=initialize_session,
106
  inputs=[],
107
+ outputs=[user_input, session_state, chatbot_instance, chatbot_history]
108
  )
109
 
110
+ # Launch
111
+ demo.launch(share=True)
 
 
 
 
 
 
 
 
 
112
 
113
+ # import os
114
+ # os.environ["OTEL_TRACES_EXPORTER"] = "none"
 
 
 
 
 
115
 
116
+ # import gradio as gr
117
+ # import uuid
118
+ # from utils.chat import ChatLaborLaw
 
 
 
 
119
 
120
 
121
+ # def initialize_session():
122
+ # """
123
+ # สร้าง session ID ใหม่ และสร้าง instance ใหม่ของ ChatLaborLaw
124
+ # """
125
+ # session_id = str(uuid.uuid4())[:8]
126
+ # chatbot_instance = ChatLaborLaw()
127
+ # return "", session_id, chatbot_instance, []
128
+
129
+ # async def chat_function(prompt: str, history_ui: list, chatbot_instance: ChatLaborLaw):
130
+ # """
131
+ # จัดการการสนทนา
132
+ # """
133
+ # if chatbot_instance is None or not prompt.strip():
134
+ # return history_ui, chatbot_instance, ""
135
+
136
+ # response = await chatbot_instance.chat(prompt)
137
+ # history_ui.append((prompt, response))
138
+ # return history_ui, chatbot_instance, ""
139
+
140
+ # def save_feedback(feedback: str, history_ui: list, session_id: str):
141
+ # """
142
+ # บันทึก Feedback
143
+ # """
144
+ # if not feedback.strip():
145
+ # return ""
146
+ # os.makedirs("feedback", exist_ok=True)
147
+ # filename = f"feedback/feedback_{session_id}.txt"
148
  # with open(filename, "a", encoding="utf-8") as f:
149
  # f.write("=== Feedback Received ===\n")
150
  # f.write(f"Session ID: {session_id}\n")
151
+ # f.write(f"Feedback: {feedback}\n\n")
152
  # f.write("Chat History:\n")
153
+ # for user_msg, assistant_msg in history_ui:
154
+ # f.write(f"User: {user_msg}\n")
155
+ # f.write(f"Assistant: {assistant_msg}\n")
156
+ # f.write("-" * 20 + "\n")
157
+ # f.write("\n==========================\n\n")
158
+ # gr.Info("ขอบคุณสำหรับข้อเสนอแนะ!")
159
+ # return ""
160
+
161
+ # # --------------------------------------------------------------------------
162
+ # # สร้าง Gradio Interface
163
+ # # --------------------------------------------------------------------------
164
  # with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
165
  # gr.Markdown("# สอบถามเรื่องกฎหมายแรงงาน")
166
 
167
+ # session_id_state = gr.State()
168
+ # chatbot_instance_state = gr.State()
169
+
170
+ # chatbot_interface = gr.Chatbot(
171
+ # label="ประวัติการสนทนา",
172
+ # height=550,
173
+ # # bubble_styling=False,
174
+ # show_copy_button=True
175
+ # )
176
+ # user_input = gr.Textbox(placeholder="พิมพ์คำถามของคุณที่นี่...", label="คำถาม", lines=2)
177
 
178
+ # with gr.Row():
179
+ # submit_button = gr.Button("ส่ง", variant="primary", scale=4)
180
+ # clear_button = gr.Button("เริ่มการสนทนาใหม่", scale=1)
181
 
182
+ # submit_event = submit_button.click(
 
183
  # fn=chat_function,
184
+ # inputs=[user_input, chatbot_interface, chatbot_instance_state],
185
+ # outputs=[chatbot_interface, chatbot_instance_state, user_input]
186
  # )
 
187
  # user_input.submit(
188
  # fn=chat_function,
189
+ # inputs=[user_input, chatbot_interface, chatbot_instance_state],
190
+ # outputs=[chatbot_interface, chatbot_instance_state, user_input]
191
  # )
192
 
 
 
193
  # clear_button.click(
194
  # fn=initialize_session,
195
  # inputs=[],
196
+ # outputs=[user_input, session_id_state, chatbot_instance_state, chatbot_interface],
197
+ # queue=False
 
 
 
198
  # )
199
 
200
+ # with gr.Accordion("ส่งข้อเสนอแนะ (Feedback)", open=False):
201
+ # feedback_input = gr.Textbox(placeholder="ความคิดเห็นของคุณมีความสำคัญต่อการพัฒนาของเรา...", label="Feedback", lines=2, scale=4)
202
+ # send_feedback_button = gr.Button("ส่ง Feedback")
 
 
203
 
204
  # send_feedback_button.click(
205
+ # fn=save_feedback,
206
+ # inputs=[feedback_input, chatbot_interface, session_id_state],
207
+ # outputs=[feedback_input],
208
+ # queue=False
209
  # )
210
 
 
211
  # demo.load(
212
  # fn=initialize_session,
213
  # inputs=[],
214
+ # outputs=[user_input, session_id_state, chatbot_instance_state, chatbot_interface]
215
  # )
216
 
217
+ # demo.queue().launch()
218
+
219
+
220
+ # # # Function to initialize a new session and create chatbot instance for that session
221
+ # # async def initialize_session():
222
+ # # session_id = str(uuid.uuid4())[:8]
223
+ # # chatbot = ChatLaborLaw()
224
+ # # # chatbot = Chat("gemini-2.0-flash")
225
+ # # history = []
226
+ # # return "", session_id, chatbot, history
227
+
228
+
229
+ # # # Function to handle user input and chatbot response
230
+ # # async def chat_function(prompt, history, session_id, chatbot):
231
+ # # if chatbot is None:
232
+ # # return history, "", session_id, chatbot # Skip if chatbot not ready
233
+
234
+ # # # Append the user's input to the message history
235
+ # # history.append({"role": "user", "content": prompt})
236
+
237
+ # # # Get the response from the chatbot
238
+ # # response = await chatbot.chat(prompt) # ใช้ await ได้แล้ว
239
+
240
+ # # # Append the assistant's response to the message history
241
+ # # history.append({"role": "assistant", "content": response})
242
+
243
+ # # return history, "", session_id, chatbot
244
+
245
+
246
+ # # # Function to save feedback with chat history
247
+ # # async def send_feedback(feedback, history, session_id, chatbot):
248
+ # # os.makedirs("app/feedback", exist_ok=True)
249
+ # # filename = f"app/feedback/feedback_{session_id}.txt"
250
+ # # with open(filename, "a", encoding="utf-8") as f:
251
+ # # f.write("=== Feedback Received ===\n")
252
+ # # f.write(f"Session ID: {session_id}\n")
253
+ # # f.write(f"Feedback: {feedback}\n")
254
+ # # f.write("Chat History:\n")
255
+ # # for msg in history:
256
+ # # f.write(f"{msg['role']}: {msg['content']}\n")
257
+ # # f.write("\n--------------------------\n\n")
258
+ # # return "" # Clear feedback input
259
+
260
+
261
+ # # # Create the Gradio interface
262
+ # # with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
263
+ # # gr.Markdown("# สอบถามเรื่องกฎหมายแรงงาน")
264
+
265
+ # # # Initialize State
266
+ # # session_state = gr.State()
267
+ # # chatbot_instance = gr.State()
268
+ # # chatbot_history = gr.State([])
269
+
270
+ # # # Chat UI
271
+ # # chatbot_interface = gr.Chatbot(type="messages", label="Chat History")
272
+ # # user_input = gr.Textbox(placeholder="Type your message here...", elem_id="user_input", lines=1)
273
+
274
+ # # submit_button = gr.Button("Send")
275
+ # # clear_button = gr.Button("Delete Chat History")
276
+
277
+ # # # Submit actions
278
+ # # submit_button.click(
279
+ # # fn=chat_function,
280
+ # # inputs=[user_input, chatbot_history, session_state, chatbot_instance],
281
+ # # outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
282
+ # # )
283
+
284
+ # # user_input.submit(
285
+ # # fn=chat_function,
286
+ # # inputs=[user_input, chatbot_history, session_state, chatbot_instance],
287
+ # # outputs=[chatbot_interface, user_input, session_state, chatbot_instance]
288
+ # # )
289
+
290
+ # # # # Clear history
291
+ # # # clear_button.click(lambda: [], outputs=chatbot_interface)
292
+ # # clear_button.click(
293
+ # # fn=initialize_session,
294
+ # # inputs=[],
295
+ # # outputs=[user_input, session_state, chatbot_instance, chatbot_history]
296
+ # # ).then(
297
+ # # fn=lambda: gr.update(value=[]),
298
+ # # inputs=[],
299
+ # # outputs=chatbot_interface
300
+ # # )
301
+
302
+
303
+ # # # Feedback section
304
+ # # with gr.Row():
305
+ # # feedback_input = gr.Textbox(placeholder="Send us feedback...", label="Feedback")
306
+ # # send_feedback_button = gr.Button("Send Feedback")
307
+
308
+ # # send_feedback_button.click(
309
+ # # fn=send_feedback,
310
+ # # inputs=[feedback_input, chatbot_history, session_state, chatbot_instance],
311
+ # # outputs=[feedback_input]
312
+ # # )
313
+
314
+ # # # Initialize session on load
315
+ # # demo.load(
316
+ # # fn=initialize_session,
317
+ # # inputs=[],
318
+ # # outputs=[user_input, session_state, chatbot_instance, chatbot_history]
319
+ # # )
320
+
321
+ # # # Launch
322
+ # # demo.launch(share=True)
utils/chat.py CHANGED
@@ -1,6 +1,7 @@
1
  import os, re
2
  # os.environ["OTEL_TRACES_EXPORTER"] = "none"
3
- os.environ["OTEL_SDK_DISABLED"] = "true"
 
4
 
5
  import uuid
6
  from dotenv import load_dotenv
@@ -117,6 +118,7 @@ class ChatLaborLaw:
117
  "document_type": 1,
118
  "law_type": 1,
119
  "law_name": 1,
 
120
  # "publication_date": 1,
121
  # "effective_date": 1,
122
  # "publication_date_utc": 1,
@@ -150,6 +152,7 @@ class ChatLaborLaw:
150
 
151
  for i, doc in enumerate(list_of_documents):
152
  law_name = doc.metadata.get('law_name', '-')
 
153
  section_number = doc.metadata.get('section_number', '-')
154
  publication_date = doc.metadata.get('publication_date', '-') # ไม่ได้มีทุกอัน
155
  effective_date = doc.metadata.get('effective_date', '-') # ไม่ได้มีทุกอัน
@@ -158,6 +161,7 @@ class ChatLaborLaw:
158
  formatted = "\n".join([
159
  f"Doc{i}",
160
  f"{law_name}",
 
161
  f"มาตรา\t{section_number}",
162
  content,
163
  f"ประกาศ\t{publication_date}",
@@ -174,11 +178,13 @@ class ChatLaborLaw:
174
 
175
  for i, doc in enumerate(list_of_docs):
176
  law_name = doc.get('law_name', '-')
 
177
  section_number = doc.get('section_number', '-')
178
  content = doc.get('text', '-')
179
 
180
  formatted = "\n".join([
181
  f"{law_name}",
 
182
  f"มาตรา\t{section_number}",
183
  content,
184
  ])
@@ -228,6 +234,7 @@ class ChatLaborLaw:
228
  self.append_history(AIMessage(content=ai_response_content))
229
 
230
  # print(f"AI:::: {ai_response_content}")
 
231
  return ai_response_content
232
 
233
 
@@ -235,9 +242,12 @@ class ChatLaborLaw:
235
  async def call_rag(self, user_input: str) -> str:
236
 
237
  # main context
238
- context_docs = self.get_main_context(user_input, law_type="summary") # chunk_type='section'
 
 
239
  # print(context_docs)
240
  main_context_str = self.format_main_context(context_docs)
 
241
 
242
  # ref context
243
  ref_context_docs = self.get_ref_context(context_docs)
 
1
  import os, re
2
  # os.environ["OTEL_TRACES_EXPORTER"] = "none"
3
+ # os.environ["OTEL_SDK_DISABLED"] = "true"
4
+ os.environ["OTEL_TRACES_EXPORTER"] = "console"
5
 
6
  import uuid
7
  from dotenv import load_dotenv
 
118
  "document_type": 1,
119
  "law_type": 1,
120
  "law_name": 1,
121
+ "chapter":1,
122
  # "publication_date": 1,
123
  # "effective_date": 1,
124
  # "publication_date_utc": 1,
 
152
 
153
  for i, doc in enumerate(list_of_documents):
154
  law_name = doc.metadata.get('law_name', '-')
155
+ chapter = doc.metadata.get('chapter', '-')
156
  section_number = doc.metadata.get('section_number', '-')
157
  publication_date = doc.metadata.get('publication_date', '-') # ไม่ได้มีทุกอัน
158
  effective_date = doc.metadata.get('effective_date', '-') # ไม่ได้มีทุกอัน
 
161
  formatted = "\n".join([
162
  f"Doc{i}",
163
  f"{law_name}",
164
+ f"{chapter}"
165
  f"มาตรา\t{section_number}",
166
  content,
167
  f"ประกาศ\t{publication_date}",
 
178
 
179
  for i, doc in enumerate(list_of_docs):
180
  law_name = doc.get('law_name', '-')
181
+ chapter = doc.get('chapter', '-')
182
  section_number = doc.get('section_number', '-')
183
  content = doc.get('text', '-')
184
 
185
  formatted = "\n".join([
186
  f"{law_name}",
187
+ f"{chapter}"
188
  f"มาตรา\t{section_number}",
189
  content,
190
  ])
 
234
  self.append_history(AIMessage(content=ai_response_content))
235
 
236
  # print(f"AI:::: {ai_response_content}")
237
+ # print(input_type)
238
  return ai_response_content
239
 
240
 
 
242
  async def call_rag(self, user_input: str) -> str:
243
 
244
  # main context
245
+ context_docs = self.get_main_context(user_input,
246
+ law_type="summary",
247
+ chunk_type="section")
248
  # print(context_docs)
249
  main_context_str = self.format_main_context(context_docs)
250
+ # print(main_context_str)
251
 
252
  # ref context
253
  ref_context_docs = self.get_ref_context(context_docs)
utils/chat_prompts.py CHANGED
@@ -1,5 +1,6 @@
1
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate, SystemMessagePromptTemplate
2
 
 
3
  RAG_CHAT_PROMPT = ChatPromptTemplate.from_messages(
4
  [
5
  SystemMessagePromptTemplate.from_template(
@@ -11,7 +12,9 @@ You are a specialized AI assistant acting as a Thai legal expert. Your persona i
11
 
12
  1. Absolute Rules (Non-negotiable):
13
  • Language Constraint: You MUST respond in Thai only. Under no circumstances should you use English or any other language in your response.
14
- • Strict Grounding: Your answer must be derived strictly from the provided context. If the context does not contain the information to answer the user's question, you must state that you cannot answer based on the information given (in Thai). Do not invent, infer, or use any external knowledge.
 
 
15
 
16
  2. Context Handling and Reasoning:
17
  • Context Structure: The provided context will be divided into two types: Main Context and Ref Context.
@@ -28,6 +31,7 @@ You are a specialized AI assistant acting as a Thai legal expert. Your persona i
28
  • Citations: At the end of your response, you MUST provide a summary of the legal sources you used. List all the specific articles (e.g., มาตรา ๑๑๘, มาตรา ๑๒๑) that you referenced to build your answer.
29
 
30
 
 
31
  **Example of Excellence**
32
  This is an example of an ideal interaction to guide your behavior.
33
  User Query:
@@ -76,9 +80,9 @@ Ideal Response (Your output should look like this): "ตามข้อมูล
76
 
77
  **แหล่งข้อมูลอ้างอิง:**
78
  * พระราชบัญญัติคุ้มครองแรงงาน
79
- * มาตรา ๑๑๘ (ค่าชดเชยกรณีเลิกจ้างทั่วไป)
80
- * มาตรา ๑๒๑ (เหตุเลิกจ้างเนื่องจากการนำเทคโนโลยีมาใช้ และค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้า)
81
- * มาตรา ๑๒๒ (ค่าชดเชยพิเศษกรณีเลิกจ้างตามมาตรา ๑๒๑)"
82
  """
83
  ),
84
  MessagesPlaceholder(variable_name="history"),
@@ -104,9 +108,123 @@ User's Current Question: {question}
104
  ]
105
  )
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
 
109
- from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate
110
 
111
  CLASSIFICATION_INPUT_PROMPT = ChatPromptTemplate.from_messages([
112
  SystemMessagePromptTemplate.from_template(
@@ -130,6 +248,17 @@ This includes, but is not limited to:
130
  * **Royal Decree:** (พระราชกฤษฎีกา) - Decrees issued by the King on the Cabinet's advice to detail an Act.
131
  * **Ministerial Regulation:** (กฎกระทรวง) - Regulations issued by a Minister to implement an Act.
132
  * **Local Ordinance:** (ข้อบัญญัติท้องถิ่น) - Laws issued by local administrative organizations.
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  ---
135
 
@@ -139,6 +268,11 @@ This includes, but is not limited to:
139
  * **General Knowledge Questions:** Inquiries answerable with common knowledge and not specific to the legal database (e.g., "Who is the president of the USA?").
140
  * **Sensitive or Opinion-Based Topics:** Personal opinions, political discussions, topics about the monarchy, or general religious discussions.
141
  * **Unrelated Services or Competitors:** Questions about other companies, services, or topics completely outside the scope of Thai labor law.
 
 
 
 
 
142
 
143
  ---
144
 
@@ -160,34 +294,30 @@ User Input: "{user_input}"
160
 
161
 
162
 
163
-
164
- from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
165
-
166
  NON_RAG_PROMPT = ChatPromptTemplate.from_messages([
167
  SystemMessagePromptTemplate.from_template(
168
- """You are a highly specialized AI assistant with a strict and defined scope. Your persona is that of a polite, professional, and gender-neutral expert.
 
 
 
169
 
170
- **Your Primary Directive:**
171
- Your task is to formulate a response to the user, and **your response MUST be 100% in the Thai language.**
 
 
 
172
 
173
- **Core Task & Conditional Logic:**
174
- You must analyze the user's input and choose ONE of the following two scenarios to formulate your response.
175
 
176
- ---
177
- **Scenario A: The input is a simple greeting.**
178
- - **Condition:** The user's input is a standard greeting, a simple hello, or a basic introduction (e.g., "สวัสดี", "ดีครับ", "Hello").
179
- - **Required Action:** Respond with a professional, welcoming message that invites the user to ask a question about Thai labor law.
180
- - **[Response Example in Thai]:** "ระบบพร้อมให้ข้อมูลเกี่ยวกับกฎหมายแรงงานไทย มีข้อสงสัยใดให้ช่วยเหลือ สามารถสอบถามได้"
181
 
182
- ---
183
- **Scenario B: The input is any other out-of-scope topic.**
184
- - **Condition:** The user's input is not a greeting and is not related to Thai labor law (e.g., general knowledge, politics, chit-chat).
185
- - **Required Action:** Politely inform the user that their question is outside your area of expertise. **DO NOT** attempt to answer the user's original question under any circumstances.
186
- - **[Response Example in Thai]:** "ขออภัย ระบบสามารถให้ข้อมูลได้เฉพาะในขอบเขตของกฎหมายแรงงานไทยเท่านั้น หากท่านมีคำถามที่เกี่ยวข้อง โปรดสอบถาม"
187
- ---
188
 
189
- Now, based on these rules and scenarios, formulate the single, most appropriate Thai response for the following user input.
190
  """
191
  ),
192
- HumanMessagePromptTemplate.from_template("User Input: '{user_input}'")
193
  ])
 
1
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate, SystemMessagePromptTemplate
2
 
3
+
4
  RAG_CHAT_PROMPT = ChatPromptTemplate.from_messages(
5
  [
6
  SystemMessagePromptTemplate.from_template(
 
12
 
13
  1. Absolute Rules (Non-negotiable):
14
  • Language Constraint: You MUST respond in Thai only. Under no circumstances should you use English or any other language in your response.
15
+ • Strict Grounding: Your answer must be derived strictly from the provided context.
16
+ If the context does not contain the information to answer the user's question, you must state that you cannot answer based on the information given (in Thai). Do not invent, infer, or use any external knowledge.
17
+ And ถ้า context ไม่พอ เราก็จะตอบประมาณว่า "ขออภัย ระบบสามารถให้ข้อมูลได้เฉพาะในขอบเขตของกฎหมายแรงงานไทยเท่านั้น หากท่านมีคำถามที่เกี่ยวข้อง โปรดสอบถาม" แต่ตอนนี้บอทมันใส่แหล่งข้อมูลอ้างอิงตามที่ได้รับมา จริงๆ ไม่ต้องใส่แหล่งข้อมูลอ้างอิง เพราะมันไม่ make sense
18
 
19
  2. Context Handling and Reasoning:
20
  • Context Structure: The provided context will be divided into two types: Main Context and Ref Context.
 
31
  • Citations: At the end of your response, you MUST provide a summary of the legal sources you used. List all the specific articles (e.g., มาตรา ๑๑๘, มาตรา ๑๒๑) that you referenced to build your answer.
32
 
33
 
34
+
35
  **Example of Excellence**
36
  This is an example of an ideal interaction to guide your behavior.
37
  User Query:
 
80
 
81
  **แหล่งข้อมูลอ้างอิง:**
82
  * พระราชบัญญัติคุ้มครองแรงงาน
83
+ * มาตรา ๑๑๘ (ค่าชดเชยกรณีเลิกจ้างทั่วไป), หมวด 11 ค่าชดเชย
84
+ * มาตรา ๑๒๑ (เหตุเลิกจ้างเนื่องจากการนำเทคโนโลยีมาใช้ และค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้า), หมวด 11 ค่าชดเชย
85
+ * มาตรา ๑๒๒ (ค่าชดเชยพิเศษกรณีเลิกจ้างตามมาตรา ๑๒๑)", หมวด 11 ค่าชดเชย
86
  """
87
  ),
88
  MessagesPlaceholder(variable_name="history"),
 
108
  ]
109
  )
110
 
111
+ # RAG_CHAT_PROMPT = ChatPromptTemplate.from_messages(
112
+ # [
113
+ # SystemMessagePromptTemplate.from_template(
114
+ # """
115
+ # **Persona and Role:**
116
+ # You are a specialized AI assistant acting as a Thai legal expert. Your persona is helpful, precise, and authoritative. Your primary goal is to provide accurate and helpful answers to legal questions based exclusively on the provided Thai legal context.
117
+
118
+ # **Core Instructions:**
119
+
120
+ # 1. Absolute Rules (Non-negotiable):
121
+ # • Language Constraint: You MUST respond in Thai only. Under no circumstances should you use English or any other language in your response.
122
+ # • Strict Grounding: Your answer must be derived strictly from the provided context. If the context does not contain the information to answer the user's question, you must state that you cannot answer based on the information given (in Thai).
123
+ # DO NOT invent, infer, or use any external knowledge.
124
+
125
+ # 2. Context Handling and Reasoning:
126
+ # • Context Structure: The provided context will be divided into two types: Main Context and Ref Context.
127
+ # - Main Context: Contains the primary legal articles retrieved directly for the user's query.
128
+ # - Ref Context: Contains supporting legal articles that are referenced by name (e.g., 'ตามมาตรา ๑๑๘') within the Main Context.
129
+ # • Using Ref Context: You must intelligently decide whether the Ref Context is necessary to formulate a complete and accurate answer. Often, it will be essential for a comprehensive explanation.
130
+ # • Interpreting Internal References (<วรรค X>):
131
+ # - The context may contain markers like <วรรค X> (meaning Paragraph X). You must not include these markers in your final output.
132
+ # - However, you must understand their meaning to correctly interpret the law. For example, if a paragraph refers to "ตามวรรคหนึ่ง" (according to paragraph one), you must correctly resolve this reference to the content of the first paragraph of that same article.
133
+ # • Legal Terminology: When constructing your answer, use the formal legal terminology found within the provided context. Do not oversimplify the language into colloquial Thai.
134
+
135
+ # 3. Output Formatting and Structure:
136
+ # • Clarity: Structure your answers clearly. Use bullet points, numbered lists, or distinct sections (e.g., separating different cases or scenarios) to make the information easy to understand.
137
+ # • Citations: At the end of your response, you MUST provide a summary of the legal sources you used. List all the specific articles (e.g., มาตรา ๑๑๘, มาตรา ๑๒๑) that you referenced to build your answer.
138
+
139
+
140
+ # 4. Context not sufficient:
141
+ # • If the provided context does not contain enough information to answer the user's question, reply with the following structure (translated to Thai):
142
+ # ตามข้อมูลจากพระราชบัญญัติคุ้มครองแรงงาน พ.ศ. 2541 ในบริบทที่ให้มา ไม่มีข้อกำหนดหรือบทลงโทษที่ระบุไว้เกี่ยวกับ(...รายละเอียดคำถามของผู้ใช้...)
143
+ # • DO NOT include citations if you are unable to answer based on context.
144
+
145
+
146
+ # **Example of Excellence**
147
+ # This is an example of an ideal interaction to guide your behavior.
148
+ # User Query:
149
+ # "ในกรณีที่นายจ้างเลิกจ้างลูกจ้างแล้วลูกจ้างนั้นทำงานติดต่อกันเกิน 6 ปีขึ้นไป นายจ้างจะต้องจ่ายค่าชดเชยเท่าไหร่"
150
+
151
+ # Provided Context:
152
+
153
+ # Main Context: "
154
+ # หมวด 11 ค่าชดเชย
155
+ # ### มาตรา ๑๒๒
156
+ # ในกรณีที่นายจ้างเลิกจ้างลูกจ้างตามมาตรา ๑๒๑ และลูกจ้างนั้นทำงานติดต่อกันเกินหกปีขึ้นไป ให้นายจ้างจ่ายค่าชดเชยพิเศษเพิ่มขึ้นจากค่าชดเชยตามมาตรา ๑๑๘ ไม่น้อยกว่าค่าจ้างอัตราสุดท้ายสิบห้าวันต่อการทำงานครบหนึ่งปี หรือไม่น้อยกว่าค่าจ้างของการทำงานสิบห้าวันสุดท้ายต่อการทำงานครบหนึ่งปีสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย แต่ค่าชดเชยตามมาตรานี้รวมแล้วต้องไม่เกินค่าจ้างอัตราสุดท้ายสามร้อยหกสิบวัน หรือไม่เกินค่าจ้างของการทำงานสามร้อยหกสิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
157
+ # "
158
+
159
+ # Ref Context: "
160
+ # หมวด 11 ค่าชดเชย
161
+ # ### มาตรา ๑๒๑
162
+ # ในกรณีที่นายจ้างจะเลิกจ้างลูกจ้างเพราะเหตุที่นายจ้างปรับปรุงหน่วยงาน กระบวนการผลิต การจำหน่าย หรือการบริการอันเนื่องมาจากการนำเครื่องจักรมาใช้หรือเปลี่ยนแปลงเครื่องจักรหรือเทคโนโลยี ซึ่งเป็นเหตุให้ต้องลดจำนวนลูกจ้าง ห้ามมิให��นำมาตรา ๑๗ วรรคสอง มาใช้บังคับ และให้นายจ้างแจ้งวันที่จะเลิกจ้าง เหตุผลของการเลิกจ้างและรายชื่อลูกจ้างต่อพนักงานตรวจแรงงาน และลูกจ้างที่จะเลิกจ้างทราบล่วงหน้าไม่น้อยกว่าหกสิบวันก่อนวันที่จะเลิกจ้าง
163
+ # ในกรณีที่นายจ้างไม่แจ้งให้ลูกจ้างที่จะเลิกจ้างทราบล่วงหน้า หรือแจ้งล่วงหน้าน้อยกว่าระยะเวลาที่กำหนดตามวรรคหนึ่ง นอกจากจะได้รับค่าชดเชยตามมาตรา ๑๑๘ แล้ว ให้นายจ้างจ่ายค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้าเท่ากับค่าจ้างอัตราสุดท้ายหกสิบวัน หรือเท่ากับค่าจ้างของการทำงานหกสิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วยด้วย
164
+ # ในกรณีที่มีการจ่ายค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้าตามวรรคสองแล้ว ให้ถือว่านายจ้างได้จ่ายสินจ้างแทนการบอกกล่าวล่วงหน้าตามประมวลกฎหมายแพ่งและพาณิชย์ด้วย
165
+
166
+ # หมวด 11 ค่าชดเชย
167
+ # ### มาตรา ๑๑๘
168
+ # ให้นายจ้างจ่ายค่าชดเชยให้แก่ลูกจ้างซึ่งเลิกจ้างดังต่อไปนี้
169
+ # (๑) ลูกจ้างซึ่งทำงานติดต่อกันครบหนึ่งร้อยยี่สิบวัน แต่ไม่ครบหนึ่งปี ให้จ่ายไม่น้อยกว่าค่าจ้างอัตราสุดท้ายสามสิบวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานสามสิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
170
+ # (๒) ลูกจ้างซึ่งทำงานติดต่อกันครบหนึ่งปี แต่ไม่ครบสามปี ให้จ่ายไม่น้อยกว่าค่าจ้างอัตราสุดท้ายเก้าสิบวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานเก้าสิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
171
+ # (๓) ลูกจ้างซึ่งทำงานติดต่อกันครบสามปี แต่ไม่ครบหกปี ให้จ่ายไม่น้อยกว่าค่าจ้างอัตราสุดท้ายหนึ่งร้อยแปดสิบวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานหนึ่งร้อยแปดสิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
172
+ # (๔) ลูกจ้างซึ่งทำงานติดต่อกันครบหกปี แต่ไม่ครบสิบปี ให้จ่ายไม่น้อยกว่าค่าจ้างอัตราสุดท้ายสองร้อยสี่สิบวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานสองร้อยสี่สิบวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
173
+ # (๕) ลูกจ้างซึ่งทำงานติดต่อกันครบสิบปี แต่ไม่ครบยี่สิบปี ให้จ่ายไม่น้อยกว่าค่าจ้างอัตร���สุดท้ายสามร้อยวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานสามร้อยวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
174
+ # (๖) ลูกจ้างซึ่งทำงานติดต่อกันครบยี่สิบปีขึ้นไป ให้จ่ายไม่น้อยกว่าค่าจ้างอัตราสุดท้ายสี่ร้อยวัน หรือไม่น้อยกว่าค่าจ้างของการทำงานสี่ร้อยวันสุดท้ายสำหรับลูกจ้างซึ่งได้รับค่าจ้างตามผลงานโดยคำนวณเป็นหน่วย
175
+ # การเลิกจ้างตามมาตรานี้ หมายความว่า การกระทำใดที่นายจ้างไม่ให้ลูกจ้างทำงานต่อไปและไม่จ่ายค่าจ้างให้ ไม่ว่าจะเป็นเพราะเหตุสิ้นสุดสัญญาจ้างหรือเหตุอื่นใด และหมายความรวมถึงกรณีที่ลูกจ้างไม่ได้"
176
+
177
+ # Ideal Response (Your output should look like this): "ตามข้อมูลจากพระราชบัญญัติคุ้มครองแรงงาน กรณีที่นายจ้างเลิกจ้างลูกจ้างซึ่งทำงานติดต่อกันเกิน 6 ปีขึ้นไป จำนวนค่าชดเชยที่จะได้รับจะขึ้นอยู่กับ "สาเหตุ" ของการเลิกจ้าง ซึ่งสามารถแบ่งได้เป็น 2 กรณีหลัก ดังนี้ครับ
178
+
179
+ # **กรณีที่ 1: การเลิกจ้างทั่วไป (ที่ไม่ได้เกิดจากเหตุตามมาตรา 121)**
180
+ # หากเป็นการเลิกจ้างทั่วไปที่ไม่ได้เกิดจากการปรับปรุงองค์กรโดยใช้เครื่องจักรหรือเทคโนโลยี นายจ้างจะต้องจ่ายค่าชดเชยตามปกติ ตามอายุงานของลูกจ้าง ซึ่งกำหนดไว้ในมาตรา 118 ดังนี้:
181
+ # * ทำงานครบ 6 ปี แต่ไม่ครบ 10 ปี: ได้รับค่าชดเชยไม่น้อยกว่าค่าจ้างอัตราสุดท้าย 240 วัน
182
+ # * ทำงานครบ 10 ปี แต่ไม่ครบ 20 ปี: ได้รับค่าชดเชยไม่น้อยกว่าค่าจ้างอัตราสุดท้าย 300 วัน
183
+ # * ทำงานครบ 20 ปีขึ้นไป: ได้รับค่าชดเชยไม่น้อยกว่าค่าจ้างอัตราสุดท้าย 400 วัน
184
+
185
+ # **กรณีที่ 2: การเลิกจ้างเนื่องจากการปรับปรุงองค์กรโดยใช้เทคโนโลยี (ตามมาตรา 121)**
186
+ # หากนายจ้างเลิกจ้างเพราะเหตุปรับปรุงหน่วยงาน กระบวนการผลิต การจำหน่าย หรือการบริการ อันเนื่องมาจากการนำเครื่องจักรมาใช้หรือเปลี่ยนแปลงเทคโนโลยี ซึ่งทำให้ต้องลดจำนวนลูกจ้าง ลูกจ้างจะได้รับค่าชดเชย 2 ส่วนประกอบกัน คือ:
187
+ # 1. **ค่าชดเชยตามปกติ (ตามมาตรา 118):**
188
+ # ลูกจ้างจะได้รับค่าชดเชยตามอายุงานเช่นเดียวกับกรณีที่ 1 (คือ 240, 300 หรือ 400 วัน ขึ้นอยู่กับอายุงาน)
189
+ # 2. **บวกกับ ค่าชดเชยพิเศษ (ตามมาตรา 122):**
190
+ # นายจ้างต้องจ่ายค่าชดเชยพิเศษเพิ่มขึ้น ในอัตราไม่น้อยกว่าค่าจ้างอัตราสุดท้าย 15 วัน ต่อการทำงานครบ 1 ปี แต่ค่าชดเชยพิเศษนี้เมื่อรวมกันแล้วจะต้องไม่เกินค่าจ้างอัตราสุดท้าย 360 วัน
191
+
192
+ # **สรุป**
193
+ # จำนวนค่าชดเชยสำหรับลูกจ้างที่ทำงานเกิน 6 ปี จะแตกต่างกันอย่างมีนัยสำคัญขึ้นอยู่กับเหตุผลของการเลิกจ้าง หากเป็นเพราะการนำเทคโนโลยีมาใช้ตามมาตรา 121 ลูกจ้างจะได้รับค่าชดเชยปกติบวกด้วยค่าชดเชยพิเศษ ซึ่งจะทำให้ได้รับเงินชดเชยในจำนวนที่สูงกว่าการเลิกจ้างทั่วไป
194
+
195
+ # **ข้อควรทราบเพิ่มเติม:** กรณีเลิกจ้างตามมาตรา 121 นายจ้างมีหน้าที่ต้องแจ้งล่วงหน้าไม่น้อยกว่า 60 วัน หากไม่แจ้งหรือแจ้งน้อยกว่ากำหนด จะต้องจ่ายค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้าเท่ากับค่าจ้าง 60 วัน เพิ่มเติมจากค่าชดเชยทั้งหมดด้วย
196
+
197
+ # **แหล่งข้อมูลอ้างอิง:**
198
+ # * พระราชบัญญัติคุ้มครองแรงงาน
199
+ # * มาตรา ๑๑๘ (ค่าชดเชยกรณีเลิกจ้างทั่วไป), หมวด 11 ค่าชดเชย
200
+ # * มาตรา ๑๒๑ (เหตุเลิกจ้างเนื่องจากการนำเทคโนโลยีมาใช้ และค่าชดเชยพิเศษแทนการบอกกล่าวล่วงหน้า), หมวด 11 ค่าชดเชย
201
+ # * มาตรา ๑๒๒ (ค่าชดเชยพิเศษกรณีเลิกจ้างตามมาตรา ๑๒๑), หมวด 11 ค่าชดเชย"
202
+ # """
203
+ # ),
204
+ # MessagesPlaceholder(variable_name="history"),
205
+ # HumanMessagePromptTemplate.from_template(
206
+ # """Based on the conversation history (if any) and the new question, generate an answer.
207
+ # IMPORTANT: Use the conversation history ONLY to understand the context of the user's question (like what 'that' or 'in this case' refers to).
208
+ # Your final answer MUST be based exclusively on the information within the 'Main Context' and 'Ref Context' provided below.
209
+
210
+ # Conversation History:
211
+ # {history}
212
+
213
+ # -----------------
214
+
215
+ # Provided Context for this turn:
216
+ # Main Context: {main_context}
217
+ # Ref Context: {ref_context}
218
+
219
+ # -----------------
220
+
221
+ # User's Current Question: {question}
222
+ # """
223
+ # ),
224
+ # ]
225
+ # )
226
 
227
 
 
228
 
229
  CLASSIFICATION_INPUT_PROMPT = ChatPromptTemplate.from_messages([
230
  SystemMessagePromptTemplate.from_template(
 
248
  * **Royal Decree:** (พระราชกฤษฎีกา) - Decrees issued by the King on the Cabinet's advice to detail an Act.
249
  * **Ministerial Regulation:** (กฎกระทรวง) - Regulations issued by a Minister to implement an Act.
250
  * **Local Ordinance:** (ข้อบัญญัติท้องถิ่น) - Laws issued by local administrative organizations.
251
+ * **Definition or meaning of legal terms related to Thai labor law:**
252
+ * If the user asks for the **meaning, interpretation, or legal definition** of any term related to labor law, such as:
253
+ - นายจ้าง (Employer)
254
+ - ลูกจ้าง (Employee)
255
+ - ผู้ว่าจ้าง (Contractee), ผู้รับเหมาช่วง (Subcontractor), ผู้รับเหมาชั้นต้น
256
+ - สัญญาจ้าง (Employment contract), ค่าจ้าง (Wage), วันทำงาน, วันหยุด, วันลา
257
+ - การเลิกจ้าง, การจ้างงาน, การโอนสิทธิ
258
+ - ค่าจ้างต่างๆ เช่น ค่าจ้างในวันทำงาน, อัตราค่าจ้างต่างๆ เช่น อัตราค่าจ้างขั้นต่ำ, อัตราค่าจ้างขั้นต่ำพื้นฐาน
259
+ - อื่นๆ เช่น การทำงานล่วงเวลา, ค่าล่วงเวลาในวันหยุด, ค่าชดเชย, เงินสะสม, เงินสมทบ, อธิบดี, รัฐมนตรี
260
+ * These questions should be classified as **RAG**, as they require referencing legal definitions.
261
+
262
 
263
  ---
264
 
 
268
  * **General Knowledge Questions:** Inquiries answerable with common knowledge and not specific to the legal database (e.g., "Who is the president of the USA?").
269
  * **Sensitive or Opinion-Based Topics:** Personal opinions, political discussions, topics about the monarchy, or general religious discussions.
270
  * **Unrelated Services or Competitors:** Questions about other companies, services, or topics completely outside the scope of Thai labor law.
271
+ * **Creative or technical transformation requests:** Requests that involve transforming or creating content based on legal text in a non-legal format, such as:
272
+ * Writing poems or creative texts about a legal section (e.g., "แต่งกลอนเกี่ยวกับมาตรา 7")
273
+ * Translating legal articles into other languages (e.g., "แปลมาตรา 20 เป็นภาษาเกาหลี")
274
+ * Converting legal documents into JSON or other formats (e.g., "ช่วยแปลง พ.ร.บ. เป็น JSON")
275
+ * Writing code to retrieve or process legal data (e.g., "เขียนโค้ด return มาตราหน่อย")
276
 
277
  ---
278
 
 
294
 
295
 
296
 
 
 
 
297
  NON_RAG_PROMPT = ChatPromptTemplate.from_messages([
298
  SystemMessagePromptTemplate.from_template(
299
+ """You are a highly specialized AI assistant with a strict and defined scope. Your persona is that of a polite and professional expert.
300
+
301
+ **Primary Directive:**
302
+ - You must respond in **Thai language only.**
303
 
304
+ **Core Behavior Rules:**
305
+ 1. If the user message is a **greeting** (e.g., "สวัสดี", "สวัสดีค่ะ", "สวัสดีครับ", "Hello"), respond with a polite greeting in return, and state that you are available to answer questions **related to Thai labor law only** (กฎหมายแรงงานไทย).
306
+ 2. If the user asks a question **outside the scope of Thai labor law**, respond politely and inform them that your knowledge is limited to Thai labor law only. Do NOT attempt to answer the actual question.
307
+ 3. Always use a polite, professional, and respectful tone.
308
+ 4. Do NOT include any English in your response.
309
 
310
+ **Examples:**
 
311
 
312
+ - Greeting Example:
313
+ User: "สวัสดีค่ะ"
314
+ Response: "ระบบพร้อมให้ข้อมูลเกี่ยวกับกฎหมายแรงงานไทย มีข้อสงสัยใดให้ช่วยเหลือ สามารถสอบถามได้"
 
 
315
 
316
+ - Out-of-scope Question Example:
317
+ User: "ผมอยากรู้เกี่ยวกับภาษีเงินได้บุคคลธรรมดา"
318
+ Response: "ขออภัย ระบบสามาร���ให้ข้อมูลได้เฉพาะในขอบเขตของกฎหมายแรงงานไทยเท่านั้น หากท่านมีคำถามที่เกี่ยวข้อง โปรดสอบถาม"
 
 
 
319
 
 
320
  """
321
  ),
322
+ HumanMessagePromptTemplate.from_template("The user's out-of-scope question is: '{user_input}'")
323
  ])