Repository navigation
Expand file tree
/
Copy pathnodes.py
More file actions
585 lines (456 loc) · 26.9 KB
/
Copy pathnodes.py
File metadata and controls
585 lines (456 loc) · 26.9 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import os
import re
import json
import logging
import requests
import psycopg2
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_ollama import ChatOllama, OllamaEmbeddings
import chromadb
from state import AgentState
load_dotenv()
# Initialize the dedicated logger for our debugging session
logger = logging.getLogger("rag_debugger")
# =====================================================================
# PIPELINE 1: BACKGROUND AUTOMATION GRAPH (For run_cron.py Tasks)
# =====================================================================
def preprocessing_law_changes(http_body, law_id):
data = json.loads(http_body) if isinstance(http_body, str) else http_body
service = data.get("OldAndNewService", {})
new_info = service.get("신조문_기본정보", {})
old_info = service.get("구조문_기본정보", {})
# 1. Metadata
changed_meta = [f"{k}: {old_info.get(k)} -> {v}" for k, v in new_info.items() if v != old_info.get(k)]
# 2. Extract Clause Lists
new_list = service.get("신조문목록", {}).get("조문", [])
old_list = service.get("구조문목록", {}).get("조문", [])
if isinstance(new_list, dict): new_list = [new_list]
if isinstance(old_list, dict): old_list = [old_list]
old_lookup = {item.get('no'): item.get('content', '') for item in old_list}
grouped_clauses = {}
current_title = "기타"
# Initialize a global counter for new indexing
new_index = 1
title_pattern = re.compile(r'제\d+조의?\d*\(.*?\)')
skip_pattern = re.compile(r"\(현행과\s*같음\)|\(생\s*략\)")
html_pattern = re.compile(r'<[^>]*>')
for item in new_list:
no = item.get('no') # Keep this just for the lookup
new_content_raw = item.get('content', '')
old_content_raw = old_lookup.get(no, '')
title_match = title_pattern.search(new_content_raw)
if title_match:
current_title = html_pattern.sub('', title_match.group())
is_new_skip = bool(skip_pattern.search(new_content_raw))
is_old_skip = bool(skip_pattern.search(old_content_raw))
if new_content_raw != old_content_raw:
if not (is_new_skip and is_old_skip):
if current_title not in grouped_clauses:
grouped_clauses[current_title] = []
clean_new = html_pattern.sub('', new_content_raw).strip()
clean_old = html_pattern.sub('', old_content_raw).strip()
grouped_clauses[current_title].append({
"index": new_index, # Use the new sequential number
"old": clean_old if clean_old else "(내용 없음)",
"new": clean_new if clean_new else "(내용 없음)"
})
# Increment the counter only when a change is actually added
new_index += 1
return (f"[법령명]: {new_info.get("법령명")}\n"
f"[법령ID]: {law_id}\n"
f"[변경된 기본정보]: {"\n".join(changed_meta) if changed_meta else "변경 사항 없음"}\n\n"
f"[변경된 조문]: \n{json.dumps(grouped_clauses, ensure_ascii=False, indent=2) if grouped_clauses else "실질적인 조문 변경 사항 없음"}")
def fetch_law_change_http(id: str) -> str:
"""Fetches law changes from an external HTTP endpoint"""
api_url = os.getenv("LAW_API_ENDPOINT")
params = {"target": "oldAndNew",
"OC": "cmsoft",
"type": "JSON",
"ID": id}
try:
# Perform the HTTP GET request
response = requests.get(api_url, params=params)
if response.status_code == 200:
law_changes = preprocessing_law_changes(response.json(), id)
# For testing, let's assume it returns a list or dict of changes
return law_changes
else:
return f"HTTP Fetch Failed. Status Code: {response.status_code}"
except Exception as e:
return f"HTTP Node Error: {str(e)}"
def fetch_law_changes_node(state: AgentState) -> dict:
law_changes = {}
for id in state.get("updated_law_ids", []):
law_changes[id] = fetch_law_change_http(id)
return {"updated_law_changes": law_changes}
def get_db_connection():
return psycopg2.connect(
host=os.getenv("DB_HOST"),
port=os.getenv("DB_PORT"),
database=os.getenv("DB_NAME"),
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD")
)
def fetch_target_users_node(state: AgentState) -> dict:
updated_ids = state.get("updated_law_ids")
law_changes = state.get("updated_law_changes")
conn = get_db_connection()
cursor = conn.cursor()
# Secure parameterization using single quotes behind the scenes
query = "SELECT name, slack_id, law_list FROM law_mapping ;"
cursor.execute(query)
rows = cursor.fetchall()
targets = {}
for user in rows:
user_name = user[0]
slack_id = user[1]
user_needed_laws = user[2]
# Find intersections matching updated items
matched = [str(law) for law in user_needed_laws if str(law) in updated_ids]
if matched:
changes = {k: law_changes[k] for k in matched if k in law_changes}
# 3. FIX: Bind parameter cleanly into the JSONB update string directly
update_query = "UPDATE law_mapping SET law_changes = %s::jsonb WHERE slack_id = %s;"
# Ensure Korean text remains completely readable inside PostgreSQL JSONB
json_payload = json.dumps(changes, ensure_ascii=False, indent=2)
# 4. Execute and immediately commit to apply the change
cursor.execute(update_query, (json_payload, slack_id))
conn.commit()
targets[slack_id] = {
"name": user_name,
"matched_laws": list(matched)
}
# 5. Clean wrap-up: Close the connections after the looping logic terminates
cursor.close()
conn.close()
return {"updated_laws_target_users": targets}
def notification(slack_id, user_info) -> str:
"""Formats the data using Slack Block Kit and fires an HTTP POST request."""
webhook_url = os.getenv("SLACK_WEBHOOK_URL")
if not webhook_url:
return "Slack Webhook URL is missing"
# Construct a clean, modern Slack Block Kit payload
payload = {
"channel": slack_id,
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"안녕하세요 {user_info["name"]}님!\n관심 법령인 {user_info["matched_laws"]}이 개정되었습니다."
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "은행 업무 영향도를 확인하시려면 아래 버튼을 클릭하여 어시스턴트의 도움을 받으세요!"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "법령 변경사항 분석하기",
"emoji": True
},
"style": "primary",
"url": f"{os.getenv("CHAT_URL")}:{os.getenv("CHAR_PORT")}?id={slack_id}&name={user_info['name']}&law_ids={"-".join(user_info["matched_laws"])}",
"action_id": "button_click"
}
]
}
]
}
try:
res = requests.post(
webhook_url,
json=payload,
headers={"Authorization": os.getenv("SLACK_AUTH")},
params={"Content-Type": "application/json"}
)
if res.status_code == 200:
return "Slack 알림 전송 완료!"
return f"Slack 전송 실패: {res.text}"
except Exception as e:
return f"Slack 연결 오류: {str(e)}"
def send_notifications_node(state: AgentState) -> dict:
notifications = {}
for slack_id, user_info in state["updated_laws_target_users"].items():
notifications[slack_id] = notification(slack_id, user_info)
return {"final_output": notifications}
# =====================================================================
# PIPELINE 2: INTERACTIVE CHATFLOW GRAPH (For api.py / Web Users)
# =====================================================================
# Enforce strict single-integer classification using Pydantic
class IntentSchema(BaseModel):
class_number: int = Field(
description="Intent class identifier integer: "
"1(List), "
"2(Specific Law), "
"3(All Laws), "
"4(To-Do), "
"5(Other)"
)
# Initialize the local model instance
def get_local_llm(temperature=0):
return ChatOllama(
base_url=os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
model=os.getenv("OLLAMA_LLM_MODEL", "qwen3:4b-instruct-2507-q4_K_M"),
streaming=True
)
def classify_intent_node(state: AgentState) -> dict:
# Lock temperature to 0 for strict routing decisions
llm = get_local_llm(temperature=0).with_structured_output(IntentSchema)
prompt = f"""
당신은 사용자의 입력(Query)과 대화 맥락을 바탕으로 의도를 5가지 클래스 중 하나로 분류하는 정밀 분류 전문가입니다.
### [의도 정의 (5 Classes)]
- Class 1: 개정 또는 변경된 법령들의 전체 ID나 명칭 '리스트'의 조회를 단순 요청하는 경우 (예: "목록 보여줘", "리스트 확인", "뭐가 바뀌었어?")
- Class 2: 개정된 법령들 중 사용자가 번호, 명칭을 활용하여 '특정 법령들만 선택'해 지정하여 검토 및 요약을 요청하는 경우 (예: "130번 분석해줘")
- Class 3: 개정된 '모든 법령 전체'에 대해 일괄 검토 및 요약을 요청하는 경우 (예: "모든 법령 검토해줘", "다 검토")
- Class 4: 법령 변경으로 인해 은행 실무자가 실무 현장에서 구체적으로 취해야 하는 실무 지침, 변경 행위, 해야 할 일(To-Do)을 물어보는 경우 (예: "내가 이제 실무에서 뭐 해야 돼?", "직원 실무 변화 알려줘", "할 일이 어떻게 달라져?")
- Class 5: 금융 법령, 지침, 은행 실무, 법령 변경사항 검토 및 어시스턴트 기능과 전혀 상관없는 무관한 질문이나 요청을 하는 경우 (예: "오늘 날씨 어때?", "맛집 추천해줘", "코딩해줘")
### [대화 맥락 및 입력 데이터]
- [사용자가 마지막으로 받은 답변]: {state.get('target_last_response', '')}
- [사용자의 새로운 입력 (Query)]: {state.get('target_query', '')}
### [응답 규칙 - 절대 준수]
1. 마크다운 백틱(```), JSON 기호, 마침표(.), 문장, 설명, 따옴표("), 공백, 또는 "Class 3" 같은 접두사를 절대 붙이지 말고 오직 분류된 클래스의 숫자 하나(예: 1, 2, 3, 4, 5)만 순수하게 출력하세요.
2. 규칙 위반 시 다음 시스템 파이프라인이 파괴됩니다. 오직 숫자 '1', '2', '3', '4', '5' 중 하나만 반환하세요.
"""
response = llm.invoke(prompt)
return {"target_classification": response.class_number}
def fetch_law_list_node(state: AgentState) -> dict:
current_user_id = state.get("target_id")
if not current_user_id:
return {"final_output": "사용자 ID를 식별할 수 없어 리스트를 불러올 수 없습니다."}
user_law_list = state.get("target_updated_law_ids")
# Build a clean, professional string report for the bank staff
report_lines = [
f"총 {len(user_law_list)}개의 관심 법령 변경 사항이 있습니다. 검토를 원하시는 법령 ID(숫자)를 입력해 주세요.\n"
]
for i, law_id in enumerate(user_law_list, 1):
report_lines.append(f"{i}. 법령 ID: **{law_id}**")
final_list_text = "\n".join(report_lines)
# FIX: Return this string directly to 'final_output' so the Chat UI can print it instantly!
return {"final_output": final_list_text}
def fetch_specific_law_node(state: AgentState) -> dict:
# Simple logic to pull digits from query text if a parameter extractor isn't linked yet
extracted_ids = re.findall(r"\d+", state.get('target_query', ''))
if not extracted_ids:
return {"final_output": "죄송합니다. 법령 ID를 정확이 인식하지 못했습니다. 숫자를 포함하여 다시 입력해주세요."}
updated_law_ids = state.get("target_updated_law_ids") or []
matched = [str(law) for law in extracted_ids if str(law) in updated_law_ids]
unmatched = [str(law) for law in extracted_ids if not str(law) in updated_law_ids]
note = ''
if unmatched:
note = f"※ 참고: 요청하신 법령 중 (법령ID: {','.join(unmatched)})은 오늘 변경 내역에 포함되어 있지 않습니다."
# Handle case where user entered numbers but none are in their allowed list
if not matched:
# Format list to clean text (e.g., "145, 999")
id_str = ", ".join(extracted_ids)
return {"final_output": f"죄송합니다. 요청하신 법령(법령ID: {id_str})은 오늘 변경 내역에 포함되어 있지 않습니다."}
conn = get_db_connection()
cursor = conn.cursor()
# Secure parameterization using single quotes behind the scenes
query = "SELECT law_changes FROM law_mapping WHERE slack_id = %s ;"
cursor.execute(query, (state.get('target_id'),))
row = cursor.fetchone()
cursor.close()
conn.close()
if not row or not row[0]:
return {"final_output": "죄송합니다. 등록된 최신 개정 내역 데이터가 존재하지 않습니다."}
raw_changes = row[0]
updated_law_changes = json.loads(raw_changes) if isinstance(raw_changes, str) else raw_changes
filtered_changes = {}
for law_id in matched:
if law_id in updated_law_changes:
filtered_changes[law_id] = updated_law_changes[law_id]
else:
print(f"Warning: Law ID {law_id} not found in database.")
target_law_changes = json.dumps(filtered_changes, ensure_ascii=False)
if matched:
return {
"target_law_changes": target_law_changes,
"target_note": note,
"target_query": f"법령 {','.join(matched)}를 검토해 주세요."
}
else:
return {
"final_output": f"죄송합니다. 요청하신 법령(법령ID: {extracted_ids})은 오늘 변경 내역에 포함되어 있지 않습니다."
}
def fetch_all_laws_node(state: AgentState) -> dict:
conn = get_db_connection()
cursor = conn.cursor()
# Secure parameterization using single quotes behind the scenes
query = "SELECT law_changes FROM law_mapping WHERE slack_id = %s ;"
cursor.execute(query, (state.get('target_id'),))
row = cursor.fetchone()
cursor.close()
conn.close()
if not row or not row[0]:
return {"final_output": "죄송합니다. 등록된 최신 개정 내역 데이터가 존재하지 않습니다."}
else:
return {
"target_law_changes": row[0]
}
def analyze_law_changes_node(state: AgentState) -> dict:
# If the database fetch step pushed an exception fallback message, skip LLM synthesis
if "죄송합니다" in state.get("final_output", ""):
return {}
llm = get_local_llm(temperature=0)
prompt = f"""
당신은 은행 직원에게 개정 법령 정보를 정확히 안내하는 금융 법률 전문 어시스턴트입니다.
제공된 [법령 데이터]에 기재된 팩트 정보만 그대로 활용하여, 절대 지어내거나 추론하지 말고 정확하게 답변하세요.
### [법령 데이터]
{state.get('target_law_changes')}
### [사용자 입력]
{state.get('target_query')}
### [참고 메시지]
{state.get('target_note')}
### [응답 규칙 - 절대 준수]
1. 출력 포맷 지정 (마크다운 기반의 엄격한 가이드라인):
- 각 법령별로 반드시 아래의 마크다운 템플릿 형식을 토씨 하나 틀리지 말고 적용하세요.
- **강조 준수 사항**: 변경 전후 데이터나 단어를 서술할 때, 새롭게 바뀌어 들어온 변경 후(new)의 핵심 단어는 **반드시 쌍별표 `**`를 감싼 굵은 글씨(`**단어**`)로 감싸 하이라이트(Highlight) 처리하여 출력**하세요.
###### 법령ID: [해당 숫자 ID]
■ **법령명**:
[매칭된 실제 법령명]
■ **주요 변경 내용**:
[변경된 조문 및 구체적인 항목 분석 요약 내용 서술]
2. 텍스트 제어 가이드 (문장 끊김 및 중복 단어 방지):
- 변경 데이터를 서술할 때는 "이번 수정된~", "현재 적용됨" 같은 주관적인 설명조의 불필요한 미사여구를 절대 덧붙이지 마세요.
- 무조건 숫자 지표와 명사 단어 위주로 끊어서 간결하게 나열식 리스트(`-`)로만 표기하세요. (예: "시행일자: 20241017 ➔ 20260102")
3. 참고 메시지 노출 circuit breaker (예외 조건 차단):
- 상단에 전달된 [참고 메시지]가 비어 있거나, 문자열 내용이 없거나, None인 경우에는 답변 최하단에 [참고 메시지]라는 단어 자체를 절대로 쓰거나 언급하지 마세요. (즉, "[참고 메시지] 없음"이라는 문구 출력을 엄격히 금지합니다.)
- 오직 [참고 메시지]에 구체적인 텍스트 내용이 존재할 때만, 전체 답변의 맨 마지막 줄에 한 줄로 덧붙여서 출력하세요.
"""
response = llm.invoke(prompt)
return {"final_output": response.content}
def fallback_router_node(state: AgentState) -> dict:
llm = get_local_llm(temperature=0)
prompt = f"""
당신은 은행 직원에게 3가지 일을 제공해 주는 어시스턴트입니다. 관련이 없는 질문에 답변하지 마세요. 다음 질문에 친절히 응대하세요: {state.get('target_query')}
### [사용자 성함]
{state.get('target_name')}
### [당신이 할 수 있는 일]
- 사용자가 알아야 할 변경된 법령 리스트 제공
- 변경된 법령 검토
- 법령 변경에 따라 해야 되는 일 제공
"""
response = llm.invoke(prompt)
return {"final_output": response.content}
def generate_optimized_search_query_node(state: AgentState) -> dict:
"""
Advanced RAG Pattern: Rewrites conversational user text
into optimized, dense legal search phrases.
"""
user_query = state.get("target_query", "")
# law_changes = state.get("target_law_changes", "") # Existing metadata change context
llm = get_local_llm(temperature=0)
prompt = f"""
당신은 금융 법률 및 규정 검색을 위한 쿼리 최적화 전문가입니다.
사용자의 자연어 받은 chat 메시지,질문과 개정 맥락을 분석하여, 벡터 데이터베이스(ChromaDB)에서 가장 정확한 조문을 찾아낼 수 있는 '법률적 단어 중심의 검색 쿼리'를 한 줄로 생성하세요.
### [사용자의 마지막으로 받은 chat 메시지]
{state.get('target_last_response')}
### [사용자의 자연어 질문]
{state.get('target_query')}
### [법령 개정 맥락]
{state.get('target_law_changes')}
### [출력 규칙]
- 사족, 설명, 인사말, 따옴표, 그리고 조사 및 어미 연결문구(예: "~관련하여", "~대해", "~분석")를 절대 붙이지 마세요.
- 오직 벡터 검색에 최적화된 핵심 법률 명사구와 구체적인 조문 번호(숫자)로만 연결된 명사식 나열로 출력하세요.
- 항상 법령ID로 시작하세요. 예시 출력: "130 제17조의3 적극적 고용개선조치 시행계획 제출 대상"
"""
response = llm.invoke(prompt)
optimized_query = response.content.strip()
print(f"🔍 [Query Rewriter] Original: '{user_query}' ➔ Optimized: '{optimized_query}'")
# Temporarily store the rewritten query inside the query field for the next node to consume
return {"target_rag_query": optimized_query}
def retrieve_rag_context_node(state: AgentState) -> dict:
"""
Elite Agent Node: Searches your pre-compiled vector index
without duplicating the RAG construction codebase.
"""
query_text = state.get('target_rag_query')
vector_db_dir = os.getenv("VECTOR_DB_DIR")
logger.info("\n╔════════════════════════════════════════════════════════════")
logger.info("📥 [RAG ENTER] -> Starting Semantic Retrieval Sequence...")
logger.info(f" • Active Search Query String: '{query_text}'")
# Validation safeguard check
if not query_text or not str(query_text).strip():
logger.warning("⚠️ Warning: target_query is blank. Skipping vector database lookup.")
return {"target_knowledge": "검색 키워드가 비어 있어 관련 법령을 조회할 수 없습니다."}
try:
logger.info(f" • Connecting to ChromaDB directory: '{vector_db_dir}'")
# Open a read-only channel to your existing storage directory
chroma_client = chromadb.PersistentClient(path=vector_db_dir)
collection = chroma_client.get_collection(name="bank_compliance_laws")
# Connect to local Ollama embedding encoder over the network pipeline
ollama_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
logger.info(f" • Connecting to Ollama Embeddings Engine: {ollama_url} (Model: bge-m3)")
# Instantiate the math embedding engine reference hook
ollama_embeddings = OllamaEmbeddings(
base_url=ollama_url,
model=os.getenv("OLLAMA_EMB_MODEL", "bge-m3")
)
# Calculate the question query coordinates
logger.info(" • Generating numeric coordinates for search text string...")
query_vector = ollama_embeddings.embed_query(query_text)
# Retrieve the top 10 closest high-context legal matches
logger.info(" • Querying ChromaDB collection vector spaces...")
results = collection.query(
query_embeddings=[query_vector],
n_results=10
)
retrieved_documents = results.get('documents', [[]])
# ChromaDB results return as a list of lists: [[doc1, doc2, doc3]]
# Safely extract and check if we found anything matching the query coordinate bounds
if retrieved_documents and len(retrieved_documents[0]) > 0:
context_block = "\n\n".join(retrieved_documents[0])
logger.info(f"🚀 [RAG SUCCESS] -> Retrieved {len(retrieved_documents[0])} context passages.")
logger.info("╚════════════════════════════════════════════════════════════\n")
return {"target_knowledge": context_block}
else:
logger.warning("⚠️ ChromaDB lookup complete, but 0 similarity matches were found.")
logger.info("╚════════════════════════════════════════════════════════════\n")
return {"target_knowledge": "검색어와 관련된 일치하는 법령 내용을 찾지 못했습니다."}
except Exception as e:
# 🚨 THE CRITICAL DEBUG FORCING LINE:
# Prints the precise raw Python traceback straight to your PyCharm terminal console!
logger.error("\n❌ [RAG CRITICAL CRASH LOGGED]")
logger.error(f" • ERROR DETAILS: {str(e)}")
logger.error(f" • ERROR CLASS: {e.__class__.__name__}")
logger.error("╚════════════════════════════════════════════════════════════\n")
return {"target_knowledge": "시스템 일시적 오류로 실시간 관련 법령 검색 결과를 불러오지 못했습니다."}
def analyze_todo_list_node(state: AgentState) -> dict:
llm = get_local_llm(temperature=0)
prompt = f"""
당신은 은행 실무자에게 금융 법률 개정 사항에 따른 실무 대응 지침(To-Do List)을 정확히 명시해 주는 금융 컴플라이언스 총괄 마스터입니다.
모호하고 수동적인 표현(예: "~확인 필요", "~해야 합니다")은 일절 배제하고, 실무 현장에서 즉시 집행 가능한 명확한 행동 규칙만 작성하세요.
### [RAG 기반 개정 법령 정보]
{state.get('target_knowledge')}
### [대화 맥락 (마지막 답변)]
{state.get('target_last_response')}
### [사용자 질의]
{state.get('target_query')}
### [응답 규칙 - 절대 준수]
1. 실무자 중심 To-Do 리스트 포맷 (마크다운 기반의 엄격한 가이드라인):
- 상단의 [RAG 기반 개정 법령 정보]와 대화 맥락을 면밀히 분석하여, 은행 직원이 실무에서 취해야 하는 행동 지침을 반드시 아래의 구획 형식을 엄격히 반복 적용하여 마크다운으로 출력하세요. (인사말이나 "지침입니다" 같은 사족 절대 금지)
###### 📋 [소관 법령/주제명] 실무 변경 지침
■ **법령ID**: [해당 숫자 ID]
■ **핵심 실무 변화**:
- 기존 [과거 업무 행위/수신처]에서 ➔ **[변경된 새로운 업무 행위/수신처]**로 실무 책임 범위가 공식 전환됨.
■ **필수 실무 To-Do 핵심 액션**:
1. **[구체적인 1차 조치 명칭]**: [RAG 정보를 기반으로 직원이 실무 서식, 시스템, 보고 라인에서 즉시 바꾸어야 하는 명확한 행동 명령문 서술. 변경된 신규 기관명이나 부서령은 반드시 쌍별표 `**`를 감싸 볼드 하이라이트 처리할 것]
2. **[구체적인 2차 조치 명칭]**: [업무 매뉴얼 개정, 시스템 수신처 변경, 기한 준수 등 후속 실무 처리 명령문 서술]
2. 동사형 텍스트 제어 가이드 (행동 유도형 종결 어미 강제):
- 각 To-Do 항목의 종결 어미는 반드시 "~할 것", "~변경 처리 완료할 것", "~제출할 것"과 같은 **명령형/명사형 종결어미(`~할 것`)**로 끝나도록 철저히 통일하세요. 수동적인 어조는 절대 금지합니다.
3. 컨텍스트 차단 규칙:
- 만약 [RAG 기반 개정 법령 정보]에 구체적인 실무 변경 내역이 없거나 데이터가 비어 있는 경우, 사족을 지어내지 말고 아래 문장만 단호하게 출력하세요:
"현재 매핑된 RAG 지식베이스 내에 실무 지침(To-Do)을 도출할 수 있는 구체적인 조문 변경 데이터가 확인되지 않습니다."
"""
response = llm.invoke(prompt)
return {"final_output": response.content}