55
66import asyncio
77import hashlib
8+ import logging
89import os
910import traceback
1011from concurrent .futures .thread import ThreadPoolExecutor
2829
2930from database import Document as DBDocument
3031
32+ logger = logging .getLogger (__name__ )
33+
3134# DEBUG日志
3235
3336# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
@@ -133,7 +136,7 @@ def __init__(
133136 # 用于存储用户的查询和模型的回答,以支持上下文增强生成(RAG)。
134137 # 格式通常为[(用户查询, 模型回答), ...],在后续查询中,历史上下文将拼接到用户的新查询中。
135138 self .history = []
136- print ("RAG 初始化完成" )
139+ logger . info ("RAG 初始化完成" )
137140
138141 # async:这是一个异步函数,允许通过await 调用异步操作,提高性能(特别是涉及I/O操作时,如数据库或网络访问)
139142 # text: str:用户提供的文本内容,通常为需要存储和处理的文档。
@@ -190,10 +193,10 @@ async def upload_files(self, file_paths: list[str]):
190193 """
191194 docs = []
192195 for file_path in file_paths [:50 ]:
193- print (f"Ingesting file: { file_path } " )
196+ logger . info (f"Ingesting file: { file_path } " )
194197 with open (file_path , "r" , encoding = "utf-8" ) as f :
195198 text = f .read ()
196- print (f"Text length: { len (text )} " )
199+ logger . info (f"Text length: { len (text )} " )
197200 doc_id = f"web_{ os .path .basename (file_path )} _{ hashlib .md5 (text .encode ()).hexdigest ()} "
198201 docs .append (
199202 Document (
@@ -255,7 +258,7 @@ async def remove_all_documents(self, num_workers: int = 5):
255258 else :
256259 tasks = [self .remove_document_by_id (doc_id ) for doc_id in all_docs .keys ()]
257260 await asyncio .gather (* tasks )
258- print ("All documents removed" )
261+ logger . info ("All documents removed" )
259262
260263 async def retrieve (
261264 self ,
@@ -418,6 +421,7 @@ async def query_documents(rag, request: QueryRequest):
418421 return QueryResponse (response = result ["response" ], sources = result ["sources" ])
419422 except Exception as e :
420423 traceback .print_exc ()
424+ logger .error (f"查询文档时发生错误: { str (e )} { traceback .format_exc ()} " )
421425 raise e
422426
423427
@@ -429,6 +433,7 @@ async def upload_text_to_rag(rag, text: str):
429433 return {"message" : "文本上传成功" , "doc_id" : doc_id }
430434 except Exception as e :
431435 traceback .print_exc ()
436+ logger .error (f"上传纯文本时发生错误: { str (e )} { traceback .format_exc ()} " )
432437 raise e
433438
434439
0 commit comments