-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathold.py
921 lines (774 loc) Β· 35 KB
/
old.py
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
import os # μ΄μ체μ μ κ΄λ ¨λ κ²½λ‘ λ° νκ²½ λ³μ μμ
μ μν λΌμ΄λΈλ¬λ¦¬
from dotenv import load_dotenv # .env νμΌμμ νκ²½ λ³μλ₯Ό λ‘λνκΈ° μν λΌμ΄λΈλ¬λ¦¬
from fastapi import FastAPI, HTTPException # FastAPI μλ² λ° HTTP μμΈ μ²λ¦¬
from fastapi.responses import JSONResponse # JSON μλ΅μ λ°ννκΈ° μν ν΄λμ€
from fastapi.middleware.cors import CORSMiddleware # CORS μ€μ μ μν λ―Έλ€μ¨μ΄
from contextlib import (
asynccontextmanager,
) # λΉλκΈ° 리μμ€ κ΄λ¦¬μ μ μ©ν 컨ν
μ€νΈ 맀λμ
from pydantic import BaseModel # λ°μ΄ν° μ ν¨μ± κ²μ¦μ μν λͺ¨λΈ ν΄λμ€
# LangChain κ΄λ ¨ λͺ¨λ
from langchain_community.document_loaders import (
PyPDFLoader,
TextLoader,
) # λ¬Έμλ₯Ό λ‘λνκΈ° μν λ‘λ
from langchain.text_splitter import (
RecursiveCharacterTextSplitter,
) # κΈ΄ ν
μ€νΈλ₯Ό λΆν νκΈ° μν μ νΈλ¦¬ν°
from langchain_community.vectorstores import Chroma # λ²‘ν° μ€ν μ΄λ‘ Chromaλ₯Ό μ¬μ©
from langchain_openai import (
OpenAIEmbeddings,
ChatOpenAI,
) # OpenAI κΈ°λ° μλ² λ© λ° LLM μ¬μ©
from langchain.chains.combine_documents import (
create_stuff_documents_chain,
) # κ²μλ λ¬Έμ κ²°ν© μ²΄μΈ μμ±
from langchain.chains import (
create_history_aware_retriever,
) # λν νμ€ν 리λ₯Ό κ³ λ €ν κ²μκΈ° μμ±
from langchain_core.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
) # λνν ν둬ννΈ ν
νλ¦Ώ μ μ
from langchain_core.runnables.history import (
RunnableWithMessageHistory,
) # λν νμ€ν 리λ₯Ό μ²λ¦¬νλ μ€ν κ°λ₯ 체μΈ
from langchain_community.chat_message_histories import (
ChatMessageHistory,
)
# λν λ©μμ§ νμ€ν 리 κ΄λ¦¬
from langchain.schema import HumanMessage, SystemMessage
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
# λ°°μΉ κ΄λ ¨ λΌμ΄λΈλ¬λ¦¬
from sqlalchemy import create_engine
from sqlalchemy.sql import text # SQLAlchemyμ text λͺ¨λ μΆκ°
import pandas as pd
from langchain.schema import Document
from concurrent.futures import ThreadPoolExecutor # λ³λ ¬ μ²λ¦¬λ₯Ό μν λͺ¨λ
from datetime import datetime # λ°°μΉ μ£ΌκΈ°λ₯Ό μν λͺ¨λ
import shutil # λλ ν 리 μμ λ₯Ό μν λͺ¨λ
import asyncio # μκ° λκΈ°λ₯Ό μν λͺ¨λ
import traceback # μλ¬ λλ²κΉ
λ° νΈλ μ΄μ€λ°± μΆμ
import uvicorn # FastAPI μλ² μ€ν
# λ‘κΉ
μ€μ
import time
import logging
# λ‘κΉ
μ€μ
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
# .env νμΌ λ‘λ
load_dotenv()
# λ°μ΄ν° κ²½λ‘ μ€μ
# DATA_DIR = r"C:\lecture\FinalProject\InFlow-AI\data"
# CHROMA_DB_DIR = r"C:\lecture\FinalProject\InFlow-AI\chromadb"
# CSV_DIR = r"C:\lecture\FinalProject\InFlow-AI\chromadb\csv_files"
# λ°μ΄ν° κ²½λ‘ μ€μ
DATA_DIR = r"C:\lecture\FinalProject\InFlow-AI\data"
CHROMA_DB_DIR = f"C:/lecture/FinalProject/InFlow-AI/chromadb_worker_{os.getpid()}"
CSV_DIR = r"C:\lecture\FinalProject\InFlow-AI\chromadb\csv_files"
LOCK_FILE = r"C:/lecture/FinalProject/InFlow-AI/chroma.lock" # μ κΈ νμΌ κ²½λ‘
# MariaDB μ°κ²° μ 보
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_PORT = int(os.getenv("DB_PORT", 3306))
DB_USER = os.getenv("DB_USER", "root")
DB_PASSWORD = os.getenv("DB_PASSWORD", "")
DB_NAME = os.getenv("DB_NAME", "test_db")
# OpenAI API ν€ λ‘λ
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY not found in .env file.")
# OpenAI μλ² λ© μ€μ
embeddings = OpenAIEmbeddings(
openai_api_key=OPENAI_API_KEY, model="text-embedding-ada-002"
)
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
# λ²‘ν° μ€ν μ΄ μ΄κΈ°ν
vectorstore = None
# # CSV λλ ν 리μ Chroma DB λλ ν 리λ₯Ό μ΄κΈ°ν λ° μμ±
# def initialize_directories():
# # Chroma DB λλ ν 리 μ΄κΈ°ν
# if os.path.exists(CHROMA_DB_DIR):
# shutil.rmtree(CHROMA_DB_DIR) # κΈ°μ‘΄ Chroma DB λλ ν 리 μμ
# print(f"Cleared Chroma DB directory: {CHROMA_DB_DIR}")
# os.makedirs(CHROMA_DB_DIR, exist_ok=True) # Chroma DB λλ ν 리 μ¬μμ±
# print(f"Created Chroma DB directory: {CHROMA_DB_DIR}")
# # CSV λλ ν 리 μ΄κΈ°ν
# if os.path.exists(CSV_DIR):
# shutil.rmtree(CSV_DIR) # κΈ°μ‘΄ CSV λλ ν 리 μμ
# print(f"Cleared CSV directory: {CSV_DIR}")
# os.makedirs(CSV_DIR, exist_ok=True) # CSV λλ ν 리 μ¬μμ±
# print(f"Created CSV directory: {CSV_DIR}")
def initialize_directories():
os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True) # μ κΈ νμΌμ λλ ν 리 μμ±
lock = InterProcessLock(LOCK_FILE) # μ κΈ νμΌμ ν΅ν λμμ± μ μ΄
try:
if lock.acquire(blocking=True, timeout=10): # μ κΈ νλ λκΈ° (μ΅λ 10μ΄)
try:
if os.path.exists(CHROMA_DB_DIR):
print(f"Chroma DB directory already exists: {CHROMA_DB_DIR}")
else:
os.makedirs(CHROMA_DB_DIR, exist_ok=True)
print(f"Created Chroma DB directory: {CHROMA_DB_DIR}")
finally:
lock.release()
else:
print("Failed to acquire lock. Another process is initializing.")
except Exception as e:
print(f"Error during directory initialization: {e}")
# SQLAlchemy μμ§ μμ±(mariadb )
def connect_sqlalchemy():
try:
engine = create_engine(
f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
)
return engine
except Exception as e:
print(f"Error creating SQLAlchemy engine: {e}")
raise
# λͺ¨λ ν
μ΄λΈμ λ³λ ¬λ‘ CSVλ‘ μ μ₯
def export_tables_to_csv():
# λλ ν 리 μ ν¨μ± κ²μ¬
if not os.path.exists(CSV_DIR):
raise FileNotFoundError(f"CSV directory does not exist: {CSV_DIR}")
engine = connect_sqlalchemy() # SQLAlchemy μμ§ μ¬μ©
try:
# λͺ¨λ ν
μ΄λΈ μ΄λ¦ κ°μ Έμ€κΈ°
with engine.connect() as connection:
# μμ SQL μ€ν
result = connection.execute(text("SHOW TABLES;"))
tables = [row[0] for row in result]
# λ³λ ¬ μ²λ¦¬λ‘ κ° ν
μ΄λΈ λ°μ΄ν°λ₯Ό CSVλ‘ μ μ₯
with ThreadPoolExecutor() as executor:
executor.map(
lambda table: export_table_to_csv_parallel(table, engine), tables
)
except Exception as e:
print(f"Error exporting all tables: {e}")
# νΉμ ν
μ΄λΈμ λ³λ ¬λ‘ CSVλ‘ μ μ₯
def export_table_to_csv_parallel(table_name, engine):
try:
# λλ ν 리 μ ν¨μ± κ²μ¬
if not os.path.exists(CSV_DIR):
raise FileNotFoundError(f"CSV directory does not exist: {CSV_DIR}")
# employee ν
μ΄λΈμΌ κ²½μ° λ―Όκ° μ 보 μ μΈ
if table_name == "employee":
query = """
SELECT
employee_id,
employee_number,
employee_role,
gender,
name,
birth_date,
email,
phone_number,
profile_img_url,
join_date,
resignation_date,
resignation_status,
department_code,
attendance_status_type_code,
position_code,
role_code,
duty_code
FROM employee
"""
else:
# λ€λ₯Έ ν
μ΄λΈμ μ 체 λ°μ΄ν°λ₯Ό κ°μ Έμ΄
query = f"SELECT * FROM {table_name}"
# λ°μ΄ν° νλ μμΌλ‘ κ°μ Έμ€κΈ°
df = pd.read_sql(query, engine)
# CSV νμΌλ‘ μ μ₯
csv_path = os.path.join(CSV_DIR, f"{table_name}.csv")
df.to_csv(csv_path, index=False, encoding="utf-8")
print(f"Exported {table_name} to {csv_path}")
except Exception as e:
print(f"Error exporting table {table_name}: {e}")
# CSV.pdf λ°μ΄ν°λ₯Ό 벑ν°ννκ³ Chroma DBμ μ μ₯
def store_files_in_chroma():
"""CSVμ PDF νμΌμ λ²‘ν° μ€ν μ΄μ μ μ₯"""
global vectorstore
documents = []
# λ°μ΄ν° κ²°ν©μ© μμ μ μ₯μ
employee_data = {}
# CSV νμΌ μ²λ¦¬
for csv_file in os.listdir(CSV_DIR):
if csv_file.endswith(".csv"):
csv_path = os.path.join(CSV_DIR, csv_file)
df = pd.read_csv(csv_path)
if df.empty:
print(f"Skipped empty file: {csv_file}")
continue
# ν
μ΄λΈλ³ λ°μ΄ν° μ²λ¦¬
for _, row in df.iterrows():
if "employee_id" in row:
emp_id = row["employee_id"]
# μ§μ λ°μ΄ν°λ₯Ό μμ μ μ₯μμ μΆκ°
if emp_id not in employee_data:
employee_data[emp_id] = {}
employee_data[emp_id][csv_file] = row.to_dict()
# μ§μλ³ λ°μ΄ν°λ₯Ό λ¬Έμ₯μΌλ‘ λ³ν
for emp_id, tables in employee_data.items():
content_parts = []
for table_name, row_data in tables.items():
if table_name == "vacation.csv":
content_parts.append(
f"μ¬μ ID {emp_id}: λ¨μ μ°μ°¨ {row_data.get('remaining_days', 0)}μΌ, "
f"λ³κ° {row_data.get('sick_leave_used', 0)}μΌ μ¬μ©."
)
elif table_name == "evaluation.csv":
content_parts.append(
f"μ¬μ ID {emp_id}: νκ° λ±κΈ {row_data.get('grade', 'N/A')}, "
f"νκ° μ μ {row_data.get('score', 'N/A')}."
)
elif table_name == "commute.csv":
content_parts.append(
f"μ¬μ ID {emp_id}: μ΅κ·Ό μΆκ·Ό μν {row_data.get('status', 'N/A')}."
)
else:
# κΈ°ν ν
μ΄λΈ λ°μ΄ν° μ²λ¦¬
table_content = " ".join(
[f"{key}:{value}" for key, value in row_data.items()]
)
content_parts.append(f"{table_name}: {table_content}")
# μ΅μ’
λ¬Έμ μμ±
full_content = " ".join(content_parts)
documents.append(
Document(page_content=full_content, metadata={"employee_id": emp_id})
)
# PDF νμΌ μ²λ¦¬
for file in os.listdir(DATA_DIR):
if file.endswith(".pdf"):
pdf_path = os.path.join(DATA_DIR, file)
loader = PyPDFLoader(pdf_path)
documents.extend(loader.load_and_split())
# λ¬Έμ λΆν λ° λ²‘ν°ν
split_docs = text_splitter.split_documents(documents)
if split_docs:
vectorstore = Chroma.from_documents(
documents=split_docs,
embedding=embeddings,
persist_directory=CHROMA_DB_DIR,
)
print("Data stored in Chroma DB.")
# 24μκ° κ°κ²©μΌλ‘ λ°°μΉλ₯Ό μ€ν
async def run_batch():
while True:
try:
print(f"Batch started at {datetime.now()}")
initialize_directories() # 1. λλ ν 리 μ΄κΈ°ν λ° μμ±
export_tables_to_csv() # 2. λͺ¨λ ν
μ΄λΈ λ°μ΄ν°λ₯Ό CSVλ‘ μ μ₯
store_files_in_chroma() # 3. CSV, PDF λ°μ΄ν°λ₯Ό λ²‘ν° DBμ μ μ₯
print(f"Batch completed at {datetime.now()}")
except Exception as e:
print(f"Error during batch execution: {e}")
await asyncio.sleep(24 * 60 * 60) # 4. 24μκ° λκΈ°
# FastAPI μΈμ€ν΄μ€ μμ±
app = FastAPI()
# CORS μ€μ
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# FastAPI μμ μ μ΄κΈ°ν μμ
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan μ΄λ²€νΈ νΈλ€λ¬"""
global vectorstore # μ μ λ³μλ‘ vectorstore μ¬μ©
try:
close_vectorstore() # Vectorstore μ’
λ£
print("Initializing directories...")
initialize_directories()
print("Exporting tables to CSV...")
export_tables_to_csv()
print("Storing files in Chroma...")
store_files_in_chroma()
print("Chroma Vectorstore Initialized.")
# 24μκ° λ°°μΉ μμ
λ³λ ¬ μ€ν
asyncio.create_task(run_batch())
yield # μ ν리μΌμ΄μ
μ΄ μ€νλ λμ μ΄λ²€νΈ μ²λ¦¬
except Exception as e:
print(f"Error during startup: {e}")
raise
finally:
print("Shutting down the application...")
# νμμ ν΄λ¦°μ
μμ
μΆκ°
# Vectorstore μμ
μ’
λ£ ν¨μ
def close_vectorstore():
global vectorstore
if vectorstore is not None:
vectorstore = None
print("Vectorstore closed successfully.")
# Lifespan μ΄λ²€νΈ νΈλ€λ¬
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan μ΄λ²€νΈ νΈλ€λ¬"""
try:
# μ ν리μΌμ΄μ
μ΄κΈ°ν μ μ€νν μμ
print("Application starting...")
initialize_directories() # λλ ν 리 μ΄κΈ°ν
export_tables_to_csv() # CSV μμ±
store_files_in_chroma() # Vectorstoreμ λ°μ΄ν° μ μ₯
yield # μ ν리μΌμ΄μ
μ€ν
finally:
# μ ν리μΌμ΄μ
μ’
λ£ μ μ€νν μμ
print("Shutting down...")
close_vectorstore() # Vectorstore μ’
λ£
# FastAPI μΈμ€ν΄μ€μ lifespan μ€μ
app = FastAPI(lifespan=lifespan)
# μ
λ ₯ λ°μ΄ν° λͺ¨λΈ μ μ
class QueryRequest(BaseModel):
query: str
employee_id: str
session_id: str
# λ΅λ³ λ¬Έμ μ§λ ¬ν λ° ν
μ΄λΈ μ€λͺ
ν¬ν¨
def serialize_documents(documents):
serialized_docs = []
for doc in documents:
serialized_docs.append(
{
"page_content": doc.page_content.replace("\\", ""),
"metadata": {
"table": doc.metadata.get("table", "unknown"),
"table_korean": doc.metadata.get(
"table_korean", "μ μ μλ ν
μ΄λΈ"
),
},
}
)
return serialized_docs
def serialize_data(data):
"""
λͺ¨λ λ°μ΄ν°μμ NaN, Infinity κ°μ μμ ν κ°μΌλ‘ λ³ννκ³ Timestamp κ°μ²΄λ₯Ό λ¬Έμμ΄λ‘ λ³ν
"""
if isinstance(data, list):
return [serialize_data(item) for item in data]
elif isinstance(data, dict):
return {key: serialize_data(value) for key, value in data.items()}
elif isinstance(data, pd.Timestamp): # pandas Timestamp κ°μ²΄ μ²λ¦¬
return data.isoformat()
elif hasattr(data, "isoformat"): # μΌλ° datetime κ°μ²΄ μ²λ¦¬
return data.isoformat()
elif isinstance(data, float): # NaN, Infinity μ²λ¦¬
if pd.isna(data) or data != data: # NaN νμΈ
return None
if data == float("inf") or data == float("-inf"): # Infinity νμΈ
return None
return data
else:
return data
# νμ€ν 리 μμ± λ° μ‘°ν
chat_history_storage = {} # λν νμ€ν 리 μ μ₯μ
def get_or_create_history(session_id):
if session_id not in chat_history_storage:
chat_history_storage[session_id] = ChatMessageHistory()
return chat_history_storage[session_id]
table_name_mapping = {
"monthly_employee_num_statistics": "μλ³ μ¬μ μ ν΅κ³ ν
μ΄λΈ (μ¬μμ μλ³ λ³ν μΆμ΄λ₯Ό ν¬ν¨)",
"monthly_department_overtime_allowance_statistics": "μλ³ λΆμλ³ μ΄κ³Όκ·Όλ¬΄ μλΉ ν΅κ³ ν
μ΄λΈ",
"semiannual_department_performance_ratio_statistics": "λ°κΈ°λ³ λΆμ μ±κ³Ό λΉμ¨ ν΅κ³ ν
μ΄λΈ",
"feedback": "νΌλλ°± ν
μ΄λΈ (μ¬μ λ° λΆμμ λν νΌλλ°± μ 보λ₯Ό ν¬ν¨)",
"task_eval": "κ³Όμ νκ° ν
μ΄λΈ (κ°λ³ κ³Όμ μ λν νκ° κΈ°λ‘ ν¬ν¨)",
"task_type_eval": "κ³Όμ μ ν νκ° ν
μ΄λΈ (κ° μ νλ³ νκ° μ 보 ν¬ν¨)",
"grade": "λ±κΈ ν
μ΄λΈ (μ¬μμ νκ° λ±κΈ μ 보λ₯Ό ν¬ν¨)",
"evaluation": "νκ° ν
μ΄λΈ (μ¬μμ μ±κ³Ό λ° λ₯λ ₯ νκ° κΈ°λ‘ ν¬ν¨)",
"task_item": "κ³Όμ νλͺ© ν
μ΄λΈ (μΈλΆ κ³Όμ νλͺ© μ 보 ν¬ν¨)",
"evaluation_policy": "νκ° μ μ±
ν
μ΄λΈ (νκ° κΈ°μ€ λ° μ μ±
μ 보 ν¬ν¨)",
"task_type": "κ³Όμ μ ν ν
μ΄λΈ (κ³Όμ μ λΆλ₯ λ° μ ν μ 보 ν¬ν¨)",
"business_trip": "μΆμ₯ ν
μ΄λΈ (μ¬μμ μΆμ₯ κΈ°λ‘ λ° μΈλΆ μ 보 ν¬ν¨)",
"leave_return": "λ³΅μ§ ν
μ΄λΈ (ν΄μ§ ν λ³΅μ§ μ 보 ν¬ν¨)",
"commute": "μΆν΄κ·Ό ν
μ΄λΈ (μ¬μμ μΆν΄κ·Ό μκ° λ° κΈ°λ‘ ν¬ν¨)",
"attendance_request_file": "κ·Όν μμ² νμΌ ν
μ΄λΈ (κ·Όν μμ²μ 첨λΆλ νμΌ μ 보 ν¬ν¨)",
"attendance_request": "κ·Όν μμ² ν
μ΄λΈ (μ¬μμ κ·Όν λ³κ²½ μμ² κΈ°λ‘ ν¬ν¨)",
"attendance_request_type": "κ·Όν μμ² μ ν ν
μ΄λΈ (κ·Όν μμ²μ λΆλ₯ λ° μ ν μ 보 ν¬ν¨)",
"payment": "μ§κΈ ν
μ΄λΈ (μ¬μμ κΈμ¬ λ° λ³΄λμ€ μ§κΈ λ΄μ ν¬ν¨)",
"irregular_allowance": "λΉμ κΈ° μλΉ ν
μ΄λΈ (νΉλ³ μλΉ λ° λΉμ κΈ° μλΉ μ 보 ν¬ν¨)",
"public_holiday": "곡ν΄μΌ ν
μ΄λΈ (νμ¬μμ μΈμ νλ 곡ν΄μΌ μ 보 ν¬ν¨)",
"tax_credit": "μΈμ‘ 곡μ ν
μ΄λΈ (μ¬μμ μΈμ‘ 곡μ μ 보 ν¬ν¨)",
"non_taxable": "λΉκ³ΌμΈ νλͺ© ν
μ΄λΈ (λΉκ³ΌμΈ μλΉ λ° κΈ°ν νλͺ© μ 보 ν¬ν¨)",
"major_insurance": "μ£Όμ 보ν ν
μ΄λΈ (4λ 보ν κ΄λ ¨ μ 보 ν¬ν¨)",
"earned_income_tax": "κ·Όλ‘ μλμΈ ν
μ΄λΈ (μ¬μμ μλμΈ κ³μ° μ 보 ν¬ν¨)",
"annual_vacation_promotion_policy": "μ°μ°¨ μ΄μ§ μ μ±
ν
μ΄λΈ (μ°μ°¨ μ¬μ© λ° μ΄μ§ μ μ±
μ 보 ν¬ν¨)",
"vacation_request_file": "ν΄κ° μμ² νμΌ ν
μ΄λΈ (ν΄κ° μμ²μ 첨λΆλ νμΌ μ 보 ν¬ν¨)",
"vacation_request": "ν΄κ° μμ² ν
μ΄λΈ (μ¬μμ ν΄κ° μ μ² κΈ°λ‘ ν¬ν¨)",
"vacation": "ν΄κ° ν
μ΄λΈ (ν΄κ° μ¬μ© κΈ°λ‘ λ° μν μ 보 ν¬ν¨)",
"vacation_policy": "ν΄κ° μ μ±
ν
μ΄λΈ (μ°μ°¨ λ° μ κΈ/λ¬΄κΈ ν΄κ° μ μ±
κ΄λ ¨ μ 보 ν¬ν¨)",
"vacation_type": "ν΄κ° μ ν ν
μ΄λΈ (μ°μ°¨, λ³κ° λ± ν΄κ° μ ν μ 보 ν¬ν¨)",
"department_member": "λΆμ ꡬμ±μ ν
μ΄λΈ (λΆμλ³ μμ μ¬μ μ 보 ν¬ν¨)",
"appointment": "μΈμ¬ λ°λ Ή ν
μ΄λΈ (μ¬μμ μΈμ¬ λ°λ Ή κΈ°λ‘ ν¬ν¨)",
"appointment_item": "μΈμ¬ λ°λ Ή νλͺ© ν
μ΄λΈ (μΈλΆ μΈμ¬ λ°λ Ή νλͺ© μ 보 ν¬ν¨)",
"discipline_reward": "μ§κ³ λ° ν¬μ ν
μ΄λΈ (μ¬μμ μ§κ³ λ° ν¬μ κΈ°λ‘ ν¬ν¨)",
"language_test": "μ΄ν μν ν
μ΄λΈ (μ¬μμ μ΄ν μν κΈ°λ‘ λ° μ μ ν¬ν¨)",
"language": "μΈμ΄μ 보 ν
μ΄λΈ (μ§μ κ°λ₯ν μΈμ΄ μ 보 ν¬ν¨)",
"qualification": "μκ²©μ¦ ν
μ΄λΈ (μ¬μμ μκ²©μ¦ μ 보 ν¬ν¨)",
"contract": "κ³μ½ ν
μ΄λΈ (μ¬μμ κ³μ½ μ 보 λ° λ΄μ© ν¬ν¨)",
"career": "κ²½λ ₯ ν
μ΄λΈ (μ¬μμ μ΄μ κ²½λ ₯ λ° κΈ°λ‘ ν¬ν¨)",
"education": "νλ ₯ ν
μ΄λΈ (μ¬μμ νλ ₯ μ 보 ν¬ν¨)",
"family_member": "κ°μ‘± ꡬμ±μ ν
μ΄λΈ (μ¬μμ λΆμ κ°μ‘± μ 보 ν¬ν¨)",
"family_relationship": "κ°μ‘± κ΄κ³ ν
μ΄λΈ (κ°μ‘± ꡬμ±μμ κ΄κ³ μ 보 ν¬ν¨)",
"employee": "μ¬μ μ 보 ν
μ΄λΈ (μ¬μμ κ°μΈ μ 보μ μ§μ±
μ 보λ₯Ό ν¬ν¨)",
"duty": "μ§λ¬΄ ν
μ΄λΈ (μ¬μμ μ§λ¬΄ λ° μν μ 보 ν¬ν¨)",
"role": "μν ν
μ΄λΈ (μ¬μμ μν λ° κΆν μ 보 ν¬ν¨)",
"position": "μ§μ ν
μ΄λΈ (μ¬μμ μ§μ μ 보 ν¬ν¨)",
"attendance_status_type": "κ·Όν μν μ ν ν
μ΄λΈ (μΆκ·Ό, μ‘°ν΄ λ± κ·Όν μν μ 보 ν¬ν¨)",
"department": "λΆμ ν
μ΄λΈ (λΆμμ μ΄λ¦ λ° μ½λ μ 보 ν¬ν¨)",
"company": "νμ¬ ν
μ΄λΈ (νμ¬ μ 보 λ° μ‘°μ§ κ΅¬μ‘° ν¬ν¨)",
}
# ν
μ΄λΈλͺ
μ νκ΅μ΄ μ€λͺ
μΌλ‘ 맀ν
def map_table_name_to_korean(table_name):
return table_name_mapping.get(table_name, f"μ μ μλ ν
μ΄λΈ: {table_name}")
# λ¬Έμμ νκ΅μ΄ ν
μ΄λΈλͺ
μ£Όμ μΆκ°
def annotate_with_table_names(documents):
for doc in documents:
table_name = doc.metadata.get("table")
if table_name:
doc.metadata["table_korean"] = map_table_name_to_korean(table_name)
return documents
# μ²΄μΈ μμ± ν¨μ
def create_chain_with_message_history():
global rag_chain # μ μ λ³μλ₯Ό μ¬μ©νλλ‘ μ μΈ
# retriever = vectorstore.as_retriever(
# search_type="cosine", search_kwargs={"fetch_k": 5, "k": 3}
# )
retriever = vectorstore.as_retriever(
search_type="mmr", search_kwargs={"lambda_mult": 0.9, "fetch_k": 10, "k": 3}
)
# μ§λ¬Έ λ¬Έλ§₯ν ν둬ννΈ
contextualize_q_system_prompt = """Given a chat history and the latest user question \
which might reference context in the chat history, formulate a standalone question \
which can be understood without the chat history. If the input is not a question, \
generate a plausible question that matches the intent. Do NOT answer the question, \
just reformulate or generate it.
μ§λ¬Έμ μμ±νμΈμ."""
contextualize_q_prompt = ChatPromptTemplate.from_messages(
[
("system", contextualize_q_system_prompt),
MessagesPlaceholder("history"),
("human", "{input}"),
]
)
# μ§λ¬Έ λ΅λ³ ν둬ννΈ
qa_system_prompt = """
You are an HR management system chatbot. Use the retrieved context, including the document metadata (table names and descriptions), to generate an accurate and helpful answer.\
For each table referenced in the retrieved context, include its Korean name and description in the response if relevant.\
If the context or history does not provide enough information, respond as follows:\
- If you can guess the intent, provide a relevant response or a suggestion.\
- If no answer can be reasonably inferred, reply politely: "μ§λ¬Έμ λν΄ μ νν λ΅λ³μ λ리기 μ΄λ €μμ. μ‘°κΈ λ ꡬ체μ μΌλ‘ μ§λ¬Έν΄ μ£Όμλ©΄ κ°μ¬νκ² μ΅λλ€."\
λλ΅μ λ°λμ νκ΅μ΄μ€λ½κ² μμ±νκ³ , λ°λμ μ‘΄λλ§μ μ¨μ£ΌμΈμ.\
{context}
"""
qa_prompt = ChatPromptTemplate.from_messages(
[
("system", qa_system_prompt),
MessagesPlaceholder("history"),
("human", "{input}"),
]
)
# LLM μ€μ
llm = ChatOpenAI(
api_key=OPENAI_API_KEY,
model="gpt-4o-mini",
temperature=0.2,
)
contextualize_chain = RunnableWithMessageHistory(
runnable=contextualize_q_prompt | llm,
get_session_history=lambda session_id: chat_history_storage.setdefault(
session_id, ChatMessageHistory()
),
input_messages_key="input",
history_messages_key="history",
)
history_aware_retriever = create_history_aware_retriever(
llm, retriever, contextualize_q_prompt
)
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
def combined_chain(input_data):
session_id = input_data.get("session_id")
user_query = input_data.get("input")
employee_id = input_data.get("employee_id") # employee_id μΆκ°
# νμ€ν 리 κ°μ Έμ€κΈ°
chat_history = chat_history_storage.get(session_id, ChatMessageHistory())
history_as_list = chat_history.messages
# 1. μ¬μ λ°μ΄ν° μ‘°ν λ° μμ½
employee_data = {}
employee_summary = ""
if employee_id:
employee_data = fetch_employee_data(employee_id)
# print(f"Employee Data for ID {employee_id}: {employee_data}")
# print()
employee_summary = summarize_employee_data(employee_data, employee_id)
print(f"Employee summary Data for ID {employee_id}: {employee_summary}")
print()
# 2. μ§λ¬Έ λ¬Έλ§₯ν μ²λ¦¬
contextualized_result = contextualize_chain.invoke(
{"input": user_query, "history": history_as_list},
{"configurable": {"session_id": session_id}},
)
print(f"Contextualized Question: {contextualized_result}")
print()
# λ¬Έλ§₯νλ μ§λ¬Έμ΄ λΉμ΄ μμ κ²½μ° μ²λ¦¬
if not contextualized_result.content.strip():
return {
"contextualized_question": None,
"retrieval_response": "ꡬ체μ μΈ HR κ΄λ ¨ μ§λ¬Έμ μ
λ ₯ν΄ μ£ΌμΈμ.",
"source_documents": [],
}
# 3. RAG μ²΄μΈ μ€ν
retrieval_result = rag_chain.invoke(
{
"input": contextualized_result.content,
"history": history_as_list,
}
)
print(f"Retrieval Result: {retrieval_result}")
print()
# 4. RAG κ²°κ³Όμ μ¬μ λ°μ΄ν° κ²°ν©
combined_context = (
annotate_with_table_names(retrieval_result.get("context", []))
+ history_as_list
)
# μ¬μ μμ½ μ 보λ₯Ό Document κ°μ²΄λ‘ μΆκ°
if employee_summary:
# ν
μ€νΈ μ²νΉμ μν TextSplitter μ΄κΈ°ν
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500, chunk_overlap=50
)
# μ¬μ μμ½ μ 보λ₯Ό Documentλ‘ μμ±
employee_summary_document = Document(
page_content=f"μ§λ¬Έν μ¬μ(μ¬μ©μ)μ μμ½ μ 보:\n{employee_summary}",
metadata={"source": "employee_summary"},
)
# μμ½ μ 보λ₯Ό λΆν νμ¬ Documentλ‘ λ³ν
split_documents = text_splitter.split_documents([employee_summary_document])
combined_context.extend(split_documents)
# 5. μ΅μ’
LLM μ
λ ₯ ꡬμ±
llm_input = [
SystemMessage(
content="You are a helpful assistant. Use the following context and history to answer the user's question."
),
HumanMessage(
content=f"Context: {combined_context}\n\nQuestion: {contextualized_result.content}"
),
]
# LLM νΈμΆ
print(f"LLM input: {llm_input}") # LLM Response μΆλ ₯
print()
llm_response = llm.invoke(llm_input)
print(f"LLM Response: {llm_response}") # LLM Response μΆλ ₯
print()
return {
"contextualized_question": contextualized_result.content,
"retrieval_response": llm_response.content, # LLM μλ΅
"source_documents": retrieval_result.get("context", []),
"employee_data": employee_data, # μλ΅μ μ¬μ λ°μ΄ν° μΆκ°
}
return combined_chain
# μ¬μ λ°μ΄ν° μ΄κΈ°ν
employee_data = {}
@app.post("/query")
async def query(request: QueryRequest):
# μ€ν μκ° μΈ‘μ
start_time = time.time()
global employee_data
try:
user_input = request.query
session_id = request.session_id
employee_id = request.employee_id # employee_id μΆκ°
# μ²΄μΈ μμ± λ° μ€ν
chain = create_chain_with_message_history()
response = chain(
{"input": user_input, "session_id": session_id, "employee_id": employee_id}
)
# μ§λ¬Έ λ° λ΅λ³ μ²λ¦¬
contextualized_question = response.get("contextualized_question", "").replace(
"\\", ""
)
answer = response.get(
"retrieval_response", "λ΅λ³μ μμ±νμ§ λͺ»νμ΅λλ€."
).replace("\\", "")
serialized_documents = serialize_documents(response.get("source_documents", []))
# νμ€ν 리 κ°μ Έμ€κΈ°
chat_history = get_or_create_history(session_id)
serialized_history = [
{
"type": message.type, # λ©μμ§ νμ
(human/system λ±)
"content": message.content.replace("\n", " ").replace("\\", ""),
}
for message in chat_history.messages
]
# μλ΅ λ°μ΄ν° ν΅ν©
response_content = {
"contextualized_question": contextualized_question,
"answer": answer,
"source_documents": serialized_documents,
"history": serialized_history,
}
# JSON μ§λ ¬ν 보μ₯
serialized_response = serialize_data(response_content)
end_time = time.time()
# μ€ν μκ° λ‘κ·Έ μΆλ ₯
execution_time = end_time - start_time
logging.info(f"μ€ν μκ°: {execution_time:.2f} seconds.")
return JSONResponse(content=serialized_response)
except Exception as e:
error_trace = traceback.format_exc()
print(f"Error in query: {error_trace}")
raise HTTPException(status_code=500, detail=str(e))
# νΉμ μ¬μμ λ°μ΄ν°λ₯Ό μμ½νμ¬ LLMμμ νμ©ν μ μλ κ°λ¨ν ννλ‘ λ³ν.
def summarize_employee_data(employee_data, employee_id):
"""
νΉμ μ¬μμ λ°μ΄ν°λ₯Ό μμ½νμ¬ LLMμμ νμ©ν μ μλ κ°λ¨ν ννλ‘ λ³ν.
Args:
employee_data (dict): μ 체 μ¬μ λ°μ΄ν°.
employee_id (int): μμ½ν μ¬μμ ID.
Returns:
str: μμ½λ λ°μ΄ν° λ¬Έμμ΄.
"""
employee_name = employee_data.get("employee_name", "μ μ μμ")
# print(
# f"μ λ¬ λ°μ μ¬μμ λ°μ΄ν° {employee_id} (μ΄λ¦: {employee_name}): {employee_data}"
# )
# print()
summaries = [f"μ¬μ μ΄λ¦: {employee_name[0]["name"]}"] # μ¬μ μ΄λ¦ μΆκ°
# μ°μ°¨ λ°μ΄ν° μμ½
vacations = employee_data.get("vacation", [])
# print(f"ν΄κ° λ°μ΄ν° (μ 체): {vacations}")
# print()
if vacations: # vacation λ°μ΄ν°κ° λΉμ΄ μμ§ μμ κ²½μ°
vacation_summary = "\n".join(
f"- {vacation.get('vacation_name', 'μ΄λ¦ μμ')}: λ¨μ {vacation.get('vacation_left', 0)}μΌ, μ¬μ© {vacation.get('vacation_used', 0)}μΌ"
for vacation in vacations
)
summaries.append(f"ν΄κ° μ 보:\n{vacation_summary}")
else:
print("ν΄κ° λ°μ΄ν° μν: λ°μ΄ν°κ° λΉμ΄ μμ΅λλ€.")
summaries.append("ν΄κ° μ 보: λ°μ΄ν°κ° λΉμ΄ μμ΅λλ€.")
# κ·Όν λ°μ΄ν° μμ½
commutes = employee_data.get("commute", [])
if commutes: # commute λ°μ΄ν°κ° λΉμ΄ μμ§ μμ κ²½μ°
commute_summary = f"- μ΅κ·Ό κ·Όν κΈ°λ‘ μ: {len(commutes)}κ°"
summaries.append(f"κ·Όν μ 보:\n{commute_summary}")
else:
summaries.append("κ·Όν μ 보: λ°μ΄ν°κ° λΉμ΄ μμ΅λλ€.")
# νκ° λ°μ΄ν° μμ½
evaluations = employee_data.get("evaluation", [])
if evaluations: # evaluation λ°μ΄ν°κ° λΉμ΄ μμ§ μμ κ²½μ°
evaluation_summary = "\n".join(
f"- λ±κΈ: {evaluation.get('grade', 'N/A')}, μ μ: {evaluation.get('score', 'N/A')}"
for evaluation in evaluations
)
summaries.append(f"νκ° μ 보:\n{evaluation_summary}")
else:
summaries.append("νκ° μ 보: λ°μ΄ν°κ° λΉμ΄ μμ΅λλ€.")
# μμ½μ΄ λΉμ΄μλ κ²½μ° μ²λ¦¬
if not summaries:
return f"μ¬μ ID {employee_id}μ λ°μ΄ν°κ° μ‘΄μ¬νμ§ μμ΅λλ€."
return "\n".join(summaries)
def fetch_employee_data(employee_id):
"""
μ£Όμ΄μ§ employee_idλ‘ μ¬μ κ΄λ ¨ λ°μ΄ν°λ₯Ό μ‘°νν©λλ€.
- NaN λ° Infinity κ°μ μ²λ¦¬νμ¬ μμ νκ² λ°ν
"""
try:
engine = connect_sqlalchemy() # λ°μ΄ν°λ² μ΄μ€ μ°κ²° μμ§
with engine.connect() as connection:
# κ° ν
μ΄λΈμμ λ°μ΄ν°λ₯Ό μ‘°ν
employee_query = text(
"SELECT name FROM employee WHERE employee_id = :employee_id"
)
vacation_query = text(
"SELECT * FROM vacation WHERE employee_id = :employee_id"
)
evaluation_query = text(
"SELECT * FROM evaluation WHERE employee_id = :employee_id"
)
commute_query = text(
"SELECT * FROM commute WHERE employee_id = :employee_id"
)
employee_data = (
pd.read_sql(
employee_query, connection, params={"employee_id": employee_id}
)
.where(
pd.notnull(
pd.read_sql(
employee_query,
connection,
params={"employee_id": employee_id},
)
),
None,
) # NaNμ NoneμΌλ‘ λ³ν
.replace([float("inf"), float("-inf")], None)
.to_dict(orient="records")
)
vacation_data = (
pd.read_sql(
vacation_query, connection, params={"employee_id": employee_id}
)
.where(
pd.notnull(
pd.read_sql(
vacation_query,
connection,
params={"employee_id": employee_id},
)
),
None,
) # NaNμ NoneμΌλ‘ λ³ν
.replace([float("inf"), float("-inf")], None)
.to_dict(orient="records")
)
evaluation_data = (
pd.read_sql(
evaluation_query, connection, params={"employee_id": employee_id}
)
.where(
pd.notnull(
pd.read_sql(
evaluation_query,
connection,
params={"employee_id": employee_id},
)
),
None,
) # NaNμ NoneμΌλ‘ λ³ν
.replace([float("inf"), float("-inf")], None)
.to_dict(orient="records")
)
commute_data = (
pd.read_sql(
commute_query, connection, params={"employee_id": employee_id}
)
.where(
pd.notnull(
pd.read_sql(
commute_query,
connection,
params={"employee_id": employee_id},
)
),
None,
) # NaNμ NoneμΌλ‘ λ³ν
.replace([float("inf"), float("-inf")], None)
.to_dict(orient="records")
)
# λͺ¨λ λ°μ΄ν° μ§λ ¬ν
return {
"employee_name": serialize_data(employee_data), # μ¬μ μ΄λ¦ μΆκ°
"vacation": serialize_data(vacation_data),
"evaluation": serialize_data(evaluation_data),
"commute": serialize_data(commute_data),
}
except Exception as e:
print(f"Error fetching employee data: {e}")
return {}
# if __name__ == "__old__":
# uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
if os.environ.get("IS_MAIN_PROCESS", "1") == "1": # λ©μΈ νλ‘μΈμ€λ§ μ€ν
initialize_directories()
uvicorn.run(app, host="0.0.0.0", port=8000, workers=10)