fix(training-pdf-import): 修复培训试题PDF导入判断题解析
This commit is contained in:
1 parent
3a22df736e
commit
91758ef2b4
19 files changed
+1767
-12
No files matched your search
@@ -61,3 +61,19 @@ def update_agent_permissions(id: int):
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@require_admin
|
||||
def import_training_question_bank_from_pdf(id: int):
|
||||
"""
|
||||
从已上传的培训试题 PDF 解析题库。
|
||||
|
||||
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = agent_service.import_training_question_bank_from_pdf(
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return jsonify(payload), 200
|
||||
@@ -57,6 +57,7 @@ class AgentGuide(Base):
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
guide_usage: Mapped[str] = mapped_column(String(50), nullable=False, default='general')
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1)
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
|
||||
|
||||
def serialize_agent(agent: Agent) -> dict:
|
||||
@@ -288,3 +289,15 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
for user in users_to_remove:
|
||||
user.agents.remove(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
解析指定 Agent 的培训试题 PDF,并返回结构化题库。
|
||||
|
||||
用途:当前端点击“从试题 PDF 导入”时使用;这里只做解析,不直接覆盖 Agent 配置,避免误导入后无法人工复核。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
return parse_training_question_bank_from_guide(agent_id=agent_id, guide_id=guide_id)
|
||||
@@ -17,6 +17,16 @@ from app.models import AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
|
||||
GUIDE_USAGE_GENERAL = 'general'
|
||||
GUIDE_USAGE_TRAINING_VIDEO = 'training_video'
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf'
|
||||
ALLOWED_GUIDE_USAGES = {
|
||||
GUIDE_USAGE_GENERAL,
|
||||
GUIDE_USAGE_TRAINING_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
}
|
||||
|
||||
|
||||
def _infer_file_type(content_type: str | None) -> str:
|
||||
ct = str(content_type or '')
|
||||
if ct.startswith('video'):
|
||||
@@ -36,6 +46,7 @@ def serialize_guide(guide: AgentGuide) -> dict:
|
||||
'file_path': guide.file_path,
|
||||
'file_url': minio_service.get_public_url(guide.file_path),
|
||||
'file_size': guide.file_size,
|
||||
'guide_usage': guide.guide_usage,
|
||||
'remark': guide.remark,
|
||||
'sort_order': guide.sort_order,
|
||||
'status': guide.status,
|
||||
@@ -43,6 +54,23 @@ def serialize_guide(guide: AgentGuide) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str:
|
||||
"""
|
||||
归一化指南用途并校验与文件类型是否匹配。
|
||||
|
||||
用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。
|
||||
参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。
|
||||
"""
|
||||
usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL
|
||||
if usage not in ALLOWED_GUIDE_USAGES:
|
||||
raise ValidationError('Invalid guide usage')
|
||||
if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video':
|
||||
raise ValidationError('Training video usage requires a video file')
|
||||
if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf':
|
||||
raise ValidationError('Training exam PDF usage requires a PDF file')
|
||||
return usage
|
||||
|
||||
|
||||
def upload_guide_file(file_storage: FileStorage | None) -> dict:
|
||||
"""
|
||||
上传引导文件至 MinIO。
|
||||
@@ -80,12 +108,14 @@ def list_guides(*, agent_id: int | None = None) -> list[dict]:
|
||||
|
||||
def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict:
|
||||
"""创建 AgentGuide 记录。"""
|
||||
file_type = str(data['file_type'])
|
||||
guide = AgentGuide(
|
||||
agent_id=data['agent_id'],
|
||||
file_name=data['file_name'],
|
||||
file_type=data['file_type'],
|
||||
file_type=file_type,
|
||||
file_path=data['file_path'],
|
||||
file_size=data.get('file_size'),
|
||||
guide_usage=_normalize_guide_usage(data.get('guide_usage'), file_type=file_type),
|
||||
remark=data.get('remark'),
|
||||
sort_order=data.get('sort_order', 0),
|
||||
status=data.get('status', 1),
|
||||
@@ -109,6 +139,8 @@ def update_guide(guide_id: int, data: dict[str, Any]) -> None:
|
||||
guide.sort_order = data['sort_order']
|
||||
if 'status' in data:
|
||||
guide.status = data['status']
|
||||
if 'guide_usage' in data:
|
||||
guide.guide_usage = _normalize_guide_usage(data.get('guide_usage'), file_type=guide.file_type)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"""
|
||||
backend/app/services/admin/training_exam_pdf_service.py
|
||||
|
||||
用途:把员工培训试题 PDF 解析成结构化题库,供 Agent extra_config.training_config 回填。
|
||||
依赖:models.AgentGuide、minio_service、pypdf、edkb_system PDF/OCR 技能。
|
||||
逻辑:优先读取已标记为 training_exam_pdf 的指南文件,先抽取 PDF 原生文本;若文本缺失或解析失败,再回退到 OCR 识别,最终把题目、选项、答案与解析返回给管理端表单继续人工校验。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.minio_service import minio_service
|
||||
from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills import loader_pdf, ocr
|
||||
|
||||
_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$')
|
||||
_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*')
|
||||
_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE)
|
||||
_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题')
|
||||
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
|
||||
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
|
||||
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
|
||||
|
||||
|
||||
def _normalize_line_breaks(text: str) -> str:
|
||||
return str(text or '').replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
|
||||
def _normalize_spaces(text: str) -> str:
|
||||
return re.sub(r'[ \t\u3000]+', ' ', str(text or '')).strip()
|
||||
|
||||
|
||||
def _normalize_answer_token(raw_answer: str) -> str:
|
||||
answer = str(raw_answer or '').strip().upper()
|
||||
if answer in {'A', 'B', 'C', 'D'}:
|
||||
return answer.lower()
|
||||
if answer in {'正确', '对', 'T', 'V', '√', 'TRUE'}:
|
||||
return 'true'
|
||||
if answer in {'错误', '错', 'F', 'X', '×', 'FALSE'}:
|
||||
return 'false'
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_pdf_text(raw_bytes: bytes) -> str:
|
||||
"""
|
||||
从 PDF 原始字节中抽取纯文本。
|
||||
|
||||
用途:为培训试题导入提供统一文本输入,避免每个管理接口重复组装 PdfReader。
|
||||
参数约束:raw_bytes 必须是 PDF 文件内容;若整份文件无可读文本,将由上层决定是否报错。
|
||||
"""
|
||||
reader = PdfReader(io.BytesIO(raw_bytes))
|
||||
page_texts: list[str] = []
|
||||
for page in reader.pages:
|
||||
text = _normalize_spaces(_normalize_line_breaks(page.extract_text() or ''))
|
||||
if text:
|
||||
page_texts.append(text)
|
||||
return '\n'.join(page_texts).strip()
|
||||
|
||||
|
||||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||||
"""
|
||||
把 edkb_system 的段落/OCR 结果统一折叠成纯文本。
|
||||
|
||||
用途:扫描件 PDF 会先被 loader_pdf 切成 paragraph/image/ocr_text block,这里负责收敛成后续题库解析可消费的文本。
|
||||
参数约束:只拼接 paragraph 与 ocr_text,避免把图片元数据等噪音混入题干。
|
||||
"""
|
||||
lines: list[str] = []
|
||||
for block in blocks:
|
||||
if block.type not in {'paragraph', 'ocr_text'}:
|
||||
continue
|
||||
text = _normalize_line_breaks(block.text or '').strip()
|
||||
if not text:
|
||||
continue
|
||||
if block.type == 'ocr_text':
|
||||
if text.startswith('OCR_TEXT:'):
|
||||
text = text[len('OCR_TEXT:') :].strip()
|
||||
text = re.sub(r'(?m)^\s*-\s*', '', text).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return '\n'.join(lines).strip()
|
||||
|
||||
|
||||
def _extract_pdf_text_via_ocr(raw_bytes: bytes) -> tuple[str, list[str]]:
|
||||
"""
|
||||
使用仓库内置 PDF loader + OCR 管线提取扫描件文本。
|
||||
|
||||
用途:当 pypdf 拿不到可读文本,或题目结构解析失败时,回退到这条路径兼容图片型 PDF。
|
||||
参数约束:raw_bytes 必须是完整 PDF 字节;若当前环境未安装 rapidocr 相关依赖,会在 warnings 中返回原因而不是直接抛异常。
|
||||
"""
|
||||
temp_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
|
||||
temp_file.write(raw_bytes)
|
||||
temp_path = Path(temp_file.name)
|
||||
|
||||
context = Context(file_type='pdf')
|
||||
blocks = loader_pdf.run({'file_path': str(temp_path)}, context)
|
||||
if any(block.type == 'image' for block in blocks):
|
||||
blocks = ocr.run(blocks, context)
|
||||
return _blocks_to_text(blocks), list(context.warnings)
|
||||
finally:
|
||||
if temp_path is not None:
|
||||
try:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _collect_candidate_lines(text: str) -> list[str]:
|
||||
normalized_text = _normalize_line_breaks(text)
|
||||
lines: list[str] = []
|
||||
for raw_line in normalized_text.split('\n'):
|
||||
line = _normalize_spaces(raw_line)
|
||||
if line:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _is_answer_sheet_line(line: str) -> bool:
|
||||
"""
|
||||
判断当前行是否更像“答案表”而不是题干。
|
||||
|
||||
用途:很多培训试卷会在末尾给出“1.B 2.A 3.正确”这类答案表;这些行不能再被当成题目块切进去,否则会污染上一题或额外生成伪题目。
|
||||
参数约束:仅识别高置信度答案行,避免误伤正常题干。
|
||||
"""
|
||||
normalized_line = _normalize_spaces(line)
|
||||
if not normalized_line:
|
||||
return False
|
||||
if '答案' in normalized_line:
|
||||
return True
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(normalized_line)
|
||||
if range_match:
|
||||
token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3))
|
||||
expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1
|
||||
if len(token_matches) >= max(expected_count - 1, 2):
|
||||
return True
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
|
||||
return len(matches) >= 2
|
||||
|
||||
|
||||
def _extract_answer_sequence(lines: list[str]) -> list[str]:
|
||||
"""
|
||||
按文本顺序提取整卷答案序列。
|
||||
|
||||
用途:当 PDF 内部“单选题/判断题”分别从 1 重新编号,或答案表使用整卷顺序编号时,单靠题号已无法稳定对齐,这里保留顺序型答案用于按题目出现顺序兜底匹配。
|
||||
参数约束:只从明确的答案行提取,避免把题干中的 A/B/C/D 选项误收进答案序列。
|
||||
"""
|
||||
answers: list[str] = []
|
||||
for line in lines:
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(_normalize_spaces(line))
|
||||
if range_match:
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3)):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
continue
|
||||
for match in _ANSWER_PAIR_PATTERN.finditer(line):
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
return answers
|
||||
|
||||
|
||||
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
|
||||
"""
|
||||
从“参考答案”区域提取题号与答案映射。
|
||||
|
||||
用途:很多试卷会把题目和答案分成两段展示,这里先把独立答案表收集出来,供后续题目块回填正确答案。
|
||||
参数约束:只解析明显的答案行,避免把题干里的选项误判成答案。
|
||||
"""
|
||||
answer_map: dict[int, str] = {}
|
||||
for line in lines:
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(line))
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
for match in matches:
|
||||
question_no = int(match.group(1))
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer and question_no not in answer_map:
|
||||
answer_map[question_no] = answer
|
||||
return answer_map
|
||||
|
||||
|
||||
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
|
||||
blocks: list[tuple[int, str]] = []
|
||||
current_no: int | None = None
|
||||
current_lines: list[str] = []
|
||||
|
||||
for line in lines:
|
||||
if _SECTION_HEADING_PATTERN.match(line):
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
continue
|
||||
question_match = _QUESTION_START_PATTERN.match(line)
|
||||
if question_match:
|
||||
if _is_answer_sheet_line(line) and '答案' not in line:
|
||||
continue
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
current_no = int(question_match.group(1))
|
||||
current_lines = [question_match.group(2)]
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
if current_no is not None:
|
||||
current_lines.append(line)
|
||||
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
return blocks
|
||||
|
||||
|
||||
def _extract_inline_answer(block_text: str) -> str:
|
||||
match = _INLINE_ANSWER_PATTERN.search(block_text)
|
||||
if not match:
|
||||
return ''
|
||||
return _normalize_answer_token(match.group(1))
|
||||
|
||||
|
||||
def _extract_inline_explanation(block_text: str) -> str:
|
||||
match = _INLINE_EXPLANATION_PATTERN.search(block_text)
|
||||
return _normalize_spaces(match.group(1)) if match else ''
|
||||
|
||||
|
||||
def _strip_inline_meta(block_text: str) -> str:
|
||||
cleaned = _INLINE_EXPLANATION_PATTERN.sub('', block_text)
|
||||
cleaned = _INLINE_ANSWER_PATTERN.sub('', cleaned)
|
||||
return _normalize_spaces(cleaned)
|
||||
|
||||
|
||||
def _build_boolean_question(question_no: int, prompt: str, answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if answer not in {'true', 'false'}:
|
||||
return None
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'boolean',
|
||||
'prompt': prompt,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
}
|
||||
|
||||
|
||||
def _build_answer_candidates(
|
||||
*,
|
||||
inline_answer: str,
|
||||
mapped_answer: str,
|
||||
ordered_answer: str,
|
||||
) -> list[str]:
|
||||
"""
|
||||
组合单题可用的答案候选,并按可信度排序。
|
||||
|
||||
用途:优先使用题干内联答案,其次使用题号映射;若 PDF 存在分节重编号,再退回整卷顺序答案,尽量把判断题补齐。
|
||||
参数约束:返回结果会去重,避免同一答案在多种来源下重复尝试。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
for raw in (inline_answer, mapped_answer, ordered_answer):
|
||||
value = _normalize_answer_token(raw)
|
||||
if value and value not in candidates:
|
||||
candidates.append(value)
|
||||
return candidates
|
||||
|
||||
|
||||
def _looks_like_boolean_question(prompt: str, option_matches: list[re.Match[str]], answer_candidates: list[str]) -> bool:
|
||||
"""
|
||||
判断题型是否更接近判断题。
|
||||
|
||||
用途:避免答案表错位时把带 A/B/C/D 选项的单选题误判成判断题,同时允许“句子 + ( )”这类常见判断题格式被识别。
|
||||
参数约束:只在没有完整选项结构时才考虑判断题,单选题仍以选项结构为主。
|
||||
"""
|
||||
if len(option_matches) >= 2:
|
||||
return False
|
||||
if any(answer in {'true', 'false'} for answer in answer_candidates):
|
||||
return True
|
||||
return bool(_BOOLEAN_PROMPT_HINT_PATTERN.search(prompt))
|
||||
|
||||
|
||||
def _build_single_choice_question(question_no: int, prompt: str, option_matches: list[re.Match[str]], answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if len(option_matches) < 2:
|
||||
return None
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
for index, match in enumerate(option_matches):
|
||||
start = match.end()
|
||||
end = option_matches[index + 1].start() if index + 1 < len(option_matches) else len(prompt)
|
||||
label = _normalize_spaces(prompt[start:end])
|
||||
option_id = match.group(1).lower()
|
||||
if not label:
|
||||
continue
|
||||
options.append({'id': option_id, 'label': f"{match.group(1).upper()}. {label}"})
|
||||
|
||||
if len(options) < 2 or answer not in {item['id'] for item in options}:
|
||||
return None
|
||||
|
||||
prompt_text = _normalize_spaces(prompt[:option_matches[0].start()])
|
||||
if not prompt_text:
|
||||
return None
|
||||
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'single',
|
||||
'prompt': prompt_text,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
'options': options,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
"""
|
||||
将 PDF 抽出的纯文本解析成培训题库。
|
||||
|
||||
用途:给管理后台的“从试题 PDF 导入题库”提供核心解析逻辑;优先保证答题链路可用,无法确定答案的题目宁可跳过也不乱导入。
|
||||
参数约束:text 应来自同一份试卷文本;若完全无法识别题目或答案,调用方应直接提示人工处理。
|
||||
"""
|
||||
lines = _collect_candidate_lines(text)
|
||||
answer_map = _extract_answer_map(lines)
|
||||
answer_sequence = _extract_answer_sequence(lines)
|
||||
question_blocks = _split_question_blocks(lines)
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
for index, (question_no, raw_block) in enumerate(question_blocks):
|
||||
inline_answer = _extract_inline_answer(raw_block)
|
||||
explanation = _extract_inline_explanation(raw_block)
|
||||
block_text = _strip_inline_meta(raw_block)
|
||||
option_matches = list(_OPTION_PATTERN.finditer(block_text))
|
||||
answer_candidates = _build_answer_candidates(
|
||||
inline_answer=inline_answer,
|
||||
mapped_answer=answer_map.get(question_no, ''),
|
||||
ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '',
|
||||
)
|
||||
|
||||
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_boolean_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
answer=answer,
|
||||
explanation=explanation,
|
||||
)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
break
|
||||
else:
|
||||
question_payload = None
|
||||
if question_payload:
|
||||
continue
|
||||
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_single_choice_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
option_matches=option_matches,
|
||||
answer=answer,
|
||||
explanation=explanation,
|
||||
)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
break
|
||||
else:
|
||||
question_payload = None
|
||||
if question_payload:
|
||||
continue
|
||||
|
||||
skipped_questions.append(question_no)
|
||||
|
||||
if not question_bank:
|
||||
raise ValidationError('未能从试题 PDF 中识别出可用题目,请检查 PDF 是否包含可复制文本与标准答案')
|
||||
|
||||
return {
|
||||
'question_bank': question_bank,
|
||||
'parsed_count': len(question_bank),
|
||||
'skipped_question_numbers': skipped_questions,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
从指定 Agent 的试题 PDF 指南中解析题库。
|
||||
|
||||
用途:管理后台点击“从已上传试题 PDF 导入”时使用,优先读取显式标记为 training_exam_pdf 的资料。
|
||||
参数约束:guide_id 若传入,必须属于当前 agent 且文件类型为 pdf。
|
||||
"""
|
||||
query = db.session.query(AgentGuide).filter(AgentGuide.agent_id == agent_id)
|
||||
if guide_id is not None:
|
||||
query = query.filter(AgentGuide.id == guide_id)
|
||||
query = query.filter(AgentGuide.file_type == 'pdf')
|
||||
guide = query.order_by(AgentGuide.sort_order.asc(), AgentGuide.id.desc()).first()
|
||||
if not guide:
|
||||
raise NotFoundError('Training exam PDF guide not found')
|
||||
if guide.guide_usage != GUIDE_USAGE_TRAINING_EXAM_PDF:
|
||||
raise ValidationError('Selected guide is not marked as training exam PDF')
|
||||
|
||||
raw_bytes = minio_service.get_file_bytes(guide.file_path)
|
||||
text = _extract_pdf_text(raw_bytes)
|
||||
ocr_text = ''
|
||||
ocr_warnings: list[str] = []
|
||||
extraction_mode = 'pdf_text'
|
||||
|
||||
# [STEP 1] 先尝试 PDF 原生文本,速度快且不会引入 OCR 噪音。
|
||||
if text:
|
||||
try:
|
||||
parsed = parse_training_question_bank_text(text)
|
||||
except ValidationError as primary_error:
|
||||
# [STEP 2] 原生文本存在但结构解析失败时,再尝试 OCR,兼容“页面能选中文本但题号/答案错位”的扫描型 PDF。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text or ocr_text == text:
|
||||
raise primary_error
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr_fallback'
|
||||
else:
|
||||
# [STEP 2] 完全拿不到 PDF 文本时,直接走 OCR;若 OCR 依旧为空,则给管理端明确报错并带回诊断 warnings。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text:
|
||||
raise ValidationError(
|
||||
'试题 PDF 未提取到可读文本,请检查是否为扫描件或图片 PDF,并确认 OCR 依赖已正确安装',
|
||||
details={'ocr_warnings': ocr_warnings},
|
||||
)
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr'
|
||||
|
||||
parsed['guide_id'] = guide.id
|
||||
parsed['guide_file_name'] = guide.file_name
|
||||
parsed['extraction_mode'] = extraction_mode
|
||||
parsed['extraction_warnings'] = ocr_warnings
|
||||
return parsed
|
||||
@@ -88,6 +88,25 @@ class MinioService:
|
||||
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
|
||||
return f"{base_url}/{self.bucket_name}/{object_name}"
|
||||
|
||||
def get_file_bytes(self, object_name: str) -> bytes:
|
||||
"""
|
||||
读取对象的原始字节内容。
|
||||
|
||||
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
|
||||
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
|
||||
"""
|
||||
local_path = os.path.join('data/agent-guides', object_name)
|
||||
if os.path.exists(local_path):
|
||||
with open(local_path, 'rb') as file_obj:
|
||||
return file_obj.read()
|
||||
|
||||
response = self.client.get_object(self.bucket_name, object_name)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
def delete_file(self, object_name: str):
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
tests/services/admin/test_training_exam_pdf_service.py
|
||||
|
||||
用途:验证培训试题 PDF 文本解析逻辑,确保可从常见试卷文本中抽出题目、选项、答案与解析。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, AgentGuide
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.admin.training_exam_pdf_service import (
|
||||
parse_training_question_bank_from_guide,
|
||||
parse_training_question_bank_text,
|
||||
)
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_supports_inline_answers():
|
||||
text = """
|
||||
一、单选题
|
||||
1. 工资每月几号发放? A. 8号 B. 9号 C. 15号 D. 27号 答案:C 解析:工资固定在每月15号发放。
|
||||
2. 餐厅订餐的系统是? A. OA B. 中米新订餐系统 C. ERP 答案:B
|
||||
"""
|
||||
|
||||
payload = parse_training_question_bank_text(text)
|
||||
|
||||
assert payload['parsed_count'] == 2
|
||||
assert payload['skipped_question_numbers'] == []
|
||||
assert payload['question_bank'][0]['type'] == 'single'
|
||||
assert payload['question_bank'][0]['answer'] == 'c'
|
||||
assert payload['question_bank'][0]['options'][2]['label'] == 'C. 15号'
|
||||
assert payload['question_bank'][0]['explanation'] == '工资固定在每月15号发放。'
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_supports_answer_sheet_mapping():
|
||||
text = """
|
||||
1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122
|
||||
2、入职培训未达到90分必须重新考试。 正确还是错误?
|
||||
|
||||
参考答案:
|
||||
1.B 2.正确
|
||||
"""
|
||||
|
||||
payload = parse_training_question_bank_text(text)
|
||||
|
||||
assert payload['parsed_count'] == 2
|
||||
assert payload['question_bank'][0]['answer'] == 'b'
|
||||
assert payload['question_bank'][1]['type'] == 'boolean'
|
||||
assert payload['question_bank'][1]['answer'] == 'true'
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_supports_global_answer_sequence_for_section_reset_numbering():
|
||||
text = """
|
||||
一、单选题
|
||||
1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122
|
||||
2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM
|
||||
|
||||
二、判断题(每题5分)
|
||||
1、正常出勤必须打卡。( )
|
||||
2、忘记刷卡需要OA补刷卡单。( )
|
||||
|
||||
参考答案:
|
||||
1.B 2.B 3.正确 4.正确
|
||||
"""
|
||||
|
||||
payload = parse_training_question_bank_text(text)
|
||||
|
||||
assert payload['parsed_count'] == 4
|
||||
assert payload['skipped_question_numbers'] == []
|
||||
assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean']
|
||||
assert payload['question_bank'][2]['answer'] == 'true'
|
||||
assert payload['question_bank'][3]['answer'] == 'true'
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_supports_answer_sheet_with_section_local_numbering():
|
||||
text = """
|
||||
一、单选题
|
||||
1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122
|
||||
2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM
|
||||
|
||||
二、判断题
|
||||
1、正常出勤必须打卡。( )
|
||||
2、忘记刷卡需要OA补刷卡单。( )
|
||||
|
||||
单选题答案:
|
||||
1.B 2.B
|
||||
判断题答案:
|
||||
1.正确 2.错误
|
||||
"""
|
||||
|
||||
payload = parse_training_question_bank_text(text)
|
||||
|
||||
assert payload['parsed_count'] == 4
|
||||
assert payload['skipped_question_numbers'] == []
|
||||
assert payload['question_bank'][2]['type'] == 'boolean'
|
||||
assert payload['question_bank'][2]['answer'] == 'true'
|
||||
assert payload['question_bank'][3]['answer'] == 'false'
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_supports_boolean_range_answer_sheet():
|
||||
text = """
|
||||
一、选择题(每题5分)
|
||||
1、工资每月几号发放( )
|
||||
A、8号 B、9号 C、15号 D、27号
|
||||
2、餐厅订餐的系统是( )
|
||||
A、OA B、中米新订餐系统 C、ERP
|
||||
|
||||
二、判断题(每题5分)
|
||||
1、正常出勤必须打卡,加班需要提前申请提报。( )
|
||||
2、忘记刷卡需要OA开补刷卡单。( )
|
||||
3、每月工资从上月21日至本月20日为止计算。( )
|
||||
|
||||
一、单选题(每题10分)
|
||||
1、C 2、B
|
||||
二、判断题(每题10分)
|
||||
1-3 V V ×
|
||||
"""
|
||||
|
||||
payload = parse_training_question_bank_text(text)
|
||||
|
||||
assert payload['parsed_count'] == 5
|
||||
assert payload['skipped_question_numbers'] == []
|
||||
assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean', 'boolean']
|
||||
assert [item['answer'] for item in payload['question_bank']] == ['c', 'b', 'true', 'true', 'false']
|
||||
|
||||
|
||||
def test_parse_training_question_bank_text_raises_when_no_usable_questions():
|
||||
with pytest.raises(ValidationError, match='未能从试题 PDF 中识别出可用题目'):
|
||||
parse_training_question_bank_text('这是一份扫描件占位文本,没有题号也没有答案。')
|
||||
|
||||
|
||||
def test_parse_training_question_bank_from_guide_falls_back_to_ocr_when_pdf_text_empty(app, monkeypatch):
|
||||
with app.app_context():
|
||||
agent = Agent(name='员工培训', type='api', is_active=True)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
guide = AgentGuide(
|
||||
agent_id=agent.id,
|
||||
file_name='training.pdf',
|
||||
file_type='pdf',
|
||||
file_path='training/training.pdf',
|
||||
guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
status=1,
|
||||
)
|
||||
db.session.add(guide)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes',
|
||||
lambda _path: b'%PDF-1.4 fake',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service._extract_pdf_text',
|
||||
lambda _raw: '',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr',
|
||||
lambda _raw: (
|
||||
'1. 消防电话是多少? A.110 B.119 C.120 D.122 答案:B',
|
||||
['pdf likely scanned; OCR recommended'],
|
||||
),
|
||||
)
|
||||
|
||||
payload = parse_training_question_bank_from_guide(agent.id, guide.id)
|
||||
|
||||
assert payload['parsed_count'] == 1
|
||||
assert payload['extraction_mode'] == 'ocr'
|
||||
assert payload['extraction_warnings'] == ['pdf likely scanned; OCR recommended']
|
||||
assert payload['question_bank'][0]['answer'] == 'b'
|
||||
|
||||
|
||||
def test_parse_training_question_bank_from_guide_retries_ocr_when_native_text_parse_fails(app, monkeypatch):
|
||||
with app.app_context():
|
||||
agent = Agent(name='员工培训', type='api', is_active=True)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
guide = AgentGuide(
|
||||
agent_id=agent.id,
|
||||
file_name='training.pdf',
|
||||
file_type='pdf',
|
||||
file_path='training/training.pdf',
|
||||
guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
status=1,
|
||||
)
|
||||
db.session.add(guide)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes',
|
||||
lambda _path: b'%PDF-1.4 fake',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service._extract_pdf_text',
|
||||
lambda _raw: '这是错位文本,题号和答案都缺失',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr',
|
||||
lambda _raw: (
|
||||
'1. 工资每月几号发放? A.8号 B.9号 C.15号 D.27号 答案:C',
|
||||
['pdf page-image mode pages: 1'],
|
||||
),
|
||||
)
|
||||
|
||||
payload = parse_training_question_bank_from_guide(agent.id, guide.id)
|
||||
|
||||
assert payload['parsed_count'] == 1
|
||||
assert payload['extraction_mode'] == 'ocr_fallback'
|
||||
assert payload['extraction_warnings'] == ['pdf page-image mode pages: 1']
|
||||
assert payload['question_bank'][0]['answer'] == 'c'
|
||||
+4
-3
@@ -26,11 +26,12 @@
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 管理角色可在同一聊天页查看真实培训统计、筛选记录并导出 Excel |
|
||||
| 培训题库前端内置 | 前端已实现 | 内置 20 道新人试卷题目,支持一题一答、即时反馈、未通过重考 |
|
||||
| 管理端培训模式配置 | 前端已实现 | Agent 管理表单支持显式开启培训工作区,并可一键套用培训默认配置 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 |
|
||||
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
|
||||
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
## 1. 功能总览
|
||||
|
||||
+122
@@ -911,6 +911,128 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
|
||||
- Web 进程压力下降,系统稳定性提升
|
||||
- 失败任务可重试,进度展示更清晰
|
||||
- 整体知识库链路更适合后续扩展为高并发、多批次处理模式
|
||||
|
||||
---
|
||||
|
||||
## 19. 新人入职培训 Agent 推荐技术路径
|
||||
|
||||
### 19.1 推荐结论
|
||||
|
||||
“新人入职培训 Agent”不建议走纯 Dify 考试编排主链,推荐采用:
|
||||
|
||||
- **主链**:Chat 页面内嵌培训工作区 + 前端受控状态机 + 后端真实记录落库
|
||||
- **辅助层**:Dify 承担培训 FAQ、知识点解释、HR 自然语言统计问答(ChatBI)
|
||||
|
||||
该方案更符合培训考试场景对“流程刚性、成绩可信、状态可恢复、结果可审计”的要求。
|
||||
|
||||
### 19.2 为什么不建议纯 Dify 主导考试
|
||||
|
||||
- 培训考试需要严格控制“看视频 -> 看总结 -> 一题一答 -> 结算 -> 补考”顺序
|
||||
- 题号推进、得分计算、补考次数不适合交给大模型对话变量作为唯一事实源
|
||||
- 纯 Dify 方案更适合自然语言问答,不适合作为考试状态机和唯一判卷引擎
|
||||
- HR 统计和导出需要稳定的数据事实源,不能依赖对话历史反推
|
||||
|
||||
### 19.3 推荐架构
|
||||
|
||||
```text
|
||||
员工
|
||||
-> Chat 页面
|
||||
-> 培训工作区(视频 / 总结 / 考试 / 结算)
|
||||
-> 聊天气泡卡片(视频卡片 / 总结卡片 / 题目卡片 / 结果卡片)
|
||||
|
||||
前端培训工作区
|
||||
-> /api/user/training-record
|
||||
-> /api/user/training-record/progress
|
||||
|
||||
后端 training 域
|
||||
-> TrainingRecord 表
|
||||
-> training_service
|
||||
-> HR 列表 / 统计 / Excel 导出
|
||||
|
||||
Dify
|
||||
-> 培训 FAQ
|
||||
-> 知识点解释
|
||||
-> HR ChatBI
|
||||
```
|
||||
|
||||
### 19.4 培训权限模型
|
||||
|
||||
- 学员端默认面向所有已登录员工开放,允许查看视频、知识点复盘、考试与个人成绩回显。
|
||||
- `HR 管理` 视图与 `/api/admin/training-records*` 接口统一走 `training_hr_manage` 功能权限判断。
|
||||
- 权限来源采用“**角色默认值 + 用户显式配置覆盖**”:
|
||||
- `admin`、`hr` 角色默认拥有 `training_hr_manage`
|
||||
- 管理后台用户编辑表单可对单个用户显式授予或关闭该权限
|
||||
- 前端只根据登录态里的 `feature_permissions.training_hr_manage` 决定是否展示 `HR 管理` 标签;后端仍做强校验,避免仅靠前端隐藏导致越权。
|
||||
|
||||
### 19.5 培训资料维护
|
||||
|
||||
- 后台继续复用 `AgentGuide` 资料模型承载培训素材,不单独新建一套上传体系。
|
||||
- `guide_usage` 用于标识资料用途:
|
||||
- `general`:普通应用指南
|
||||
- `training_video`:员工培训视频
|
||||
- `training_exam_pdf`:员工培训试题 PDF
|
||||
- 员工培训工作区读取顺序:
|
||||
1. 优先读取 `training_video` 指南作为培训视频
|
||||
2. 若未配置,再回退到 Agent `extra_config.training_video_url`
|
||||
3. 仍未配置时使用默认演示视频
|
||||
- “查看试题 PDF”入口只读取 `training_exam_pdf`,避免把普通指南 PDF 误识别成考试资料。
|
||||
|
||||
### 19.6 培训内容后台化
|
||||
|
||||
- 培训工作区的结构化内容统一收敛到 `Agent.extra_config.training_config`,避免继续把题库、复盘要点散落在前端静态文案里。
|
||||
- 当前约定字段:
|
||||
- `pass_score`:及格线,按百分制判定是否通过
|
||||
- `summary_points`:知识点复盘数组
|
||||
- `summary_checklist`:考前必知数组
|
||||
- `question_bank`:结构化题库(`id/type/prompt/answer/explanation/options`)
|
||||
- 员工培训工作区读取顺序:
|
||||
1. 优先读取 `extra_config.training_config`
|
||||
2. 若某项未配置,则仅该项回退到前端默认值,保证旧 Agent 不因缺字段而失效
|
||||
- 题库题量改为后台可配后,前端分数计算改为“按当前题量折算百分制”,不再硬编码每题 5 分。
|
||||
- 管理端支持从已上传并标记为 `training_exam_pdf` 的指南 PDF 解析题库:
|
||||
1. 后端按 `guide_id` 读取 PDF 文本
|
||||
2. 若 PDF 原生文本缺失或错位,则回退到 `loader_pdf + rapidocr` 识别扫描件页面
|
||||
3. 识别题号、选项、答案与解析,生成 `question_bank`
|
||||
4. 解析结果先回填 Agent 表单,由 HR 复核后再保存,避免误解析直接落库
|
||||
- 扫描件 PDF 的 OCR 回退依赖 `backend/requirements-ocr.txt` 中的 rapidocr / onnxruntime 栈;若环境未安装,接口会返回带 `ocr_warnings` 的诊断信息,提示先补齐 OCR 依赖。
|
||||
|
||||
### 19.4 Dify 职责边界
|
||||
|
||||
#### 建议由 Dify 负责
|
||||
|
||||
- 培训制度问答
|
||||
- 培训知识点解释
|
||||
- 培训 FAQ
|
||||
- HR 自然语言统计和导出问答
|
||||
|
||||
#### 不建议由 Dify 负责
|
||||
|
||||
- 当前题号推进
|
||||
- 当前分数累计
|
||||
- 最终是否通过的唯一判定
|
||||
- 补考次数控制
|
||||
- 培训考试记录事实落库
|
||||
|
||||
### 19.5 推荐实施顺序
|
||||
|
||||
#### P0
|
||||
|
||||
- 保留现有培训工作区主链
|
||||
- 完善 training 接口测试与前端回归测试
|
||||
- 确保培训记录、统计、导出全链路稳定
|
||||
|
||||
#### P1
|
||||
|
||||
- 题库、知识点、通过线、欢迎语后台配置化
|
||||
- 培训视频素材正式配置化
|
||||
- 题库版本化与记录快照化
|
||||
|
||||
#### P2
|
||||
|
||||
- 接入 Dify 作为培训 FAQ / HR ChatBI 的辅助层
|
||||
- 对外形成“Chat 化体验 + 受控考试主链”的最终形态
|
||||
|
||||
详细说明见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md)。
|
||||
# 设备维保助手技术设计补充
|
||||
|
||||
## 数据模型
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/api/admin.api.ts
|
||||
* 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。
|
||||
*/
|
||||
@@ -131,6 +131,27 @@ export const uploadAdminAgentGuideFile = async (file: File) => {
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
export const importAdminAgentTrainingQuestionBankFromPdf = (agentId: number, payload: { guide_id?: number | null }) =>
|
||||
requestJson<{
|
||||
guide_id: number;
|
||||
guide_file_name: string;
|
||||
parsed_count: number;
|
||||
skipped_question_numbers: number[];
|
||||
extraction_mode?: 'pdf_text' | 'ocr' | 'ocr_fallback';
|
||||
extraction_warnings?: string[];
|
||||
question_bank: Array<{
|
||||
id: string;
|
||||
type: 'single' | 'boolean';
|
||||
prompt: string;
|
||||
answer: string;
|
||||
explanation: string;
|
||||
options?: Array<{ id: string; label: string }>;
|
||||
}>;
|
||||
}>(`/api/admin/agents/${agentId}/training-question-bank/import-pdf`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
export const testAdminAgent = (id: number) =>
|
||||
requestJson<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
|
||||
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/agents/AgentsPage.vue
|
||||
*
|
||||
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
|
||||
@@ -29,9 +29,11 @@ const { t } = useI18n();
|
||||
const {
|
||||
agents,
|
||||
scheduleTasks,
|
||||
trainingExamPdfGuides,
|
||||
activeUsers,
|
||||
isLoading,
|
||||
isSaving,
|
||||
isImportingTrainingPdf,
|
||||
isEditing,
|
||||
selectedAgentId,
|
||||
form,
|
||||
@@ -50,6 +52,11 @@ const {
|
||||
submitAgent,
|
||||
addSuggestedQuestion,
|
||||
removeSuggestedQuestion,
|
||||
addTrainingQuestion,
|
||||
removeTrainingQuestion,
|
||||
addTrainingOption,
|
||||
removeTrainingOption,
|
||||
importTrainingQuestionBankFromPdf,
|
||||
deleteAgent,
|
||||
openTestModal,
|
||||
runAgentTest,
|
||||
@@ -229,12 +236,19 @@ onMounted(() => {
|
||||
:visible="showFormDialog"
|
||||
:is-editing="isEditing"
|
||||
:is-saving="isSaving"
|
||||
:is-importing-training-pdf="isImportingTrainingPdf"
|
||||
:form="form"
|
||||
:schedule-tasks="scheduleTasks"
|
||||
:training-exam-pdf-guides="trainingExamPdfGuides"
|
||||
@close="showFormDialog = false"
|
||||
@save="saveAgentForm"
|
||||
@add-suggested-question="addSuggestedQuestion"
|
||||
@remove-suggested-question="removeSuggestedQuestion"
|
||||
@add-training-question="addTrainingQuestion"
|
||||
@remove-training-question="removeTrainingQuestion"
|
||||
@add-training-option="addTrainingOption"
|
||||
@remove-training-option="removeTrainingOption"
|
||||
@import-training-pdf="importTrainingQuestionBankFromPdf"
|
||||
/>
|
||||
|
||||
<AgentPermissionModal
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Plus, Trash2, X } from 'lucide-vue-next';
|
||||
import { FileDown, Plus, Trash2, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AgentFormState } from '@/features/admin/types/agent.types';
|
||||
import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types';
|
||||
import type { ScheduleTask } from '@/shared/types/schedule.types';
|
||||
import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue';
|
||||
|
||||
@@ -17,8 +17,10 @@ defineProps<{
|
||||
visible: boolean;
|
||||
isEditing: boolean;
|
||||
isSaving: boolean;
|
||||
isImportingTrainingPdf: boolean;
|
||||
form: AgentFormState;
|
||||
scheduleTasks: ScheduleTask[];
|
||||
trainingExamPdfGuides: AgentGuideSummary[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -26,9 +28,40 @@ const emit = defineEmits<{
|
||||
save: [];
|
||||
addSuggestedQuestion: [];
|
||||
removeSuggestedQuestion: [index: number];
|
||||
addTrainingQuestion: [];
|
||||
removeTrainingQuestion: [index: number];
|
||||
addTrainingOption: [questionIndex: number];
|
||||
removeTrainingOption: [questionIndex: number, optionIndex: number];
|
||||
importTrainingPdf: [guideId?: number | null];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
||||
|
||||
/**
|
||||
* 切换培训题型时同步修正表单结构。
|
||||
* 核心逻辑:判断题固定使用 true/false;单选题至少保留两个选项,并把答案回落到首个可用选项。
|
||||
*/
|
||||
const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) => {
|
||||
const question = form.training_question_bank[index];
|
||||
if (!question) return;
|
||||
if (question.type === 'boolean') {
|
||||
question.options = [];
|
||||
question.answer = question.answer === 'false' ? 'false' : 'true';
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(question.options)) {
|
||||
question.options = ['', ''];
|
||||
}
|
||||
while (question.options.length < 2) {
|
||||
question.options.push('');
|
||||
}
|
||||
const validAnswerIds = question.options
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((_, optionIndex) => String.fromCharCode(97 + optionIndex));
|
||||
question.answer = validAnswerIds.includes(question.answer) ? question.answer : (validAnswerIds[0] || 'a');
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -202,6 +235,218 @@ const { t } = useI18n();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('admin.agent.training.title') }}</div>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ t('admin.agent.training.subtitle') }}</p>
|
||||
</div>
|
||||
<label class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary">
|
||||
<input v-model="form.training_workspace_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.agent.training.enable') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p class="mt-3 text-xs leading-5 text-muted">
|
||||
{{ form.training_workspace_enabled ? t('admin.agent.training.enableHint') : t('admin.agent.training.disabledHint') }}
|
||||
</p>
|
||||
|
||||
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.passScore') }}</label>
|
||||
<input
|
||||
v-model.number="form.training_pass_score"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
step="1"
|
||||
class="w-full input-field text-sm"
|
||||
/>
|
||||
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.training.passScoreHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-2 md:col-span-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.summaryPoints') }}</label>
|
||||
<textarea
|
||||
v-model="form.training_summary_points_text"
|
||||
rows="5"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.summaryPointsPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2 md:col-span-3">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.summaryChecklist') }}</label>
|
||||
<textarea
|
||||
v-model="form.training_summary_checklist_text"
|
||||
rows="4"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.summaryChecklistPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-primary">{{ t('admin.agent.training.questionBank') }}</div>
|
||||
<p class="mt-1 text-xs leading-5 text-muted">{{ t('admin.agent.training.questionHint') }}</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="!isEditing || trainingExamPdfGuides.length === 0 || isImportingTrainingPdf"
|
||||
@click="emit('importTrainingPdf', trainingExamPdfGuides[0]?.id || null)"
|
||||
>
|
||||
<FileDown class="h-4 w-4" />
|
||||
{{ isImportingTrainingPdf ? t('admin.agent.training.importingPdf') : t('admin.agent.training.importFromPdf') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="emit('addTrainingQuestion')"
|
||||
>
|
||||
<Plus class="h-4 w-4" />
|
||||
{{ t('admin.agent.training.addQuestion') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-xs leading-5 text-muted">
|
||||
{{
|
||||
!isEditing
|
||||
? t('admin.agent.training.importPdfCreateFirst')
|
||||
: trainingExamPdfGuides.length > 0
|
||||
? t('admin.agent.training.importPdfHint', { fileName: trainingExamPdfGuides[0]?.file_name || '--' })
|
||||
: t('admin.agent.training.importPdfMissing')
|
||||
}}
|
||||
</p>
|
||||
|
||||
<div v-if="form.training_question_bank.length === 0" class="rounded-xl border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">
|
||||
{{ t('admin.agent.training.emptyQuestionBank') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
<div
|
||||
v-for="(question, questionIndex) in form.training_question_bank"
|
||||
:key="questionIndex"
|
||||
class="rounded-2xl border border-default bg-white p-4"
|
||||
>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('admin.agent.training.questionCardTitle', { index: questionIndex + 1 }) }}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-medium text-red-600 transition-colors hover:bg-red-100"
|
||||
@click="emit('removeTrainingQuestion', questionIndex)"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
{{ t('admin.agent.training.removeQuestion') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionId') }}</label>
|
||||
<input
|
||||
v-model="question.id"
|
||||
type="text"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.questionIdPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionType') }}</label>
|
||||
<select
|
||||
v-model="question.type"
|
||||
class="w-full input-field text-sm"
|
||||
@change="handleTrainingQuestionTypeChange(form, questionIndex)"
|
||||
>
|
||||
<option value="single">{{ t('admin.agent.training.single') }}</option>
|
||||
<option value="boolean">{{ t('admin.agent.training.boolean') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.correctAnswer') }}</label>
|
||||
<select v-model="question.answer" class="w-full input-field text-sm">
|
||||
<template v-if="question.type === 'boolean'">
|
||||
<option value="true">{{ t('admin.agent.training.booleanTrue') }}</option>
|
||||
<option value="false">{{ t('admin.agent.training.booleanFalse') }}</option>
|
||||
</template>
|
||||
<template v-else>
|
||||
<option
|
||||
v-for="(_, optionIndex) in question.options.filter((item) => String(item || '').trim())"
|
||||
:key="`${questionIndex}-${optionIndex}`"
|
||||
:value="String.fromCharCode(97 + optionIndex)"
|
||||
>
|
||||
{{ t('admin.agent.training.optionLabel', { label: optionLabels[optionIndex] || optionIndex + 1 }) }}
|
||||
</option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 md:col-span-3">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionPrompt') }}</label>
|
||||
<textarea
|
||||
v-model="question.prompt"
|
||||
rows="3"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.questionPromptPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 md:col-span-3">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionExplanation') }}</label>
|
||||
<textarea
|
||||
v-model="question.explanation"
|
||||
rows="3"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.questionExplanationPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="question.type === 'single'" class="space-y-3 md:col-span-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionOptions') }}</label>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-surface-soft px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-slate-100"
|
||||
@click="emit('addTrainingOption', questionIndex)"
|
||||
>
|
||||
<Plus class="h-4 w-4" />
|
||||
{{ t('admin.agent.training.addOption') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 md:grid-cols-2">
|
||||
<div
|
||||
v-for="(_, optionIndex) in question.options"
|
||||
:key="`${questionIndex}-option-${optionIndex}`"
|
||||
class="flex items-center gap-2 rounded-xl border border-default bg-surface-soft/40 p-3"
|
||||
>
|
||||
<span class="min-w-6 text-xs font-semibold text-muted">{{ optionLabels[optionIndex] || optionIndex + 1 }}.</span>
|
||||
<input
|
||||
v-model="question.options[optionIndex]"
|
||||
type="text"
|
||||
class="w-full input-field text-sm"
|
||||
:placeholder="t('admin.agent.training.optionPlaceholder')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-red-200 bg-red-50 text-red-600 transition-colors hover:bg-red-100"
|
||||
@click="emit('removeTrainingOption', questionIndex, optionIndex)"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AgentToolRunProgressConfig
|
||||
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
|
||||
:form="form"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/agents/composables/useAgentsAdmin.ts
|
||||
*
|
||||
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
|
||||
@@ -10,6 +10,8 @@ import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
createAdminAgent,
|
||||
deleteAdminAgent,
|
||||
importAdminAgentTrainingQuestionBankFromPdf,
|
||||
listAdminAgentGuides,
|
||||
listAdminAgents,
|
||||
listAdminUsers,
|
||||
saveAdminAgentPermissions,
|
||||
@@ -19,10 +21,19 @@ import {
|
||||
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import type { AgentFormState, AgentRow, AgentSuggestedQuestionItem, AgentTestResult } from '@/features/admin/types/agent.types';
|
||||
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
|
||||
import type {
|
||||
AgentFormState,
|
||||
AgentRow,
|
||||
AgentSuggestedQuestionItem,
|
||||
AgentTestResult,
|
||||
AgentTrainingQuestionFormItem,
|
||||
AgentGuideSummary,
|
||||
} from '@/features/admin/types/agent.types';
|
||||
import { createEmptyAgentForm, createEmptyTrainingQuestionForm } from '@/features/admin/types/agent.types';
|
||||
import type { ScheduleTask } from '@/shared/types/schedule.types';
|
||||
|
||||
const TRAINING_OPTION_IDS = 'abcdefghijklmnopqrstuvwxyz'.split('');
|
||||
|
||||
const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
@@ -39,6 +50,169 @@ const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem
|
||||
.filter((item): item is AgentSuggestedQuestionItem => !!item);
|
||||
};
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> => (
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: {}
|
||||
);
|
||||
|
||||
const toMultilineText = (value: unknown) => (
|
||||
Array.isArray(value)
|
||||
? value.map((item) => String(item || '').trim()).filter(Boolean).join('\n')
|
||||
: ''
|
||||
);
|
||||
|
||||
const splitMultilineText = (value: string): string[] => value
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
type TrainingImportPayload = Awaited<ReturnType<typeof importAdminAgentTrainingQuestionBankFromPdf>>;
|
||||
|
||||
/**
|
||||
* 从 Agent extra_config 解析员工培训配置表单字段。
|
||||
* 核心逻辑:优先读取 extra_config.training_config,兼容历史顶层字段;单选题选项统一收敛成纯文本数组,便于后台表单维护。
|
||||
*/
|
||||
const parseTrainingConfigFromExtra = (extra: Record<string, unknown> | undefined) => {
|
||||
const trainingConfig = asRecord(extra?.training_config);
|
||||
const merged = {
|
||||
...asRecord(extra),
|
||||
...trainingConfig,
|
||||
};
|
||||
const rawQuestionBank: unknown[] = Array.isArray(merged.question_bank ?? merged.questionBank)
|
||||
? (merged.question_bank ?? merged.questionBank) as unknown[]
|
||||
: [];
|
||||
const questionBank: AgentTrainingQuestionFormItem[] = rawQuestionBank
|
||||
.map((item: unknown, index: number): AgentTrainingQuestionFormItem => {
|
||||
const raw = asRecord(item);
|
||||
const type: AgentTrainingQuestionFormItem['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
|
||||
const rawOptions: unknown[] = Array.isArray(raw.options) ? raw.options : [];
|
||||
const optionLabels = type === 'single'
|
||||
? rawOptions
|
||||
.map((option: unknown) => {
|
||||
if (typeof option === 'string') return option.trim();
|
||||
return String(asRecord(option).label || '').trim();
|
||||
})
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
while (type === 'single' && optionLabels.length < 2) {
|
||||
optionLabels.push('');
|
||||
}
|
||||
return {
|
||||
id: String(raw.id || '').trim() || `q${index + 1}`,
|
||||
type,
|
||||
prompt: String(raw.prompt || '').trim(),
|
||||
explanation: String(raw.explanation || '').trim(),
|
||||
options: optionLabels,
|
||||
answer: type === 'boolean'
|
||||
? (String(raw.answer || '').trim() === 'false' ? 'false' : 'true')
|
||||
: (() => {
|
||||
const answer = String(raw.answer || '').trim();
|
||||
const optionIds = optionLabels.map((_, optionIndex) => TRAINING_OPTION_IDS[optionIndex]).filter(Boolean);
|
||||
return optionIds.includes(answer) ? answer : (optionIds[0] || 'a');
|
||||
})(),
|
||||
};
|
||||
})
|
||||
.filter((item) => Boolean(item.prompt || item.id || item.options.length));
|
||||
const hasTrainingContent = questionBank.length > 0
|
||||
|| Boolean(toMultilineText(merged.summary_points ?? merged.summaryPoints))
|
||||
|| Boolean(toMultilineText(merged.summary_checklist ?? merged.summaryChecklist));
|
||||
|
||||
return {
|
||||
training_workspace_enabled:
|
||||
extra?.training_workspace_enabled === true
|
||||
|| extra?.training_workspace_enabled === 'true'
|
||||
|| extra?.training_mode === true
|
||||
|| extra?.training_mode === 'true'
|
||||
|| extra?.training_agent === true
|
||||
|| extra?.training_agent === 'true'
|
||||
|| hasTrainingContent,
|
||||
training_pass_score: Number.isFinite(Number(merged.pass_score ?? merged.passScore))
|
||||
? Math.max(0, Math.min(100, Math.round(Number(merged.pass_score ?? merged.passScore))))
|
||||
: 90,
|
||||
training_summary_points_text: toMultilineText(merged.summary_points ?? merged.summaryPoints),
|
||||
training_summary_checklist_text: toMultilineText(merged.summary_checklist ?? merged.summaryChecklist),
|
||||
training_question_bank: questionBank,
|
||||
};
|
||||
};
|
||||
|
||||
const buildTrainingQuestionPayload = (question: AgentTrainingQuestionFormItem, index: number) => {
|
||||
const id = String(question.id || '').trim() || `q${index + 1}`;
|
||||
const prompt = String(question.prompt || '').trim();
|
||||
const explanation = String(question.explanation || '').trim();
|
||||
if (question.type === 'boolean') {
|
||||
return {
|
||||
id,
|
||||
type: 'boolean' as const,
|
||||
prompt,
|
||||
answer: question.answer === 'false' ? 'false' : 'true',
|
||||
explanation,
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedOptions = question.options
|
||||
.map((label) => String(label || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((label, optionIndex) => ({
|
||||
id: TRAINING_OPTION_IDS[optionIndex] || `option_${optionIndex + 1}`,
|
||||
label,
|
||||
}));
|
||||
const optionIds = normalizedOptions.map((item) => item.id);
|
||||
return {
|
||||
id,
|
||||
type: 'single' as const,
|
||||
prompt,
|
||||
answer: optionIds.includes(question.answer) ? question.answer : (optionIds[0] || 'a'),
|
||||
explanation,
|
||||
options: normalizedOptions,
|
||||
};
|
||||
};
|
||||
|
||||
const hasTrainingConfigContent = (form: AgentFormState) => (
|
||||
form.training_workspace_enabled
|
||||
|| Boolean(form.training_summary_points_text.trim())
|
||||
|| Boolean(form.training_summary_checklist_text.trim())
|
||||
|| form.training_question_bank.length > 0
|
||||
);
|
||||
|
||||
/**
|
||||
* 生成培训试题 PDF 导入完成后的反馈文案。
|
||||
* 核心逻辑:先反馈题库导入结果,再补充 OCR 回退与诊断提示,避免 HR 误以为扫描件导入结果可直接信任。
|
||||
*/
|
||||
const buildTrainingPdfImportMessages = (
|
||||
payload: TrainingImportPayload,
|
||||
t: ReturnType<typeof useI18n>['t'],
|
||||
): { primary: string; notices: string[] } => {
|
||||
const skipped = Array.isArray(payload.skipped_question_numbers) ? payload.skipped_question_numbers : [];
|
||||
const extractionWarnings = Array.isArray(payload.extraction_warnings)
|
||||
? payload.extraction_warnings.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const primary = skipped.length
|
||||
? t('admin.agent.training.importPdfPartialSuccess', {
|
||||
count: payload.parsed_count,
|
||||
skipped: skipped.join('、'),
|
||||
})
|
||||
: t('admin.agent.training.importPdfSuccess', {
|
||||
count: payload.parsed_count,
|
||||
fileName: payload.guide_file_name,
|
||||
});
|
||||
|
||||
const notices: string[] = [];
|
||||
if (payload.extraction_mode === 'ocr') {
|
||||
notices.push(t('admin.agent.training.importPdfOcrUsed'));
|
||||
} else if (payload.extraction_mode === 'ocr_fallback') {
|
||||
notices.push(t('admin.agent.training.importPdfOcrFallback'));
|
||||
}
|
||||
if (extractionWarnings.length) {
|
||||
notices.push(t('admin.agent.training.importPdfWarnings', {
|
||||
warnings: extractionWarnings.join(';'),
|
||||
}));
|
||||
}
|
||||
|
||||
return { primary, notices };
|
||||
};
|
||||
|
||||
/**
|
||||
* 从 Agent extra_config 解析 tool_run_progress 表单字段。
|
||||
* 核心逻辑:capabilities 含 tool_run_progress 时视为启用;task_id 与 schedule_task_id 等价。
|
||||
@@ -120,8 +294,10 @@ export function useAgentsAdmin() {
|
||||
const agents = ref<AgentRow[]>([]);
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const scheduleTasks = ref<ScheduleTask[]>([]);
|
||||
const trainingExamPdfGuides = ref<AgentGuideSummary[]>([]);
|
||||
const isLoading = ref(true);
|
||||
const isSaving = ref(false);
|
||||
const isImportingTrainingPdf = ref(false);
|
||||
const isEditing = ref(false);
|
||||
const selectedAgentId = ref<number | null>(null);
|
||||
const form = ref<AgentFormState>(createEmptyAgentForm());
|
||||
@@ -168,6 +344,22 @@ export function useAgentsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadTrainingExamPdfGuides = async (agentId: number | null | undefined): Promise<void> => {
|
||||
if (!agentId) {
|
||||
trainingExamPdfGuides.value = [];
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const guides = await listAdminAgentGuides(agentId);
|
||||
trainingExamPdfGuides.value = (Array.isArray(guides) ? guides : []).filter((guide) => (
|
||||
guide?.file_type === 'pdf' && guide?.guide_usage === 'training_exam_pdf'
|
||||
));
|
||||
} catch (e) {
|
||||
console.error('Error loading training exam PDF guides:', e);
|
||||
trainingExamPdfGuides.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await Promise.all([loadAgents(), loadUsers(), loadScheduleTasks()]);
|
||||
@@ -177,6 +369,7 @@ export function useAgentsAdmin() {
|
||||
const resetForm = (): void => {
|
||||
selectedAgentId.value = null;
|
||||
form.value = createEmptyAgentForm();
|
||||
trainingExamPdfGuides.value = [];
|
||||
isEditing.value = false;
|
||||
};
|
||||
|
||||
@@ -185,6 +378,7 @@ export function useAgentsAdmin() {
|
||||
? agent.extra_config
|
||||
: {};
|
||||
const toolRunProgress = parseToolRunProgressFromExtra(extra);
|
||||
const trainingConfig = parseTrainingConfigFromExtra(extra);
|
||||
selectedAgentId.value = agent.id;
|
||||
form.value = {
|
||||
id: agent.id,
|
||||
@@ -205,8 +399,10 @@ export function useAgentsAdmin() {
|
||||
? Math.floor(Number(extra.sort_order))
|
||||
: 0,
|
||||
...toolRunProgress,
|
||||
...trainingConfig,
|
||||
};
|
||||
isEditing.value = true;
|
||||
void loadTrainingExamPdfGuides(agent.id);
|
||||
};
|
||||
|
||||
const openDeleteConfirm = (
|
||||
@@ -242,6 +438,32 @@ export function useAgentsAdmin() {
|
||||
msg.warning(t('admin.dept.msg.nameRequired'));
|
||||
return false;
|
||||
}
|
||||
if (form.value.training_workspace_enabled) {
|
||||
if (form.value.training_question_bank.length === 0) {
|
||||
msg.warning(t('admin.agent.training.validation.questionRequired'));
|
||||
return false;
|
||||
}
|
||||
for (let index = 0; index < form.value.training_question_bank.length; index += 1) {
|
||||
const question = form.value.training_question_bank[index];
|
||||
if (!question) continue;
|
||||
if (!String(question.prompt || '').trim()) {
|
||||
msg.warning(t('admin.agent.training.validation.questionPromptRequired', { index: index + 1 }));
|
||||
return false;
|
||||
}
|
||||
if (question.type === 'single') {
|
||||
const validOptions = question.options.map((item) => String(item || '').trim()).filter(Boolean);
|
||||
if (validOptions.length < 2) {
|
||||
msg.warning(t('admin.agent.training.validation.questionSingleOptions', { index: index + 1 }));
|
||||
return false;
|
||||
}
|
||||
const validAnswerIds = validOptions.map((_, optionIndex) => TRAINING_OPTION_IDS[optionIndex]).filter(Boolean);
|
||||
if (!validAnswerIds.includes(question.answer)) {
|
||||
msg.warning(t('admin.agent.training.validation.questionAnswerRequired', { index: index + 1 }));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const supportsToolRunProgress = form.value.type === 'api' && form.value.dify_app_type !== 'workflow';
|
||||
if (supportsToolRunProgress && form.value.tool_run_progress_enabled && !form.value.schedule_task_id) {
|
||||
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
|
||||
@@ -280,6 +502,17 @@ export function useAgentsAdmin() {
|
||||
applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false });
|
||||
}
|
||||
applyAgentCategoryToExtra(extra_config, form.value);
|
||||
extra_config.training_workspace_enabled = Boolean(form.value.training_workspace_enabled);
|
||||
if (hasTrainingConfigContent(form.value)) {
|
||||
extra_config.training_config = {
|
||||
pass_score: Math.max(0, Math.min(100, Math.round(Number(form.value.training_pass_score) || 90))),
|
||||
summary_points: splitMultilineText(form.value.training_summary_points_text),
|
||||
summary_checklist: splitMultilineText(form.value.training_summary_checklist_text),
|
||||
question_bank: form.value.training_question_bank.map((question, index) => buildTrainingQuestionPayload(question, index)),
|
||||
};
|
||||
} else {
|
||||
delete extra_config.training_config;
|
||||
}
|
||||
|
||||
try {
|
||||
const editingId = isEditing.value ? Number(form.value.id) : null;
|
||||
@@ -336,6 +569,70 @@ export function useAgentsAdmin() {
|
||||
form.value.suggested_questions.splice(index, 1);
|
||||
};
|
||||
|
||||
const addTrainingQuestion = (): void => {
|
||||
form.value.training_question_bank.push(createEmptyTrainingQuestionForm());
|
||||
};
|
||||
|
||||
const removeTrainingQuestion = (index: number): void => {
|
||||
form.value.training_question_bank.splice(index, 1);
|
||||
};
|
||||
|
||||
const addTrainingOption = (questionIndex: number): void => {
|
||||
const question = form.value.training_question_bank[questionIndex];
|
||||
if (!question || question.type !== 'single') return;
|
||||
question.options.push('');
|
||||
};
|
||||
|
||||
const removeTrainingOption = (questionIndex: number, optionIndex: number): void => {
|
||||
const question = form.value.training_question_bank[questionIndex];
|
||||
if (!question || question.type !== 'single') return;
|
||||
question.options.splice(optionIndex, 1);
|
||||
if (question.options.length < 2) {
|
||||
question.options.push('');
|
||||
}
|
||||
const validAnswerIds = question.options
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((_, normalizedIndex) => TRAINING_OPTION_IDS[normalizedIndex])
|
||||
.filter(Boolean);
|
||||
question.answer = validAnswerIds.includes(question.answer) ? question.answer : (validAnswerIds[0] || 'a');
|
||||
};
|
||||
|
||||
/**
|
||||
* 从已上传的培训试题 PDF 导入题库到当前 Agent 表单。
|
||||
* 核心逻辑:解析结果只回填当前表单,不直接保存数据库,确保 HR 可以先检查题干、选项和答案后再提交。
|
||||
*/
|
||||
const importTrainingQuestionBankFromPdf = async (guideId?: number | null): Promise<void> => {
|
||||
const agentId = Number(form.value.id);
|
||||
if (!agentId) {
|
||||
msg.warning(t('admin.agent.training.importPdfAgentRequired'));
|
||||
return;
|
||||
}
|
||||
isImportingTrainingPdf.value = true;
|
||||
try {
|
||||
const payload = await importAdminAgentTrainingQuestionBankFromPdf(agentId, { guide_id: guideId ?? null });
|
||||
form.value.training_question_bank = (payload.question_bank || []).map((question, index) => ({
|
||||
id: String(question.id || '').trim() || `q${index + 1}`,
|
||||
type: question.type === 'boolean' ? 'boolean' : 'single',
|
||||
prompt: String(question.prompt || '').trim(),
|
||||
explanation: String(question.explanation || '').trim(),
|
||||
options: question.type === 'boolean'
|
||||
? []
|
||||
: (question.options || []).map((option) => String(option.label || '').replace(/^[A-D]\.\s*/i, '').trim()),
|
||||
answer: String(question.answer || '').trim() || (question.type === 'boolean' ? 'true' : 'a'),
|
||||
}));
|
||||
form.value.training_workspace_enabled = true;
|
||||
const importMessages = buildTrainingPdfImportMessages(payload, t);
|
||||
msg.success(importMessages.primary);
|
||||
importMessages.notices.forEach((notice) => msg.warning(notice));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
} finally {
|
||||
isImportingTrainingPdf.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteAgent = async (id: number): Promise<void> => {
|
||||
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
|
||||
try {
|
||||
@@ -436,9 +733,11 @@ export function useAgentsAdmin() {
|
||||
agents,
|
||||
users,
|
||||
scheduleTasks,
|
||||
trainingExamPdfGuides,
|
||||
activeUsers,
|
||||
isLoading,
|
||||
isSaving,
|
||||
isImportingTrainingPdf,
|
||||
isEditing,
|
||||
selectedAgentId,
|
||||
form,
|
||||
@@ -457,6 +756,11 @@ export function useAgentsAdmin() {
|
||||
submitAgent,
|
||||
addSuggestedQuestion,
|
||||
removeSuggestedQuestion,
|
||||
addTrainingQuestion,
|
||||
removeTrainingQuestion,
|
||||
addTrainingOption,
|
||||
removeTrainingOption,
|
||||
importTrainingQuestionBankFromPdf,
|
||||
deleteAgent,
|
||||
openTestModal,
|
||||
runAgentTest,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
|
||||
@@ -19,6 +19,7 @@ const form = ref({
|
||||
file_name: '',
|
||||
file_path: '',
|
||||
file_type: 'pdf',
|
||||
guide_usage: 'general',
|
||||
file_size: 0,
|
||||
remark: '',
|
||||
sort_order: 0,
|
||||
@@ -68,6 +69,7 @@ const openCreateModal = () => {
|
||||
file_name: '',
|
||||
file_path: '',
|
||||
file_type: 'pdf',
|
||||
guide_usage: 'general',
|
||||
file_size: 0,
|
||||
remark: '',
|
||||
sort_order: 0,
|
||||
@@ -84,6 +86,7 @@ const openEditModal = (guide: any) => {
|
||||
file_name: guide.file_name,
|
||||
file_path: guide.file_path,
|
||||
file_type: guide.file_type,
|
||||
guide_usage: guide.guide_usage || 'general',
|
||||
file_size: guide.file_size,
|
||||
remark: guide.remark,
|
||||
sort_order: guide.sort_order,
|
||||
@@ -105,6 +108,12 @@ const handleFileUpload = async (event: Event) => {
|
||||
form.value.file_path = res.file_path;
|
||||
form.value.file_type = res.file_type;
|
||||
form.value.file_size = res.file_size;
|
||||
if (form.value.guide_usage === 'training_video' && res.file_type !== 'video') {
|
||||
form.value.guide_usage = 'general';
|
||||
}
|
||||
if (form.value.guide_usage === 'training_exam_pdf' && res.file_type !== 'pdf') {
|
||||
form.value.guide_usage = 'general';
|
||||
}
|
||||
if (!form.value.file_name) {
|
||||
form.value.file_name = res.file_name;
|
||||
}
|
||||
@@ -215,6 +224,7 @@ const getIcon = (type: string) => {
|
||||
<tr>
|
||||
<th class="px-6 py-4">类型</th>
|
||||
<th class="px-6 py-4">资料名称</th>
|
||||
<th class="px-6 py-4">{{ t('admin.platformApps.guideUsage') }}</th>
|
||||
<th class="px-6 py-4">Agent应用</th>
|
||||
<th class="px-6 py-4">文件大小</th>
|
||||
<th class="px-6 py-4">排序</th>
|
||||
@@ -231,6 +241,11 @@ const getIcon = (type: string) => {
|
||||
<div class="font-medium text-default">{{ guide.file_name }}</div>
|
||||
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-muted">
|
||||
<span v-if="guide.guide_usage === 'training_video'">{{ t('admin.platformApps.trainingVideo') }}</span>
|
||||
<span v-else-if="guide.guide_usage === 'training_exam_pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</span>
|
||||
<span v-else>{{ t('admin.platformApps.generalGuide') }}</span>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
|
||||
{{ currentAgentName }}
|
||||
@@ -296,6 +311,15 @@ const getIcon = (type: string) => {
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.guideUsage') }}</label>
|
||||
<select v-model="form.guide_usage" class="input-field w-full">
|
||||
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
|
||||
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
|
||||
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
|
||||
</select>
|
||||
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium text-default">排序权重</label>
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*
|
||||
* Agent 管理模块专用类型,供 AgentsPage 与相关 composable / 组件使用。
|
||||
*/
|
||||
import type { TrainingQuestionType } from '@/features/chat/training/training.types';
|
||||
|
||||
export interface AgentRow {
|
||||
id: number;
|
||||
@@ -24,6 +25,23 @@ export interface AgentSuggestedQuestionItem {
|
||||
group: string;
|
||||
}
|
||||
|
||||
export interface AgentTrainingQuestionFormItem {
|
||||
id: string;
|
||||
type: TrainingQuestionType;
|
||||
prompt: string;
|
||||
explanation: string;
|
||||
options: string[];
|
||||
answer: string;
|
||||
}
|
||||
|
||||
export interface AgentGuideSummary {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
guide_usage?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export interface AgentTestResult {
|
||||
success: boolean;
|
||||
request_url: string;
|
||||
@@ -58,8 +76,22 @@ export interface AgentFormState {
|
||||
schedule_task_id: number | null;
|
||||
poll_interval_seconds: number;
|
||||
lock_input_when_running: boolean;
|
||||
training_workspace_enabled: boolean;
|
||||
training_pass_score: number;
|
||||
training_summary_points_text: string;
|
||||
training_summary_checklist_text: string;
|
||||
training_question_bank: AgentTrainingQuestionFormItem[];
|
||||
}
|
||||
|
||||
export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem => ({
|
||||
id: '',
|
||||
type: 'single',
|
||||
prompt: '',
|
||||
explanation: '',
|
||||
options: ['', ''],
|
||||
answer: 'a',
|
||||
});
|
||||
|
||||
export const createEmptyAgentForm = (): AgentFormState => ({
|
||||
name: '',
|
||||
dify_app_id: '',
|
||||
@@ -79,4 +111,9 @@ export const createEmptyAgentForm = (): AgentFormState => ({
|
||||
schedule_task_id: null,
|
||||
poll_interval_seconds: 2,
|
||||
lock_input_when_running: true,
|
||||
training_workspace_enabled: false,
|
||||
training_pass_score: 90,
|
||||
training_summary_points_text: '',
|
||||
training_summary_checklist_text: '',
|
||||
training_question_bank: [],
|
||||
});
|
||||
@@ -28,6 +28,13 @@
|
||||
"reports": "Data Reports",
|
||||
"schedules": "Schedule Management"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "Guide Usage",
|
||||
"generalGuide": "General Guide",
|
||||
"trainingVideo": "Employee Training Video",
|
||||
"trainingExamPdf": "Employee Training Exam PDF",
|
||||
"guideUsageHint": "The training workspace will prioritize guides marked as employee training video or employee training exam PDF."
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "Active Agents",
|
||||
"totalUsers": "Total Users",
|
||||
@@ -85,6 +92,9 @@
|
||||
"email": "Email",
|
||||
"department": "Department",
|
||||
"role": "Role",
|
||||
"featurePermissions": "Feature Permissions",
|
||||
"trainingHrManage": "Training HR Admin",
|
||||
"trainingHrManageHint": "Allows this user to open the employee training agent HR Management view for stats, filtering, and Excel export.",
|
||||
"password": "Password",
|
||||
"passwordHint": "(leave blank to keep)",
|
||||
"noAgents": "No agents available."
|
||||
@@ -203,6 +213,58 @@
|
||||
"pollInterval": "Progress refresh interval (seconds)",
|
||||
"lockInput": "Prevent sending new messages while a task is running",
|
||||
"scheduleTaskRequired": "Please select a linked schedule first"
|
||||
},
|
||||
"training": {
|
||||
"title": "Employee Training Configuration",
|
||||
"subtitle": "Configure the training workspace pass line, review points, and question bank. After saving, the employee training page will read this backend content first.",
|
||||
"enable": "Enable employee training workspace",
|
||||
"enableHint": "When enabled, this agent uses the training flow of video, review, exam, and settlement.",
|
||||
"disabledHint": "When disabled, this agent will not show the employee training workspace. Existing training content remains stored in the backend.",
|
||||
"passScore": "Passing score",
|
||||
"passScoreHint": "The frontend exam and result copy both use this percentage score as the pass line.",
|
||||
"summaryPoints": "Review points",
|
||||
"summaryPointsPlaceholder": "One item per line, for example: Salary is paid on the 15th of each month",
|
||||
"summaryChecklist": "Must know before the exam",
|
||||
"summaryChecklistPlaceholder": "One item per line, for example: Scores below 90 require a retake",
|
||||
"questionBank": "Question bank",
|
||||
"questionHint": "Supports single choice and true or false questions. Employees will use the updated bank immediately after saving.",
|
||||
"emptyQuestionBank": "No question bank configured yet. The employee view will fall back to the default bank.",
|
||||
"importFromPdf": "Import From Exam PDF",
|
||||
"importingPdf": "Parsing PDF...",
|
||||
"importPdfHint": "The system will parse the uploaded exam PDF \"{fileName}\" first. You can still review and edit the result manually after import.",
|
||||
"importPdfMissing": "This agent does not have any uploaded guide marked as Employee Training Exam PDF yet. Please upload it first in Platform App Guides.",
|
||||
"importPdfCreateFirst": "Please save this agent first, then import the question bank from an uploaded exam PDF.",
|
||||
"importPdfAgentRequired": "Please save this agent first before importing the exam PDF",
|
||||
"importPdfSuccess": "Imported {count} questions from \"{fileName}\"",
|
||||
"importPdfPartialSuccess": "Imported {count} questions. These question numbers were skipped: {skipped}",
|
||||
"importPdfOcrUsed": "This import was completed through OCR. Please review the prompts, options, and answers carefully.",
|
||||
"importPdfOcrFallback": "Native PDF text parsing failed, so the import automatically fell back to OCR. Please review the prompts, options, and answers carefully.",
|
||||
"importPdfWarnings": "Parsing notes: {warnings}",
|
||||
"addQuestion": "Add question",
|
||||
"removeQuestion": "Remove question",
|
||||
"questionCardTitle": "Question {index}",
|
||||
"questionId": "Question ID",
|
||||
"questionIdPlaceholder": "For example: q1",
|
||||
"questionType": "Question type",
|
||||
"single": "Single choice",
|
||||
"boolean": "True or false",
|
||||
"correctAnswer": "Correct answer",
|
||||
"booleanTrue": "True",
|
||||
"booleanFalse": "False",
|
||||
"questionPrompt": "Prompt",
|
||||
"questionPromptPlaceholder": "Enter the question content",
|
||||
"questionExplanation": "Explanation",
|
||||
"questionExplanationPlaceholder": "Enter the explanation shown to the learner after answering",
|
||||
"questionOptions": "Options",
|
||||
"addOption": "Add option",
|
||||
"optionLabel": "Option {label}",
|
||||
"optionPlaceholder": "Enter option text",
|
||||
"validation": {
|
||||
"questionRequired": "Please configure at least one training question",
|
||||
"questionPromptRequired": "Question {index} prompt is required",
|
||||
"questionSingleOptions": "Question {index} needs at least 2 valid options",
|
||||
"questionAnswerRequired": "Please choose the correct answer for question {index}"
|
||||
}
|
||||
}
|
||||
},
|
||||
"question": {
|
||||
@@ -1023,6 +1085,7 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "User",
|
||||
"hr": "HR",
|
||||
"admin": "Admin",
|
||||
"guest": "Guest"
|
||||
},
|
||||
|
||||
@@ -28,6 +28,13 @@
|
||||
"reports": "รายงานข้อมูล",
|
||||
"schedules": "Schedule Management"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "ประเภทการใช้งานเอกสาร",
|
||||
"generalGuide": "คู่มือทั่วไป",
|
||||
"trainingVideo": "วิดีโออบรมพนักงาน",
|
||||
"trainingExamPdf": "PDF ข้อสอบอบรมพนักงาน",
|
||||
"guideUsageHint": "พื้นที่อบรมจะให้ความสำคัญกับเอกสารที่ทำเครื่องหมายเป็นวิดีโออบรมพนักงานหรือ PDF ข้อสอบอบรมพนักงานก่อน"
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "ตัวแทนที่ใช้งานอยู่",
|
||||
"totalUsers": "ผู้ใช้ทั้งหมด",
|
||||
@@ -85,6 +92,9 @@
|
||||
"email": "อีเมล",
|
||||
"department": "แผนก",
|
||||
"role": "บทบาท",
|
||||
"featurePermissions": "สิทธิ์ฟีเจอร์",
|
||||
"trainingHrManage": "จัดการ HR การฝึกอบรม",
|
||||
"trainingHrManageHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าใช้มุมมอง HR 管理 ใน employee training agent เพื่อดูสถิติ คัดกรองข้อมูล และส่งออก Excel ได้",
|
||||
"password": "รหัสผ่าน",
|
||||
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
|
||||
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
|
||||
@@ -203,6 +213,58 @@
|
||||
"pollInterval": "ช่วงรีเฟรชความคืบหน้า (วินาที)",
|
||||
"lockInput": "ห้ามส่งข้อความใหม่ขณะงานกำลังทำงาน",
|
||||
"scheduleTaskRequired": "โปรดเลือกตารางงานที่เชื่อมก่อน"
|
||||
},
|
||||
"training": {
|
||||
"title": "การตั้งค่าการอบรมพนักงาน",
|
||||
"subtitle": "กำหนดคะแนนผ่าน ประเด็นทบทวน และคลังข้อสอบของ workspace การอบรม หลังบันทึกแล้ว หน้าการอบรมพนักงานจะอ่านค่าจาก backend นี้ก่อน",
|
||||
"enable": "เปิดใช้ workspace การอบรมพนักงาน",
|
||||
"enableHint": "เมื่อเปิดใช้ Agent นี้จะใช้ลำดับวิดีโอ ทบทวน สอบ และสรุปผล",
|
||||
"disabledHint": "เมื่อปิดใช้ Agent นี้จะไม่แสดง workspace การอบรมพนักงาน แต่ข้อมูลการอบรมที่กรอกไว้จะยังคงอยู่ใน backend",
|
||||
"passScore": "คะแนนผ่าน",
|
||||
"passScoreHint": "ข้อสอบหน้าเว็บและข้อความผลลัพธ์จะใช้คะแนนเปอร์เซ็นต์นี้เป็นเกณฑ์ผ่าน",
|
||||
"summaryPoints": "ประเด็นทบทวน",
|
||||
"summaryPointsPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น เงินเดือนจ่ายทุกวันที่ 15",
|
||||
"summaryChecklist": "สิ่งที่ต้องรู้ก่อนสอบ",
|
||||
"summaryChecklistPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น คะแนนต่ำกว่า 90 ต้องสอบใหม่",
|
||||
"questionBank": "คลังข้อสอบ",
|
||||
"questionHint": "รองรับข้อสอบแบบปรนัยและถูกหรือผิด หลังบันทึกแล้วพนักงานจะใช้ชุดข้อสอบใหม่นี้ทันที",
|
||||
"emptyQuestionBank": "ยังไม่ได้ตั้งค่าคลังข้อสอบ ฝั่งพนักงานจะใช้คลังข้อสอบเริ่มต้นแทน",
|
||||
"importFromPdf": "นำเข้าจาก PDF ข้อสอบ",
|
||||
"importingPdf": "กำลังแปลง PDF...",
|
||||
"importPdfHint": "ระบบจะใช้ไฟล์ PDF ข้อสอบ \"{fileName}\" ที่อัปโหลดไว้เพื่อแปลงเป็นคลังข้อสอบก่อน และยังแก้ไขต่อด้วยมือได้",
|
||||
"importPdfMissing": "Agent นี้ยังไม่มีไฟล์ที่ถูกทำเครื่องหมายเป็น PDF ข้อสอบอบรมพนักงาน กรุณาอัปโหลดก่อนในหน้าคู่มือแอป",
|
||||
"importPdfCreateFirst": "กรุณาบันทึก Agent นี้ก่อน แล้วจึงนำเข้าคลังข้อสอบจาก PDF ที่อัปโหลดไว้",
|
||||
"importPdfAgentRequired": "กรุณาบันทึก Agent นี้ก่อน แล้วจึงนำเข้า PDF ข้อสอบ",
|
||||
"importPdfSuccess": "นำเข้า {count} ข้อจาก \"{fileName}\" แล้ว",
|
||||
"importPdfPartialSuccess": "นำเข้าได้ {count} ข้อ และข้อต่อไปนี้ไม่สามารถแปลงได้: {skipped}",
|
||||
"importPdfOcrUsed": "การนำเข้าครั้งนี้เสร็จสิ้นด้วย OCR กรุณาตรวจทานโจทย์ ตัวเลือก และคำตอบอย่างละเอียด",
|
||||
"importPdfOcrFallback": "การแยกข้อความจาก PDF แบบปกติล้มเหลว ระบบจึงสลับไปใช้ OCR อัตโนมัติ กรุณาตรวจทานโจทย์ ตัวเลือก และคำตอบอย่างละเอียด",
|
||||
"importPdfWarnings": "หมายเหตุการแปลง: {warnings}",
|
||||
"addQuestion": "เพิ่มข้อสอบ",
|
||||
"removeQuestion": "ลบข้อสอบ",
|
||||
"questionCardTitle": "ข้อสอบ {index}",
|
||||
"questionId": "รหัสข้อสอบ",
|
||||
"questionIdPlaceholder": "เช่น q1",
|
||||
"questionType": "ประเภทข้อสอบ",
|
||||
"single": "ปรนัย",
|
||||
"boolean": "ถูกหรือผิด",
|
||||
"correctAnswer": "คำตอบที่ถูกต้อง",
|
||||
"booleanTrue": "ถูก",
|
||||
"booleanFalse": "ผิด",
|
||||
"questionPrompt": "คำถาม",
|
||||
"questionPromptPlaceholder": "กรอกข้อความคำถาม",
|
||||
"questionExplanation": "คำอธิบาย",
|
||||
"questionExplanationPlaceholder": "กรอกคำอธิบายที่จะแสดงให้พนักงานหลังตอบ",
|
||||
"questionOptions": "ตัวเลือก",
|
||||
"addOption": "เพิ่มตัวเลือก",
|
||||
"optionLabel": "ตัวเลือก {label}",
|
||||
"optionPlaceholder": "กรอกข้อความตัวเลือก",
|
||||
"validation": {
|
||||
"questionRequired": "กรุณาตั้งค่าข้อสอบการอบรมอย่างน้อย 1 ข้อ",
|
||||
"questionPromptRequired": "ข้อ {index} ต้องกรอกคำถาม",
|
||||
"questionSingleOptions": "ข้อ {index} ต้องมีตัวเลือกที่ใช้ได้อย่างน้อย 2 ตัวเลือก",
|
||||
"questionAnswerRequired": "กรุณาเลือกคำตอบที่ถูกต้องของข้อ {index}"
|
||||
}
|
||||
}
|
||||
},
|
||||
"question": {
|
||||
@@ -882,6 +944,7 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "ผู้ใช้ทั่วไป",
|
||||
"hr": "HR",
|
||||
"admin": "ผู้ดูแลระบบ",
|
||||
"guest": "ผู้เยี่ยมชม"
|
||||
},
|
||||
|
||||
@@ -29,6 +29,13 @@
|
||||
"reports": "数据报表",
|
||||
"schedules": "排程管理"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "资料用途",
|
||||
"generalGuide": "通用指南",
|
||||
"trainingVideo": "员工培训视频",
|
||||
"trainingExamPdf": "员工培训试题 PDF",
|
||||
"guideUsageHint": "培训工作区会优先读取“员工培训视频”和“员工培训试题 PDF”这两类资料。"
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "活跃应用",
|
||||
"totalUsers": "总用户数",
|
||||
@@ -86,6 +93,9 @@
|
||||
"email": "邮箱",
|
||||
"department": "部门",
|
||||
"role": "角色",
|
||||
"featurePermissions": "功能权限",
|
||||
"trainingHrManage": "培训 HR 管理",
|
||||
"trainingHrManageHint": "勾选后可进入员工培训 Agent 的【HR 管理】视图,查看统计、筛选记录并导出 Excel。",
|
||||
"password": "密码",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暂无可用应用"
|
||||
@@ -204,6 +214,58 @@
|
||||
"pollInterval": "进度刷新间隔(秒)",
|
||||
"lockInput": "任务执行期间禁止发送新消息",
|
||||
"scheduleTaskRequired": "请先选择关联的排程任务"
|
||||
},
|
||||
"training": {
|
||||
"title": "员工培训配置",
|
||||
"subtitle": "配置培训工作区的及格线、复盘要点和题库。保存后,员工培训页会优先读取这里的后台内容。",
|
||||
"enable": "启用员工培训工作区",
|
||||
"enableHint": "开启后,当前 Agent 会使用“视频 -> 复盘 -> 考试 -> 结算”的培训工作区流程。",
|
||||
"disabledHint": "关闭后,当前 Agent 不展示员工培训工作区;已填写的培训配置仍会保留在后台。",
|
||||
"passScore": "及格线",
|
||||
"passScoreHint": "按百分制判定是否通过,前台考试和结果文案会同步使用这个分数。",
|
||||
"summaryPoints": "知识点复盘",
|
||||
"summaryPointsPlaceholder": "每行一条,例如:工资每月 15 号发放",
|
||||
"summaryChecklist": "考前必知",
|
||||
"summaryChecklistPlaceholder": "每行一条,例如:低于 90 分必须重新考试",
|
||||
"questionBank": "题库",
|
||||
"questionHint": "支持单选题和判断题;保存后员工考试会即时使用新的题库。",
|
||||
"emptyQuestionBank": "暂未配置题库,员工端会回退到默认题库。",
|
||||
"importFromPdf": "从试题 PDF 导入",
|
||||
"importingPdf": "正在解析 PDF...",
|
||||
"importPdfHint": "将优先使用已上传的试题 PDF《{fileName}》解析题库,导入后仍可继续人工调整。",
|
||||
"importPdfMissing": "当前 Agent 还没有上传并标记“员工培训试题 PDF”的资料,请先去“平台应用说明”上传。",
|
||||
"importPdfCreateFirst": "请先保存当前 Agent,再从已上传的试题 PDF 导入题库。",
|
||||
"importPdfAgentRequired": "请先保存当前 Agent,再导入试题 PDF",
|
||||
"importPdfSuccess": "已从《{fileName}》导入 {count} 道题目",
|
||||
"importPdfPartialSuccess": "已导入 {count} 道题目,以下题号未识别成功:{skipped}",
|
||||
"importPdfOcrUsed": "本次导入通过 OCR 识别完成,建议重点复核题干、选项和答案。",
|
||||
"importPdfOcrFallback": "原生 PDF 文本解析失败,已自动回退到 OCR 识别,建议重点复核题干、选项和答案。",
|
||||
"importPdfWarnings": "解析提示:{warnings}",
|
||||
"addQuestion": "添加题目",
|
||||
"removeQuestion": "删除题目",
|
||||
"questionCardTitle": "题目 {index}",
|
||||
"questionId": "题目编号",
|
||||
"questionIdPlaceholder": "例如:q1",
|
||||
"questionType": "题型",
|
||||
"single": "单选题",
|
||||
"boolean": "判断题",
|
||||
"correctAnswer": "正确答案",
|
||||
"booleanTrue": "正确",
|
||||
"booleanFalse": "错误",
|
||||
"questionPrompt": "题干",
|
||||
"questionPromptPlaceholder": "请输入题目内容",
|
||||
"questionExplanation": "解析",
|
||||
"questionExplanationPlaceholder": "请输入答题解析,答错后会直接展示给员工",
|
||||
"questionOptions": "选项",
|
||||
"addOption": "添加选项",
|
||||
"optionLabel": "选项 {label}",
|
||||
"optionPlaceholder": "请输入选项内容",
|
||||
"validation": {
|
||||
"questionRequired": "请至少配置一道培训题目",
|
||||
"questionPromptRequired": "第 {index} 题题干不能为空",
|
||||
"questionSingleOptions": "第 {index} 题至少需要 2 个有效选项",
|
||||
"questionAnswerRequired": "第 {index} 题请选择正确答案"
|
||||
}
|
||||
}
|
||||
},
|
||||
"question": {
|
||||
@@ -1003,6 +1065,7 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "普通用户",
|
||||
"hr": "HR",
|
||||
"admin": "管理员",
|
||||
"guest": "访客"
|
||||
},
|
||||
|
||||
@@ -28,6 +28,13 @@
|
||||
"reports": "數據報表",
|
||||
"schedules": "排程管理"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "資料用途",
|
||||
"generalGuide": "通用指南",
|
||||
"trainingVideo": "員工培訓視頻",
|
||||
"trainingExamPdf": "員工培訓試題 PDF",
|
||||
"guideUsageHint": "培訓工作區會優先讀取「員工培訓視頻」和「員工培訓試題 PDF」這兩類資料。"
|
||||
},
|
||||
"dash": {
|
||||
"activeAgents": "活躍應用",
|
||||
"totalUsers": "總用戶數",
|
||||
@@ -85,6 +92,9 @@
|
||||
"email": "郵箱",
|
||||
"department": "部門",
|
||||
"role": "角色",
|
||||
"featurePermissions": "功能權限",
|
||||
"trainingHrManage": "培訓 HR 管理",
|
||||
"trainingHrManageHint": "勾選後可進入員工培訓 Agent 的【HR 管理】視圖,查看統計、篩選記錄並匯出 Excel。",
|
||||
"password": "密碼",
|
||||
"passwordHint": "(留空表示不修改)",
|
||||
"noAgents": "暫無可用應用"
|
||||
@@ -203,6 +213,58 @@
|
||||
"pollInterval": "進度刷新間隔(秒)",
|
||||
"lockInput": "任務執行期間禁止發送新訊息",
|
||||
"scheduleTaskRequired": "請先選擇關聯的排程任務"
|
||||
},
|
||||
"training": {
|
||||
"title": "員工培訓配置",
|
||||
"subtitle": "配置培訓工作區的及格線、複盤要點和題庫。保存後,員工培訓頁會優先讀取這裡的後台內容。",
|
||||
"enable": "啟用員工培訓工作區",
|
||||
"enableHint": "開啟後,當前 Agent 會使用「影片 -> 複盤 -> 考試 -> 結算」的培訓工作區流程。",
|
||||
"disabledHint": "關閉後,當前 Agent 不顯示員工培訓工作區;已填寫的培訓配置仍會保留在後台。",
|
||||
"passScore": "及格線",
|
||||
"passScoreHint": "按百分制判定是否通過,前台考試和結果文案會同步使用這個分數。",
|
||||
"summaryPoints": "知識點複盤",
|
||||
"summaryPointsPlaceholder": "每行一條,例如:工資每月 15 號發放",
|
||||
"summaryChecklist": "考前必知",
|
||||
"summaryChecklistPlaceholder": "每行一條,例如:低於 90 分必須重新考試",
|
||||
"questionBank": "題庫",
|
||||
"questionHint": "支援單選題和判斷題;保存後員工考試會即時使用新的題庫。",
|
||||
"emptyQuestionBank": "暫未配置題庫,員工端會回退到預設題庫。",
|
||||
"importFromPdf": "從試題 PDF 導入",
|
||||
"importingPdf": "正在解析 PDF...",
|
||||
"importPdfHint": "將優先使用已上傳的試題 PDF《{fileName}》解析題庫,導入後仍可繼續人工調整。",
|
||||
"importPdfMissing": "當前 Agent 還沒有上傳並標記「員工培訓試題 PDF」的資料,請先去「平台應用說明」上傳。",
|
||||
"importPdfCreateFirst": "請先保存當前 Agent,再從已上傳的試題 PDF 導入題庫。",
|
||||
"importPdfAgentRequired": "請先保存當前 Agent,再導入試題 PDF",
|
||||
"importPdfSuccess": "已從《{fileName}》導入 {count} 道題目",
|
||||
"importPdfPartialSuccess": "已導入 {count} 道題目,以下題號未識別成功:{skipped}",
|
||||
"importPdfOcrUsed": "本次導入透過 OCR 識別完成,建議重點複核題幹、選項與答案。",
|
||||
"importPdfOcrFallback": "原生 PDF 文字解析失敗,已自動回退至 OCR 識別,建議重點複核題幹、選項與答案。",
|
||||
"importPdfWarnings": "解析提示:{warnings}",
|
||||
"addQuestion": "添加題目",
|
||||
"removeQuestion": "刪除題目",
|
||||
"questionCardTitle": "題目 {index}",
|
||||
"questionId": "題目編號",
|
||||
"questionIdPlaceholder": "例如:q1",
|
||||
"questionType": "題型",
|
||||
"single": "單選題",
|
||||
"boolean": "判斷題",
|
||||
"correctAnswer": "正確答案",
|
||||
"booleanTrue": "正確",
|
||||
"booleanFalse": "錯誤",
|
||||
"questionPrompt": "題幹",
|
||||
"questionPromptPlaceholder": "請輸入題目內容",
|
||||
"questionExplanation": "解析",
|
||||
"questionExplanationPlaceholder": "請輸入答題解析,答錯後會直接展示給員工",
|
||||
"questionOptions": "選項",
|
||||
"addOption": "添加選項",
|
||||
"optionLabel": "選項 {label}",
|
||||
"optionPlaceholder": "請輸入選項內容",
|
||||
"validation": {
|
||||
"questionRequired": "請至少配置一道培訓題目",
|
||||
"questionPromptRequired": "第 {index} 題題幹不能為空",
|
||||
"questionSingleOptions": "第 {index} 題至少需要 2 個有效選項",
|
||||
"questionAnswerRequired": "第 {index} 題請選擇正確答案"
|
||||
}
|
||||
}
|
||||
},
|
||||
"question": {
|
||||
@@ -883,6 +945,7 @@
|
||||
},
|
||||
"role": {
|
||||
"user": "普通用戶",
|
||||
"hr": "HR",
|
||||
"admin": "管理員",
|
||||
"guest": "訪客"
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user