@@ -66,27 +66,33 @@ def __init__(self) -> None:
6666 "&socketTimeoutMS=6000" # 네 번째 옵션
6767 )
6868
69- # 이벤트 루프 가져오기
70- self .loop = asyncio .get_event_loop ()
69+ # 클라이언트와 데이터베이스 초기화
70+ self .client = None
71+ self .db = None
7172
72- # MongoDB 클라이언트 초기화 (이벤트 루프 지정)
73- self .client = AsyncIOMotorClient (
74- self .mongo_uri ,
75- io_loop = self .loop ,
76- serverSelectionTimeoutMS = 500 ,
77- connectTimeoutMS = 1000 ,
78- socketTimeoutMS = 6000
79- )
80-
81- # 연결 테스트는 비동기로 수행
82- async def test_connection ():
83- await self .client .admin .command ('ping' )
84-
85- # 연결 테스트 실행
86- self .loop .run_until_complete (test_connection ())
87- self .db = self .client [mongo_db ]
88- print (f"{ GREEN } INFO{ RESET } : MongoDB 연결 성공: { mongo_host } :{ mongo_port } " )\
73+ print (f"{ GREEN } INFO{ RESET } : MongoDBHandler 초기화 완료" )
8974
75+ except Exception as e :
76+ raise InternalServerErrorException (detail = f"MongoDBHandler 초기화 오류: { str (e )} " )
77+
78+ async def init (self ):
79+ """
80+ MongoDB 클라이언트를 초기화하고 데이터베이스에 연결합니다.
81+
82+ Raises:
83+ InternalServerErrorException: MongoDB 연결 중 오류 발생 시
84+ """
85+ try :
86+ # MongoDB 클라이언트 초기화
87+ self .client = AsyncIOMotorClient (self .mongo_uri )
88+
89+ # 연결 테스트
90+ await self .client .admin .command ('ping' )
91+
92+ # 데이터베이스 선택
93+ self .db = self .client [os .getenv ("MONGO_DATABASE" )]
94+ print (f"{ GREEN } INFO{ RESET } : MongoDB 연결 성공" )
95+
9096 except PyMongoError as e :
9197 print (f"{ RED } ERROR{ RESET } : MongoDB 연결 실패" )
9298 raise InternalServerErrorException (detail = f"MongoDB 연결 오류 - 호스트: { mongo_host } , 포트: { mongo_port } " )
@@ -96,16 +102,6 @@ async def test_connection():
96102 async def get_office_log (self , user_id : str , document_id : str , router : str ) -> List [Dict ]:
97103 try :
98104 collection = self .db [f'{ router } _log_{ user_id } ' ]
99-
100- # 이벤트 루프 확인 및 설정
101- if self .loop != asyncio .get_event_loop ():
102- self .loop = asyncio .get_event_loop ()
103- self .client = AsyncIOMotorClient (
104- self .mongo_uri ,
105- io_loop = self .loop
106- )
107- self .db = self .client [os .getenv ("MONGO_DATABASE" )]
108- collection = self .db [f'{ router } _log_{ user_id } ' ]
109105
110106 document = await collection .find_one ({"id" : document_id })
111107
@@ -114,7 +110,7 @@ async def get_office_log(self, user_id: str, document_id: str, router: str) -> L
114110
115111 value_list = document .get ("value" , [])
116112 sorted_value_list = sorted (value_list , key = lambda x : x .get ("index" , 0 ))
117-
113+
118114 # 최신 8개만 선택
119115 latest_messages = sorted_value_list [- 8 :] if len (sorted_value_list ) > 8 else sorted_value_list
120116
@@ -123,69 +119,8 @@ async def get_office_log(self, user_id: str, document_id: str, router: str) -> L
123119 for chat in latest_messages :
124120 formatted_chat = {
125121 "index" : chat .get ("index" ),
126- "input_data" : chat .get ("input_data" ), # input_data 직접 사용
127- "output_data" : chat .get ("output_data" ) # output_data 직접 사용
128- }
129- formatted_chat_list .append (formatted_chat )
130-
131- return formatted_chat_list
132-
133- except PyMongoError as e :
134- raise InternalServerErrorException (detail = f"Error retrieving chatlog value: { str (e )} " )
135- except Exception as e :
136- raise InternalServerErrorException (detail = f"Unexpected error: { str (e )} " )
137-
138- async def get_character_log (self , user_id : str , document_id : str , router : str ) -> List [Dict ]:
139- """
140- 최신 10개의 대화 기록을 가져와서 Llama 프롬프트 형식으로 변환합니다.
141-
142- Args:
143- user_id (str): 사용자 ID
144- document_id (str): 문서 ID
145- router (str): 라우터 이름
146-
147- Returns:
148- List[Dict]: Llama 프롬프트 형식의 대화 기록 리스트. 대화 기록이 없으면 빈 리스트 반환.
149- """
150- try :
151- collection = self .db [f'{ router } _log_{ user_id } ' ]
152-
153- # 이벤트 루프 확인 및 설정
154- if self .loop != asyncio .get_event_loop ():
155- self .loop = asyncio .get_event_loop ()
156- self .client = AsyncIOMotorClient (
157- self .mongo_uri ,
158- io_loop = self .loop
159- )
160- self .db = self .client [os .getenv ("MONGO_DATABASE" )]
161- collection = self .db [f'{ router } _log_{ user_id } ' ]
162-
163- document = await collection .find_one ({"id" : document_id })
164-
165- # 문서가 없거나 value 리스트가 비어있는 경우 빈 리스트 반환
166- if document is None or not document .get ("value" , []):
167- return []
168-
169- value_list = document .get ("value" , [])
170-
171- # index 기준으로 정렬
172- sorted_value_list = sorted (value_list , key = lambda x : x .get ("index" , 0 ))
173-
174- # 최신 10개만 선택 (마지막 10개)
175- latest_messages = sorted_value_list [- 10 :] if len (sorted_value_list ) > 10 else sorted_value_list
176-
177- # 대화 기록 변환 수행
178- formatted_chat_list = []
179- for chat in latest_messages :
180- formatted_chat = {
181- "index" : chat .get ("index" ),
182- "img_url" : chat .get ("img_url" ),
183- "dialogue" : (
184- f"<|start_header_id|>user<|end_header_id|>\n "
185- f"{ chat .get ('input_data' )} <|eot_id|>"
186- f"<|start_header_id|>assistant<|end_header_id|>\n "
187- f"{ chat .get ('output_data' )} <|eot_id|>"
188- )
122+ "input_data" : chat .get ("input_data" ),
123+ "output_data" : chat .get ("output_data" )
189124 }
190125 formatted_chat_list .append (formatted_chat )
191126
0 commit comments