RAG问答系统查询与溯源
这个版本更健壮、更易维护,并且提供了更好的可观察性,适合生产环境使用。• 默认doc_id改为"unknown"比0更合理。• 使用列表推导式简化sources构建。• 添加了详细的docstring文档。• 日志记录处理过程的关键步骤。• 添加了不同级别的日志记录。(更符合RAG术语)• 添加了默认错误响应。• 包含错误处理日志。
·
以下是优化后的代码,包括函数名、变量名、日志描述的改进,以及代码结构的优化:
def query_rag_pipeline(qa_pipeline: object, question: str) -> dict:
"""
Query the RAG (Retrieval-Augmented Generation) pipeline with a question and return the answer with sources.
Args:
qa_pipeline: The initialized RAG pipeline object
question: The input question to query
Returns:
dict: A dictionary containing:
- answer: The generated answer
- sources: List of relevant documents with metadata and content
"""
import logging
# Initialize logger
logger = logging.getLogger(__name__)
try:
logger.info(f"Processing question: {question}")
# Get the generated answer
query_result = qa_pipeline.invoke({"query": question})
# Retrieve relevant documents
relevant_docs = qa_pipeline.retriever.get_relevant_documents(question)
logger.info(f"Retrieved {len(relevant_docs)} relevant documents")
# Prepare response
response = {
"answer": query_result["result"],
"sources": [
{
"doc_id": doc.metadata.get("doc_id", "unknown"),
"metadata": doc.metadata, # Renamed from doc_metadata for brevity
"content": doc.page_content
}
for doc in relevant_docs
]
}
logger.debug(f"Response prepared: {response}")
return response
except Exception as e:
logger.error(f"Error processing question '{question}': {str(e)}")
return {
"answer": "Sorry, an error occurred while processing your question.",
"sources": []
}
优化点说明:
-
函数签名改进:
• 添加了类型提示• 添加了详细的docstring文档
-
变量名优化:
•result→query_result(更明确)•
retrieved_docs→relevant_docs(更符合RAG术语)•
doc_metadata→metadata(保持简洁) -
日志系统:
• 添加了不同级别的日志记录• 包含错误处理日志
-
代码结构优化:
• 使用列表推导式简化sources构建• 添加了异常处理
• 默认doc_id改为"unknown"比0更合理
-
其他改进:
• 添加了默认错误响应• 日志记录处理过程的关键步骤
这个版本更健壮、更易维护,并且提供了更好的可观察性,适合生产环境使用。
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)