diff --git a/rag-python/app.py b/rag-python/app.py
index e53154b9..2e952195 100644
--- a/rag-python/app.py
+++ b/rag-python/app.py
@@ -88,6 +88,11 @@ def search():
results = knowledge_service.search(query, top_k)
+ # 打印调试信息
+ print(f"[Search] Query: {query[:50]}..., Results: {len(results)}")
+ for i, r in enumerate(results):
+ print(f" [{i+1}] filename: {r.get('filename')}, content_len: {len(r.get('content', ''))}")
+
return jsonify({
'success': True,
'data': results
@@ -131,6 +136,78 @@ def scan_folder():
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
+@app.route('/api/rag-analyze', methods=['POST'])
+def rag_analyze():
+ """RAG增强的AI分析 - 结合知识库生成分析报告"""
+ try:
+ data = request.get_json()
+ report_content = data.get('reportContent', '')
+ report_title = data.get('reportTitle', '心理测评报告')
+
+ if not report_content:
+ return jsonify({'success': False, 'error': '报告内容不能为空'}), 400
+
+ # 1. 从报告中提取关键词进行知识库检索
+ # 提取纯文本(去除HTML标签)
+ import re
+ text_content = re.sub(r'<[^>]*>', '', report_content)
+
+ # 提取关键信息用于检索
+ query_keywords = []
+ # 提取因子名称
+ factor_matches = re.findall(r'([\u4e00-\u9fa5]+(?:焦虑|抑郁|压力|情绪|睡眠|躯体|认知|人格|心理)[\u4e00-\u9fa5]*)', text_content)
+ query_keywords.extend(factor_matches[:5])
+ # 提取等级
+ level_matches = re.findall(r'(正常|轻度|中度|重度|严重)', text_content)
+ query_keywords.extend(level_matches[:3])
+
+ query = ' '.join(set(query_keywords)) if query_keywords else '心理测评 分析 建议'
+
+ # 2. 检索相关知识
+ search_results = knowledge_service.search(query, top_k=5)
+
+ # 3. 构建知识库上下文
+ knowledge_context = ""
+ sources = []
+ if search_results and len(search_results) > 0:
+ knowledge_parts = []
+ for i, result in enumerate(search_results[:5]):
+ content = result.get('content', '')
+ filename = result.get('filename', '未知来源')
+ similarity = result.get('similarity', 0)
+ if content:
+ knowledge_parts.append(f"【参考资料{i+1}】({filename})\n{content[:500]}")
+ sources.append({
+ 'filename': filename,
+ 'content': content[:200] + '...' if len(content) > 200 else content,
+ 'similarity': similarity
+ })
+ knowledge_context = '\n\n'.join(knowledge_parts)
+
+ # 打印调试信息到控制台
+ print("=" * 50)
+ print("📚 RAG-Analyze 检索结果")
+ print("=" * 50)
+ print(f"查询关键词: {query}")
+ print(f"检索到文档数: {len(sources)}")
+ for i, s in enumerate(sources):
+ print(f" [{i+1}] {s['filename']} (相似度: {s.get('similarity', 0):.4f})")
+ print("=" * 50)
+
+ # 4. 返回检索结果,让前端调用AI
+ return jsonify({
+ 'success': True,
+ 'data': {
+ 'knowledgeContext': knowledge_context,
+ 'sources': sources,
+ 'query': query
+ }
+ })
+ except Exception as e:
+ import traceback
+ traceback.print_exc()
+ return jsonify({'success': False, 'error': str(e)}), 500
+
def init_service():
"""初始化服务"""
print("=" * 50)
diff --git a/ry-xinli-system/src/main/java/com/ddnai/system/rag/util/PromptBuilder.java b/ry-xinli-system/src/main/java/com/ddnai/system/rag/util/PromptBuilder.java
index 3892699b..1276a728 100644
--- a/ry-xinli-system/src/main/java/com/ddnai/system/rag/util/PromptBuilder.java
+++ b/ry-xinli-system/src/main/java/com/ddnai/system/rag/util/PromptBuilder.java
@@ -1,14 +1,15 @@
package com.ddnai.system.rag.util;
import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONWriter;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
- * 提示词构建工?
- * 构建发送给大模型的提示词,确保包含所有必要信?
+ * 提示词构建工具
+ * 构建发送给大模型的提示词,确保包含所有必要信息
*
* @author ddnai
*/
@@ -16,156 +17,282 @@ import java.util.Map;
public class PromptBuilder {
/**
- * 构建报告生成提示?
+ * 构建报告生成提示词
*
- * @param retrievedDocs 检索到的文?
+ * @param retrievedDocs 检索到的文档
* @param assessmentData 测评数据
* @param userProfile 用户档案
- * @return 提示?
+ * @return 提示词
*/
public String buildReportPrompt(List
+
+ ${this.ragSourcesForReport && this.ragSourcesForReport.length > 0 ? `
+
+
参考知识库资料
+
+ ${this.ragSourcesForReport.map(source => `- ${source.filename}
`).join('')}
+
+
+ ` : ''}
`
return reportHtml